message:
exit status 1 - expected primary-expression before '(' token

When I try to compile the following sketch, the compiler returns the error "exit status 1 - expected primary-expression before '(' token", and highlights "midi();" in my code.

Here is my sketch:

    #include <Stepper.h>
    #include <Servo.h>
    #include <MIDI.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 = 1;     // assigning name "tonePin" to pin 1

    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() {
    //Serial.begin(31250);   // initialize the serial port for messaging & troubleshooting
     //Serial.println("Running UNO Setup");

     // 1 Stepper Motor
    // Serial.println("\nStepper Motor");
     pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
     digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)
    // Serial.println("Channel A Dir - PIN 12 - set as Output & Low");
     pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
     digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)
    // Serial.println("Channel B Dir - PIN 13 - set as Output & Low");
     pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
     digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)
    // Serial.println("Channel A PWM - PIN 3 - set as Output & Low");
     pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
     digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)
    // Serial.println("Channel B PWM - PIN 11 - set as Output & Low");
     pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
     digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)
    // Serial.println("Channel A Brake - PIN 9 - set as Output & Low");
     pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
     digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)
    // Serial.println("Channel B Brake - PIN 8 - set as Output & Low");

     myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM
    // Serial.println("\nSet Stepper Speed to 60 RPM");

     // 4 Push Buttons
    // Serial.println("\n4 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)
    // Serial.println("Push Button 1 - PIN 4 - set a Input & Low");
     pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
     digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
    // Serial.println("Push Button 2 - PIN 5 - set a Input & Low");
     pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
     digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
    // Serial.println("Push Button 3 - PIN 6 - set a Input & Low");
     pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
     digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)
    // Serial.println("Push Button 4 - PIN 7 - set a Input & Low");

     // 1 Led Light
    // Serial.println("\nLED Light");
     pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
     digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)
    // Serial.println("LED Light - PIN 2 - set to Output & Low");

     // 1 Piezo Speaker
    midi();
    // Serial.println("Piezo Speaker Inialized");
    }

    void loop() {
      //Read button state (pressed or not pressed?)
    //  Serial.println("\nReading button 1 thru 4 states - high or low");
      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) {
     //    Serial.println("\nPush Button 1 Pressed");
         pButtonFlag=1;  // change pButton1Flag variable
     //    Serial.println("Button 1 flag = 1");
      }
         if (pButtonFlag == 1){
     //       Serial.println("Stepper Start - Forward 40 steps");
            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
     //       Serial.println("Stepper Stop");
            delay(2000);

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

            if (myServoFlag == 1){
     //          Serial.println("Servo Start");
               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
     //          Serial.println("Attach 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
     //          Serial.println("\nDetach Servo Library to PIN 10");
     //          Serial.println("Servo Stop");
     //          Serial.println("Hold position OPEN for 3 sec");
               delay(2000);

               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
     //          Serial.println("Attach 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
     //          Serial.println("\nDetach Servo Library to PIN 10");
     //          Serial.println("Servo Stop - Awaiting next selection");
            }
            myServoFlag=0;                // changes myServoFlag value back to zero (0)
     //       Serial.println("Servo Flag = 0");

            digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
     //       Serial.println("\nLed Light ON");
     //       Serial.println("\nPlay Tones");

            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(3000);

    //        Serial.println("Stepper Start - Return to position zero");
            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
    //        Serial.println("Stepper Stop");

            digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
    //        Serial.println("\nReset Button 1 - PIN 4 - Low");
            digitalWrite(ledLight, LOW);   //turns off light to indicate the sequence is completed
    //        Serial.println("\nLed Light OFF");

            pButtonFlag=0;                // changes pButtonFlat value back to zero (0)
    //        Serial.println("\Button 1 Flag = 0");
            delay(2000);
         }

      // position 2
      if (pButton2State == HIGH) {
    //     Serial.println("\nPush Button 2 Pressed");
         pButtonFlag=1;  // change pButtonFlag variable
    //     Serial.println("Button 2 flag = 1");
      }
         if (pButtonFlag == 1){
    //        Serial.println("Stepper Start - Forward 80 steps");
            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
    //        Serial.println("Stepper Stop");
            delay(2000);

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

            if (myServoFlag == 1){
    //           Serial.println("Servo Start");
               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
    //           Serial.println("Attach 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
    //           Serial.println("\nDetach Servo Library to PIN 10");
    //           Serial.println("Servo Stop");
    //           Serial.println("Hold position OPEN for 2 sec");
               delay(2000);

               myServo.attach(srvoMtr);   // attaches the servo library to pin 10
    //           Serial.println("Attach 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
    //           Serial.println("\nDetach Servo Library to PIN 10");
    //           Serial.println("Servo Stop - Awaiting next selection");
            }
            myServoFlag=0;                // changes myServoFlag value back to zero (0)
    //        Serial.println("Servo Flag = 0");

            digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed
    //        Serial.println("\nLed Light ON");
            delay(3000);

    //        Serial.println("Stepper Start - Return to position zero");
            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
    //        Serial.println("Stepper Stop");

            digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
    //        Serial.println("\nReset Button 2 - PIN 5 - Low");
            digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
    //        Serial.println("\nLed Light OFF");

            pButtonFlag=0;   // changes pButton2Flag value back to zero (0)
    //        Serial.println("\Button 2 Flag = 0");
            delay(2000);
        }

        // position 3
        if (pButton3State == HIGH) {
    //       Serial.println("\nPush Button 3 Pressed");
           pButtonFlag=1;   // change pButtonFlag variable
    //       Serial.println("Button 3 flag = 1");
        }
           if (pButtonFlag == 1){
    //          Serial.println("Stepper Start - Forward 120 steps");
              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
    //          Serial.println("Stepper Stop");
              delay(2000);

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

              if (myServoFlag == 1){
    //            Serial.println("Servo Start");
                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
    //             Serial.println("Attach 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
    //             Serial.println("\nDetach Servo Library to PIN 10");
    //             Serial.println("Servo Stop");
    //             Serial.println("Hold position OPEN for 2 sec");
                 delay(2000);

                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
    //             Serial.println("Attach 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
    //             Serial.println("\nDetach Servo Library to PIN 10");
    //             Serial.println("Servo Stop - Awaiting next selection");
              }
              myServoFlag=0;                // changes myServoFlag value back to zero (0)
    //          Serial.println("Servo Flag = 0");

              digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
    //          Serial.println("\nLed Light ON");
              delay(3000);

    //          Serial.println("Stepper Start - Return to position zero");
              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
    //          Serial.println("Stepper Stop");

              digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
    //          Serial.println("\nReset Button 3 - PIN 6 - Low");
              digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
    //          Serial.println("\nLed Light OFF");

              pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
    //          Serial.println("\Button 3 Flag = 0");
              delay(2000);
         }
        // position 4
        if (pButton4State == HIGH) {
    //       Serial.println("\nPush Button 4 Pressed");
           pButtonFlag=1;   // change pButtonFlag variable
    //       Serial.println("Button 3 flag = 1");
        }
           if (pButtonFlag == 1){
    //          Serial.println("Stepper Start - Forward 160 steps");
              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
    //          Serial.println("Stepper Stop");
              delay(2000);

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

              if (myServoFlag == 1){
    //             Serial.println("Servo Start");
                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
    //             Serial.println("Attach 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
    //             Serial.println("\nDetach Servo Library to PIN 10");
    //             Serial.println("Servo Stop");
    //             Serial.println("Hold position OPEN for 2 sec");
                 delay(2000);

                 myServo.attach(srvoMtr);   // attaches the servo library to pin 10
    //             Serial.println("Attach 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
    //             Serial.println("\nDetach Servo Library to PIN 10");
    //             Serial.println("Servo Stop - Awaiting next selection");
              }
              myServoFlag=0;   // changes myServoFlag value back to zero (0)
    //          Serial.println("Servo Flag = 0");

              digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
    //          Serial.println("\nLed Light ON");
              delay(3000);

    //          Serial.println("Stepper Start - Return to position zero");
              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
    //          Serial.println("Stepper Stop");

              digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
    //          Serial.println("\nReset Button 3 - PIN 6 - Low");
              digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
    //          Serial.println("\nLed Light OFF");

              pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
    //          Serial.println("\Button 4 Flag = 0");
              delay(2000);
           }
    }

