message:
Proper use of the tone() function within the loop () function

I am trying to have my sketch run a short series of tones (melody) through a Piezo buzzer after a selection is made by the user. I am getting a compilation error with my use of the tone function in the code I've written. I would kindly ask if someone in the "know" could have a look and provide me with a clear, step by step explanation of what I need to change to get it to work. I thank you in advance, your help is much needed and appreciated. -Steve

Here is my sketch:

    #include <Stepper.h>
    #include <Servo.h>
    #include <Tone.h>

    /*ARDUINO MOTOR SHIELD
     * The pin breakdown is as follows:
     * Function          Channel A   Channel B
     * Direction         Digital 12  Digital 13
     * Speed (PWM)       Digital 3   Digital 11
     * Brake             Digital 9   Digital 8
     * Current Sensing   Analog 0  Analog 1
     */

    const int stepsPerRevolution = 200;  // 1.8 deg. step angle(200 steps/360 deg. rev)
    const int dirChA = 12;     // assigning name "dirChA" to pin 12
    const int dirChB = 13;     // assigning name "dirChB" to pin 13
    const int pwmChA = 3;      // assigning name "pwmChA" to pin 3
    const int pwmChB = 11;     // assigning name "pwmChB" to pin 11
    const int brkChA = 9;      // assigning name "brkChA" to pin 9
    const int brkChB = 8;      // assigning name "brkChB" to pin 8

    const int srvoMtr = 10;    // assigning name "srvoMtr" to pin 10

    const int pButton1 = 4;    // assigning name "pButton1" to pin 4
    const int pButton2 = 5;    // assigning name "pButton2" to pin 5
    const int pButton3 = 6;    // assigning name "pButton3" to pin 6
    const int pButton4 = 7;    // assigning name "pButton4" to pin 7

    const int ledLight = 2;    // assigning name "ledLight" to pin 2

    const int tonePin = 14;     // assigning name "tonePin" to pin 14

    Stepper myStepper(stepsPerRevolution, dirChA, dirChB);  // initialize the stepper library on pins 12 & 13
    Servo myServo;  // initialize the servo library to logical name myServo

    int pButton1State = 0;     // variable for reading the pButton1 state as LOW or HIGH
    int pButton2State = 0;     // variable for reading the pButton2 state as LOW or HIGH
    int pButton3State = 0;     // variable for reading the pButton3 state as LOW or HIGH
    int pButton4State = 0;   // variable for reading the pButton4 state as LOW or HIGH

    int pButtonFlag = 0;     // variable for when button 1 has been pressed and released

    int myServoPos = 0;    // variable for when servo has reached it's position
    int myServoFlag = 0;   // variable for servo when any of the 4 pButton are pressed

    void setup() {

     // 1 Stepper Motor
     pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
     digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)

     pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
     digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)

     pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
     digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)

     pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
     digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)

     pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
     digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)

     pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
     digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)

     myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM

     // 4 Push Buttons
     pinMode(pButton1, INPUT);   // initialize pin 4 as an INPUT
     digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)

     pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
     digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)

     pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
     digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)

     pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
     digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)

     // 1 Led Light
     pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
     digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)

    // 1 Piezo Speaker
     tone();
     pinMode(tonePin, OUTPUT);   // initialize pin 1 as an OUTPUT
     digitalWrite(tonePin, LOW);   // initialize pin 1 as LOW (pin voltage is 0 V)
    }

    void loop() {
      //Read button state (pressed or not pressed?)
      pButton1State = digitalRead(pButton1);   // read the state of pButton1 as LOW or HIGH
      pButton2State = digitalRead(pButton2);   // read the state of pButton2 as LOW or HIGH
      pButton3State = digitalRead(pButton3);   // read the state of pButton3 as LOW or HIGH
      pButton4State = digitalRead(pButton4);   // read the state of pButton4 as LOW or HIGH

      // check if the pushbutton is pressed. If it is, the pbuttonState is HIGH:
      if (pButton1State == HIGH) {
         pButtonFlag=1;  // change pButton1Flag variable
      }
         if (pButtonFlag == 1){
            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(40);          // step forward 40 steps to position 1
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    //disable power to stepper

            myServoFlag=1;             // change ServoFlag variable to dispense chocolate

            if (myServoFlag == 1){
               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                   delay(15);                    // waits 15 milliseconds for the servo to reach the position
               }
               myServo.detach();   // detaches the servo library from pin 10
               delay(2000); // hold position OPEN for 2 sec

               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
               }
               myServo.detach();   // detaches the servo library from pin 10
            }

            myServoFlag=0;         // changes myServoFlag value back to zero (0)
            digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed

            if (ledLight == HIGH){
               digitalWrite(tonePin, HIGH); // turn on Piezo speaker

               // Play Melody
               void tone();{
               tone(tonePin, 233, 203.992851562);
               delay(226.658723958);
               delay(4.82252604167);
               tone(tonePin, 184, 412.325976562);
               delay(458.139973958);
               delay(4.82252604167);
               tone(tonePin, 184, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 155, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(236.303776042);
               tone(tonePin, 184, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 155, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(236.303776042);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(236.303776042);
               tone(tonePin, 233, 555.555);
               }
            }
            digitalWrite(tonePin, LOW);    // turns off Piezo speaker

            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(-40);          // step backward 40 steps to position 0
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    // disable power to stepper

            digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
            digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

            pButtonFlag=0;                // changes pButtonFlat value back to zero (0)
            delay(2000);
         }

      // position 2
      if (pButton2State == HIGH) {
         pButtonFlag=1;  // change pButtonFlag variable
      }
         if (pButtonFlag == 1){
            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(80);          // step forward 80 steps to position 2
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    //disable power to stepper
            delay(2000);

            myServoFlag=1;    // change ServoFlag variable to dispense chocolate

            if (myServoFlag == 1){
               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                   delay(15);                    // waits 15 milliseconds for the servo to reach the position
               }
               myServo.detach();   // detaches the servo library from pin 10
               delay(2000);

               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
               }
               myServo.detach();   // detaches the servo library from pin 10
            }
            myServoFlag=0;                // changes myServoFlag value back to zero (0)
            digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed

            if (ledLight == HIGH){
               digitalWrite(tonePin, HIGH); // turn on Piezo speaker

               // Play Melody
               tone(tonePin, 233, 203.992851562);
               delay(226.658723958);
               delay(4.82252604167);
               tone(tonePin, 184, 412.325976562);
               delay(458.139973958);
               delay(4.82252604167);
               tone(tonePin, 184, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 155, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(236.303776042);
               tone(tonePin, 184, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 155, 99.8262890625);
               delay(110.918098958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(4.82252604167);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(236.303776042);
               tone(tonePin, 184, 203.992851562);
               delay(226.658723958);
               delay(236.303776042);
               tone(tonePin, 233, 555.555);
            }
            digitalWrite(tonePin, LOW);    // turns off Piezo speaker

            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(-80);          // step backward 80 steps to position 0
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    //disable power to stepper

            digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
            digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

            pButtonFlag=0;   // changes pButton2Flag value back to zero (0)
            delay(2000);
        }

        // position 3
        if (pButton3State == HIGH) {
           pButtonFlag=1;   // change pButtonFlag variable
        }
           if (pButtonFlag == 1){
              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(120);          // step forward 120 steps to position 3
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    //disable power to stepper
              delay(2000);

              myServoFlag=1;   // change ServoFlag variable to dispense chocolate

              if (myServoFlag == 1){
                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                     myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                     delay(15);                    // waits 3 sec for the servo to reach the position
                 }
                 myServo.detach();   // detaches the servo library from pin 10
                 delay(2000);

                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
                 }
                 myServo.detach();   // detaches the servo library from pin 10
              }
              myServoFlag=0;                // changes myServoFlag value back to zero (0)
              digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed

              if (ledLight == HIGH){
                 digitalWrite(tonePin, HIGH); // turn on Piezo speaker

                 // Play Melody
                 tone(tonePin, 233, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 412.325976562);
                 delay(458.139973958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 155, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 184, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 155, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 233, 555.555);
              }
              digitalWrite(tonePin, LOW);    // turns off Piezo speaker

              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(-120);         // step backward 120 steps to position 0
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    // disable power to stepper

              digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
              digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

              pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
              delay(2000);
         }
        // position 4
        if (pButton4State == HIGH) {
           pButtonFlag=1;   // change pButtonFlag variable
        }
           if (pButtonFlag == 1){
              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(160);          // step forward 160 steps to position 3
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    //disable power to stepper
              delay(2000);

              myServoFlag=1;   // change ServoFlag variable to dispense chocolate
              Serial.println("\nServo Flag = 1 - Dispense Chocolate");

              if (myServoFlag == 1){
                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                     myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                     delay(15);                    // waits 3 sec for the servo to reach the position
                 }
                 myServo.detach();   // detaches the servo library from pin 10
                 delay(2000);

                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
                 }
                 myServo.detach();   // detaches the servo library from pin 10
              }
              myServoFlag=0;   // changes myServoFlag value back to zero (0)
              digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed

              if (ledLight == HIGH){
                 digitalWrite(tonePin, HIGH); // turn on Piezo speaker

                 // Play Melody
                 tone(tonePin, 233, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 412.325976562);
                 delay(458.139973958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 155, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 184, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 155, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 233, 555.555);
              }
              digitalWrite(tonePin, LOW);    // turns off Piezo speaker

              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(-160);         // step backward 160 steps to position 0
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    // disable power to stepper

              digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
              digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

              pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
              delay(2000);
           }
    }

