SparkFun BasicAHRS_I2C giving unstable readings SparkFun BasicAHRS_I2C giving unstable readings.

I am using the SparkFun Arduino Sketch from here.

It is giving me these results:

X-acceleration: 91.43 mg Y-acceleration: 249.51 mg Z-acceleration: 1042.05 mg
X-gyro rate: -0.549 degrees/sec Y-gyro rate: 0.557 degrees/sec Z-gyro rate: 1.595 degrees/sec
X-mag field: -164.35 mG Y-mag field: -240.16 mG Z-mag field: -20.73 mG
Temperature is 27.9 degrees C

and then the next result (when MPU9250 is still) is:

X-acceleration: 91.49 mg Y-acceleration: 252.75 mg Z-acceleration: 1039.49 mg
X-gyro rate: -0.076 degrees/sec Y-gyro rate: -0.130 degrees/sec Z-gyro rate: -0.008 degrees/sec
X-mag field: -175.07 mG Y-mag field: -222.24 mG Z-mag field: -27.64 mG
Temperature is 27.9 degrees C

Notice how the temperature has remained constant, acceleration has remained constant (although im not why there is a reading if the MPU9250 is stationary) and the mag field is fairly close. However, the Gyro values are not close.

Could I have a bad MPU9250?

I am using the Mega.

Edit: Added a complementary filter from here, however they have not added a comp filter for the z value as can be seen from my screenshot of the serial monitor:

I think this is because they have the MPU6050 and not the MPU9250. I believe the MPU9250 has the magnetometer which can be used to 'help' the drift?

How could I use the magnetometer to help counter the drift?

End goal: rotate a gameobject in unity with the MPU9250 with minimal drift and maximum accuracy.

If you haven’t noticed the difference in the two is minuscule.
For example, the change in degree is <1. Also the acceleration is measured in g’s which is acceleration due to gravity. The data says the measures are in mg which is 0.01g.
This is normal with accelerometers and all sensors when they pick up residual voltage from random vibrations or other sources of noise. It also could be with the error margin within SparkFun’s product since the product is more on the lower end of quality which once again is normal.
TLDR: everything is working fine.


Issue with Arduino car bot, the servo motor moves randomly also it turns hot pretty quickly I trying to create an Arduino avoiding obstacle car. Using Arduino Uno +shield (sensor sheild v5.0). The problem is that when I upload the code, the servo moves randomly (it doesn't rotate to the right) and becomes hot quickly, it is an SG90 with 5v. I have already checked several times and the hardware seems all right.

I have tried to change the angle of the servo, checked the pins several times - uploaded the code many times I have also used serial.prints. researched on the internet.

#include <NewPing.h>        //Ultrasonic sensor function library. You must install this library

//our L298N control pins
const int LeftMotorForward = 5;
const int LeftMotorBackward = 4;
const int RightMotorForward = 1;
const int RightMotorBackward = 0;

//sensor pins
#define trig_pin A1 //analog input 1
#define echo_pin A2 //analog input 2

#define maximum_distance 200
boolean goesForward = false;
int distance = 100;

NewPing sonar(trig_pin, echo_pin, maximum_distance); //sensor function
Servo servo_motor; //our servo name

void setup(){

  pinMode(RightMotorForward, OUTPUT);
  pinMode(LeftMotorForward, OUTPUT);
  pinMode(LeftMotorBackward, OUTPUT);
  pinMode(RightMotorBackward, OUTPUT);

  servo_motor.attach(11); //our servo pin

  servo_motor.write(90);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop(){

  int distanceRight = 0;
  int distanceLeft = 0;
  delay(50);

  if (distance <= 20){
    moveStop();
    delay(300);
    moveBackward();
    delay(400);
    moveStop();
    delay(300);
    distanceRight = lookRight();
    delay(300);
    distanceLeft = lookLeft();
    delay(300);

    if (distance >= distanceLeft){
      turnRight();
      moveStop();
    }
    else{
      turnLeft();
      moveStop();
    }
  }
  else{
    moveForward();
  }
    distance = readPing();
}

int lookRight(){
  servo_motor.write(10);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(90);
  return distance;
}

int lookLeft(){
  servo_motor.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(90);
  return distance;
  delay(100);
}

int readPing(){
  delay(70);
  int cm = sonar.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
}

void moveStop(){

  digitalWrite(RightMotorForward, LOW);
  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(LeftMotorBackward, LOW);
}

void moveForward(){

  if(!goesForward){

    goesForward=true;

    digitalWrite(LeftMotorForward, HIGH);
    digitalWrite(RightMotorForward, HIGH);

    digitalWrite(LeftMotorBackward, LOW);
    digitalWrite(RightMotorBackward, LOW);
  }
}

void moveBackward(){

  goesForward=false;

  digitalWrite(LeftMotorBackward, HIGH);
  digitalWrite(RightMotorBackward, HIGH);

  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorForward, LOW);

}

void turnRight(){

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorBackward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorForward, LOW);

  delay(500);

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorBackward, LOW);

}

void turnLeft(){

  digitalWrite(LeftMotorBackward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorBackward, LOW);

  delay(500);

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorBackward, LOW);
}

Expected to the servo to rotate 90 degrees, but right now the servo is moving randomly.

I think you need to do some rigorous testing of the individual functions of your bot.

Step 1: rename your loop function to "loop_temp" which means it won't run, but it will be retained for later.

Step 2: write a new "loop" function, which sets the LeftMotorForward for 1 second, then stop for 1 second.  And observe the results.

Step 3: repeat Step 2 with LeftMotorBackward, RightMotorForward, etc

Step 4: using serial print, experiment with the output from the sonar to make sure it's delivering the expected results.

Step 5: one at a time introduce your functions and ensure they are each working properly.

Step 6: hopefully you've discovered a bug/fault somewhere, and you can re-introduce your original "loop" function.  Otherwise that function may be the issue.

I've had a look at your code, but don't see anything obviously amiss.  So I'm afraid it may be a process of elimination.


Convert from hexadecimal to binary I need to simulate a pulse train. Everything is in order with this code, it solves its problem.
The question is: I need to change the keys, but it is too difficult to manually type in so many zeros and ones each time.
On the other hand, I know that my hexadecimal key looks much shorter: "B8C4F9".
Is it possible to create a string in such a way that the system itself translates to the binary system?
And the second question: How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?
const int KEY_LEN = 24;
const char key[KEY_LEN] = {"101110001100010011111001"};

int T = 200; // Pulse repetition period in microseconds
int Zero = 80; //0.4*T; // Duration of zero in microseconds
int One = 120; //0.6*T;// Duration of a unit in microseconds

const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  for (int n = 0; n < KEY_LEN; n++)
  {
    if (key1[n] == '1') //If the bit read == 1
    {
      sendSignal(One);
    }

    else if (key1[n] == '0')//If the bit being read == 0
    {
      sendSignal(Zero);
    }
  }
}

void sendSignal(int duration)
{
  digitalWrite(LED_PIN, LOW);
  delayMicroseconds(duration);
  digitalWrite(LED_PIN, HIGH);
  delayMicroseconds(T - duration);
}

There is really no reason to save the key as a string, as you are doing. You can just save it as a normal number. Then you can also use the hexadecimal representation on your code:
unsigned long key = 0xB8C4F9;

Then you need to send out each bit of that number:
for (int n = 0; n < KEY_LEN; n++)
{
    if (key & (1 << n)) { //If the bit read == 1
        sendSignal(One);
    } else {//If the bit being read == 0
        sendSignal(Zero);
    }
}