I'm including the "midi();" function to play a short melody through an attached Piezo speaker (buzzer) once the led is activated.

When I compile the midi code on its own in a separate sketch it works (see below).

    int tonePin = 1;
    void setup() {
     midi ();
    }

    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);

       }

    void loop() {
      // put your main code here, to run repeatedly:

    }

I've searched the Internet for an answer, but have found none that relate directly with what I'm attempting to make work. Can you help me, please?

body:
You have tried to define `void midi() {...}` inside the `loop()` function. But you cannot nest function definitions. Your definition (implementation) of `midi()` should be outside any other function.

Like this:

    #include <Stepper.h>
    #include <Servo.h>
    #include <MIDI.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 = 1;     // assigning name "tonePin" to pin 1

    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 midiplay() {
      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(31250);   // initialize the serial port for messaging & troubleshooting
      //Serial.println("Running UNO Setup");

      // 1 Stepper Motor
      // Serial.println("\nStepper Motor");
      pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
      digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)
      // Serial.println("Channel A Dir - PIN 12 - set as Output & Low");
      pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
      digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)
      // Serial.println("Channel B Dir - PIN 13 - set as Output & Low");
      pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
      digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)
      // Serial.println("Channel A PWM - PIN 3 - set as Output & Low");
      pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
      digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)
      // Serial.println("Channel B PWM - PIN 11 - set as Output & Low");
      pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
      digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)
      // Serial.println("Channel A Brake - PIN 9 - set as Output & Low");
      pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
      digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)
      // Serial.println("Channel B Brake - PIN 8 - set as Output & Low");

      myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM
      // Serial.println("\nSet Stepper Speed to 60 RPM");

      // 4 Push Buttons
      // Serial.println("\n4 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)
      // Serial.println("Push Button 1 - PIN 4 - set a Input & Low");
      pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
      digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
      // Serial.println("Push Button 2 - PIN 5 - set a Input & Low");
      pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
      digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
      // Serial.println("Push Button 3 - PIN 6 - set a Input & Low");
      pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
      digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)
      // Serial.println("Push Button 4 - PIN 7 - set a Input & Low");

      // 1 Led Light
      // Serial.println("\nLED Light");
      pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
      digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)
      // Serial.println("LED Light - PIN 2 - set to Output & Low");

      // 1 Piezo Speaker
      midiplay();
      // Serial.println("Piezo Speaker Inialized");
    }

    void loop() {
      //Read button state (pressed or not pressed?)
      //  Serial.println("\nReading button 1 thru 4 states - high or low");
      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) {
        //    Serial.println("\nPush Button 1 Pressed");
        pButtonFlag = 1; // change pButton1Flag variable
        //    Serial.println("Button 1 flag = 1");
      }
      if (pButtonFlag == 1) {
        //       Serial.println("Stepper Start - Forward 40 steps");
        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
        //       Serial.println("Stepper Stop");
        delay(2000);

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

        if (myServoFlag == 1) {
          //          Serial.println("Servo Start");
          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //          Serial.println("Attach 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
          //          Serial.println("\nDetach Servo Library to PIN 10");
          //          Serial.println("Servo Stop");
          //          Serial.println("Hold position OPEN for 3 sec");
          delay(2000);

          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //          Serial.println("Attach 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
          //          Serial.println("\nDetach Servo Library to PIN 10");
          //          Serial.println("Servo Stop - Awaiting next selection");
        }
        myServoFlag = 0;              // changes myServoFlag value back to zero (0)
        //       Serial.println("Servo Flag = 0");

        digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
        //       Serial.println("\nLed Light ON");
        //       Serial.println("\nPlay Tones");

        midiplay();
        delay(3000);

        //        Serial.println("Stepper Start - Return to position zero");
        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
        //        Serial.println("Stepper Stop");

        digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
        //        Serial.println("\nReset Button 1 - PIN 4 - Low");
        digitalWrite(ledLight, LOW);   //turns off light to indicate the sequence is completed
        //        Serial.println("\nLed Light OFF");

        pButtonFlag = 0;              // changes pButtonFlat value back to zero (0)
        //        Serial.println("\Button 1 Flag = 0");
        delay(2000);
      }

      // position 2
      if (pButton2State == HIGH) {
        //     Serial.println("\nPush Button 2 Pressed");
        pButtonFlag = 1; // change pButtonFlag variable
        //     Serial.println("Button 2 flag = 1");
      }
      if (pButtonFlag == 1) {
        //        Serial.println("Stepper Start - Forward 80 steps");
        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
        //        Serial.println("Stepper Stop");
        delay(2000);

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

        if (myServoFlag == 1) {
          //           Serial.println("Servo Start");
          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //           Serial.println("Attach 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
          //           Serial.println("\nDetach Servo Library to PIN 10");
          //           Serial.println("Servo Stop");
          //           Serial.println("Hold position OPEN for 2 sec");
          delay(2000);

          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //           Serial.println("Attach 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
          //           Serial.println("\nDetach Servo Library to PIN 10");
          //           Serial.println("Servo Stop - Awaiting next selection");
        }
        myServoFlag = 0;              // changes myServoFlag value back to zero (0)
        //        Serial.println("Servo Flag = 0");

        digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed
        //        Serial.println("\nLed Light ON");
        delay(3000);

        //        Serial.println("Stepper Start - Return to position zero");
        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
        //        Serial.println("Stepper Stop");

        digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
        //        Serial.println("\nReset Button 2 - PIN 5 - Low");
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
        //        Serial.println("\nLed Light OFF");

        pButtonFlag = 0; // changes pButton2Flag value back to zero (0)
        //        Serial.println("\Button 2 Flag = 0");
        delay(2000);
      }

      // position 3
      if (pButton3State == HIGH) {
        //       Serial.println("\nPush Button 3 Pressed");
        pButtonFlag = 1; // change pButtonFlag variable
        //       Serial.println("Button 3 flag = 1");
      }
      if (pButtonFlag == 1) {
        //          Serial.println("Stepper Start - Forward 120 steps");
        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
        //          Serial.println("Stepper Stop");
        delay(2000);

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

        if (myServoFlag == 1) {
          //            Serial.println("Servo Start");
          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //             Serial.println("Attach 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
          //             Serial.println("\nDetach Servo Library to PIN 10");
          //             Serial.println("Servo Stop");
          //             Serial.println("Hold position OPEN for 2 sec");
          delay(2000);

          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //             Serial.println("Attach 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
          //             Serial.println("\nDetach Servo Library to PIN 10");
          //             Serial.println("Servo Stop - Awaiting next selection");
        }
        myServoFlag = 0;              // changes myServoFlag value back to zero (0)
        //          Serial.println("Servo Flag = 0");

        digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
        //          Serial.println("\nLed Light ON");
        delay(3000);

        //          Serial.println("Stepper Start - Return to position zero");
        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
        //          Serial.println("Stepper Stop");

        digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
        //          Serial.println("\nReset Button 3 - PIN 6 - Low");
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
        //          Serial.println("\nLed Light OFF");

        pButtonFlag = 0; // changes pButton3Flag value back to zero (0)
        //          Serial.println("\Button 3 Flag = 0");
        delay(2000);
      }
      // position 4
      if (pButton4State == HIGH) {
        //       Serial.println("\nPush Button 4 Pressed");
        pButtonFlag = 1; // change pButtonFlag variable
        //       Serial.println("Button 3 flag = 1");
      }
      if (pButtonFlag == 1) {
        //          Serial.println("Stepper Start - Forward 160 steps");
        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
        //          Serial.println("Stepper Stop");
        delay(2000);

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

        if (myServoFlag == 1) {
          //             Serial.println("Servo Start");
          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //             Serial.println("Attach 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
          //             Serial.println("\nDetach Servo Library to PIN 10");
          //             Serial.println("Servo Stop");
          //             Serial.println("Hold position OPEN for 2 sec");
          delay(2000);

          myServo.attach(srvoMtr);   // attaches the servo library to pin 10
          //             Serial.println("Attach 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
          //             Serial.println("\nDetach Servo Library to PIN 10");
          //             Serial.println("Servo Stop - Awaiting next selection");
        }
        myServoFlag = 0; // changes myServoFlag value back to zero (0)
        //          Serial.println("Servo Flag = 0");

        digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
        //          Serial.println("\nLed Light ON");
        delay(3000);

        //          Serial.println("Stepper Start - Return to position zero");
        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
        //          Serial.println("Stepper Stop");

        digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
        //          Serial.println("\nReset Button 3 - PIN 6 - Low");
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
        //          Serial.println("\nLed Light OFF");

        pButtonFlag = 0; // changes pButton3Flag value back to zero (0)
        //          Serial.println("\Button 4 Flag = 0");
        delay(2000);
      }
    }