body:
First off
==

Even if compiled your code will not work; in [the tone function reference][1] you can read:

> Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

You seem to want to use both pins 3 & 11 for PWM output; you cannot also use the Tone library while using these pins. Although you never actually called analogWrite(...) on these pins so it probably won't do what you want anyway.

Second
==

the line:

    void tone();{

is absolutely wrong; one cannot declare a function within another function in C++ or C. And this isn't even a valid definition either. This is probably your compilation error, your compiler should tell you what line number this is on!

Third
==
It seems you don't quite understand what the code you are attempting to use even does. I would assume that you haven't read, or understood, the documentation.

    digitalWrite(tonePin, HIGH); // turn on Piezo speaker

The tone library doesn't work like this; at best this does nothing, at worst it disrupts the tone library

    myServo.attach(srvoMtr);   // attaches the servo library to pin 10
    for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
      myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
      delay(15);
    }
    myServo.detach();

This is not how you use the servo library! .attach() is generally used in setup, .detach() is almost never used.

        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(40);          // step forward 40 steps to position 1
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper

This is not how you use the stepper library! Steppers are generally powered 100% of the time. When un-powered they cannot generate torque or hold a position! Also those pins aren't associated in any way with the stepper, you assigned dirChA and dirChB to the stepper. The stepper library assumes it is talking to a stepper driver, not driving the stepper itself.

Finally
==

Your code repeats itself too much, and is too verbose, and does many nonsensical things or things that result in nothing or something very different that the comments imply was intended.

You need to structure you code better, refactor into re-useable functions and remove code that doesn't do anything

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/


sender: user

message:
How to convert a delimited string of hex numbers to an int array

I am sending a string to the Arduino via serial, I made the program that sends the data, so I can change it to anything, but for now it sends a string of hex numbers delimited by ':', so for example 00:AA:FF and I need to get that into an int array onto the Arduino, the main problem is I don't always know how big the array will be, sometimes just 2 indexes, other times 16 indexes.

As I said, I made the program sending the data so I can make the data anything, I just need to get an int array to the Arduino and get it back as an int array via serial

sender: assistant

body:
You could store the hex numbers in a `int array` using [strtok()][1] and [strtol()][2].

  [1]: http://www.cplusplus.com/reference/cstring/strtok/
  [2]: http://www.cplusplus.com/reference/cstdlib/strtol/

    char str[] = "00:AA:FF:7FFF";
    int intArray[16]; // Maximum number of hex numbers.

    void setup(){

      Serial.begin(9600);

      int counter = 0;
      char * pch = strtok(str, ":");

      while(pch != NULL){
        intArray[counter] = strtol(pch, NULL, 16);
        pch = strtok(NULL, ":");
        counter++;
      }
      Serial.print("Item Count = ");
      Serial.println(counter);

      for(int i = 0; i < counter; i++){
        Serial.println(intArray[i]);
      }

    }

    void loop(){}


message:
Emit region-neutral keyboard signals

The `Keyboard` API allows the Arduino boards such as the Micro or Leonardo to emit USB signals mimicking a physical keyboard. However, the signal seems to transmit key strokes and not characters which means that machines with different region settings interpret the USB signal differently. For example, a `y` will be interpreted as `z` in a German OS since the keyboard layout has these keys swapped.

Is there any way to output a signal that will result in the correct character being transmitted regardless of the OS settings *without any modifications to the machine the Arduino is attached to*?

body:
No. There is no such facility.

If you take a German keyboard and plug it into a US configured computer the key layout will be wrong. You have to tell the computer that you're using a German keyboard.

Keyboards don't know what is printed on the keycaps. All they understand is where the buttons are physically located.

The same with the Arduino. It's sending the keypresses that correspond to the keyboard layout of a US keyboard, and you have to tell the computer that you're using a US keyboard - because that is effectively what you are using.

If you want to change the keyboard map the Arduino uses you will have to manually modify the Keyboard library (file `Keyboard.cpp`, array `_asciimap[128]`).


body:
Download `Device Class Definition for Human Interface Devices (HID)`

https://www.usb.org/sites/default/files/documents/hid1_11.pdf

See section 6.2.1 HID Descriptor

`bCountryCode 0x09` German

also see section E.4 (page 67)

    E.4 HID Descriptor (Keyboard)
    Part            Offset/Size  Description                                         Sample
                    (Bytes)                                                          Value
    ----------------------------------------------------------------------------------------
    bLength           0/1        Size of this descriptor in bytes.                    0x09
    bDescriptorType   1/1        HID descriptor type (assigned by USB).               0x21
    bcdHID            2/2        HID Class Specification release number
                                 in binarycoded decimal—for example, 2.10 is 0x210).  0x101
    bCountryCode      4/1        Hardware target country.                             0x00
    bNumDescriptors   5/1        Number of HID class descriptors to follow.           0x01
    bDescriptorType   6/1        Report descriptor type.                              0x22
    wDescriptorLength 7/2        Total length of Report descriptor.                   0x3F


message:
How to power multiple LEDs with a microcontroller

I currently have a "tiny" setup and want to put a few (~20-30) [0402 LEDs on a 1:87 scale car][1]. My current setup is an [ATtiny85 USB Mini Dev Board][10] powered by a [90mAh 3.7V LiPo][20] battery which is connected to a [TP4056 5V micro USB Lipo battery charger][30]:[![enter image description here][2]][2]

To my bitter disappointment one cannot connect the leds in series. I've read about charlieplexing which was a little mind boggling for me to comprehend.

I was going to break down the leds and pins as follows:

 - **P0** - headlights (2x white 0402 LEDs) +  tail lights (2x red 0402 LEDs) - <s>in series</s> - **in parrallel**
 - **P1** - blinkers (4x amber 0402 LEDs) - <s>in series</s> - **in parrallel**
 - **P2** - siren (12x amber 0402 LEDs) - <s>in series</s> - **in parrallel**
 - **P3** - beacon (2x blue 0402 LEDs) - <s>in series</s> - **in parrallel**
 - **P4** - beacon (2x blue 0402 LEDs) - <s>in series</s> - **in parrallel**
 - **P5** - beacon (2x blue 0402 LEDs) - <s>in series</s> - **in parrallel**

__Question:__

 1. With space being limited inside the model car how would I be able to
    drive 20-30 LEDs with the above set up?
 2. I am in doubt that the models in the [video][1] use charlieplexing and use a similar microcontroller, how would they be doing this?
 3.  Would it be better for me use something like a [Pro Micro ATmega32U4 5V 16MHz][3] and spread the LEDs across the 16 pins (ie 2 LEDs per pin = total of 32 LEDs)?

  [1]: https://www.youtube.com/watch?v=YJ2Urvff1vo
  [2]: https://i.stack.imgur.com/3HLOS.png
  [3]: https://www.ebay.com.au/itm/Pro-Micro-ATmega32U4-5V-16MHz-Replace-ATmega328-Arduino-Pro-Mini/202591768643?hash=item2f2b691043:g:yPAAAOSw-hRcXcO4:rk:2:pf:0
 [10]: https://www.electrodragon.com/product/attiny85-usb-mini-dev-board-digispark-compatible/
  [20]: https://www.ebay.com.au/i/113322553296?chn=ps
  [30]: https://www.ebay.com.au/itm/1-2-5-10-TP4056-5V-Micro-USB-Lithium-Bat-Charging-NEW-Improved-LiPo-Charger-Mod/182632018873?hash=item2a85b773b9:m:m0nABi0ToNRyNEbNtzeAAFQ:rk:1:pf:0