The following is happening in the if statement: (1 << n) will take the value 1 (binary 0b00000001) and will shift the bits to the left by n digits. For example: If n is 2, we get (0b00000001 << 2) = 0b00000100. With this we can select a bit in our number. Then we take that and do a bitwise AND & with the key. That will set all bits to zero, which are not currently selected. The resulting number is zero, if the corresponding bit in key is zero. If the corresponding bit is 1, this will return a number different from zero (which is interpreted as true. Thus we check, if the n-th bit of key is one or zero.

How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?

Generally you can calculate the size of an array with the sizeof() function:
unsigned int size_of_array = sizeof(array)/sizeof(array[0]);

sizeof() returns the number of bytes. So to get the number of elements, we need to divide by the number of bytes in each element;
For the way shown above this is not that easy. Normally it is not really needed, since such keys normally don't change length very often. If you find a variable type, which exactly fits your key size, you could use sizeof(key)*8 to get the number of bits in it. But your current value 0xB8C4F9 only needs 3 bytes. I don't know a type with 3 bytes, but maybe somewhere you can get something like uint24_t. Honestly here I would just use a hardcoded size, just like you are using a hardcoded key value.


Arduino number detection I am planning for a project but i am stuck with a task and hope you could help me. My work is to note down a number which is actually a set of readings displayed on a meter and store it on a arduino. My problem is that i need a detection technique so that i could record the number or extract the number from a image or video if u suggest to use a camera or recorder or purely can be a sensor. Thank you guys, waiting for you.

"Number detection" sounds like you're trying to interpret a 7-segment digital display - is that correct? One way would be to place 7 photo-detectors (times the number of digits), one per segment, on or at the face of the display. Sample the photo-detectors and create a 7-bit code representing the lit segments, into a byte. You could start with a simple lookup table that translates from code to the digit it represents. You might need to get clever about interpreting codes that shouldn't appear, but do, due, perhaps to light leakage, ambient lighting, or noise. The "lit" segments may only be lit for a fraction of second at a time, and only one at a time, if the display is multiplexed, so your sampling algorithm will have to take that into account. Must the display remain visible? You might need optics or optical fibers to view the segments without obstructing them.


Arduino-RS232 converter baud rate problem i have built a TTL/RS232 converter to send strings via RS232 using an Arduino nano, following the tutorial:Arduino-RS232. My problem concerns the transmission baud rate, because in the tutorial it is suggested a short script which manually generates the code which will become the RS232 signal. In this script some constant delays are used, i.e. "bit9600Delay 100 " and so on. These delays are set for a baud rate of 9600, but i need to double it to have a baud of 19200. Is it enough to divide by two those constant values or should i use a different method? Thank you very much

It is never good to base code on delays instead of intervals.  This is especially true for faster intervals where the execution of the code its self consume a significant portion of the interval.  Also note, some protocols only occasionally resynchronize.  RS232 resynchronizes after each byte (about 8 bits of data).  So any accumulated delay errors may impact the integrity of the bits furthest from the resynchronization event.

Instead of delays use the Arduino's built in hardware to send and receive RS232 communications.  The hardware is designed to work independently of code execution and will out perform software implementations especially for the faster baud rates.


How can I wire a 12V LED switch so that it is powered, but my Arduino only receives a 5V signal? My arduino is powered by 12V.  I am getting some cool looking 12V led switches from amazon, but they need 12 volts to light up. My arduino will perform an override function when it detects the switch is closed. the digital pins can only handle 5V. How can I step down the 12V signal that powers the switch to the 5V that the pin can handle.

12V supply -> 12V led switch -> reduce 12V to 5V -> arduino digital pin

You need a voltage divider:

The formula is:

V1 = 12V

R2 = 5V max

R1 = The rest (V1-R2)

And then you have to calculate max current. If you use 1/4watt resistors, you have to convert watt to current, P = U x I.

Pmax = 0,25W

R1volt = 7 volt

Imax for R1 = P/U = 0.25/7

Imax for R2= P/U = 0.25/5

Now you have the current and voltage for R1 and R2

And the relation between R1 and R2 is:

R1 = 7/12 x Rtotal

R2 = 5/12 x Rtotal

Rtotal = R1 + R2

simulate this circuit – Schematic created using CircuitLab


How to know if arduino activated its short breaker? today i was trying to use arduino power headers as a power source for my basic laser.
I used pin "5V" to connect it to the laser anode and the "GND" pin to the laser groung pin.
after doing this arduino turned restarted, so I removed all the connections to the laser, now the arduino is normal.
booth "5V" and "GND" pins is working normal.
does this mean that I made a short circut and arduino protected it self ?
should I do anything now ?

It sounds like connecting your Laser to the 5 volts power supply did draw too much current, thereby the 5 volts dropped to very low voltage.

The Arduino didn't "protect" itself.  The Arduino simply shut down because of voltage being too low. Then, upon reapplication of 5 volts the Arduino re-started as normal.

You don't mention any details about the Laser.  But if your Laser is simply a Diode, the Laser diode would draw a lot of current, resulting in the 5 volts power source giving reduced voltage.

If your Laser is a "laser module" with a built in driver, perhaps you connected the Laser backwards to the 5 volts.

EDIT 11/20/2015 :  IF you are using the Arduino UNO ,  : The  PolyFuse only protects from 500 mA overload on the USB connector.  Schematic for the UNO shows that 5 volts for USB is called "XUSB". The  PolyFuse connects from "USB VCC" to the XUSB.  When you connected your Laser to the +5 and ground, the  PolyFuse was not involved. (Unless of course you did connect to the USB 5 volts (XUSB), and didn't tell us that.

HOWEVER,  if you powered your UNO from the USB port, then the  PolyFuse WAS involved and did shut you down as others have commented.


Cannot assign COM port to HC-05 bluetooth device I can't set a COM port to my paired BT module. For better understanding I recorded a YouTube video to make sure I show everything.

Hardware:

Arduino Nano knock-off by RobotDyn (atmega168)
Bluetooth module HC-05 (zs-040) which looks like this
Windows 10 Home 64 bit on tablet

I have wired them up like this .

However, before that, I tried to wire it up without the resistors (so I hope I didn't damage anything).

Here is my very simple code which should just echo back what it get.

void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available())
  {
    Serial.println(Serial.parseInt());
  }
  delay(100);
}

Based on my experience, there is nothing wrong (yet) on the Arduino. You can check  this or this. Unlike previous windows version, Win 10 tend to "ignore" bluetooth connection, so you have to assign the COM port manually.


2 Arduino controller boards - 1 shared input I'm beginning with electronics and don't have all the good reflexes yet. So here is my question:

Can I do what I did here?

can i do this http://www.movod-design.com/forum_img/canIDoThis.jpg

Do I have to add diodes between the Nano +5V and the junction point?

My goal is to have one button's state read by 2 Arduino Nano.

You don't need to add anymore components to your schematic. But you can leave some components.

Before you're adding a button to your schematic please consider first how you want to detect your signal. A logic 1 as if a button is pressed? Or logic 0 as if a button is pressed. You can do this using pull-up and pull-down resistors. These resistors should be wired like this.

(The 100Ohm resistor in an internal resistor from the MCU)

Using the pull-down resistor means that when the button is pressed you'd get a logic 1.
Using pull-up resistors means that when the button is pressed you'd get a logic 0.

When I see your schematic it seems like you're trying to make a pushbutton with pull-down resistor. Then you should wire your arduino like this.

Another option is to use the Arduino internal pull-up resistors. That way you don't have to add the 10k resistor in your schematic. And your schematic will look like this.

To use the internal pull-up resistors from the Arduino you'll need to put this in your setup(): pinMode(pin, INPUT_PULLUP); where pin should be your pin number. Please keep in mind that when you use the internal pull-up resistor a logic 0 means the button is pressed.


Sending number as byte through serial I'm trying to send data from an Arduino to an Android device.

I saw an online guide for that which provided this code:

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  byte msg[64];
  int len = Serial.available();
  if (len > 0)
  {
    len = Serial.readBytes((char*)msg, sizeof(msg)); // readBytes seems to need a char* not a byte*
    Serial.write(msg, len);
  }
}

I tried that example and it is working perfectly!

But when I put Serial.write("3");
in the setup loop after Serial.begin(115200);
it appears as question mark on my Android device,
I guess that I'm not sending it as a byte,
I searched online but without any luck.

Start by changing it to Serial.write("3", 1);

Does that help, you're missing the second parameter to the Serial.write call, which is the number of characters (bytes) to write.


How do I change number and bracket colors in the arduino IDE? I recently personalized my arduino IDE (changed the background color, input text color, etc....) by going into the theme.txt file and replacing some hexadecimal values. I made the background black and the text lime green, but for some reason numbers and brackets still remain black, thus I can't see them against a black background. Anyone know how to fix this? I would really appreciate the help, got sick of looking at a white background when making sketches.

Sal

Inside path C:\Program Files (x86)\Arduino\lib\theme\syntax there is file default.xml where I made some changes and the following lines are as follows:

  <style token="SEPARATOR" fg="ffffff" />
  <style token="LITERAL_NUMBER_DECIMAL_INT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_FLOAT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_HEXADECIMAL" fg="ffffff"/>

After this brackets and numbers occur white.


How to read pH value I am trying to read the pH value from a analog pH meter, SEN-01454. From the source code I found, voltage maps to pH value. This is the code:

pHArray[pHArrayIndex++]=analogRead(SensorPin);
      if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
      voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
      pHValue = 3.5*voltage+Offset;
      samplingTime=millis();

But then the value is not correct. So how do i actually do it.

The example code from Wiki page for product.

This is SOME of the code. We are missing the avergearray() function.. I suspect you're taking one reading and averaging it with both old & future ones, but this code clearly is meant to sit in a loop..

From another source, I got this:

/*
# This sample codes is for testing the pH meter V1.0.
 # Editor : YouYou
 # Date   : 2013.10.12
 # Ver    : 0.1
 # Product: pH meter
 # SKU    : SEN0161
*/

#define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
unsigned long int avgValue;  //Store the average value of the sensor feedback
float b;
int buf[10],temp;

void setup()
{
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready");    //Test the serial monitor
}
void loop()
{
  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(10);
  }
  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }
  avgValue=0;
  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];
  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue;                      //convert the millivolt into pH value
  Serial.print("    pH:");
  Serial.print(phValue,2);
  Serial.println(" ");
  digitalWrite(13, HIGH);
  delay(800);
  digitalWrite(13, LOW);

}

which reads in the array first and then averages it. Is this what your code does? If so, what sort of errors are you seeing?


Unable to configure Ethernet using Arduino Uno R3 I have purchased an Arduino Uno R3 board and a LAN shield from these locations:

Arduino UNO R3
Arduino LAN shield

I am trying to configure Ethernet using this sketch:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x4,0x2,0x45,0x68,0x5E,0x96,0x56
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  delay(5000);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  // start the Ethernet connection:
  Serial.println("trying to configure ethernet...");
  while(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP, retrying after 5 sec");
    // no point in carrying on, so do nothing forevermore:
    delay(5000);
    Serial.println("trying to configure ethernet...");
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
}

void loop() {
}

It generates this output in the Serial Monitor:

trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...

I have captured the LED indicators on video on YouTube, it shows Tx and Rx LEDs glowing occasionally, see Arduino not detecting the ethernet connection.

It looks like the Arduino is not able to connect to the Ethernet... I am using the Arduino IDE 1.6.5 on Windows 7.

Is there any debug tool for Arduino that can be used to figure out this issue?

I use more or less the same code to do my networked widgets and it has been quite reliable in my experience. Do you know if you have a DHCP server on the network segment that the Arduino is on? The absence of a server or a configuration that won't respond to the Arduino seem like the most likely explanation for the problem you're seeing.

The way to troubleshoot this would be to get another machine on the same network segment and watch the traffic with tcpdump or Wireshark or a similar tool. If you're running on a "third party" machine (e.g. not the DHCP server) then you'll be able to see the Arduino's side of the DHCP exchange, but I'm not sure if you'll be able to see the server (the Arduino will be broadcasting since it can't know the address of the DHCP server, but I think the server's response is unicast). If you've got a Linux box or some other machine that you can log into where you could run the DHCP server you can watch both sides of the negotiation. But even if you can't get to the server it will help to see if the Arduino is starting the DHCP negotiation.

If you need a fixed IP address on the Arduino, the way to do it is to configure the DHCP server to reserve an address for the Arduino. That way you can have a known address on the Arduino without having to hard code an IP address (which will eventually bite you).