sender: user

message:
Store value in EEPROM to perform different actions on reset?

I want the same button to wake up (reset) and put it to sleep but this is hard if the button is tied directly to the rst pin. My thought was to read and store a value in EEPROM so tell the chip what mode we were in so it can perform the counter action. For example, on RST if the value is 0 the chip should wake up and do things. It would then set the value to 1. If the button is pressed again, the chip resets, reads there is a 1 and now just puts the chip into deep sleep after setting the value back to 0. Rinse, repeat.

Does this make sense? Will this work? Is there a better/easier way?

sender: assistant

body:
While it looks interesting as idea, IHMO you have keep in mind:

1. Include some code for button denouncing logic. Actually you will receive couple of “resets” during ~20ms during button press. Without denouncing you may end up with reset signal right at the moment you write to the EPROM. While EPROMs are pretty “solid” nowadays, it many not be good practice. One of potential solutions IMHO is to delay update EPROM with state switch for 20ms after boot, so it be done in stable state.

2. You may also consider to include electronic circuit to hold reset long enough to reboot the controller (it may also reduce bouncing).

3. EPROM has finite lifespan in terms of rewrite cycles, if your device turned on and off ~100 timers per day, it may die in a ~year.

4. Writing the EPROM usually consumes significant amount of energy, so it may reduce battery lifespan (if you use battery).

Probably more classic approach with sleep / wake up by button looks more reasonable, unless you have shortage of pins ;)


body:
Totally agree with Serge.
To cover issues #3 and #4 of Serge's answer I recommend you to have a look at [FRAM](https://www.fujitsu.com/global/products/devices/semiconductor/memory/fram/lineup/i2c-1m-rc1mt/press-new.html).
It has more durability with 10 trillions of write cycles.


message:
Change one specific byte of an IP address

So if I have an IP address `IP Address: 192.64.5.1`, is it somehow possible to change a specific byte of that IP to like `IP Address: 192.64.**6**.1`

My idea is to change the IP Address into variables `IP Address: a.b.c.d`
Now I could say `a= 192; b= 64; c= 5 + 1; d= 1 `

But what if I receive the `IP Address: 192.64.5.1` as a String. Is it somehow possible to split it up into 4 parts that I can each individually assign to an integer (a, b, c or d)?

body:
Yes, you can split the string with the C library function `strtok`, than concatenate everything together with your own string with the C library `strcat`.
You can convert strings to `atoi`, so use the resulting string from strtok with atoi to an integer.

Tip: try it on a PC with a local C compiler, because you can check it very fast (unless you can implement it first time right). Than you copy it to your Arduino sketch. Make sure to start with a char buffer big enough for the biggest possible IP address string.


body:
You can do it all with the `IPAddress` class.

For instance: create an IP address from a string:

    IPAddress myAddr(myString);

Create a new IP address with one byte changed:

    IPAddress myNewAddr(myAddr[0], myAddr[1], myAddr[2] + 1, myAddr[3]);


message:
Mega 2560 pin output power and control question

I am trying to determine the total pin power requirements for my Mega 2560 project; it will connect to 3 1m Neopixel strips and 5 RGB laser fiberoptic lights, and control them via PWM. Each strip and light will have its own external power supply. The laser lights will be controlled by an Adafruit TLC5947 LED Breakout board with 3 (R,G,B) inputs. Further, each laser light is turned on by a logic high command.

My questions are:
How can I determine the total pin outputs? Can all this be controlled safely from the Mega, or will I need to add transistors? I have read 200mA is the maximum for the Mega, however I have found a seemingly definitive post on Arduino.cc that states 800mA is the maximum.
https://forum.arduino.cc/index.php?topic=327742.0

here's my rough schematic:
[![enter image description here][1]][1]
Thank you in advance!

  [1]: https://i.stack.imgur.com/W7i2k.png

body:
Neopixels only need a control signal and Gnd when powered externally - connect the external power supply Gnd to the Mega Gnd as well.

The 2560 chip can definitely work with 800mA (200mA per VCC & Gnd pin, and there are 4 of each). The onboard supply can't cope with that - you get a max of 500mA from USB (due the 500mA PTC fuse, the big gold or green part next to the USB connector), or something under an 1000mA depending on how 5V is created. 12V into the barrel jack and high current will over heat the 5V regulator. 7.5V into the barrel will give you a better shot at high current. Then there is 1V rated reverse polarity protection diode between the barrel jack and the regulator.  You can't put 5V into the barrel and get 5V out, you need to overcome the diode and the regulator. 7.5V wallwarts work well for that. www.dipmicro.com used to carry 7.5V/1A wallwarts, I don't know if they still do.  If you decide to use an external 5V source via the power header, then the power headers are only rated for 1A current as well.
I use this one for 5V projects, 4A to power the Arduino, make yourself a power cord splitter and have 5V for other stuff as well direct from the wallwart, and not off the Mega board.