body:
1. I see no reason why you would not be able to light 30 LEDs.
2. ATtiny85 only has 5 pins for use (unless you want to use the reset pin as well in which case hell will cover you). So with charlieplexing you are going to be able to address 20 endpoints. (where each endpoint might consist of multiple LEDs)
But beware. You CAN address 20 endpoints but you CANNOT light every combination simultaneouly. You will have to work out if there is a constellation that allows you to light all lights you want in the same time or you will have to use one of the timers to toggle between different lights. I don't know how well it works thou.
I have managed to use a timer on an 8MHz device to drive 4 LEDs at 400Hz directly without charlieplexing and not using PWM. So I assume it will be possible but might be flickering.
3. It would definitively be easier. I always recommend to stick to things that are well known and widely used. That would fit your ATmega32U4.

Make sure you layout your LEDs and think how you want to address them and if it makes sense to join multiple LEDs to one pin and toggle them at once.


message:
Interpreting pull-up values Rp and Rpu in AM3202 (DHT22) datasheet

In the [AM2302 datasheet](https://akizukidenshi.com/download/ds/aosong/AM2302.pdf) at page 3, table 4, it gives `min`, `typ` and `max` values for `Rpu` (`that the pull-up resistor` as it says verbatim) being `30K`, `45K` and `60K` ohm respectively.

Elsewhere in the same table it gives figures for `Rp` (no `u`) < 25K ohm.

What is the difference between `Rpu` and `Rp` here, and how should the two rows be interpreted?

body:
The datasheet is as inaccurate as the sensor itself and it is even worse than you think!

In that datasheet is also written: "usually require an external about 5.1kΩ pull-up resistor".

In the datasheet is also mentioned that the output signal can go up to 8 mA for a high output and minimal 10 µA low output. The 10 µA means that the pullup resistor should be 500k or more. That is not correct.

In [this datasheet][2] is a picture with 1k.
In [this Chinese datasheet][1] is a picture with 5k.
I ran that Chinese datasheet through Google Translate, but that did not help.

**Conclusion: The datasheet is not reliable.**

You can do as everyone else: use a 10k resistor for short wires, and try 4k7 for longer wires.

That is not the only problem. [Some DHT libraries create a shortcut][3] on the data signal.

The AM3202 is not accurate for measuring the humidity. If you want to avoid trouble, then use a better sensor.
A sensor from Bosch is a good choice (for example the BME280 or BME680). Bosch makes datasheets that are reliable. Those sensors from Bosch operate at 3.3V, if you are going to connect that to a 5V Arduino board, then you need level shifters for the signals.

  [1]: http://www.adafruit.com/datasheets/DHT11-chinese.pdf
  [2]: https://cdn-shop.adafruit.com/datasheets/Digital+humidity+and+temperature+sensor+AM2302.pdf
  [3]: https://github.com/adafruit/DHT-sensor-library/issues/48


message:
Motors triggering Interrupt

[![enter image description here][1]][1]I am using a 4wd robotic car to measure straight distances. I have attached two encoders on the front two wheels to measure the distance and I am using the back two wheels to adjust the car and keep it driving straight by using a compass as a reference. The Problem is that when my program is executing the section that drives the back wheels this somehow triggers the interrupt and increments the number of ticks. What is causing this issue?

    volatile unsigned long enc_l = 0;
    volatile unsigned long enc_r = 0;

    void driveStraight(float drive_distance, int motor_power)
    {
      Serial.print("\n");
      Serial.println("num_tick_l \t num_tick_r \t diff_l \t diff_r \t enc_1_prev \t enc_r_prev \t Power_l \t Power_r \t Power_a \t Power_b ");

      unsigned long num_ticks_l;
      unsigned long num_ticks_r;

      // Set initial motor power
      int power_l = motor_power;
      int power_r = motor_power;

      // Used to determine which way to turn to adjust
      unsigned long diff_l;
      unsigned long diff_r;

      // Reset encoder counts
      enc_l = 0;
      enc_r = 0;

      // Remember previous encoder counts
      unsigned long enc_l_prev = enc_l;
      unsigned long enc_r_prev = enc_r;

      // Calculate targer number of ticks
      float num_rev = (drive_distance * 10) / wheel_c;   // Convert to mm
      unsigned long target_count =  29; //num_rev * counts_per_rev;

      /*
        // Debug
        Serial.print("Driving for ");
        Serial.print(drive_distance);
        Serial.print(" cm(");
        Serial.print(target_count);
        Serial.print(" ticks) at ");
        Serial.print(motor_power);
        Serial.println(" Motor Power");
      */

      //Drive until on of the encoders reaches desired count
      while ((enc_l < target_count) && (enc_r < target_count))
      {

        bluetooth();                                // if new bluetooth value received break from loop
        if (blueToothVal == 5) {
          break;                                    // If a 'Stop' Bluetooth command is received then break from the Loop
        }

        // Sample number of encoder ticks
        num_ticks_l = enc_l;
        num_ticks_r = enc_r;

        // Sample out current number of ticks
        Serial.print(num_ticks_l);
        Serial.print("  \t\t");
        Serial.print(num_ticks_r);

        // Drive
        drive(power_l, power_r);

        // Number of ticks counted since last time
        const int StraightDriveOffset = 1;                    // Increase this or even make it a negatie number to tweak the

        diff_l = num_ticks_l - enc_l_prev;                    // + StraightDriveOffset;
        diff_r = num_ticks_r - enc_r_prev;

        Serial.print("  \t\t");
        Serial.print(diff_l);
        Serial.print(" \t \t");
        Serial.print(diff_r);

        // Store current ticks counter for next time
        enc_l_prev = num_ticks_l;
        enc_r_prev = num_ticks_r;

        Serial.print("   \t \t");
        Serial.print(enc_l_prev);
        Serial.print(" \t \t");
        Serial.print(enc_r_prev);

        // If left is faster, slow it down and speed up right
        if ( diff_l > diff_r) {
          power_l -= motor_offset;
          power_r += motor_offset;
        }

        // If right is faster, slow it down and speed up right
        if ( diff_l < diff_r) {
          power_l += motor_offset;
          power_r -= motor_offset;
        }

        // Debugging
        Serial.print(" \t\t");
        Serial.print(power_l);
        Serial.print(" \t\t");
        Serial.println(power_r);

        // Brif pause to let motors respond
        delay(20);
      }

      StopCar();
      //Buzzer();
    }

    void drive(int power_a, int power_b)
    {
      getCompass();                                                     // Update Compass Heading
      bluetooth();                                                      // Check to see if any Bluetooth commands have been sent

      if (blueToothVal == 5) {
        break; // If a Stop Bluetooth command ('5') is received then break from the Loop
      }

      // Constrain power to between -255 and 255
      power_a = constrain(power_a, -255, 255);
      power_b = constrain(power_b, -255, 255);

      if ( abs(desired_heading - compass_heading) <= compass_dev )      // If the Desired Heading and the Compass Heading are within the compass deviation, X degrees of each other then Go Forward
        // otherwise find the shortest turn radius and turn left or right
      {
        // Left motor direction
        if ( power_a < 0)
        {
          motor2.setSpeed(abs(power_a));       // Motor is the front left wheel
          motor2.run(BACKWARD);

        }
        else
        {
          motor2.setSpeed(abs(power_a));       // Motor is the front left wheel
          motor2.run(FORWARD);

        }

        // Right Motor direction
        if ( power_b < 0)
        {
          motor4.setSpeed(abs(power_b));       // Motor is the front left wheel
          motor4.run(BACKWARD);

        }
        else
        {
          motor4.setSpeed(abs(power_b));       // Motor is the front left wheel
          motor4.run(FORWARD);

        }

      }

      else
      {
        int x = (desired_heading - 359);                          // x = the GPS desired heading - 360
        int y = (compass_heading - (x));                          // y = the Compass heading - x
        int z = (y - 360);                                        // z = y - 360

        if ((z <= 180) && (z >= 0))                               // if z is less than 180 and not a negative value then turn left
        { // otherwise turn right
          motor1.setSpeed(190);
          motor3.setSpeed(190);
          motor1.run(BACKWARD);
          motor3.run(FORWARD);
        }
        else
        {
          motor1.setSpeed(190);
          motor3.setSpeed(190);
          motor1.run(FORWARD);
          motor3.run(BACKWARD);

        }
      }
    }

    void countLeft()
    {
      enc_l ++;
    }

    void countRight()
    {
      enc_r ++;
    }

and this is what is on the setup function

    const int enc_l_pin = 18;
    const int enc_r_pin = 19;

    void setup()
        {
          Serial.begin(115200);                                            // Serial 0 is for communication with the computer
          Serial3.begin(9600);                                             // Serial 1 is for Bluetooth communication - DO NOT MODIFY - JY-MCU HC-06 v1.40

          Wire.begin();                                                    // Join I2C bus used for the HMC5883L compass
          compass.begin();                                                 // initialize the compass (HMC5883L)
          compass.setRange(HMC5883L_RANGE_1_3GA);                          // Set measurement range
          compass.setMeasurementMode(HMC5883L_CONTINOUS);                  // Set measurement mode
          compass.setDataRate(HMC5883L_DATARATE_30HZ);                     // Set data rate
          compass.setSamples(HMC5883L_SAMPLES_8);                          // Set number of samples averaged
          compass.setOffset(118, 473);                                      // Set calibration offset

          // Buzzer
          pinMode(Buzzer_pin, OUTPUT);

          // Set up pins
          pinMode(enc_l_pin, INPUT);
          pinMode(enc_r_pin, INPUT);

          // Set up interrupts
          attachInterrupt(digitalPinToInterrupt(enc_l_pin), countLeft, CHANGE);
          attachInterrupt(digitalPinToInterrupt(enc_r_pin), countRight, CHANGE);

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/jcEE7.jpg
  [2]: https://i.stack.imgur.com/utxSN.png

body:
I think you have 2 problems:

1. The used Hall sensor is an analog device, not a digital one. This means it will not output either Vcc or 0V, but instead an analog (continuous) voltage depending on the magnetic field. With zero magnetic field, it will output about half the supply voltage (in this case 2.5V, since Vcc is 5V for you). For analog signals pullups or pulldowns do not make sense. Digital pins have a hysteris, which means, that they will detect a LOW between 0V and 1.67V and a HIGH between 3.33V and 5V (see [this answer][1]). This is also called a Schmitt trigger. I assume, that you just want to measure, that the magnet comes near the sensor (so only one polarity matters). This means, that the voltage will stay - let's say - above 2.5V (depending on polarity) and only going from 2.5V to 5V and back. In this condition the pin state will stay high, since it is set high, but never reaches voltage low enough for setting it to low. No interrupt will be triggered. Depending on what you want and the next problem, you can instead use a comparator (which is a special peripheral of the microcontroller) to trigger the incrementation, when a specified threshold voltage is reached (this also mean it would trigger due to small changes around the threshold), or you can buy or build an external Schmitt trigger, where you can change the threshold voltages for LOW and HIGH changes.

2. Motors send out quite a bunch of electromagnetic noise, which can distort analog Signals nearby. Most likely the noise from the motors is high enough to falsely trigger a state change at the pin. Maybe you should look at the analog signal with an oscilloscope, which can show you, how much noise do you really have in this situation. There are many ways to reduce noise on an analog signal. One is to add a low pass filter to cancel out the mostly higher frequency noise. This only works, if the frequency of your signal is considerably lower (so that you can trim the low pass filter to let your signal pass).

---

From the picture I cannot see, how the magnets and the sensors are moving in the car. Be sure to measure the different voltages in the different states (magnet near sensor, magnet for away). If the sensor is too sensitive or your magnet too strong, you might end up with an even smaller voltage range, than the 2.5V, that you already have.

  [1]: https://arduino.stackexchange.com/questions/45665/how-does-arduino-digital-input-pin-measure-its-input-voltage


message:
How to program the Robotdyn Mega 2560 PRO MINI?

I want to program the Robotdyn Mega 2560 PRO MINI which has no USB port.

How do I connect the pins to an FTDI?

Which setting do I have to use in the Arduino IDE?

body:
Connect the Arduino to the FTDI in the following way:

 - FTDI - Arduino
 - VCC - VCC
 - GND - GND
 - RX - TXD
 - TX - RXD
 - DTR - 100nf capacitor - RST
 - CTS is not connected

Use the following settings in the Arduino IDE

 - Board: Arduino/Genuino Mega or Mega 2560
 - Processor: ATMega2560 (Mega 2560)

[![Arduino with FTDI][1]][1]

The image shows the Arduino with colored connectors and with 4 extra rows of connectors. These are not part of the original Arduino. I added them to make it easy to connect lots of I2C devices for testing.

  [1]: https://i.stack.imgur.com/qZJIJ.jpg


message:
Run code once after programming

I'm using EEPROM to store project settings non-volatile.
After reuploading the sketch to my board (over SPI via ArduinoISP), the EEPROM is reset to full `0xFF`s and I have to manually do a "software reset" with a second switch, which initializes the EEPROM with its default values.

**Is it possible to run a segment of code once, and only once, after booting up the first time after being programmed?**

I'm working around it by checking whether a piece of EEPROM is `1` at startup when it would always be `0` after the initialization and during usage, but surely there's a cleaner alternative than checking for an EEPROM bit each time.

body:
This is a X->Y problem. Here is a solution for X:

Bit 3 of high fuse of the ATmega328p controls if EEPROM memory is preserved through the chip erase. You can change the high fuse setting in boards.txt. Restart the IDE to apply the new setting.

The fuses are written when you select the "burn bootloader" option in the Arduino IDE.


body:
I've actually done some tinkering with this sort of thing, or alternatively how to ensure previous EEPROM (or similar) settings are formatted on upload of a new sketch.

There are two values (C macros, in this case) that are baked into a program when it is compiled (for Arduino, the program is recompiled on each upload) that can be used to tell if the programming is "fresh."

The values you'd want are `__DATE__` and `__TIME__`. They are converted to char arrays (strings, basically) at the time the compiler is run. You can store them directly to EEPROM, or use some sort of hash to convert it to a convenient number to store instead. Then, whenever the code boots, compare the stored value with the one computed from the values coded into the program. If they *differ*, overwrite the stored value with the new one and execute the run-once code.

Something along the lines of

    byte i=0;
    char checkVal[]=__TIME__ __DATE__;
    for (int j=0; j<strlen(checkVal); j++){
      i+=(byte)checkVal[j];//Creates a modulo 256 sum of the ASCII values of the chars (really poor hash)
    }
    if(EEPROM.read(26)!=i){//stored EEPROM location (arbitrary) -- feel free to use wear leveling, though, or some other method
      //DO RUN-ONCE CODE HERE
      EEPROM.write(26,i);//store the new value to stop it running again
    }


message:
I cannot compile the Arduino sketch when I remove the void loop function?

#include <AFMotor.h>

    AF_DCMotor motor(2,MOTOR12_64KHZ);

    void movefor ();

    void moveback();

        void setup()

        {

        Serial.begin(9600);

        Serial.println("Motor test!");` `motor.setSpeed(200);

        movefor ();
        moveback ();
        }

            void movefor( ){
            motor.run(FORWARD);
        delay(1000);
        motor.run(RELEASE);
         delay(100);
        }

        void moveback( ) {
          motor.run(BACKWARD);
        delay(1000);
        motor.run(RELEASE);
         delay(100);
        }

While trying to compile this the error message is *error compiling for board Arduino Uno*

I want the functions outside loop so removed it.

Even if I keep void loop and leave it blank then my motors will like run forward, backward and forward afterwards continuously .

body:
There must be something wrong within the motor, circuit or the motor class.

What happens is when you use a setup and loop is the following:

    setup();
    while (1) { loop(); }

So the loop function is executed forever, if it is empty, nothing will happen. If you say that the motor runs forward, it is probably because of a wrong implementation of the motor class.

Arduino IDE dictates there is always a loop, and having an empty loop is the same as having no loop at all.

What you can try is:

- In the setup, only execute movefor() and check what happens
- Than only execute moveback() and check what happens
- Than make combinations and see if the problem is inside movefor or moveback

For the first steps you can add a delay to easier see if there is a side effect.


body:
You can't, and shouldn't, remove the loop function. Arduino sketches must have a setup function and a loop function. The setup function is called once and the loop function is called repeatedly.

Just make your loop function look like this:

    void loop() {
        movefor ();
        moveback ();
    }

Your motor will move forward, then move backwards, forever.

Note that you should read up on how to avoid using the delay function. You really need to use `millis()` to do your timing rather than delays. Do an internet search on "Arduino blink no delay." That's basic Arduino programming.


message:
Latest datasheet for Leonardo's ATmega32U4

What is the authoritative source(s) for the ATmega32U4 (or any Arduino chip for that matter) datasheet?

body:
4/2016 does appear to be the latest datasheet for the Atmega32U4. If you go here www.microchip.com and select Design, then Documentation, then Datasheets, then Search by Products, you can enter a part number. Entering Atmega328P brings up the complete datasheet dated 1 Nov 2018. You can check that to see if there is more characterization data.

(question was originally about characerization of ADC for '32U4 and other sources of info on same, hence the '328P reference here).


message:
Using an external pull-up resistor vs INPUT_PULLUP

When would one would prefer to use an external pull-up resistor vs the internal:

    pinMode(fanPin, INPUT_PULLUP);

Dredging through the forums and this site, the commonly recommended value for a pull-up resistor is seems to fall at 10K.

However, the [ATmega32U4 datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf)'s Table 29-1 says that RPU or "I/O Pin Pull-up Resistor" is between 20K and 50K ohms.

[This question](https://arduino.stackexchange.com/q/4725/53509) asks about internal vs external pull-ups for a simple button, but I'm asking in the general case.

What types of projects would fare better with internal pull-ups, and what type of projects would be better off with external pull-ups?

What are the considerations for preferring one over the other?

At the present, my project is hooking up an AM2302 / DHT22 temperature sensor.

body:
There is no OUTPUT_PULLUP that I am aware of. Use INPUT_PULLUP for most things.

Add 3.3K (3.3V) or 4.7K (5V) external pullups for I2C. If you saw a 'scope trace with 10K I2C pullup on 5V system and even short wiring, the rise time is really slow. 4.7K is much quicker.

10K for external pullup works well for slow things, like buttons, switches.  If the wire lengths are longer, then 4.7K could be used as well, maybe even 1K if the wires are long.  If running on battery power, 10K is better as there is less current flow when the input is low.


body:
I almost always use external pull up/down resistors. I get more control over the value and can do more in hardware with them, whether that is debouncing buttons or using different types of transistors.

The easiest way to answer your question is to ask what you want to do. If you want active low, use pull up. Active high is pull down. Some transistors work much better with one or the other, so they could determine what you use. I2C uses weak pull ups to bias the transmission lines. If you need hardware filtering its much easier to design a filter with a known 25k resistor than with an unknown 20k-50k resistor. The list could go on an on but those are the most common situations I've run into.


message:
Replace 6 pin on/off switch on Power Bank with 3pin or 2pin?

I'm looking to finish up my project in a box and i'm using a battery bank to power the Leonardo micro pro and other components. The bank has a little on/off which on it which has 6 pins underneath.

To make the project neater I wanted to fit an on/off rocker switch to the project box making it look better and providing a more substantial switch. Mostly the on/off rocker switches come in 3 pin or 2 pin connections though. Is it possible for me to join it the 6 pin combining some of the pins in some way or not? I can also pick up another battery shield which has a 3 pin switch, again could I combine that with a 2pin if required or do I need to use a 3 pin rocker with it?

Some pictures of what i'm (or could be) using

[![Current power bank, on/off switch on the right side in the middle, 6 pins][1]][1]
(Current power bank, on/off switch on the right side in the middle, 6 pins)
[![Possible smaller power bank for my project with 3 pins on the on/off switch (bottom left side)][2]][2]
Possible smaller power bank for my project with 3 pins on the on/off switch (bottom left side)
[![Two pin rocker switch][3]][3]
Two pin rocker switch
[![Three pin, two way rocker switch][4]][4]
Three pin, two way rocker switch

  [1]: https://i.stack.imgur.com/KjfvR.jpg
  [2]: https://i.stack.imgur.com/KysLi.jpg
  [3]: https://i.stack.imgur.com/eINr9.jpg
  [4]: https://i.stack.imgur.com/QSTkE.jpg

body:
Looks like only 2 of the 6 pins are used. It's a simple on-off. The switch itself is a "Double Pole Double Throw", but the two poles are tied together to make it single pole (like a 3 pin switch), and one throw is ignored, making it 2-pin.

You can see on the underside of your board which pins are tied together with traces. Bridge those pin pairs to turn the board on.


message:
Not able to find right library for MPU9250

I am using an Arduino Uno and learning to use the motion sensor. Currently I was not able to find the library which looks simple and would like to get your suggestion. I found this https://github.com/hideakitai/MPU9250 library to be simple but don't know how to use it.

For example, take this code:-

    #include "MPU9250.h"

    MPU9250 mpu;

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

        Wire.begin();

        delay(2000);
        mpu.setup();
    }

    void loop()
    {
        static uint32_t prev_ms = millis();
        if ((millis() - prev_ms) > 16)
        {
            mpu.update();
            mpu.print();

            Serial.print("roll  (x-forward (north)) : ");
            Serial.println(mpu.getRoll());
            Serial.print("pitch (y-right (east))    : ");
            Serial.println(mpu.getPitch());
            Serial.print("yaw   (z-down (down))     : ");
            Serial.println(mpu.getYaw());

            prev_ms = millis();
        }
    }

Some values are not defined here, like registration code and input pins. I am not used to reading the documentation code so might need help in that.

body:
In the Arduino IDE, click on SKETCH > INCLUDE LIBRARY > MANAGE LIBRARIES.

[![enter image description here][1]][1]

Then, search for 9250, select the SparkFun one, and click INSTALL.

[![enter image description here][2]][2]

Finally, from the examples, choose the MPU9250BasicAHRS_I2C.

  [1]: https://i.stack.imgur.com/gBexC.png
  [2]: https://i.stack.imgur.com/8Le8b.png


message:
What is mean of 700,150 number?

if ((leftsensor >= 700) && (rightsensor >= 700))
       forward();
           else if((leftsensor <= 150) && (rightsensor <= 150))
       backward();
       else if((leftsensor <= 150) && (rightsensor >= 700))
       turnright();
       else if((leftsensor >= 700) && (rightsensor <= 150))
       turnleft();

body:
I have somewhat large experience in understanding people that use "bad" english as their secondary language. That's why I assume that even though the question you asked was "**What is mean of 700,150 number?**" the question you wanted to ask is "**What is meaning of numbers 700,150 in code below?**"

This was already answered by @MaximilianGerhardt in the comments.

If we assume that `leftsensor`is an integer value coming from `analogRead` then it's possible values are between 0 and 1023. The programmed created two arbitrary thresholds of values 700 and 150. Those values were probably calculated experimentally to negate signal noise, sensor imperfections and interference.


message:
Code causing Servo motor not to work!

My sketch is compiling and loading, but when the program runs, the Servo motor does not work. The buttons work, the LED light works, Piezo buzzer plays the melody, the Stepper motor works but not consistently. The Servo/Stepper motors and LED worked until I introduced the code for the Piezo buzzer to play a melody. I'm new to programming and want to learn from others in a constructive way. I hope this forum is a place where people at all levels of knowledge and experience want to lend a helping hand. Here is my sketch:

    #include <Stepper.h>
    #include <Servo.h>

    /*ARDUINO MOTOR SHIELD
     * The pin breakdown is as follows:
     * Function          Channel A   Channel B
     * Direction         Digital 12  Digital 13
     * Speed (PWM)       Digital 3   Digital 11
     * Brake             Digital 9   Digital 8
     * Current Sensing   Analog 0  Analog 1
     */

    const int stepsPerRevolution = 200;  // 1.8 deg. step angle(200 steps/360 deg. rev)
    const int dirChA = 12;     // assigning name "dirChA" to pin 12
    const int dirChB = 13;     // assigning name "dirChB" to pin 13
    const int pwmChA = 3;      // assigning name "pwmChA" to pin 3
    const int pwmChB = 11;     // assigning name "pwmChB" to pin 11
    const int brkChA = 9;      // assigning name "brkChA" to pin 9
    const int brkChB = 8;      // assigning name "brkChB" to pin 8

    const int srvoMtr = 10;    // assigning name "srvoMtr" to pin 10

    const int pButton1 = 4;    // assigning name "pButton1" to pin 4
    const int pButton2 = 5;    // assigning name "pButton2" to pin 5
    const int pButton3 = 6;    // assigning name "pButton3" to pin 6
    const int pButton4 = 7;    // assigning name "pButton4" to pin 7

    const int ledLight = 2;    // assigning name "ledLight" to pin 2

    Stepper myStepper(stepsPerRevolution, dirChA, dirChB);  // initialize the stepper library on pins 12 & 13
    Servo myServo;  // initialize the servo library to logical name myServo

    int pButton1State = 0;     // variable for reading the pButton1 state as LOW or HIGH
    int pButton2State = 0;     // variable for reading the pButton2 state as LOW or HIGH
    int pButton3State = 0;     // variable for reading the pButton3 state as LOW or HIGH
    int pButton4State = 0;     // variable for reading the pButton4 state as LOW or HIGH

    int pButtonFlag = 0;     // variable for when button 1 has been pressed and released

    int myServoPos = 0;      // variable for when servo has reached it's position
    int myServoFlag = 0;     // variable for servo when any of the 4 pButton are pressed

    int tonePin = A3;        //variable for buzzer

    void midi() {
        tone(tonePin, 233, 203.992851562);
        delay(226.658723958);
        delay(4.82252604167);
        tone(tonePin, 184, 412.325976562);
        delay(458.139973958);
        delay(4.82252604167);
        tone(tonePin, 184, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 155, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(236.303776042);
        tone(tonePin, 184, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 155, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(236.303776042);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(236.303776042);
        tone(tonePin, 233, 555.555);
        delay(617.283333333);
        delay(77.1604166667);
        tone(tonePin, 233, 203.992851562);
        delay(226.658723958);
        delay(4.82252604167);
        tone(tonePin, 184, 412.325976562);
        delay(458.139973958);
        delay(4.82252604167);
        tone(tonePin, 184, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 155, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(236.303776042);
        tone(tonePin, 184, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 155, 99.8262890625);
        delay(110.918098958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(4.82252604167);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(236.303776042);
        tone(tonePin, 184, 203.992851562);
        delay(226.658723958);
        delay(236.303776042);
        tone(tonePin, 233, 555.555);
    }

    void setup() {
    // Serial.begin(9600);   // initialize the serial port for messaging & troubleshooting

     // 1 Stepper Motor
     pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
     digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)

     pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
     digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)

     pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
     digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)

     pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
     digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)

     pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
     digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)

     pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
     digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)

     myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM

     // 4 Push Buttons
     pinMode(pButton1, INPUT);   // initialize pin 4 as an INPUT
     digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)

     pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
     digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)

     pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
     digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)

     pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
     digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)

     // 1 Led Light
     pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
     digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)
    }

    void loop() {
      //Read button state (pressed or not pressed?)
      pButton1State = digitalRead(pButton1);   // read the state of pButton1 as LOW or HIGH
      pButton2State = digitalRead(pButton2);   // read the state of pButton2 as LOW or HIGH
      pButton3State = digitalRead(pButton3);   // read the state of pButton3 as LOW or HIGH
      pButton4State = digitalRead(pButton4);   // read the state of pButton4 as LOW or HIGH

      // check if the pushbutton is pressed. If it is, the pbuttonState is HIGH:
      if (pButton1State == HIGH) {
         pButtonFlag=1;  // change pButton1Flag variable
      }
         if (pButtonFlag == 1){
            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(40);          // step forward 40 steps to position 1
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    //disable power to stepper

            myServoFlag=1;             // change ServoFlag variable to dispense chocolate

            if (myServoFlag == 1){
               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                   delay(15);                    // waits 15 milliseconds for the servo to reach the position
               }
               myServo.detach();   // detaches the servo library from pin 10
               delay(2000); // hold position OPEN for 2 sec

               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
               }
               myServo.detach();   // detaches the servo library from pin 10
            }

            myServoFlag=0;         // changes myServoFlag value back to zero (0)
            digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
            midi();

            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(-40);          // step backward 40 steps to position 0
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    // disable power to stepper

            digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
            digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

            pButtonFlag=0;                // changes pButtonFlat value back to zero (0)
            delay(2000);
         }

      // position 2
      if (pButton2State == HIGH) {
         pButtonFlag=1;  // change pButtonFlag variable
      }
         if (pButtonFlag == 1){
            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(80);          // step forward 80 steps to position 2
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    //disable power to stepper
            delay(2000);

            myServoFlag=1;    // change ServoFlag variable to dispense chocolate

            if (myServoFlag == 1){
               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                   delay(15);                    // waits 15 milliseconds for the servo to reach the position
               }
               myServo.detach();   // detaches the servo library from pin 10
               delay(2000);

               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
               for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
               }
               myServo.detach();   // detaches the servo library from pin 10
            }
            myServoFlag=0;                // changes myServoFlag value back to zero (0)
            digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed
            midi();

            digitalWrite(pwmChA, HIGH);   // enable power to stepper
            digitalWrite(pwmChB, HIGH);   // enable power to stepper
            myStepper.step(-80);          // step backward 80 steps to position 0
            digitalWrite(pwmChA, LOW);    // disable power to stepper
            digitalWrite(pwmChB, LOW);    //disable power to stepper

            digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
            digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

            pButtonFlag=0;   // changes pButton2Flag value back to zero (0)
            delay(2000);
        }

        // position 3
        if (pButton3State == HIGH) {
           pButtonFlag=1;   // change pButtonFlag variable
        }
           if (pButtonFlag == 1){
              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(120);          // step forward 120 steps to position 3
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    //disable power to stepper
              delay(2000);

              myServoFlag=1;   // change ServoFlag variable to dispense chocolate

              if (myServoFlag == 1){
                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                     myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                     delay(15);                    // waits 3 sec for the servo to reach the position
                 }
                 myServo.detach();   // detaches the servo library from pin 10
                 delay(2000);

                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
                 }
                 myServo.detach();   // detaches the servo library from pin 10
              }
              myServoFlag=0;                // changes myServoFlag value back to zero (0)
              digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
              midi();

              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(-120);         // step backward 120 steps to position 0
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    // disable power to stepper

              digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
              digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

              pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
              delay(2000);
         }
        // position 4
        if (pButton4State == HIGH) {
           pButtonFlag=1;   // change pButtonFlag variable
        }
           if (pButtonFlag == 1){
              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(160);          // step forward 160 steps to position 3
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    //disable power to stepper
              delay(2000);

              myServoFlag=1;   // change ServoFlag variable to dispense chocolate
              Serial.println("\nServo Flag = 1 - Dispense Chocolate");

              if (myServoFlag == 1){
                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                     myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                     delay(15);                    // waits 3 sec for the servo to reach the position
                 }
                 myServo.detach();   // detaches the servo library from pin 10
                 delay(2000);

                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
                 for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
                   myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
                   delay(15);
                 }
                 myServo.detach();   // detaches the servo library from pin 10
              }
              myServoFlag=0;   // changes myServoFlag value back to zero (0)
              digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
              midi();

              digitalWrite(pwmChA, HIGH);   // enable power to stepper
              digitalWrite(pwmChB, HIGH);   // enable power to stepper
              myStepper.step(-160);         // step backward 160 steps to position 0
              digitalWrite(pwmChA, LOW);    // disable power to stepper
              digitalWrite(pwmChB, LOW);    // disable power to stepper

              digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
              digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

              pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
              delay(2000);
           }
    }