Atmega328p and cp2102 with error avrdude: stk500_getsync(): not in sync: resp=0x00 I recently bought a usb/ttl cp2102 converter for testing with a standalone Atmega328p, I made the DTR connection with the pin 1 in the Atmega  using a ceramic capacitor of 0.10uf (104) so that when I send my code to my Atmega standalone it save the code without having to worry about the reset. However, when trying to send it the first time it worked and the other attempts failed, it seems that whenever I restart the computer and turn it on again it sends the code to the Atmega and in the other attempts it fails.
To try to solve I tested with IDE Arduino 1.8.5 and 1.8.9 in Linux Mint and Windows 10 and gave the same problem, I recorded the bootloader again and did not solve.

The error that appears in the output of the IDE is this:

avrdude: stk500_getsync(): not in sync: resp=0x00

From what I read, this error is generic and hardly helps to solve the error.

Researching a little and found the solution! In addition to capacitor 104, its necessari need to add a 10k resistor by connecting the 5 volts to pin 1.

This is the link of the GitHub project where I found the solution with the assembly scheme, I hope this helps somebody else!

https://github.com/leonvandenbeukel/Arduino-on-a-breadboard/blob/master/README.md


Arduino Comms disrupted, prevents program loading (catch 22) I have written some software which, when loaded onto an Arduino Micro, blocks communications for some reason. Lets stipulate that there is something wrong with it.

Using the Ardiono IDE on Windows 10, and (ex internet) pressing the board's reset button twice within 5 seconds of power-up, then (device manager) a comms port comes into existence for 2 seconds, presumably under control of the micro-controller's bootstrap program.

In the IDE, you can only select an existing comms port. As above, a comms port comes into existence for 2 seconds.

The download button causes compilation and downloading to the comms port - typically taking 8 seconds.

Thus, one can only replace the duff program by selecting the briefly available comms port, compiling and downloading to it, which takes longer that the port availability window.

And so replacing the duff code with anything is impossible. Have I missed something here? Does anyone have some "emergency" code that waits for a port to appear and immediately loads something innocuous?

BTW the Tags restriction is preventing me from using meaningful tags.

I would suggest:

Turn on verbose compilation in the IDE.
Set up as you have been with the right port selected and go to upload - it will fail as normal
Find the avrdude command in the verbose output and copy the full command and its parameters
Open a command prompt or terminal window and paste in the command you copied (but don't run it yet).
Press reset twice to trigger the serial port creation
Run the command you pasted. It should immediately start uploading and "fix" your problem.


Connecting an arbitrary number of pins to pin holes without soldering? I want to avoid soldering for health reasons. I have no well-ventilated open area in my apartment. For a board/modules that have no pins but only holes, how can I connect pins to the holes without soldering?
For certain popular hardware like Raspberry Pi Zero, there seems to be something called "hammer header"

but the problem is those have a fixed, pre-determined number of pins, not individual pins. So, if a hardware has 5 holes instead of 20 holes, that thing cannot be used. Is there a hammer header for a single pin? So that if the hardware has 5 holes I would just use 5 of them. I have searched the Internet, but no result. Also, the "hammer header" itself seems to be rare. I could not find a single online store in my country that sells it.
Some existing answer mentioned "Pomona minigrabber", but that thing seems to be temporary. That is, I cannot move the device (it looks that it will fall off). So, that is probably not the answer I want.
A secondary, less-important question, but if I installed hammer pin headers (seems like one has to hit it with an actual hammer to install it), can I un-install (remove) the headers?

As you already have seen, there are not many options to contact such boards without soldering, because they are meant to be soldered. Those hammer headers are an option. When you find a seller for your country, it should also have these in different sizes/numbers of pins.
Though contacting the board with the pins is not the only problem, you may face. As long as you are experimenting, the typical breadboard is often enough. But when you want to make something more permanent, reliable, current thirsty or noise sensitive, a breadboard is a bad choice. In that case you would also need to solder. Soldering is just a very integral part of electronics.

As others have wrote in the comments, I would also consider soldering as a hobbyist as safe, especially, when you take some precautions. A "well ventilated area" can be a simple room with the window open and a small fan directed to the working place, so that the fumes don't directly go up your nose. That is already a very big improvement, which is also rather cheap. That's also about what the woman does in the video, that you linked. And washing your hands after soldering is also a good measure. (I'm doing soldering the described way for about 15 years now, without any health issues)
In the video, that you linked, they say, that the fumes are toxic and their effect adds up. Letting aside, that they don't back it up with any data and I cannot either, they also don't talk about the amount of solder work, that they consider here. As an electronics beginner you most likely will just solder very rarely for getting pin headers on boards or maybe contacting a motor. The main work most likely will still be done on the breadboard. So here the exposure is so small, that you don't need to consider more than the above safety measures. These will also last rather long, as you get more profound in electronics. And when keeping up that hobby, you maybe wanna invest in a more professional filter system, as you are doing more solder work.
Doing electronics while being that scared of soldering will not be much fun. For the start you might get away by only buying presoldered boards. But very fast you will run against walls with this. Not a good start for a beginner.
But in the end it's your own decision. You have all right to be afraid of solder fumes, though that just might disqualify electronics as a hobby for you.

if I installed hammer pin headers (seems like one has to hit it with an actual hammer to install it), can I un-install (remove) the headers?

That depends on the pin headers, but most likely no. You would need physical force to get them off. And the pads on a PCB are not very strong. They are made to be soldered, not for tearing the pins off without any damage. But why would you want to remove the headers? You only very rarely solder wires directly to the board for connecting with other parts. Either you solder it onto another PCB (where the pin headers come in handy), or you use a female header on a PCB or a cable for making the connection temporary. For example all my small Arduinos get pin headers soldered to them, so I can put them onto my own PCBs via female headers on the PCB. With that I can also disconnect or replace the Arduino if I need to.


FT232RL Chip pinout to flash Arduino Pro Mini Looks I have a FTDI USB to TTL adapter that doesn't follow the standard Arduino FTDI pinout order. The chipset is FT232RL and here is the link to Amazon page.

https://www.amazon.com/Adapter-Serial-Converter-Development-Projects/dp/B075N82CDL#customerReviews

Please can someone tell me the right pinout to connect this to Arduino Pro Mini 3.3v Thanks!

This is the standard FTDI Basic connections. CTS is an input to the module and is typically just connected to Gnd as seen on the right side here from the Arduino Promini schematic (so the FT232 is always Clear(ed) To Send, i.e. no flow control is used).

DTR may be broken out on one of the side holes.  RTS may work for you in place of DTR to create the reset pulse to start the bootloader code.  If not,  you may have to cut the trace and wire the RTS header pin to DTR. DTR is pin 2 on the FT232, use a meter and confirm it goes to one of the side holes, that way  you don't  have to try a solder a wire on to a pin.


Vary voltage using relay. Is this possible? I am planning to control a RGB lamp using Arduino. The lamp is 24V and I want to be able to control the brightness of the lamp. I found a relay that will let me control the 3 channels (red green and blue), but will only let me turn it on and off (Not control brightness)

I am looking for a way to control the lamp both on/off and brightness. What component will do the same as my relay, but also let me use the varying voltage from the arduino to control my 24V lamp? (Just like a transistor)

I have an external 24V powersupply along with 5V for the arduino

Thanks!

No, you can't vary the voltage with a relay. The only way you could do it with a relay would be to have a selection of different voltages available, and then use multiple relays to select which voltage is used. Less than ideal.

You need to use PWM to create a square wave with varying duty cycle. The duty cycle (the percentage of time the power is on within a given period) defines the average voltage of the output.  That PWM needs to be fed into a MOSFET which will in turn control the 24V power to the lamp.

It's exactly the same as driving RGB LED strips, except it's in the shape of a lamp not a long strip.


Wifi stopped connecting (Wemos D1 Mini) I am stumped.  I have a few Wemos D1 Mini boards that were working on the local WiFi yesterday, yet today none of them will connect.  More puzzling is that I can flash Tasmota on them and they all connect to the WiFi, but none with this code that was working yesterday.  Any tips would be appreciated.

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  //Connect to WiFi network so we can reach the MQTT broker and publish messages to topics.
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print(F("WiFi connected, "));
  Serial.print(F("IP address: "));
  Serial.println(WiFi.localIP());
}

Fixed.
My router is ancient and does not support WPA.  As of ESP8266WiFi library Version 2.5.0, WPA is is the preferred mode.  The solution is to get a better router, or add WiFi.enableInsecureWEP(); before calling WiFi.begin().

WiFi.enableInsecureWEP();
WiFi.begin(wifi_ssid, wifi_password);


compile error when using two typename in template class I am using Arduino 1.8.5 ide. I am just creating a class with two typename which name is "Map". This class takes all int and String variations. Like;

class Map<int, int>;
class Map<int, String>;
class Map<String, int>;
class Map<String, String>;

Map<int, String> *list = new Map<int, String>();

If I create instance of this class like above in Main.ino file then everything is ok. But if I create it another file with .h extension which is "Test.h" then compilation fails. These are files;

    Main.ino

#include "Map.h"
#include "Test.h"

Test *test = new Test();
Map<int, String> *list = new Map<int, String>();

void setup() {

}

void loop() {

}

Map.cpp

#include "Arduino.h"
#include "Map.h"

template<typename E, typename T> Map<E, T>::Map()
{

}

template class Map<int, int>;
template class Map<int, String>;
template class Map<String, int>;
template class Map<String, String>;

Map.h

#ifndef Map_h
#define Map_h

#include "Arduino.h"

template<typename E, typename T> class Map {

public:
    Map();
    ~Map();
};

#endif

Test.h

#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

#endif

Error is;

In file included from C:\Users\zafer\Desktop\Main\Main.ino:3:0:
Test.h:14: error: expected ';' at end of member declaration
  Map<int, String> *list = new Map<int, String>();

                                        ^

Test.h:14: error: expected unqualified-id before '>' token
  Map<int, String> *list = new Map<int, String>();

                                              ^

Test.h:14: error: wrong number of template arguments (1, should be 2)
  Map<int, String> *list = new Map<int, String>();

                                   ^

In file included from C:\Users\zafer\Desktop\Main\Main.ino:2:0:
Map.h:6: error: provided for 'template<class E, class T> class Map'
 template<typename E, typename T> class Map {

                                        ^
exit status 1
expected ';' at end of member declaration

Sorry, If it's been already resolved and I couldn't find it.

Thank you.

In this class declaration:

class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

This line is wrong:

    Map<int, String> *list = new Map<int, String>();

You can't execute procedural code when declaring a class. That has to go into the constructor or some other function.

For example, this compiles without errors:

Test.h

#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test() { list = new Map<int, String>; } ;
    ~Test();
    Map<int, String> *list;
};

#endif


How do I set a constant in setup() that I can use in loop()? I am new with coding, and I was wondering how I could run something once and define it as a constant. Here is my code:

int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
int g0 = 9.81*9.8;
int h1 = 48;
int R = 287.06;
int a = -0.0065;

void setup() {
    Serial.begin(9600);
    int p1 = (1.09512*sensorValue2-22.105)*133.3225;
    int t1 = (-0.08126*sensorValue1+65.6597)*274.15;
}

void loop() {
    String t = "Temperature:    ";
    String tt = " Celsius";
    String p = "Preassure:    ";
    String pp = " Pascal";
    float celsius = -0.08126*sensorValue1+65.6597;
    float kelvin = celsius*274.15;
    float pascal = (1.09512*sensorValue2-22.105)*133.3225;
    float height = (t1/a)*((pascal/p1)^((a*R)/g0))-1)+h1;
    Serial.println(t+celsius+tt);
    Serial.println(p+pascal+pp);
    Serial.println(kelvin);
    Serial.println( );
    Serial.println(height);
    delay(1000);
}