Are the lasers controlled by current into the R,G,B pins, or are they externally powered and R,G,B are just control signals? If their power comes from RGB, then you'll also want to power the TLC5947 seperately and just connect control signals and Gnd to the Mega.


message:
LED not turning on with following code

LED is not turning on with the following code. Have tried multiple LED's and double checked wiring. What's wrong? Using an uno.

    int ldr = A1;
    int  ldrVal = ldr;
    int led = 6;
    int lvalue = 900;

    void setup() {
      pinMode(led, OUTPUT);

      Serial.begin(9600);

    delay(1000);

    }

    void loop() {

    Serial.println(analogRead(ldrVal));
    if (ldrVal > lvalue) {

    digitalWrite(led, HIGH);
    }
    delay (50);

    if (ldrVal < lvalue)
    {
      digitalWrite(led, LOW);
    }
    delay (1000);

    }

body:
Apart from the bad indentation and the bad variable naming, which makes your code not only look ugly, but messy and poorly readable, you have multiple problems in your few lines of code.

One problem is the variable `lvalue` never gets set, meaning its value remains `900` no matter what's the value you are reading through `analogRead()`.

A second mistake is your `ldrVal`, which should represent the boundary between *lit* and *powered off*, is set to `A1`, which in turn is a *macro define* for a valid integer, but a very small value (less than `20`).

In other words the code that should decide to turn on/off the LED continously compare 900 and 20 with no opportunity for those values to change: not surprising the LED won't change state, do you agree?

BTW, `50ms` is a very short time interval: if you want to be able to see the LED turn on and then off, increase the delay to 200 or more.


body:
Your code is wrong. `analogRead(ldrVal)` does not read the analog pin's value and store it into ldrVal, it is a function who's result is the analog pin value.

Try this edit:

    void loop() {

    int newValue = analogRead(ldrVal);
    Serial.println(newValue);
    if (newValue > lvalue) {  //Check newValue, not ldrVal
        digitalWrite(led, HIGH);
    }
    delay (50);

    if (newValue < lvalue)
    {
        digitalWrite(led, LOW);
    }
    delay (1000);
    }


message:
Powering a Tiny Arduino Project

I'm trying to build a tiny project. After I program the board, to power the dev board - how can I power it to run the code?

__Question:__

- I was curious as to how I would be able to power the [ATtiny85 USB Mini Dev Board][1] by using a [90mAh 3.7V LiPo][2] battery which is connected to a [TP4056 5V micro USB Lipo battery charger][3]? The power is regulated to 5V by a  [3v to 5v 1a USB Charger DC-DC Converter][4] feeding the 5V pin on the ATtiny85.
- If now, how else can I power the [ATtiny85 USB Mini Dev Board][1] with a rechargeable battery?

__New Circuit__
[![enter image description here][5]][5]

__Old Circuit__
[![enter image description here][6]][6]

---

__Final Circuit__

[![enter image description here][7]][7]

  [1]: https://www.electrodragon.com/product/attiny85-usb-mini-dev-board-digispark-compatible/
  [2]: https://www.ebay.com.au/i/113322553296?chn=ps
  [3]: 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
  [4]: https://www.ebay.com.au/p/2pcs-3v-to-5v-1a-USB-Charger-Dc-dc-Converter-Step-up-Boost-Module/1663444523?iid=191674152965&chn=ps
  [5]: https://i.stack.imgur.com/EiUF6.png
  [6]: https://i.stack.imgur.com/jxD4u.png
  [7]: https://i.stack.imgur.com/eGiHo.png

body:
The old circuit will not work as you expect. While the ATtiny85 can run happily with 2.7 to 5.5V in this setup it expects 5V. I assume this is due to the high CPU clock setting. To run stable at a high CPU clock it requires 4.5V.

The VIN pin is connected to a linear regulator that has a 2V drop-out. Thus the supplied voltage has to be at least 2V about the target voltage. That is why the shopping page states a 5V (direct) or 7-35V (regulated at VIN) power supply.

Your LiPo charger already has a boost converter built in that boosts the battery voltage (3.0 - 4.2V) to 5V. No need to use a separate DC-DC boost converter here.

Just connect OUT+ to 5V and you are done.


message:
When does a pre/post increment occur?

Editing here to clarify. The headline asks the question but the example given was not ideal. This was a more general Q than about the example code.

Compilers have *sequence points*, places where you can be assured that the equations have been evaluated etc and no lingering effects will occur: the compilation is stable. When I couldn't test the original example I went looking for theory, and came across SE/SO posts where there was some discussion about issues like:

       int a = 1;
       int b = a++ - a++ + a++;

What would you expect the values of a and b to be after this? It turns out it hinges on whether the arithmetic operators are sequence points. Apparently this was not well settled in early versions of C, and in other languages (like Java) the results may differ yet again.

I now understand that an expression like `(item++ > max)` contains no sequence points -- the `>` operator does not trigger evaluation, but assignment operators and *some* arithmetic operators do.

//================================

Original Q:

I've read several Qs here concerning `x++` vs `++x` but I don't see this specific case. I'm still something of a C novice here.

Do these two code fragments do the same thing?

      // assume itemNum == maxItem on entry

    if (++itemNum > maxItem) itemNum = 0;

    if (itemNum++ > maxItem) itemNum = 0;

I gather that when the increment takes effect depends on the occurrence a 'sequence point' but I don't know if the comparison creates such an inflection.

body:
Both ++x and x++ increment the value of x. The difference is whether you evaluate the value of x in your expression (formula) before or after incrementing it.

    int x1 = 0;
    int y1 = 0;

    int x2 = x1++; //Post-increment: Move current value of x1 (0) to x2, THEN increment x1
    int y2 = ++y1; //Pre-increment: Increment y1. Then move the NEW value of y1 (1) to y2.

In the above, x2 will be 0, and y2 will be 1.

The same logic applies to your if expression. If you use pre-increment, your if statement makes its decision on the new value after incrementing it.

If you use post-increment, the if statement makes its decision based on the value **before** it's incremented.


message:
Slow refresh rate on I2C OLED screen

I'm trying to create a small handheld console with 6 buttons and an I2C 0.96" OLED display:
https://i.stack.imgur.com/gWqZP.jpg

The directional buttons use the analog pin and different resistors technique to save space while the two remaining buttons use a digital pin each.
However, despite using the same libraries as other projects, the sketch seems to run very slowly, resulting in a lowered screen refresh rate.

Here is the code:

    #define wid 64  // Defines half of the width of the screen for graphic reference
    #define hei 32

    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    Adafruit_SSD1306 display;  // Create display

    int av;
    const float sp = 3;
    float pos[2]={0,0};  // Cursor position

    void setup() {
       delay(100);  // Gives the screen time to setup
       display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // Initialize display with the I2C address of 0x3C
       display.clearDisplay();
       display.setTextColor(WHITE);
       display.display();   // Clears the screen of any remaining images
      }

    void loop() {
      av=analogRead(A0);  // Reads the directional input
      av=inputRefine(av); // Assigns it to a direction
      switch (av)         // Changes the cursor position accordingly
      {
        case 1:
        pos[1]-=sp;
        break;

        case 2:
        pos[0] += sp;
        break;

        case 3:
        pos[1] += sp;
        break;

        case 4:
        pos[0] -= sp;
        break;
      }
      display.clearDisplay();

      display.setCursor(5,5);
      display.print(millis());  // Prints the system time on the corner of the screen

      display.drawCircle(wid + pos[0], hei + pos[1], 5, WHITE);  // Draws a circle on the cursor position
      display.display();
      }

    int inputRefine(int av)
    {
      int a=0;
      if (av>500&&av<600) a=2;
      else if(av>1000) a=3;
      else if(av>920&&av<950) a=4;
      else if(av>680&&av<720) a=1;

      return a;
    }