body:
As already reported in the comments, the `Tone` library uses Timer2 an hardware module of the Atmega328P microcontroller, which is also in charge of generating the PWM signal on pins 3 and 11.
As pins 3 and 11 are both used by your code to pilot the servo motor, it should be of no surprise the motor starts to behave erratically once you added the code to play tones on the buzzer.

A solution would be not to use the PWM pins 3 and 11 as PWM (you can still use those, just not to generate PWM signals)

That is clearly reported in the docs:

>  PWM frequencies are tied together in pairs of pins. If one in a pair is changed, the other is also changed to match:
>
>  - Pins 5 and 6 are paired on timer0
>  - Pins 9 and 10 are paired on timer1
>  - Pins 3 and 11 are paired on timer2

And also:

> Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).


message:
What functions are disabled with noInterrupts()?

The Arduino page for [`noInterrupts()`](https://www.arduino.cc/reference/en/language/functions/interrupts/nointerrupts/) says:

> Some functions will not work while interrupts are disabled, and incoming communication may be ignored.

While it may not be possible to give a complete listing of what would be disabled, having an incomplete list of functions which definitely are disabled would be useful.

I was thinking of calling a DHT sensor library which internally uses `millis()` while interrupts were disabled to avoid both bit banging and servicing interrupts simultaneously if possible (the interrupt would hold and be processed after).

Which functions are definitely disabled when interrupts are disabled?

What about incoming communication? My guess is that it would be slightly worse on the ATmega32U4 (eg Leonardo) as the one processor does USB and everything else as well.

body:
From what I found turning off interrupts will definitely disable incrementing values of `micros()` and `millis()` This means that also every method that uses them like `delay()` will also not work correctly.

Of course manually attached interrupts using `attachInterrupt()` will also not work as intended.

According to comments by @Juraj Things that also will not work are Serial interrupts. Also libraries like `Wire` require interrupts for their logic.

EDIT: @EdgarBonet You are right, I removed incorrect info.


body:
SPI.transfer() also uses interrupts - but you can 'manually' wait them out to know when to proceed.  For example, I had a program where I needed to send out 45 bytes in 50uS (20KHz refresh rate). During testing, I kept seeing jitters in the datastream - about every 4uS if I recall. The micros() interrupt time. Turned off interrupts during the data burst and the jitter went away. So the command to send out a byte looked this, repeated 45 times (no for loop):

    spdr = byte0; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
    spdr = byte1; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
    spdr = byte2; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
    :
    spdr = byte43; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
    spdr = byte44; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;

So the transfer needed 17 clocks with the SPI clock set to 8 MHz.
After the transfer I turned interrupts back on to wait for the next incoming signal edge to send out the next burst.


message:
How can big Arduino programs be analyzed easily?

I have an Arduino project code, but the problem is it has multiple functions and flow of control.

How could I convert this code into flowchart or control flow diagram?

Any software or online website?

body:
Although there are programs who can automatically make some documentation (like doxygen), I haven't seen any software so far that can make USEFUL flowcharts or diagrams. The main reason is that such software does not know which are the important parts and which are not.

To do it manually:

Assuming your code contains multiple files, use an UML (Unified Modeling Language) application. Than if classes are used, you can easily port them to UML, otherwise assume each (.c) file is a 'class'.

By adding properties/fields and methods (functions) and drawing dependencies between the classes/files you get a good idea how everything works together.


message:
Same output on displays with different I2C-addresses (AdaFruit library, ESP32)

I've got two displays hooked up to a ESP32 via I2C and I'm using the AdaFruit library. All handling display output is packed in a own library. As I was testing I only had one display set up and everything looked fine. Now, in my actual setup with two displays, I only get the output of the first display on both screens. The displays are running on the same I2C-bus, different addresses are set. I also ran a address/portscanner that confirmed the different addresses (0x3C and 0x3D).

I have used separate displays with the AdaFruit library in such a setup before, but only on an Arduino uno and without having code moved to own libraries. So I can't tell if the ESP32 or having multiple files is messing things up or I'm missing something.

Here are parts of code in the cpp-file I used to initialize the displays and some functions I call:

    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include <Wire.h>
    #include <gfxfont.h>
    #include <SPI.h>
    #include "DisplayOut.h"
    #include "Game.h"

     /* -------------esp32 Pin setup --------------------- */
     const byte displayData = 21; // I2C SDA
     const byte displayClock = 23; // I2C SCL
     /* --------------------------------------------------- */

    // Define OLED
    #define OLED_RESET displayData
    Adafruit_SSD1306 display1(OLED_RESET);
    Adafruit_SSD1306 display2(OLED_RESET);

    /* some variables */

    void DisplayOutClass::init()
    {
     // Initialize each display with i2c-address

     display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
     display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
     display1.setTextWrap(false);
     display2.setTextWrap(false);
    }

    void DisplayOutClass::scorePlayer1(int score1)
    {
     display1.clearDisplay();

     if (gameMode == 2)
     {
      display1.clearDisplay();
      display1.setCursor(0, 0);
      display1.setTextSize(2);
      display1.setTextColor(WHITE);
      display1.print(playerName[player1]);
     }

     display1.setTextSize(4);
     display1.setTextColor(WHITE);
     display1.setCursor(getCenteredPosX(3, String(score1)), 24);
     display1.print(score1);
    }

    void DisplayOutClass::scorePlayer2(int score2)
    {
     display2.clearDisplay();

     if (gameMode == 2)
     {
      display2.clearDisplay();
      display2.setCursor(0, 0);
      display2.setTextSize(2);
      display2.setTextColor(WHITE);
      display2.print(playerName[player2]);
     }

     display2.setTextSize(4);
     display2.setTextColor(WHITE);
     display2.setCursor(getCenteredPosX(3, String(score2)), 24);
     display2.print(score2);
    }

    /* some more Functions */

    DisplayOutClass DisplayOut;

I didn't post the complete code or the header file, because it exceeds a few hundred lines. But this should show how the I2C-addresses are used. If necessary, I of course can post the rest of the code.

My next approach would be either trying the U8g2 library or trying start a second I2C bus. Since I already have a finished circuit board, so this would be my least preferred option.

body:
Try the [new constructors](https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.h#L115) (old ones are deprecated):

```
Wire.begin(21, 23); // SDA, SCL

Adafruit_SSD1306 display1(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT);
Adafruit_SSD1306 display2(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT);

display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);

```


message:
Issues with I2C and Wire.Available()

I am working on a project which requires communication from an Arduino Due (*Master*) and an FDC2214Q1 C to D IC (*Slave*), but there is some variability as to whether the code works or not depending on seemingly random variables.

I have narrowed the issue to the function I am using to read 2 bytes from the *slave*. The code is pretty standard, and is as follows:

    // Read 2 byte from the FDC at 'address'
    uint16_t FDC2214::read16FDC(uint16_t address) {

        uint16_t data;

        Wire.beginTransmission(_i2caddr);
        Wire.write(address);
        Wire.endTransmission(false); //restart
        Wire.requestFrom(_i2caddr, (uint8_t) 2);

        while (!Wire.available());
     data = Wire.read();
     data <<= 8;

        while (!Wire.available());
     data |= Wire.read();
     Wire.endTransmission(true); //end

        return data;
    }

The code seems to get hung up sometimes on **while (!Wire.available())** and if I simply remove that step, I never get the correct Device ID.

However, if I simply unplug the DUE and close the Serial Monitor and replug in and upload, it works. I just kind of upload and disconnect a few times and open and close the Serial Monitor and sometimes it works great, other times it gets hung up?

Any ideas what could be causing such and issue?

Code based on this library: [https://github.com/zharijs/FDC2214/blob/master/src/FDC2214.cpp][1]

  [1]: https://github.com/zharijs/FDC2214/blob/master/src/FDC2214.cpp

________________________________________________________________________

***Final code that has been working, removes need for While loop:***

    uint16_t FDC2214::read16FDC(uint16_t address) {

        uint16_t data;
      Wire.beginTransmission(_i2caddr); //queuing the slave address
      Wire.write(address); //queuing the register address/pointing regsiter
      byte busStatus = Wire.endTransmission(); //transmit all queued data and bring STOP condition on I2C Bus
      if(busStatus != 0x00)
      {
         Serial.print("Transmission Error....!");//transmissiion error wait here for ever
         while(1);
      }

      Wire.requestFrom(_i2caddr, (uint8_t) 2);     //this is looping code; when 2-byte has arrived, the loop terminates
      data = Wire.read();   //read the first byte from FIFO Buffer
      data = (data <<8)| Wire.read();   //16-bit data is formed
      Wire.endTransmission(true); //end
      return data;
    }

body:
Adafruit tells to avoid the Arduino Due. One of the reasons is the I2C bus. Can you use an other Arduino board? For example one of the MKR boards with a SAMD21 processor.

The Due has pullup resistors on the board for SDA and SCL which are too low in value. Sometimes the I2C bus with SDA and SCL works, but sometimes it does not work at all. Perhaps you are able to remove the pullup resistors at SDA and SCL from the board.

If possible use Wire1 with SDA1 and SCL1. Those have no pullup resistors at all, so you need to add 4k7 pullup resistors to 3.3V. When you use a library, you might have to change the library to use "Wire1" instead of "Wire".

You need to remove these, they are not doing something:

    while (!Wire.available());    <- not doing something

Remove the [Wire.endTransmission][1] at the end.

    Wire.endTransmission(true);   <- remove this
    return data;

That library does not use the Wire library in a proper way.

----------

The pullup resistors are 1k5 or sometimes 1k and are located in the upper-right corner, near pin 20 and 21. A value of 1k5 should be okay, when there are no other pullup resistors. When you board has 1k resistors, then I suggest to remove them.

[![photo of pullup resistors][2]][2]
[![the pullup resistors in the schematic][3]][3]

Removing them is possible with a soldering iron and a big blob of solder. Check if the board is clean afterwards, for example with a magnifier. Avoid overheating your expensive Arduino Due board.

The I2C bus needs pullup resistors to work. A normal value is 4k7. Sometimes there are already 10k pullup resistors on a sensor module.

If the I2C has problems, start by using short seperate wires for SDA and SCL. When a cable is used for the I2C bus, then the cable is probably the problem and not the pullup resistors.

  [1]: https://www.arduino.cc/en/Reference/WireEndTransmission
  [2]: https://i.stack.imgur.com/RkDxQ.jpg
  [3]: https://i.stack.imgur.com/TDatW.png


message:
SPI Connections to DAC

I'm hoping to construct a feedback loop for a laser using an Chipkit UC32 and an analog-digitial converter ( the one of I have is an AD5780 evaluation board). I've been reading through [Digilint's ][1] SPI library but I admit I am pretty lost.

( I believe this is on topic to Arduino because I am using an Arduino API. The micro-controller I use is basically an Arduino so I see no difference. )

 I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from [here][2], I am just using the `digitalWrite`command which is basically binary. How do transfer something more complicated to have the DAC convert it?

Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

  [1]: https://reference.digilentinc.com/learn/fundamentals/communication-protocols/spi/start
  [2]: https://core-electronics.com.au/tutorials/spi-arduino-tutorial.html

body:
> I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?

SPI is a communication *protocol*.  It uses digital signals, coupled with *time*, to transfer information.

To use DSPI you need to first define an SPI object

    DSPI0 SPI;

From then on it's the same as using the Arduino SPI library.

Start it

    SPI.begin();

Then transfer the correct commands (found in the DAC datasheet) to set the voltage of the output

    digitalWrite(10, LOW);
    SPI.transfer(0x43);
    SPI.transfer(0x1A);
    digitalWrite(10, HIGH);

The values there are just examples. The 10 is the chip select pin for the DAC, and the values used in the transfers (however many are needed) need to be found in the datasheet.

If you only want to use the pins associated with DSPI0 you can use the SPI library instead (which only supports one SPI channel - the uC32 has two), in which case it is identical to working with the Arduino SPI library.

> Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

You don't. DACs are DACs and ADCs are ADCs. They aren't interchangeable.

For ADC functionality just use any of pins A0 through A11 and the `analogRead()` function.


message:
28 BYJ stepper motor runs faster using delay() and little slower using millis(), why?

I'm working to develop a code for the stepper motor to use it in a project. And since using delay() isn't as efficient as millis(). So I first developed the code that use delay with 1ms delay between the steps which is the fastest I could do with this stepper motor.

Then I developed similar code using millis() with same 1ms delay but it didn't feel as smooth/fast as the one with delay() function.

So what's the reason for that?

These are the code:

1. With delay():

            void clockwise(void){
                digitalWrite(in4, HIGH);
                digitalWrite(in3, LOW);
                digitalWrite(in2, LOW);
                digitalWrite(in1, LOW);
            delay(1);
                digitalWrite(in4, HIGH);
                digitalWrite(in3, HIGH);
                digitalWrite(in2, LOW);
                digitalWrite(in1, LOW);
            delay(1);
                digitalWrite(in4, LOW);
                digitalWrite(in3, HIGH);
                digitalWrite(in2, LOW);
                digitalWrite(in1, LOW);
            delay(1);
                digitalWrite(in4, LOW);
                digitalWrite(in3, HIGH);
                digitalWrite(in2, HIGH);
                digitalWrite(in1, LOW);
            delay(1);
                digitalWrite(in4, LOW);
                digitalWrite(in3, LOW);
                digitalWrite(in2, HIGH);
                digitalWrite(in1, LOW);
            delay(1);
                digitalWrite(in4, LOW);
                digitalWrite(in3, LOW);
                digitalWrite(in2, HIGH);
                digitalWrite(in1, HIGH);
            delay(1);
                digitalWrite(in4, LOW);
                digitalWrite(in3, LOW);
                digitalWrite(in2, LOW);
                digitalWrite(in1, HIGH);
            delay(1);
                digitalWrite(in4, HIGH);
                digitalWrite(in3, LOW);
                digitalWrite(in2, LOW);
                digitalWrite(in1, HIGH);
            delay(1);
        }

2. With millis():

          void stepper_run_cw(void){
          stepper_step_cw(1,0,0,0,1);
          stepper_step_cw(1,1,0,0,1);
          stepper_step_cw(0,1,0,0,1);
          stepper_step_cw(0,1,1,0,1);
          stepper_step_cw(0,0,1,0,1);
          stepper_step_cw(0,0,1,1,1);
          stepper_step_cw(0,0,0,1,1);
          stepper_step_cw(1,0,0,1,1);
        }

        void stepper_step_cw(uint8_t m_in1, uint8_t m_in2, uint8_t m_in3, uint8_t m_in4, uint8_t delay_time){
          if (!stepper_run){
            digitalWrite(in1, m_in1);
            digitalWrite(in2, m_in2);
            digitalWrite(in3, m_in3);
            digitalWrite(in4, m_in4);
            stepper_start = millis();
            stepper_run = 1;
          }

          if(stepper_run){
            stepper_current = millis();
            if(stepper_current - stepper_start >= delay_time){
              stepper_run = 0;
            }
          }
        }

body:
Maybe for the second function you want something like this:

     void stepper_run_cw(void){
      stepper_step_cw(1,0,0,0,1);
      stepper_step_cw(1,1,0,0,1);
      stepper_step_cw(0,1,0,0,1);
      stepper_step_cw(0,1,1,0,1);
      stepper_step_cw(0,0,1,0,1);
      stepper_step_cw(0,0,1,1,1);
      stepper_step_cw(0,0,0,1,1);
      stepper_step_cw(1,0,0,1,1);
    }

    void stepper_step_cw(uint8_t m_in1, uint8_t m_in2, uint8_t m_in3, uint8_t m_in4, uint8_t delay_time){
      unsigned long temp, i;
      for (i=0;i<delay_time;i++){
        temp = millis();
        while (temp == millis){};//wait for millis to change
      }
        digitalWrite(in1, m_in1);
        digitalWrite(in2, m_in2);
        digitalWrite(in3, m_in3);
        digitalWrite(in4, m_in4);
    }
This code is also avoiding the millis overflow issue if you run your board for a long time.

Still, apart for a improved timing, there is no gain in using millis(), you still have to wait for millis to change, you might want to use a timer interrupt to do the job in background.


body:
After working on developing the function couple times, I got a way with this function and runs smoothly too :)

Hope anyone find it useful.

    // this library is for the 28BYJ stepper motor

      #define in1 6
      #define in2 7
      #define in3 8
      #define in4 9

      // blink
      unsigned long blink_start_millis;
      unsigned long blink_current_millis;
      unsigned long blink_period = 100;

      uint8_t stepper_masks[] = {0x80,0xc0,0x40,0x60,0x20,0x30,0x10,0x90};
      int8_t s=0;
      uint32_t stepper_start;
      uint32_t stepper_current;
      uint32_t stepper_period;
      byte stepper_run;

      void blink_pin13(void);
      void stepper_step(uint8_t *mask, uint8_t delay_time, uint8_t dir);

      void setup() {
        Serial.begin(9600);// put your setup code here, to run once:
        for(byte i=in1;i<=in4;i++){
          pinMode(i,OUTPUT);}

        pinMode(13,OUTPUT);

      }

      void loop() {
       stepper_step(stepper_masks,1,0);
        blink_pin13();

      }

      void blink_pin13(void){
          blink_current_millis = millis();
          if(blink_current_millis - blink_start_millis >= blink_period){
          digitalWrite(13, !digitalRead(13));
          blink_start_millis = blink_current_millis;
        }
      }

      void stepper_step(uint8_t *mask, uint8_t delay_time, uint8_t dir){
        if (!stepper_run){
          for(byte i=6;i<10;i++){
            digitalWrite(i, 0<(mask[s]&0x80>>i-6));
          }
          if(!dir){s++;if(s>7)s=0;}
          else {s--;if(s<0)s=7;}
          stepper_start = millis();
          stepper_run = 1;
        }

        if(stepper_run){
          stepper_current = millis();
          if(stepper_current - stepper_start >= delay_time){
            stepper_run = 0;
          }
        }
      }


message:
How to converte EPOCH time into time and date on Arduino?

I have a question on how to convert EPOCH timestamps, which I receive as char*, into `DD.MM.YYYY` and `HH:MM:SS` format separately?

Here is more information on my Arduino project: The Arduino is receiving through an ESP8266 module three different EPOCH timestamps from the OpenWeatherMap API for sunrise, sunset and the current date. I want these 3 pieces of information to be displayed on a 1,3" OLED display, the date in `DD.MM.YYYY` and the other two timestamps in `HH:MM` format.

I was looking in several time libraries like TimeLib and RTC for a solution, but I wasn't able to find one.

That's my code fragment on receiving the timestamps:

    DynamicJsonBuffer jsonBuffer(4096);
    JsonObject& root = jsonBuffer.parseObject(client);

    const char* date = root["dt"];
    const char* sunrise = root["sys"]["sunrise"];
    const char* sunset = root["sys"]["sunset"];

How to convert those timestamps?

body:
Epoch are seconds from 1970-01-01. Get it from JSON as unsigned long. They are a number in the returned JSON (no `"`)

from https://openweathermap.org/ doc:

`"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},`

----------

to convert it to string with TimeLib.h:

    #include <TimeLib.h>
    #include <ArduinoJson.h>

    void setup() {

      Serial.begin(115200);

      const char* json = "{\"country\":\"JP\",\"sunrise\":1369769524,\"sunset\":1369821049}";

      DynamicJsonBuffer jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(json);

      unsigned long t = root["sunrise"];

      char buff[32];
      sprintf(buff, "d.d.d d:d:d", day(t), month(t), year(t), hour(t), minute(t), second(t));

      Serial.println(buff);
    }

    void loop() {
    }


body:
I'm was having a similar challenge with my custom Wifi library `m_wifi..cpp` for the ESP32 ( [see here](https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries#readme) )

After reading and googling I ended up coding the solution below:

    ESP32Time rtc(0);
    long int epochTime;
    ...

    rtc.setTime( epochTime  );
    Serial.println( rtc.getDateTime(true) );