You can't, and there's other things wrong with your code.

int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);

Calling functions from the global scope is an incredibly bad idea.  Those are run before the board has been properly initialized, and the results you may get from it are not guaranteed in any way, shape, or form.  Instead you must call functions like analogRead() from within another function, like setup(), or loop().

As for const - a const is just that - a constant value that can never change.  You can only assign a value to it at the moment of creation.

And that means that you can only use it within the scope it was defined within.  As you can't do that in the global scope (see above) then you cannot use a constant.

So just use a normal global variable.  It will only change when you tell it to change.  Using a const only makes sense when you have a numeric literal that you want to refer to by name. Using const doesn't protect the variable from being changed at run-time by memory leaks, etc, it just protects it from attempts to modify it at compile time - and if possible replace it with the numeric literal that it refers to.

So in summary just use:

int sensorValue1;
int sensorValue2;
int p1;
int t1;

void setup() {
    sensorValue1 = analogRead(A0);
    sensorValue2 = analogRead(A1);
    p1 = (1.09512*sensorValue2-22.105)*133.3225;
    t1 = (-0.08126*sensorValue1+65.6597)*274.15;
}
... etc ...

HOWEVER: Your program methodology is also completely flawed.  You read the analog values once, and do calculations with them once, then repeatedly display the same values over and over again.

You must perform a new analogRead() of your sensors every iteration of loop() in order to update the values in your variables.


Pro Micro recognised as Micro (win10, IDE 1.8.1) I just got this pro-micro clone 5V and it's my first pro micro ever. After reading lots of discussions about how easy it is to brick and how it's just a smaller Leonardo, I've also found tutorials where they guide you to install custom things (sprkfun) to recognise the board, and others where it shows up as a Leonardo board.

However in my case I just plugged it in my Win10 laptop, the drivers got installed and it is automatically recognised as an Arduino Micro.
Since I haven't found people having this, and since I'd like not to brick it immediately I was wondering what's the procedure between:

follow sparkfun's guide for pro micro and install their custom
drivers
treat it as a Leonardo (in the IDE)
treat it as a standard Micro (in the IDE) since it's recognised as such

Thanks!

edit: solution: it's a Leonardo.

Treat it as what it is.

What windows sees it as is just what USB reports it as. It's just a name. It has no bearing on what it is or how you program it. Select the actual board that you have in the IDE, not what Windows says it thinks it is.

As a general rule: Ignore everything Windows ever says, it's full of sh!t.


help with input in a Simon arduino uno game I' making a Simon game with the arduino uno.

I know something is wrong with the inputs but i don't know why or how to fix it.

The problem is the program takes an input and says it is correct no matter what it is or the length

#define NOTES

int tones[] = {NOTE_E5, NOTE_E6, NOTE_CS6, NOTE_A6};
String sequence;

void setup() {
    pinMode(13, OUTPUT); //green
    pinMode(12, OUTPUT); //yellow
    pinMode(11, OUTPUT); //blue
    pinMode(10, OUTPUT); //red
    pinMode(7, INPUT); //green
    pinMode(6, INPUT); //yellow
    pinMode(5, INPUT); //blue
    pinMode(4, INPUT); //red
    Serial.begin(9600);
}

void loop() {
    while(true) {
        delay(1000);
        randomSeed(random(random(1000000000)));
        sequence = String(random(4));
        boolean run = true;
        while(run) {
            for(int i = 0; i < sequence.length(); i++) {
                simonOut(sequence.charAt(i) - '0');
                delay(500);
                simonClear();
                delay(100);
            }
            for(int i = 0; i < sequence.length(); i++) {
                int input = simonIn();
                while(input < 0 || input > 3) {
                    delay(50);
                    input = simonIn();
                }
                if(sequence.charAt(i) - '0' == input) {
                    flash(0);
                    run = false;
                    goto reset;
                }
                else if(i = sequence.length() - 1)
                    flash(3);
            }
            sequence += random(4);
        }
        reset:;
    }
}

void boolOut(long pin, boolean val) {
    digitalWrite(pin,val ? HIGH : LOW);
}

void simonOut(long num) {
    boolOut(num + 10, true);
    tone(2, tones[num]);
}

 void flash(int led) {
     delay(300);
     for(int i = 0; i < 5; i++) {
         simonOut(led);
         delay(100);
         simonClear();
         delay(100);
     }
 }

 void simonClear() {
     for(int i = 0; i < 4; i++){
         boolOut(i + 10, false);
     }
     noTone(2);
 }

 int simonIn() {
     int ret = -1;
     for(int i = 0; i < 4; i++) {
         if(simonIn(i)){
             ret = i;
         }
     }
     if(ret != -1) {
         simonOut(ret);
         delay(500);
         simonClear();
         delay(100);
     }
 }

 boolean simonIn(long num) {
     return digitalRead(num + 4) == HIGH;
 }

The problem in your code is there:

int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
}

This method never returns any value, so that means the caller will just tke whatever is in the stack at that time:

            int input = simonIn();
            while(input < 0 || input > 3) {
                delay(50);
                input = simonIn();
            }

input could be anything there.

So the fix should be easy:

int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
    return ret;
}

It's surprising you did not get a warning from the compiler on that one, which IDE do you use?

Finally, regarding your code, I would also advise you the following improvements:

break down the loop() code further into functions that do ONE thing, e.g. showSequence(sequence), checkInput(seuquence), readSimonInput() (this last function would only return a value between 0 and 3 included. That would make your code much clearer.
use the right types for your variables: I see you abuse usage of long where int or byte, or you mix different types for the same data, thus forcing the compiler to cast data on some function calls.
avoid hardcoding constants in your code, e.g. you could define the number of buttons, the first pin of buttons, the first pin of LEDs, the various delays.


3pin (GND, 12V, tach) 12v FAN control using PWM I know there are fans out there that have a dedicated PWM input, but I like to know if I can PWM control a fan that does not have such a dedicated PWM input. So...
If I have a 3 pin 12v fan like the Noctua NF-A20 with connections:

GND
12 V
tach out (RPM measurement)

Can I control its speed by PWM on the 12V supply voltage (using a MOSFET most probably)?
Would the tach out still work?

Yes, and yes.
You have to modulate the +12V rather than GND because the output is referenced to ground. That means you need to use the classic N+P channel FET arrangement:

simulate this circuit – Schematic created using CircuitLab


Error messages while verifying code with Visual Studio Code I move recently to use Visual Studio Code to develop for arduino. But I'm receiving some error messages while I'm trying to verify my code that confuse me. The messages are:

2020-04-12T13:53:40.409Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=20892E5EE7E84976
2020-04-12T13:53:40.926Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=20892E5EE7E84976, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:40.926Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
2020-04-12T13:53:40.937Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=D8C082A90BB14CDF
2020-04-12T13:53:41.044Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=D8C082A90BB14CDF, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:41.044Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404

Based on this output it seems something is happening with these URLs but when I try to do the same in the same computer with Arduino IDE there is no such error messages.

Does anybody know how to get rid of these messages?

Thank you very much.

It works with Arduino IDE either 1.8.9 OR 1.8.12 BUT the VS code extension is broken. So

You have to downgrade to January release 1.42 AND
Then turn off automatic updates for the moment.

How to get the release: Click here

Before installing /downgrade
The excessive debug logging is caused by running Java with -DDEBUG=true. Adding -DDEBUG=false to the C:\Program Files (x86)\Arduino\arduino_debug.l4j.ini fixes it for now.


Speed Control of Brushless DC Motor I cannot understand the code of controlling the speed of brushless dc motor using ESP8266 WiFi Module.

I found it in- https://ubidots.com/blog/speed-control-for-brushless-motors-with-an-esp8266-2/

The part that I cannot understand is-

float btof(byte * payload, unsigned int length) {

  char * demo = (char *) malloc(sizeof(char) * 10);

  for (int i = 0; i < length; i++) {

    demo[i] = payload[i];

  }

float value = atof(demo);

  free(demo);

  return value;
}

// Callback to handle subscription

void callback(char* topic, byte* payload, unsigned int length)

{

    value = btof(payload, length);

      value = map(value, 0, 1023, 0, 180);

//Map the 0-100 values from the slider to the 0-180 to use the servo lib.

 ESC.write(value);

//Send the value (PWM) to the ESC

}

Please help me with the code!

Callback function must be data send from server to the ESP.
Payload is the data byte sent from server.
Length is the size of data in bytes.
BTOF is basically byte to float converter which converts all the data byte received into single floating variable and return that floating point value.
ECS.write must be the function that write the value to the servo motor controller H-bridge IC. It belongs to servo library.
Value range that can be mapped into this ECS.write is between 0-180 so map function will use that will convert the floating point data received from btof function.
Basic definition of map() function:

Map function maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers.

Syntax:

map(value, fromLow, fromHigh, toLow, toHigh)

Then ECS.write(value) will write that mapped value to servor motor controller H-Bridge.


How do I code my arduino to return a throttle servo to idle? I have an Arduino powering a small 180 degree Parallax servo that is used to control the throttle link for a small engine. I have code right now that will allow me to open/close the throttle (in either 1/4 or 1/5 increments) using the keyboard of my computer. This is well and fine but I really want to get it working so that when I press (hold) the hot key "t" the throttle will open but when I release the hot key I want the servo to cycle back to its original position (where the engine idles). If you have suggestions I would really appreciate them.

I am using Putty (Putty.org) to interface with the serial monitor so the arduino knows when 't' is pressed.

My Arduino code is just below this bit of wording (55 deg and 0 deg are the bounds of my throttle link, 55 is closed throttle (idle) and 0 is open throttle):

#include <Servo.h>

Servo servo;

int pos = 55;  // Stores the position (angle) of the servo. Range is [0, 180].

void setup()
{
  Serial.begin(9600);
  servo.attach(9);  // Attaches the servo on pin 9 to the servo object.
  servo.write(55);  // Resets the position.
}

void loop()
{
  if (Serial.available())   // Returns true if there is serial input.
{
    char ch = Serial.read();

    if (ch == 't')

      {if (pos <= 55)
        {pos -= 11.25 ;}}

     else

      {if (pos >= 0)
        {pos += 11.25 ;}}

    // Now ask the servo to move to that position.
    servo.write(pos);
    // Mechnical limitation to the frequency of commands given.
    delay(15);
}

}

If your terminal program uses key-repeat, then let each 't' operate the throttle for just slightly longer than the repeat period (slightly longer than twice the period, if you want to tolerate single dropped characters). After that period without another 't', close the throttle. One implementation would be to (re-)start a countdown timer every time you see a 't', and close the throttle when the timer goes to zero.

No auto-repeat? You'll have to simulate it with your finger (and code for a somewhat longer repeat interval, of course).


Wiring power new power button to UPS power module for raspberry pi I have a UPS Power Module Expansion Board for Raspberry Pi 3B/3B+(Plus) and removed the power button because it is in the way and would like to attach this read button instead. But it is not working, they board does not turn on?

Am i wiring the incorrectly?

This looks like a momentary push-button; use a latching button (push-on/push-off) instead.


Set avrdude transfer baud rate in Arduino IDE I just got an Arduino nano (from arduino.cc, not a knock-off), and have issues uploading sketches. It refuses to upload, with the error message "programmer is not responding".

Some searching led to an incorrect transfer baud rate. Indeed, the IDE (1.8.5) output before uploading displays "overriding baud rate: 57600", and the command line has a -b57600 argument. By copying this command in a terminal and removing this parameter, the upload works. It also works with -b115200. All other values I tried do not work.

Is there a way to configure the IDE to use the correct baud rate ? I know I could use the command line, but that's not very practical, I would prefer to keep the Integrated part of the IDE :).

Update the boards package for the AVR hardware. That will give you new options in the tools menu.

Then you should just select the right CPU variant.

From top to bottom those are 115200, 57600 and 19200 baud.


I2C Communication with the ICM-20789 I am trying to interface with the ICM-20789 over I2C. DataSheet

I have been successfully able to get all three gyroscope readings and all three accelerometer readings. I am now trying to get the pressure readings from the device, since it has a built-in pressure sensor, but cannot seem to get it working.

In the datasheet, it says to enable Bypass Mode.

  Bypass Mode: Set register INT_PIN_CFG (Address: 55 (Decimal); 37 (Hex)) bit 1 to value 1 and I2C_MST_EN bit is ‘0’
  (Address: 106 (Decimal); 6A (Hex). Pressure sensor data can then be accessed using the procedure described in Section 10

In the setup I use this code:

  Wire.beginTransmission(gyro_address);
  Wire.write(0x37);      //INT_PIN_CFG
  Wire.write(0x02);      //00000010
  Wire.endTransmission();

I am having trouble finding I2C_MST_EN in the datasheet as well, as I cannot find it in the 6A Address.

Once I have the bypass bit enabled, I try to request the pressure and temperature data from the sensor using this code:

Wire.beginTransmission(0x63);
Wire.write(0x7866);
Wire.endTransmission();
Wire.requestFrom(0x63, 16);

while (Wire.available() < 16);
pressure = Wire.read() << 16 | Wire.read() << 8 | Wire.read();
temp_2   = Wire.read() << 16 | Wire.read() << 8 | Wire.read();

Unfortunately, the device freezes when I try to run this code. I know I am obviously doing something wrong here, just don't know exactly what yet.

There are four things wrong with your code.

You are not sending the "start measurement" command properly. The Wire.write() function can only send 8 bits, but you are passing it a 16-bit value. Instead you should break it apart into 2 separate 8-bit values:

Wire.beginTransmission(0x63);
Wire.write(0x78);
Wire.write(0x66);
Wire.endTransmission();
The data returned is spread over 9 bytes, not 16.  According to the datasheet:

  Temperature data is transmitted in two 8-bit words and pressure data is
  transmitted in four 8-bit words.

and:

  Two bytes of data are always followed by one byte CRC checksum

That's 2 + 4 = 6 + (6/2) = 9

You aren't waiting for the conversion to complete. According to the datasheet, in "ultra low noise" mode (0x7866) it takes up to 94.5ms to perform the measurement.  So you should add a delay of slightly more than that to allow it to do what it needs to do.
The command you are sending responds with temperature first, not pressure, but you are reading pressure first (and reading the wrong bytes anyway).

In all, your code should look more like:

Wire.beginTransmission(0x63);
Wire.write(0x78);
Wire.write(0x66);
Wire.endTransmission();

delay(100);

Wire.requestFrom(0x63, 9);
uint8_t tmsb = Wire.read(); // Temperature highest byte
uint8_t tlsb = Wire.read(); // Temperature lowest byte
Wire.read();

uint8_t pmmsb = Wire.read(); // Highest pressure byte
uint8_t pmlsb = Wire.read(); // Next highest pressure byte
Wire.read(); // Discard checksum
uint8_t plmsb = Wire.read(); // Next lowest pressure byte
uint8_t pllsb = Wire.read(); // Lowest pressure byte
Wire.read(); // Discard checksum

pressure = (pmmsb << 24) | (pmlsb << 16) | (plmsb << 8) | pllsb;
temp_2   = (tmsb << 8) | (plsb << 8);


How to send Serial.Print only If Serial Connection is open? So I looked through the Arduino Mega2560 documentation and searched the web for a solution, and so far I haven't had any success.

What I'm trying to accomplish is fairly simple. I need to send a serial command over serial, ONLY if there is a serial connection between the PC and the Arduino. I've tried:

If(Serial){
   Serial.Println("COMMAND");
}

That doesn't work, and I think it's because the Arduino cannot distinguish between listening to the Serial port versus establishing a Serial connection.

Any help would be appreciated.

Cheers!

The Arduino Mega's "serial" connection comes from an external chip implementing USB-serial conversion.  While this chip knows if a session is open with a host, the standard design has no way to share that information with the main ATmega.

In contrast, on a Leonardo type board the main processor implements the USB interface, so it does know.

Your options include changing the requirement, having the PC program send some data to the Arduino, changing the processor to an ATmega or ARM with integrated USB, or perhaps modifying the USB implementation.


How to put Arduino Nano in low power sleep mode (<0.05mA) I'm trying to put an Arduino Nano in low-power mode using this guide: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery.
The article suggests 3 things: use the Low-Power library from Rocketscream, cut the power to the power LED, and remove the voltage regulator.
So far I've only done the first two and reduced the clock speed to 8 MHz.
The important part of the source code that puts the Arduino in deep sleep looks like this:
void setup() {
  CLKPR = 0x80; // (1000 0000) enable change in clock frequency
  CLKPR = 0x01; // (0000 0001) use clock division factor 2 to reduce the frequency from 16 MHz to 8
}

void loop() {
  // Go to sleep until the next scheduled wake up
  int32_t waitSeconds = 60;
  while (waitSeconds > 0) {
    period_t waitFor = SelectWaitTime(waitSeconds);
    LowPower.powerDown(waitFor, ADC_OFF, BOD_OFF);
    waitSeconds -= PeriodToSeconds(waitFor);
  }
}

period_t SelectWaitTime(int32_t secondsToWait) {
  if (secondsToWait >= 8)
    return SLEEP_8S;
  else if (secondsToWait >= 4)
    return SLEEP_4S;
  else if (secondsToWait >= 2)
    return SLEEP_2S;
  else if (secondsToWait >= 1)
    return SLEEP_1S;
}

In essence, sleep for up to 8 seconds, remove the seconds from the counter, then sleep again.
So far I've only scratched off the trace to the power LED and haven't removed the voltage regulator. According to the article above, this should reduce the power consumption to around 0.05 mA but I get around 1.7 mA, which is over 30 times more!
Electrically, I only have a MOSFET as a power switch connected to one of the analog pins (I use it as a digital output) and another controller, connected to the I2C pins (the Arduino acts as Slave). The other controller is turned off through the MOSFET when I take the measurements. Physically removing the connections doesn't change the consumption, so I don't think any of that is related.
Is there something I did wrong? What can I do to achieve power consumption similar to the one in the article?

Turns out the voltage regulator was AMS1117 - not MIC5205-KB50/KB33/KBAA like the one in the article. Ripping it off gave me the 0.026 mA idle current which is even better than what I was hoping for.


Reading HMC5883L hex values in 2's compliment C code I want to develop my C code for HMC5883L.

I have 2 questions for my current code development.

My first question is:
But what I found in the datasheet is that the values are in the 2's compliment, so I don't know how to deal with them?! Do I have to take the values as they are in the data registers and convert them to decimal values and that's it? Or I have to convert them from 2's compliment to the original hex values?

This is a quote from the datasheet:

  Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain)
  Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively.

My second question:
How o read the data registers? What is the procedure?
I saw in the datasheet the following method but I didn't understand it.

  Loop
  Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain)
  Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively.
  Send 0x3C 0x03 (point to first data register 03)
  Wait about 67 ms (if 15 Hz rate) or monitor status register or DRDY hardware interrupt pin
  End_loop