What is slowing the execution down?

EDIT: Even commenting out any unnecessary line doesn't remove the lag
EDIT 2: The problem might reside in the screen itself. Unfortunately, I don't have a backup one. I'll order one as soon as possible and test this theory.

body:
Solved by updating the Adafruit sdd1306 library and the Adafruit GFX library

EDIT: Why am I being downvoted?


message:
Custom sleep function for Nextion

I have a Nextion 7 inch enhance type display.
I have enabled sleep using `thsp = 120` and `thup = 1` line of code. Now display become sleep mode after 2min, if there is no any touch event.

But, this sleeping is completely turn off the display.

I have several pages and I want to reset to a specific page, if there is no any touch event in any page instead of sleep function.

Greatly appreciate if someone can give a solution for this.

body:
I solved the problem using a Nextion timer. (tm0)

I got a timer and change `tim` value. ( unfortunately Nexion allow to maximum to 65535mS). `vscope` should be `globle`, otherwise you cant use timer in every page.

I reset the timer in page touch event. In timer event I put this code.

    if(tm0.tim==60000) //reset time in mS
    {
       page 0 //specific page to load
    }


body:
The Nextion screen has a command for this. It is called [wup][1] and defines the id of page that the screen should go to on wake from sleep. The default is set to 255, which means that the display wakes up on the page it was on before the sleep event.

    16 wup Wake Up
     Page wup=2, n0.val=wup
    Sets which page Nextion loads when exiting sleep mode
     min is 0, max is # of last page in HMI, or default 255
     When wup=255 (not set to any existing page)
    – Nextion wakes up to current page, refreshing components only
     wup can be set even when Nextion is in sleep mode

  [1]: https://nextion.itead.cc/resources/documents/instruction-set/#s6


message:
avrdude: Error: butterfly programmer uses avr_write_page() but does not provide a cmd() method

When trying to flash my sketch, I see many errors such as:

     ***failed;
     ***failed;
     ***failed;
    avrdude: Error: butterfly programmer uses avr_write_page() but does not
    provide a cmd() method.
     *** page 127 (addresses 0x7400 - 0x747f) failed to write

And also:

    avrdude: error: programmer did not respond to command: set addr

How can I successfully flash my sketch?

body:
After much frustration in trying things, I came across [this forum post](https://forum.arduino.cc/index.php?topic=129647.msg3039571#msg3039571) which advised:

    sudo systemctl stop ModemManager.service

If this works, disable the service from starting next boot:

    sudo systemctl disable ModemManager.service

It seems like setting `ENV{ID_MM_DEVICE_IGNORE}="1"` in a `udev` rule is insufficient.


message:
I need help with U8GLIB library

I have a project which uses a 128x64 oled display. I have to use the U8GLIB as the available displays change from SSD1306 to SSH1106 depending on when you buy it which that library covers both displays.
I don't want the program for the display to eat up the memory of the arduino so I use u8glib instead of u8g2! for this project I need to display numbers 0 to 9, decimal point, omega (ohm symbol) and metric prefixes such as μ,m,k,M, etc...
I first tried to create a bitmap font (.bdf) and convert it to a C file because that was what was hinted at on a few posts. There were no tutorials and after messing about with the different formats and trying to add the font to the library I just gave up because I couldn't figure it out. Instead I decided to use this website which generates bitmaps from TTF files:
https://littlevgl.com/ttf-font-to-c-array

Now I can use those bitmaps and have my few characters which use very little memory (about 20% as opposed to more than 70% using a complete symbols font in u8g2!) but this makes things really awkward as I have to translate every number I get into separate digits and then into a bitmap! also I can only use font sizes which have a height in multiples of 8 because for some weird reason this library expects width in number of bytes and height in number of pixels!

> cnt: Number of bytes of the bitmap in horizontal direction. The width
> of the bitmap is cnt*8.

so I can do fonts of size 48 for example, but not 50 or 52 which would be more suitable for my application!
I'm not sure if anyone else has had this issue but there must be a way to display the characters you want without destroying your entire memory space like u8g2 does! Just getting to this point took me 2 days (on the left there is a 0.96" SSD1306 and on the right there is a 1.3" SSH1106):

[![enter image description here][1]][1]
Please help if you have any idea on how to deal with this library as it's driving me insane at the moment!

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

body:
While this may not exactly answer your question, there may be some information about [u8g2lib][1] that you have not seen. The library source code is linked here: [u8g2lib][1]

Within that repository is the [FAQ documentation][2] which includes such gems as:

> [Q: U8g2 requires a lot of memory. How to reduce this?][3]
> - Visit https://github.com/olikraus/u8g2/wiki/u8g2optimization
> - Disable U8g2 features if possible (see u8g2.h)
> - Limit the font size. If possible avoid "f" fonts, instead use "r" or "n" fonts
> - If the I2C interface is not required, then uncomment #define U8X8_HAVE_HW_I2C in U8x8lib.h   (Background: Due to a problem in
> Wire.h, the I2C Arduino lib is always included)

and

> [Q: How can I generate my own font.][4] A: The font must be available in
> bdf file format. Then use bdfconv to generate the font data. The font
> data can be pasted into an existing file of your project. There is
> also a nice Windows Bitmap Font Editor "Fony"
> (http://hukka.ncn.fi/?fony)  which can export .bdf files. A copy of
> Fony 1.4.7 is available here:
> https://github.com/olikraus/u8g2/tree/master/tools/font/fony

The [tools/font][5] directory includes several utilities, including what looks like one that [converts OTF fonts to BDF format][6]

Once you get a BDF format font, you use [bdfconv][7] to create the C file that holds the font array. One of the arguments for bdfconf is the `-m 'map'` option. You can place in there a list of Unicode ranges that limit which characters get included. So, you can create a font that has ONLY the characters you need.

For example `-m '45-46,48-57,77,107,109,181,937'` gets you minus, decimal, 0-9, 'M', 'k', 'm', mu, omega. Unicode character map at https://unicode-table.com/en/

The benefit to creating a font is that the u8g2lib library itself does all the mapping to bitmaps and calculating the character widths, etc. so you don't have to.

  [1]: https://github.com/olikraus/u8g2
  [2]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt
  [3]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L167
  [4]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L206
  [5]: https://github.com/olikraus/u8g2/tree/master/tools/font
  [6]: https://github.com/olikraus/u8g2/tree/master/tools/font/otf2bdf
  [7]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L213


message:
How to re-construct audio from series of analog integer input?

I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.   At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

I'm new to working with these types of break out boards, so I found an online project that I'm using as a starting point:

[Streaming audio from ESP8266 to pyaudio working in Arduino IDE][1]

I figure I start troubleshooting my popping sound issue by inspecting the UDP packets my ESP8266 code.  Below is the source code I'm working from:

 #include <ESP8266WiFi.h>
 #include <WiFiUdp.h>

 const char* ssid = "change this";
 const char* password = "change this";
 int contconexion = 0;

 WiFiUDP Udp;

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

   pinMode(5, OUTPUT);  //D1 Led de estado
   digitalWrite(15, LOW);

   WiFi.mode(WIFI_STA); //para que no inicie el SoftAP en el modo normal
   WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED and contconexion <50) { //Cuenta hasta 50 si no se puede conectar lo cancela
     ++contconexion;
     delay(250);
     Serial.print(".");
     digitalWrite(5, HIGH);
     delay(250);
     digitalWrite(5, LOW);
   }
   if (contconexion <50) {
       //para usar con ip fija
       IPAddress Ip(192,168,1,180);
       IPAddress Gateway(192,168,0,1);
       IPAddress Subnet(255,255,255,0);
       WiFi.config(Ip, Gateway, Subnet);

       Serial.println("");
       Serial.println("WiFi conectado");
       Serial.println(WiFi.localIP());
       //digitalWrite(5, HIGH);
   }
   else {
       Serial.println("");
       Serial.println("Error de conexion");
       //digitalWrite(15, LOW);
   }
 }

 void loop()
 {
   Udp.beginPacket("192.168.0.26", 1234);

   for(int i=0; i<1024;i++){
     int old=micros();

     float analog = analogRead(A0);
     if (analog > 255) {
       analog = 255;
     }
     else if (analog < 0){
       analog = 0;
     }
     Udp.write(int(analog));
     Serial.print(int(analog));
     Serial.print(",");
     while(micros()-old<87); // 90uSec = 1Sec/11111Hz - 3uSec para los otros procesos
   }
   Serial.print(";;;;;");
   Udp.endPacket();
   delay(5);
 }