So, I didn't understand that I send read command then I send write command, so how HMC5883L would return the value to me?

Regards,

2's complement is the normal signed values in any modern system, including Arduino.

Just place the bytes into a signed variable of the right size in the right positions and there is your value.

In I2C, to read a register, you typically have to make two transactions. The first is a write to set the register number you want to access, the you follow that with a read transaction to get the data.


Memory problem? dtostr() and strcat() I've been dealing with this for quite a while now and searching all over for answers.. I'm trying to put together two floats into a char*. Separated by a ",".
This is the code I'm working with.

#include <DHT.h>
#include <RH_ASK.h>
#include <SPI.h>

#define DHT_pin 10
#define DHT_type DHT11

DHT dht(DHT_pin, DHT_type);
RH_ASK rf_driver;

float temp;
float hum;

char ch_temp[6];
char ch_hum[6];
char msg_out[12] = "";

void setup() {
  Serial.begin (115200);
  dht.begin();
  if (rf_driver.init()) {
    Serial.println("Radio transmitter initiated..");
  }
  else {
    Serial.println("Radio transmitter failed to initiate..");
    delay(1000);
  }
}
void loop() {
  temp = dht.readTemperature();
  hum = dht.readHumidity();

  dtostrf(temp, 5, 2, ch_temp);
  dtostrf(hum, 5, 2, ch_hum);
  strcat(msg_out, ch_temp);
  strcat(msg_out, ",");
  strcat(msg_out, ch_hum);

  Serial.println(msg_out);
  rf_driver.send((uint8_t *)msg_out, strlen(msg_out));
  rf_driver.waitPacketSent();
  Serial.print("data sent, package size: ");
  Serial.println(strlen(msg_out));
  delay(1000);

}

I have tried using different sizes of the char arrays, but it just goes crazy.
This is the console output:

Radio transmitter initiated..
22.00,34.00
data sent, package size: 11
⸮⸮Radio transmitter initiated..
22.00,34.00
data sent, package size: 11

So on its way through the second loop it fails, restarts and then on its third way through it just gives up... What am I doing wrong? :( Really sad over this.

Your sketch is running on borrowed memory.
Every time the loop function runs, the new text is concatenated with strcat() and the buffer msg_out is never reset.
The first time 12 bytes are used, the second time 23 bytes, the third time 34, and so on.

The solution in the answer by @VE7JRO will fix that, but I prefer not to use dtostrf() and transmit binary data.

I see a few other problems as well:

Why do you want to transmit readable ASCII text? Use binary data.
Either float numbers or integers. For example an integer in 1/100 degrees.
The RadioHead library uses a lot of memory. You can not use an other
library that uses also a lot of memory.
The value of '5' for dtostrf is the minimal width,
so you better make those arrays for example 20 bytes.
I prefer to put those arrays temporarily on the stack.
The DHT11 is not accurate. If you upgrade to a better sensor with I2C,
then you need more libraries (the Wire library and a sensor library),
and you might run out of sram memory.
When using the RadioHead library in default mode, it uses three
pins (rxPin=11, txPin=12, pttPin=10). You better add a comment
section to your sketch to explain that you should not use those pins.
You have already a
conflict at pin 10 for the DHT sensor and the pttPin.

The old and no longer supported VirtualWire library has some bugs, but it uses less memory than the RadioHead library. The RadioHead library is not optimized for Arduino boards like the Uno, Nano, Leonardo, and others. It even requires to #include <SPI.h> because that is often used with transceivers, even if the SPI bus is not used in RH_ASK mode (thanks to @VE7JRO for explaining this in the comment below).

The easiest way to transmit more than one value is with an array.

float myData[2];
myData[0] = 23.456;
myData[1] = 68.0;
rf_driver.send((uint8_t *)myData, sizeof(myData));

The sizeof() is not a real function, it tells the compiler to fill in the size of that variable. Since a float is 4 bytes, you may also fill in the number 8 for the second parameter.

There are a number of solutions for the receiver. I like to use a pointer to the buffer, but perhaps it is easier to copy them to variables with memcpy().

float myData[2];
if (driver.recv(buf, &buflen)) {
  if (buflen == sizeof(myData) {  // extra check
    memcpy((uint_8 *)myData, buf, sizeof(myData));
    Serial.println(myData[0]);
    Serial.println(myData[1]);
  }
}

When the receiver is also an Arduino board, then there should be no problem. When the receiver is something else, you might have to check if the byte-order is the same. The float variable of a Arduino is 100% IEEE compatible, but sometimes it is easier to use only integers.

The most common way is to use a struct. A struct is a package that can hold all sorts of data (integers, bytes, arrays, and so on). The receiver and the sender should have exactly the same definition for the struct of course.


Value of the counter collide on my lcd while decreasing. How can I remove it? #include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);
int visitor=0;  //variable for counting visitor number

unsigned long timer_1,timer_2;  //variables for recording time for ir_1 and ir_2

void setup() {
   lcd.begin(20,4);
   pinMode(A0,INPUT);
   pinMode(A1,INPUT);
}

void loop(){
 lcd.setCursor(0,4);
   lcd.print("visitor=");
   lcd.setCursor(8, 4);

   lcd.print(visitor);

   if(digitalRead(A0)==1 && digitalRead(A1)==0)
  {
    timer_1= millis();
  }
  if(digitalRead(A0)==0 && digitalRead(A1)==1)
  {
    timer_2= millis();
  }
  if(timer_1>timer_2)
  {
   lcd.setCursor(8,4);
   visitor=visitor+1;
   lcd.print(visitor);
   delay(2000);
   timer_1=0;
   timer_2=0;
  }
 else if(timer_1<timer_2)
  {
   lcd.setCursor(8,4);
   visitor=visitor-1;
    if (visitor<=0)
  {
    visitor=0;
  }
   lcd.print(visitor);
   delay(2000);
   timer_1=0;
   timer_2=0;

  }

}

Two IR sensors are placed in A0 and A1.

While the value of visitor is decreasing from 10 to 9 the LCD is showing 90 because  the '0' of previous 10 is here. How can I remove it?

A simple option would be to call lcd.clear() at the start of loop(). That will clear the entire LCD display. Everything else should work fine because it looks like you're outputting the entire display contents every time round.

Alternatively, you could remove the extra digit by printing a space over it, e.g.:

if (visitor < 10) print(" ");
lcd.print(visitor);

If visitor is a 1-digit number (i.e. less than 10), it will output a space at the start, getting rid of any underlying digits leftover from a previous iteration. If you want the number to be left-aligned then you could print the space after the number instead.


Moving cursor on LCD and changing highlighted value I have the code shown below. The goal is to change the value of hours, minutes or seconds based on where the cursor is placed.

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
    int hours = 11;
    int minutes = 11;
    int seconds = 11;
    lcd.setCursor(0,0);
    lcd.print(hours);
    lcd.print(":");
    lcd.print(minutes);
    lcd.print(":");
    lcd.print(seconds);
    lcd.noBlink();
    delay(300);
    lcd.blink();
    delay(300);

    if (buttons & BUTTON_RIGHT) {
      move cursor right;
      if(lcd.setCursor == lcd.setCursor(0,3) {
        minutes += 1 }

}

I though of a way to do this. I would have three variables and print each of these out with a default value. With the use of the buttons, the user should be able to move the blinking cursor to hours, minutes or seconds, and increase or decrease the value of the variable.

I would do this by seeing what location the cursor is at. For example, if the cursor was on minutes, I would write something like if(lcd.setCursor == lcd.setCursor(0,3) or lcd.setCursor == lcd.setCursor(0,4)) { minutes += 1}.

Of course these functions don't exist, so I am wondering what I can do to move a cursor and check its position.

Thanks in advance

Firstly, you should set the time variables outside the main loop (as a global variable). If you put them in the main loop, the time would always reset to 11:11:11 after 0.6s of delay.

  lcd.setCursor == lcd.setCursor(0,3)

I dont think you can do this (unless the function returns you with the location of the cursor, have to check the header file of the library).

Instead, you should keep track of the location of the cursor with another variable (as mentioned by gre_gor), say int curLoc. But note that you have to keep track of the range of values it can go. (0 < curLoc < 16)

To summarise, the code could look like this:

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int hours = 11;
int minutes = 11;
int seconds = 11;

int curLoc = 0; //Current cursor location (x-axis)

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
  lcd.setCursor(0,0);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.noBlink();
  delay(300);
  lcd.blink();
  delay(300);

  //move cursor right;
  if (buttons & BUTTON_RIGHT) {
    //Keep the tracker in range
    if(curLoc >= 0 && curLoc < 16){
    curLoc += 1;
    }

    if(curLoc == 3)
    {
      minutes += 1
     }

}


Books on Arduino development in C++ I will be using the Arduino platform with other data acquisition hardware for a school electronics project. I have limited knowledge of C++ syntax.

Are there good introductory to intermediate books that can bring a high school student with some programming experience to proficiency on Arduino?

I'd recommend you go to cplusplus.com. Plenty of tutorial pages and topics to further your knowledge. However, be aware that Arduino uses a variant of C designed for microcontrollers (the exact flavour depends on the microcontroller type/family), rather than C++, so do be aware that some of the topics are not implementable on an Arduino. That said, I can't think why you'd be using some of the more elaborate C++ exclusive features in a fairly middle-of-road embedded system.

The only thing you need to ignore in C++ is memory allocation specifics - you're limited to the 'original' malloc() based functions rather than the all-singing-all-dancing operator new from C++. If you are in need of memory allocation functions, malloc is well-documented and a tutorial is only a quick Google away.

Of course I must also point you in the direction of the highly popular Stack Overflow site, part of this Stack Exchange network. While they don't have tutorials, there are plenty of great answers to common questions.


Memory usage: #define vs. static const for uint8_t I'm writing an Arduino library to communicate with an I2C device, and I'm wondering what the best way is to declare all the register addresses so as to save memory.

Using #defines:

#define REGISTER_MOTOR_1_MODE 0x44
#define REGISTER_MOTOR_2_MODE 0x47

Or using static const:

static const uint8_t REGISTER_MOTOR_1_MODE = 0x44;
static const uint8_t REGISTER_MOTOR_2_MODE = 0x47;

(Obviously I have more than just two registers I need to declare, but I thought two would illustrate the point just fine)

You'll find no noticeable difference memory-wise between the two.

The only real difference is that the const method also imposes a type to the value, which can be useful for function overloading or mathematical operations.


Arduino to Arduino Communication using HC05 I have been working on a project for work ( I'm a waiter :/ ) I was tasked to build a food wait time display that receives input from the kitchen and echoes the time via bluetooth to another display.
So that we are all on the same page I will describe what I have built and where I am stuck.

Before I do, I would like to state that I have:

been planning and prototyping this thing for over a month
googled/crawled all over the web looking for answers
read the entire manual on the HC05 module
Bound both of the bluetooth modules via AT commands One as Master the  other as Slave

Now with that out out the way here is what I have so far:

2x Arduino uno R3
2x 16x2 LCD Display
2x HC05 Bluetooth Modules (1 set as Master the other as Slave & bound using AT Commands)
2x 10K Potentiometers for adjusting the contrast
3x Momentary push Button switches on Master with pull-up resistors (timeUp, timeDown, sendButton)

Here is where I am stuck. UPDATE

I was able to get the master and slave to communicate. RX and TX on master were crossed... SMH! However now the issue is that the slave is writing both digits it receives on top of itself. First writing one digit then clearing it and then the second digit...

Enough with the prologue here is the a code:

Master

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //sets up LCD pins
int waitTime = 10; //if food comes quicker than there is no need for a display ;)
const int timeUp = 6;
const int timeDown = 7;
const int sendButton = 8;
int timeUpState = 0;
int timeDownState = 0;
int sendButtonState = 0;

void setup() {
  Serial.begin(115200);
  pinMode(timeUp, INPUT);
  pinMode(timeDown, INPUT);
  pinMode(sendButton, INPUT);
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's"); //Splash screen on start up
  lcd.setCursor(0,1);
  lcd.print("      Diner"); //Splash Screen
  delay(2000);        // Delay intended to allow the device to pair prior to use.
  lcd.clear();
  lcd.print("Essen Dauert:"); //German for "Food takes":
  lcd.setCursor(0,1);
  lcd.print("   Minuten"); // xx minutes
  }

void loop(){
  lcd.setCursor(0,1);
  timeUpState = digitalRead(timeUp);
  timeDownState = digitalRead(timeDown);
  sendButtonState = digitalRead(sendButton);
  if (timeUpState == LOW) {
  waitTime += 5;
  delay(500);  //debounce button
  lcd.print(waitTime);
  }

  if(waitTime > 90){ // Max limit for wait time
    waitTime = 10;   //default wait time
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

 if (timeDownState == LOW){
  waitTime -= 5;
  delay(500);
  lcd.print(waitTime);
  }

  if(waitTime < 10){ //Min value waiting time
    waitTime = 10;
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

  if(Serial.available()){  // **This is where I am stuck**
   if(sendButtonState == LOW){
   Serial.write(waitTime);
   delay(500);
  }
 }
}

Slave

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(9600);
  Serial.flush();
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's");
  lcd.setCursor(0,1);
  lcd.print("      Diner");
  }

void loop(){

  if (Serial.available()) {
   int waitTime = Serial.read();
    delay(200);
    lcd.clear();
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.write(waitTime);
    lcd.print(" Minuten");
     }
  }

Thanks in advance,
Jonathan

lcd.write(waitTime);

This line prints a single byte, whose (ASCII) value is the number in waitTime. You probably should write:

lcd.print(waitTime);

instead, which prints the number in waitTime using one ore more digits as needed.

This doesn't 100% explain the "both digits end up in the same place" symptom, since I'd expect random junk to be printed instead. But I'm pretty certain this is a problem, perhaps there's more problems :-)


how to wrap/scroll text with U8G2 Does anyone know how to wrap and or text using the U8G2 Libary?   I know there are other libraries that do this for you, but I'd like to use U8G2.

Thank you!

my code's here for reference.  It's not clean, but it works for now https://create.arduino.cc/editor/shaiss/0a2736f4-fb79-4e12-b9d7-fb15ff6757b7/preview

You can do something like

void loop(void) {
    u8g2_uint_t x;

    u8g2.firstPage();
    do {

        // draw the scrolling text at current offset
        x = offset;
        u8g2.setFont(u8g2_font_inb30_mr);       // set the target font
        do {                                // repeated drawing of the scrolling text...
            u8g2.drawUTF8(x, 30, text);         // draw the scolling text
            x += width;                     // add the pixel width of the scrolling text
        } while( x < u8g2.getDisplayWidth() );      // draw again until the complete display is filled

        u8g2.setFont(u8g2_font_inb16_mr);       // draw the current pixel width
        u8g2.setCursor(0, 58);
        u8g2.print(width);                  // this value must be lesser than 128 unless U8G2_16BIT is set

    } while ( u8g2.nextPage() );

    offset-=1;                          // scroll by one pixel
    if ( (u8g2_uint_t)offset < (u8g2_uint_t)-width )
        offset = 0;                         // start over again

    delay(10);                          // do some small delay
}

this is taken from here.

It is an excellent lib, but it is can require big amount of memory, fit very well on ESP8266 (tried on nodeMCU) / ESP32.

Of course on ESP32 it is faster.

Used for small OLED 0.98" screen


How to communicate between a webcam and an Arduino UNO and get the live feed on mobile using ESP8266? I am working on a project of making a Smart Robot Car using Arduino UNO, L298N Motor Driver Module, ESP8266 Esp-01 WiFi module and RemoteXY app for controlling via smartphone over WiFi.

My question is: If I want to get the live feed of the view that my robot is seeing, using a webcam (say Logitech HD Webcam C270) using a USB to serial converter module or whatsoever, how can I make it possible?
Please let me know if there is any special shield or any processing board needed. Help with coding and the conversion of Video data into the transmittable Data for Arduino and help in making that kind of data which can be read by the Device (e.g. Smartphone) is also needed and will be appreciable.

It may be mentioned here that I am a beginner and I am currently learning through YouTube and Blog Tutorials. I am totally dependent on StackExchange like forums for the help in my projects either whenever I am making a mistake or when I want to try and learn something new or both. Please Help me while keeping these things in your mind also.

Please suggest me some good books on this branch of the subject that could make me able to do these kinds of things on my own.

Thank You So Much in advance!

(P.S.: If you feel this question should be downvoted then, please firstly let me know in the comments section why do you feel like this before downvoting, I may delete my question earlier, cause I am concerned about my reputation here.)

The Uno is a very limited platform, perhaps surprisingly, given its wide range of abilities and built-in hardware features. The two most glaring limitations for you application are its 16MHz clock speed (relative to modern desktop processors) and thus its bandwidth, and it's non-expandable 2KBytes of RAM.

Image processing would be right out the window, and even merely transmitting a raw image would be pushing its bandwidth limits, for any reasonable frame-size with even a very modest frame-rate.

Example: For a 100x100 8-bit frame at 15 frames/sec, a 16MHz processor (16M instructions per sec) would have (16000000 / (100x100x15)) = ~107 clocks (instructions) available to process each byte. You'd need some of those to either poll for next-byte-ready or to enter and exit an Interrupt Service Routine to process the byte. You're probably up to around 20 clocks (at a wild guess), to do nothing more than a bit of wire can do! Maybe you could do some trivial manipulation of each byte on the way through (say, brightness manipulation) with a few more clocks and you're already using a significant fraction of the processor just for that. And there isn't enough memory to be able to process a region of the image. And if you could, you run out of processor time before you could do much .... The problem just cascades as you approach the limits of speed and memory-space.


Fast PWM working with int main(void) but not with void setup() board: Arduino Mega (ATMEGA2560)

I want to generate pulses using timer1 configured as Fast PWM, this is my code which works fine:

#include <avr/io.h>

int main(void)
//void setup()
{

  DDRB |= (1 << DDB5) | (1 << DDB6); // PWM outputs

  ICR1 = 0x7FFF;  // TOP
  OCR1A = 0x3FFF; // 50% of ICR1
  OCR1B = 0x3FFF; // 50% of ICR1

  TCCR1A |= (1 << COM1A1) | (1 << COM1B1);
  TCCR1A |= (1 << WGM11);
  TCCR1B |= (1 << WGM12) | (1 << WGM13);
  TCCR1B |= (1 << CS10);

}

void loop() {

}

I don't understand why it doesn't work if I use void setup() instead of int main(void). I'm working with arduino IDE 1.8.2 and always used void setup(), in this case I used int main(void) because it is used in some turorials I found like this one: https://www.youtube.com/watch?v=O_Yqf_cugwE

EDIT: When I say that it doesn't work, what happens is that instead of having PWM signals I just have a constant 5V output in both OC1A and OC1B pins

If you don't define your own main(), your program will be linked with
the main() provided by the Arduino core library, which roughly looks
like this (I am simplifying a little bit):

int main(void)
{
    init();      // Arduino core initialization
    setup();     // user's initialization
    for (;;)
        loop();  // user's main loop
}

The core's init() function configures Timer 1 for 8-bit phase
correct PWM at 490 Hz, which means that, by the time your setup()
runs, the timer's control registers are not in their default state
anymore, and some of their bits are already set to 1. If you then
update these registers using the |= operator, you end up with a mix of
the core's configuration and your own.

This can be fixed either by zeroing these registers first or, more
simply, by setting their values with the = operator, which has the
effect or setting every bit of those registers to the value you want.

The following works whether you use or not the Arduino core library:

#ifdef NOCORE
int main(void)
#else
void setup()
#endif
{
    DDRB   = _BV(PB5) | _BV(PB6);
    TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM11);
    TCCR1B = _BV(WGM12)
           | _BV(WGM13)
           | _BV(CS10);
    ICR1   = 0x7fff;  // TOP
    OCR1A  = 0x3fff;  // 50% of ICR1
    OCR1B  = 0x3fff;  // 50% of ICR1
}

#ifndef NOCORE
void loop(){}
#endif

Note that:

The control registers are set (=) rather than just modified with
|=
The mode is set before the output compare registers. This is because
setting the output compare registers does not work well when the timer
is in an 8-bit mode.


Servo noise during program flash on Arduino I'm running serveral servos using a driver A4988 and external power supply. Everything works fine.
I've just noticed one issue that I can't explain.
As soon as I upload a new program version on my arduino uno, while the external power supply is one, the servo makes some strange noises. After the upload has finished, the noise disappears.
Without any further details, can you explain this behavior? Does the arduino set some Pins to HIGH during flashing?
Thanks!

It would depend on which Arduino and what bootloader it's running.  Generally MCUs have their pins in INPUT mode when they reset.  Sometimes the bootloader will leave some pins configured for a particular mode by the some the sketch runs.  E.g. the Leonardo seems to leave pin 13 set to OUTPUT mode.
You usually want devices connected to your Arduino to have stable signals when the Arduino MCU is in reset, or in the bootloader, so it makes sense to pull the signal pins, that will later be output from the Arduino sketch, to known levels.  So maybe pulling your servo driver enable signal to inactive (HIGH) is appropriate.
Looking at the A4988, it has an EN (enable) pin, which seems to be active low.  So putting a high(ish) value resistor, say 5k or 10k, on it to VDD/HIGH (to inactive) is probably the thing to do.  When the Arduino is not driving the enable line to its low (active) state, that is when it's in the bootloader or being held in reset, the A4988 should stop its activity.


Assigning value inside structure array outside setup and loop functions I'm having some difficulty assigning a value to a variable in a struct array outside the loop and setup functions. Assigning a value to an int or char array works completely fine but this doesn't.

The example code and error message returned after trying to compile are below. Any help is greatly appriciated. Thanks

void setup()
{
}

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
} trap_game_details[2];

trap_game_details[0].random_min = 1;

void loop()
{

}

src/sketch.ino:13:5: error: ‘trap_game_details’ does not name a type
     trap_game_details[0].random_min = 1;
     ^
.build/uno/Makefile:166: recipe for target '.build/uno/src/sketch.o' failed

You can't access array contents in the global scope like that.  You have to assign the entire block of data in one go:

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

Items in the global scope aren't executed - only things in functions are executed.  Accessing individual parts of an array or struct like you are trying to is a programatic operation, so can't be executed since it's not in a function.


Now at IDE 1.0.5, should I upgrade to 1.0.6 or 1.5.7 Beta for Pro mini and ATMega2560 use? Do I need to re-install many libraries (or similar 'house keeping' works)? Is the upgrade straight forward?

Apparently, from Arduino web, one need 1.5 BETA series for use with Due. For Pro Mini, UNO and ATMega2560, should one use 1.5 BETA or 1.0.6 (no beta, presumable stable)?

I am running out of code space. Wonder if the upgrade will install a newer gcc compiler and smaller code size?

I have had trouble with 1.5.7 (Beta), so I would stick with 1.0.6. As for code space, you might want to look into Atmel Studio (Free), which uses a Visual Studio shell as the IDE. It blows the Arduino IDE out-of-water. Atmel is the maker of all the AT chips, so the Atmel Studio IDE is a great IDE for writing AVR code. Lots of tutorials online and there is a Arduino plug in called Visual Micro (Free also).


Need help with buttonstate I'm creating a program that works like a piano. I have four button, a piezo buzz and an LCD screen. I'm having a little trouble with the buttonstate.

Here is my program, when I run it the piezo buzz doesn't stop producing sound. The way it's suppose to work is when I push the green button, the piezo is suppose to produce a C sound but it doesn't. Can anyone please tell me what I've done wrong?

code:

#include <LiquidCrystal.h>

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

int buttonyellow = 3;
int buttonred = 4;
int buttongreen = 5;
int buttonblue = 6;

int C,D,E,F;
int buzz = 7;

int buttonstate;

void setup()
{
  lcd.begin(16, 2);

  lcd.print("hello, world!");

  Serial.begin(9600);
  pinMode(buttonyellow,INPUT);
  pinMode(buttonred,INPUT);
  pinMode(buttongreen,INPUT);
  pinMode(buttonblue,INPUT);
}

void loop()
{
  lcd.setCursor(0, 1);

  lcd.print(millis() / 1000);

  C = digitalRead(buttonyellow);
  D = digitalRead(buttonred);
  E = digitalRead(buttongreen);
  F = digitalRead(buttonblue);

  buttonstate = digitalRead(C);
  if(buttonstate == HIGH){
    tone(buzz,523);
  }  else if ( buttonstate == LOW) {
    tone(buzz,1000);
  }else{
   noTone(buzz);
  }
  delay(50);
}

As jsotola has pointed out, there is a mistake in your code. Remove the line

buttonstate = digitalRead(C)

and replace

if(buttonstate == HIGH)

with

if(C == HIGH)

Moreover, I suggest you take a look at the debouncing example in order to make the sound "smoother" ie no jitters because of the button


Servo/Motor for barrier gate I am working on a small project that will need to check for proper UPC's then if validated, lift a barrier gate to move along cardboard boxes. The Arduino comes in with the gate lifting. I have this barrier gate working with a very small servo that came included with the Arduino Starter Kit, but this could not hold the weight that might be pushing up against it with a longer arm. Has anyone had any experience with something like this or could someone direct of a power supply/servo combo that would be up to the task? These boxes could weigh up to 20 pounds.

Thanks!

You may purchase a servo motor with greater torque.

You may find both DC as well as AC servo's. If you are using it in a real industrial scenario I would suggest you to use the AC, as you may not have to convert the ac power to DC and these motors will need real high current. So it would be better if it works on the main voltage. I did find PANASONICs ac servo as google search result.

If you have problems with integrating the greater torque motor to your current system let me know i can help you out.


What is the difference between the two sensors? I am working on a project which requires the use of sensors and i don't know which one to use so i would like to know the difference between the two.

Apart from the obvious construction and component differences the two sensors seem totally equivalent from their look.
They seems to both be FC-51 modules: those are “line followers” meaning one diode (the clear one) emits infrared light and the other (the dark one) measure the amount of IR light reflected by the surface in front of them.
The potentiometer is there to determine the triggering level so that when powered you can have a LOW signal on the OUT pin when the threshold is reached.


How to use Timer1 (AT328Mega) to measure the time between rising edges of two input signals I'd like to use Timer1 to measure the time between rising edges of two input signals.  Specifically, use Tn to start the timer counter and IPCn to latch the elapsed time since the rising edge of the Tn input signal.  The goal is to measure the time between the rising edges of two input signals.   Is there a Timer1 library out there that alread does this?  Code suggestions welcomed.

It is not perfect for your simpler task, but here is a link to a sketch that I have used to record pulses, using the Timer1 Input Capture.

In short setup the Interrupt

void initTimer(void) {

  // Input Capture setup
  // ICNC1: Enable Input Capture Noise Canceler
  // ICES1: =1 for trigger on rising edge
  // CS10: =1 set prescaler to 1x system clock (F_CPU)
  TCCR1A = 0;
  TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10);
  TCCR1C = 0;

  //catchFallingEdge(); // initialize to catch
  { TCCR1B &= ~(1<<ICES1); TIFR1 |= (1<<ICF1); rising = 0; }

  // Interrupt setup
  // ICIE1: Input capture
  // TOIE1: Timer1 overflow
  TIFR1 = (1<<ICF1) | (1<<TOV1);        // clear pending
  TIMSK1 = (1<<ICIE1) | (1<<TOIE1); // and enable

  // Set up the Input Capture pin, ICP1, which corresponds to Arduino D8
  pinMode(8, INPUT);
  digitalWrite(8, 0);       // leave floating to count 60 Hz etc.
  //digitalWrite(8, 1);         // or enable the pullup
}

Then service it

ISR(TIMER1_CAPT_vect) {
  union twobyte {
    uint32_t word;
    uint8_t  byte[2];
  } timevalue;

  timevalue.byte[0] = ICR1L;        // grab captured timer value
  timevalue.byte[1] = ICR1H;        // grab captured timer value

  // watch for the other edge to catch the half-pulse width
  //rising ? catchFallingEdge() : catchRisingEdge();
  if (rising) {
    TCCR1B &= ~(1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 0;
  }
  else {
    TCCR1B |= (1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 1;
  }
}


Arduino Yun and REST call security I'm not expert about web development but very excited of doing some rest call using the yun as server (with a minimal python or node.js server inside the openwrt machine in the yun) and expose sensors and actuators to the cloud.

I'm also worried about security. I don't want the super-shellproof system but just don't want that accidental visitors reads my home temperature or make my garden light switch on when I'm out.

For instance I have a central unit yun with some logic inside it and few arduino yun that makes reads from sensors and runs actuators around my home. The communication between the central yun and the slaves is happening via REST calls. I'm using curl for testing it, for instance. Here two questions:

Arduino Yun provide a simple user/password account when arduinoname.local/arduino is called. How is it implemented?
Let's say I'm using node.js to make a super simple web-server, what is the best way to protect the communication central-yun and slave-yun? and to protect central-gun and internet communication?

Best way in term of computation (the yun machine is not very powerful and I'm going to use battery in some cases) and in term of "easy to implement".

Password protection of the REST API is done with Basic Authentication. This, coupled with HTTPS, makes API calls more secure. Since the SSL certificate is self-generated, you'll need to run curl with -k parameter.

As Annonomus Penguin suggested, before going into securing the Yuns, you should secure the network they are using (e.g.: home WiFi should use a strong password).