Notice near the bottom of the file, I print out each analog value separated by a comma, and each data packet separated by five semicolons.

Can someone suggest a way for me to re-construct these series of integers into a sound file that I can inspect via listening with my own ears?  Then I can tell if the sound data being sent is complete?  Or let me know if there's a better way to test if all the data packets are being sent correctly.

**UPDATE**

I tried to create a wav file by doing this:

 - Take the list of all integers from `Serial.print(int(analog))` and paste it into a file. I make sure all integers are space delimited (ie. no more commas or semicolons)
 - I copied the file over to a linux machine that had ffmpeg installed
 - I ran the command `ffmpeg -f u8 -ar 11111 -ac 1 -i myfileofintegers -y test.wav`

When I listen to the test.wav file, I just hear a series of rapid popping noises.  Not sure if I created the wav file properly?

  [1]: http://www.sinaptec.alomar.com.ar/2017/09/proyecto-1-esp8266-microfono-espia.html

body:
> I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.

You have described several problems; one needs to break big problems into small problems:

 1. Sample the audio
 2. Send it to another computer
 3. Decode and playback the sound

> At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

This sounds like you have got your timebases messed up; it is likely that you aren't recording enough data or playing it back incorrectly. N.b. it looks like you are recording ~92ms of audio data each 'packet' and if you get a series of pops at 2hz you are likely playing less than 1/10 of a second of audio for ever 5/10 of time, so your speaker moves for 1/10th of a second then stays still for 4/10ths and repeats; this produces your 2hz popping noises.

Your code has some other problems as well:

 - Serial.print() is **Slow!** Don't use it where performance matters!
 - Intertwining sampling and sending
 - Incorrectly scaling the analog reading
 - 11.1khz can only record signals up to 5.5khz

Lets start with the audio sampling. We have some sort of audio circuitry presenting a signal to an analog input, we need to sample it regularly and uniformly! The code presented is trying to sample at 11.1 kHz, but only does so for 1024 samples before hitting a discontinuity. We do not have circuitry dedicated to this so we will have to use the ADC circuitry on the Arduino.

First thing you will want to get you sampling regular and continuous. You will want to use an interrupt on the Arduino for this. The interrupt should take a single sample from the ADC and add it to a buffer or signal the main loop to read/buffer it.

This interrupt will need to fire regularly at the sample rate or the data will be ruined.

Second the audio circuitry should prepare the signal so that it is between 0-5v with a ~2.5v bias, this will use the ADC hardware to its fullest.

so in Pseudo code:

    // include any libs etc.
    // set up variables ect.
    void interupt_sample();
    // register and attach interrupt
    void setup() {
    //do your setup etc.
    }
    void loop() {
    // if(new_sample) add_to_buffer(new_sample);
    // if(buffer_full) send_and_flush_buffer();
    }


message:
Number of cycle depending on the number and type of statements

I did this little experiment to count the number of cycles per second in two different configurations:

1-The variable a is initialized at zero and incremented by one each cycle of the loop.
 -The value of a is written each cycle
 -at millis() = 1000, the incrementation ends, and the value of millis() is written to check the precision of timing.

Code:

    long a = 0;
    int v = 1;

    void setup() {

    Serial.begin(9600);

    }

    void loop() {

    if (v == 1){
    a = a + 1 ;

    Serial.println(a);

    if (millis() >= 1000){
    Serial.println(millis());
    v = 0;}

    }
    }

Result:
1
2
.
.
.
227
1000

2-Same as 1, but the value of a is written only at the end.

Code:

    long a = 0;
    int v = 1;

    void setup() {

    Serial.begin(9600);

    }

    void loop() {

    if (v == 1){
    a = a + 1 ;

    if (millis() >= 1000){
    Serial.println(millis());
    Serial.println(a);
    v = 0;}

    }
    }

Result:

1000
265174

-So, 227 cycles for 1, and 265174 for 2, is this correct, and can such a simple modification slow the cycling by 1000?

body: When the serial buffer (64 bytes) is full the `print` waits until bytes are send away at 9600 baud.


body:
Writing via the serial interface takes a lot of time (just consider the baud rate you selected).
You should always keep in mind that changing the amount you are printing might change your programs behaviour.
That means, your 2. configuration is (more) reliable.


body:
You could use micros() as well to increase resulution to 4uS, vs 1000uS.
Up the speed to 115200, that should show some improvement as well.


message:
Displaying characters as bitmaps

I have resorted to creating bitmaps for each number and a few letters for a 128x64 Oled module. This was to save memory and get around limitations of libraries such as the u8glib. If I had linux I could use the tools they provided to fix some of these but that's out of the question for now. I wanted to know if there's a simple way of mapping each character to it's bitmap so a function similar to XXX.print(); be used, in order to parse the characters and display the corresponding bitmaps automatically. That would make my life so much easier! thanks!

body:
I would split it down into functions.

First write a function which takes a character and a pair of coordinates, then draws the bitmap corresponding to that character at the given coordinates on the screen.

Then you want a function that is the "next level up". You just pass it a single character, and it remembers the current coordinates and uses those with the character to call the first function. It's then the job of this function to move the coordinates to the next character location ready for the next time it's called.

Finally you want an outer layer (or a few outer layer) functions that take different data types (`const char *` for example) and send each character in turn to the second function above.

If you were to make a class to wrap it all in you could inherit the `Print` class. That means you just need to provide the `size_t write(char)` function which is equivalent to the second function above (of course you still need the first function). The wrappers for different data types are then all provided for you.


message:
Oscillating Output from Arduino Pins when not in use, why?

I have A1 set to be an input, have the program read it, and then print to the serial monitor. My question is, when the circuit is not receiving power, but is grounded, and is still connected to A1, when do I see an output pattern of, for example:

    0,0,0,0,7,23,16,9,4,0,0,0,0,3,18,21,15,0,0,0.....

I have a different detector inputing to A0 and if I don't have A1 connected then I get a reading that is similar to what I would see if I was actually reading A0 (around 900). Then if I plug back into A1 the value drops to around 350. When A0 is unplugged and only A1 is plugged in I only get noise (ie the pattern above in the code section).

body: I'm thinking along the same lines as CrossRoads and dandavis above. Would you be able to post a circuit diagram? If you haven't grounded the input, it could be floating or picking up noise from the surrounding environment. A 5k pulldown resistor may fix the problem, depending on what your circuit looks like and the environment its in.


message:
SoftPWM update limitations

i'm using arduino to dimmer 9 led strips with different output pins after an FFT audio analysis gives results at 60Hz = 16ms. [FFT is performed by a PC and sent to arduino using a RF24 module]

I started the project using SoftPWM on pins D2->D9 & A4 with a lower frequency update but now i'm having problems increasing the frequency update. I have already wired 6 copies of that board and i'm looking for a software solution

To diagnose the problem i performed a test sending a pwm value and zero at a certain frequency, if the frequency is high you can only see a lower emitted power

If I set the pwm once I have a stable signal (led intensity)
If I set the pwm every ~10ms (10ms on @ certain pwm, 10ms at pwm=0) I have an unstable intensity, repeating the test on the pin 6 with a normal analogWrite i don't have the problem. With 10ms i clearly see it blinking at a random frequency (~20Hz=50ms), with 15ms I only see it random fluctuating

I'm using arduino Pro mini - 5V - 2kB
Without signals arduino performs 16k cycles/second (most without changing anything), with a 10ms signal it runs at 14k cycles/second so it seems not a load problem.

Can someone help me regarding this problem?

 - Should I change library
 - Should I move to a lower level to rewrite a more performing library
 - Should I use only 6 std pwm, draw again the board, print them again, weld all components again, and test it again?

Thanks!

PS: I can't create the SoftPWM tag for a reputation problem, can a moderator do that?

body:
The problem is not a SoftPWM limitation but a physical one. SoftPWM have a PWM cycle at 60Hz, that makes impossible to update output faster than 34mS and that explain why I see low frequency trying to change the state with every 10 ms.

[![Aliasing][1]][1]

Hardcoding the IRS I can reach a much faster PWM cycle, keeping the same PWM frequency I have roughly 60% less of CPU used. With a full CPU load and latest version of the code I can reach ~600Hz PWM cycle. I decided to use a ~300PWM cycle to have enough CPU to perform other tasks (mainly handle RF24 to receive packets @ 60Hz and, if needed, forward them too other bases)

Even at higher frequencies average intensity is not stable, but higher the frequency more stable the result. That can be explained because the eye "average" incoming light and that average is not very stable

[![avg alias][2]][2]

Since leds are used to produce visual effects I don't need a very accurate output, and 300Hz are enough. (I also don't have big mosfets and I don't want to stress them with higher frequencies)

  [1]: https://i.stack.imgur.com/c2ctk.png
  [2]: https://i.stack.imgur.com/XX3S3.png


message:
Arduino IDE can't program my Arduino Pro Micro

I have a lot of Arduino Pro Micros that I can't program through the Arduino IDE.

I'm on Windows.

I'm using the SparkFun Pro Micro board information downloaded from SparkFun's website.

I've tried manually reassigning the Pro Micro's COM port in the device manager. It seems to be no different whether I'm at COM1 or COM255.

If I use an Arduino ISP or USBASP to burn the bootloader onto the problematic Pro Micro, it responds for usually one or two more USB programmings but that's about it.

When they get into this problematic state, they are still running their code (I can see the Blink sketch flashing my LED for instance), they just can't be reprogrammed. I can even still open their Serial communications.

Verbose output during the uploading process on first attempt yields the following:

    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    Uploading using selected port: COM2
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM2 -b57600 -D -Uflash:w:C:\Users\Thompson\AppData\Local\Temp\arduino_build_668056/BareMinimum.ino.hex:i

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM2
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
    avrdude: butterfly_recv(): programmer is not responding

That last line is where it freezes for an indefinite period. I close and reopen the Arduino IDE and try to reupload, and this is my result:

    processing.app.debug.RunnerException
         at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
         at cc.arduino.UploaderUtils.upload(UploaderUtils.java:82)
         at processing.app.SketchController.upload(SketchController.java:736)
         at processing.app.SketchController.exportApplet(SketchController.java:703)
         at processing.app.Editor$DefaultExportHandler.run(Editor.java:2039)
         at java.lang.Thread.run(Thread.java:748)
        Caused by: processing.app.SerialException: Error touching serial port 'COM2'.
         at processing.app.Serial.touchForCDCReset(Serial.java:107)
         at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
         ... 5 more
        Caused by: jssc.SerialPortException: Port name - COM2; Method name - openPort(); Exception type - Port not found.
         at jssc.SerialPort.openPort(SerialPort.java:167)
         at processing.app.Serial.touchForCDCReset(Serial.java:101)
         ... 6 more

This exact same message (with a different COM number of course) plays out on any Windows machine I try this with.

In the above example I was trying to upload the Bare Minimum example.

Are all of my Pro Micros dead? Is there something wrong with the IDE? Is there an alternative IDE I can get a second opinion from?

EDIT: An update; I've gotten Atom installed with PlatformIO and I was able to write a few sketches to an Arduino Pro Mini. I attempted the same sketches on the Arduino Pro Micro and got the same error and freeze: `programmer is not responding`

body: After experimenting some more, it looks like this issue is related to a one second watchdog that I have enabled in my sketch. After removing the watchdog, I've had no problems (so far) with uploading code.


message:
Controlling 3 Steppers exactly

**Update**

Here the update regarding the code I tried to program. I have a stepper with an attached disc with little holes every 45 degrees where a microswitch can rest into (hole is the exact size of the microswitch; and be in off position then). I would like the stepper to move 45 degree (until hole 1) and then (as a first step) wait for 3 seconds and then move another 45 degree to hole and stop etc.

As a next step I would like the same to be controlled via serial from another software. So I can send to serial a "move" command and then the same as described above will happen once the Arduino get the "move" command.

Below my attempt. It does do the homing, but not very smoothly and the next step (just moving 3 seconds) is a very rough movement. Here my qestions:

1. How can I make this move smoothly ?
2. How should I adapt this code to make the stepper stop once it is in the hole ?
3. How can I make the microswitch get out of the hole after it rests in there ?

Thank you very much for your help !

**Code**

    #include "AccelStepper.h"

    int M2dirpin = 4;  //Motor Y direction pin
    int M2steppin = 5; //Motor Y step pin
    int M2en=12;  //Motor Y enable pin
    #define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

    // AccelStepper Setup
    AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
    // Stepper Travel Variables
    long initial_homing = -1; // Used to Home Stepper at startup

    void setup() {

      pinMode(home_switch, INPUT_PULLUP);
      pinMode(M2dirpin,OUTPUT);
      pinMode(M2steppin,OUTPUT);
      pinMode(M2en,OUTPUT);
      digitalWrite(M2en,LOW);
      Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

      // Start Homing procedure of Stepper Motor at startup
      Serial.print("Stepper is Homing . . . . . . . . . . . ");

      while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
        stepperX.moveTo(initial_homing);  // Set the position to move to
        initial_homing--;  // Decrease by 1 for next move if needed
        stepperX.run();  // Start moving the stepper
        delay(20);
      }

      stepperX.setCurrentPosition(0);  // Set the current position as zero for now
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
      initial_homing = 1;

      while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
        stepperX.moveTo(initial_homing);
        stepperX.run();
        initial_homing++;
        delay(20);
      }

      stepperX.setCurrentPosition(0);
      Serial.println("Homing Completed");
      Serial.println("");

     // Move 10 steps forward from the limit switch (to get out of the switch)
      while (stepperX.currentPosition() != 10)
      {
        stepperX.setSpeed(10);
        stepperX.run();

    }
    }
    void loop()
    {
    stepper1();
    }

    void stepper1()
    {
      stepperX.move(22);
      unsigned long startMillis = millis();
      while( millis()-startMillis<3000 )
    {
      stepperX.run();
    }
    }

**Old question:**
I apologize for the high level, pseudo code question, but I am trying to understand conceptional how I can achieve the following:

I have 3 steppers (1 circular motion, 2 linear motion) which I would like to stop **every time** at the exact same position. The first stepper should rotate e.g. 45 degrees and stop, after which the second stepper should push down (like a linear actuator) stay at that position for a certain time and move back to the initial position, after that the 3rd stepper should also (linear motion) move to certain position and return.
These three steps would than repeat for a very long time.

Do Steppers accumulate errors in position and if yes how can I make sure that this is not happening ?

I read abut "homing" and tried microswitches, but wasn't able to combine it with the three stepper setup. Also 3D printers should always stop exactly at the same place and therefore I assumed there must be a solution for this.

Is there a template code I can start from that is similar to the setup described ?

How can I make sure these steps are done strictly after each other.

Again I apologize for the high level question, but all my attempts so far to solve this failed.

Thank you !

body:
**About errors with stepper motors:** Stepper motors introduce errors depending on the forces, that act upon them. For example: If your stepper does not have enough power to accellerate the attached weight, it will loose steps when trying (meaning that the rotor does not do a step despite the coils being controlled for the step). (The same of course also goes for deacceleration or moving against a barrier) Since you only know the position bei counting the steps, that you "send" to the motor, you get an error.

You have basically 2 options to prevent this from happening:
1. Choose the correct strength for motors for your application and don't overburden the motors at any moment in operation.
2. You can attach a rotary encoder to the rotor, so that you can check, if the rotor really moved the number of steps, that you instructed it to do. (Here be sure, that the numbers of steps for rotary encoder and motor match, or calculate correctly, if they don't). The position in your program would then only be updated based on the rotary encoder. This solution is more difficult, since you need extra parts and good code, that will not miss any of the rotary encoder pulses.

**About Homing:** Yes, this can be used to prevent the accumulation of errors during a longer operation. Also this is often used, so that the device does not have to constantly save it's current position to peristent storage. If the power is cut off, the device will forget it's position and calibrate it again after powered on again by using the end switches. Also this means, that in the powered off state it's not a problem, when the motor is moved away from it's position by outer forces.

It is unclear, how precise you need the application to be and what errors are really introduced. It may be sufficient for you to just get the position of the motors by homing, when you power your device on, and then simply letting it work. If that's not sufficient, you might do a homing cycle after every sequence. The same goes for the rotary encoder solution. It might be an overkill here, depending on the exact properties of the application.

**Template code:** I simply googled "Arduino stepper homing" and found some articles about it, which also contain example code. That should enable you to write code for your own application. Since you didn't really described, what your setup is, we cannot see, if this really fits your application. But Homing is the same everywhere.

**Steps strictly after each other:** You can just write your program to finish one part and then go on to the next (blocking code). Or, if you want it to be more elaborate and flexible, you can use non-blocking code (like in the `BlinkWithoutDelay` example of the Arduino library) with a finite state machine. The states could be the 3 parts of your program, or divided further. In each state you are doing only 1 thing and change to the next state, when finished. The code in each state should be non-blocking, so that it only does something, when it needs to, and else let's the program continue (for example: When moving a stepper at a certain speed, you are doing 1 step, then waiting a bit, then doing the next step and so on. While waiting you can do other things.)

You didn't mention, what your problems with the limit switches were, so we cannot help you with that. Thus this answer is as high level as your question. Hope, that helps.


message:
Arduino stops logging data after ~32761 seconds

I made a small set up to log temperature on SD card, everything is running smoothly until it reach 9:06:01 of logging that is  32761 seconds. I know that corresponds roughly to the maximum value of an integer. But I made all my variables unsigned long.
Here is the code in the loop and the if condition to log or not. The timer is computed with currentTime (unsigned long) and startTime (unsigned long). So even if logCount*freq are both integers, they should reach maximum value after 32761 seconds, then the if condition should always be true.

    void loop() {
     String date;
     unsigned long timer;
     int freq = 60;

     sensors.requestTemperatures();
     tempC1 = printTemperature(insideThermometer, 18);
     tempC2 = printTemperature(outsideThermometer, 19);

     // start serial port
     Serial.begin(9600);

     mainMenuDraw();
     operateMainMenu();

     CurrentTime = millis();
     timer=(CurrentTime - StartTime)/1000;
     date = TimeShowFormatted(CurrentTime - StartTime);

     if (timer > logCount * freq and StopStatus == 0) {
      logCount += 1;
      LastLoggedDate=date;
      DataLogg(date);

     }
    }

body:
Instead of comparing absolute times you should use the following:

    unsigned long now = millis();

    if(now - time_last_log >= freq){
        logCount += 1;
        LastLoggedDate=date;
        DataLogg(date);
        time_last_log = now;
        // or if you really want fixed intervals
        // time_last_log += freq;
    }

This is guaranteed to be overflow proof.


message:
How to map integer values and round to a count of tens/thousands?

I'm mapping a potentiometer from 0-1023 to 1000-120000 (1 sec to 2 minutes) for a timer, like:

    maxDelay = map (pot2, 0, 1023, 1000, 120000);

Both variables are integers. Now I would like to convert/round values to counts of 10 seconds (a count of thousands), so if I have anything from 1001-5000 this would be rounded to 1000 (1sec), and if I have 5001-10000 it would be rounded to 10000 (10 secs), then 20sec, 30sec, etc...until it reaches 120secs. I know I could have a few "if" statements but I'm trying to figure out the right way of doing these maths. Thanks.

body:
I didn't yet compiled it, but something like this should work:

    #include <Math.h>

    int converter(int x)
    {
        if(x <= 5000)
            return 1000;
        else
            return (int)(round(x / 10000.0) * 10000.0);
    }


message:
Upgrading NRF module for drone

Hello I am trying to make a drone by using Arduino as a microcontroller both for remote controller and the drone. And I have thought for using NRF module. But I came to know it only can transmit data to 1000 m maximum but I need the range around 8 km maximum. What can I do for increasing the range of my drone? Or is there some way to increase range of NRF module?

body:
If I search I see plenty of examples of RF with 40 miles, e.g.:

- [XTend 900 1W RPSMA - 40 Mile Range][1]
- [XBee-900-Datasheet][2]

Possibilities to increase the range:

- More powerful transmitter
- External / better antenna(s)
- Better receiver
- Using directional communication (might be hard with a drone which flies/moves)

  [1]: https://www.sparkfun.com/products/retired/9411
  [2]: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-900-Datasheet.pdf