# Question
Title: 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?

# Answer
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);
  }
}

```
> 3 votes

---
Tags: library, midi
---


# Question
Title: Arduino Mega 2560 interrupt pins and port mapping with rotary encoder
I am trying to use port manipulation in interrupts to read a rotary encoder. I found code for a Uno, so the port call for pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively. My code is not working. Do I have my ports wrong? I've tried reading up on this and I'm not fully understanding the Bxxxxxxxx part. I think that might be what's incorrect. Here is part of my code with one of the interrupts.

```
static int pinA = 2;
// Our first hardware interrupt pin is digital pin 2
static int pinB = 3;
// Our second hardware interrupt pin is digital pin 3
volatile byte aFlag = 0;
// let us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
volatile byte bFlag = 0;
// let us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
volatile byte encoderPos = 0;
//this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
volatile byte oldEncPos = 0;
//stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
volatile byte reading = 0;

void setup () {
  pinMode(pinA, INPUT);
  // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
  pinMode(pinB, INPUT);
  attachInterrupt(0, PinA, RISING);
  // set an interrupt on PinA,
  //looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
  attachInterrupt(1, PinB, RISING);
  // set an interrupt on PinB,
  //looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
}

void PinA() {
  //CCW
  cli();
  //stop interrupts happening before we read pin values
  reading = PORTH & 0xC;
  // read all eight pin values then strip away all but pinA and pinB's values
  if (reading == B00001100 && aFlag) {
    //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
    encoderPos --; //decrement the encoder's position count
    bFlag = 0; //reset flags for the next turn
    aFlag = 0; //reset flags for the next turn
  } else if (reading == B00000100) bFlag = 1;
  //signal that we're expecting pinB to signal the transition to detent from free rotation
  sei(); //restart interrupts
}

```

# Answer
Re “pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively”, it's true that Arduino digital pins 2 and 3 belong to different ports on Uno vs Mega2560 boards.

Mega2560's have six INTx pins, vs two such on Uno's. On the Mega, INT0...INT3 are PD0...PD3, and INT4,INT5 are PE4,PE5. On the Uno, INT0,INT1 are PD2,PD3. Note, in an answer at Can external interrupts be OR'd together on the '328 (Uno)? I show a couple of routines that will display appropriate masks for pins on different Arduinos. See the sections “Using other pins for PCIs” and “ISR-framework-generating Sketch”.

---

Here are a few problems with the code shown in the question:

1. `aFlag` is initialized to zero, and is never set nonzero in the code shown. So the first `if` condition in `PinA()` is never met.
2. `PinA()` is an interrupt handler, connected to interrupts by your `attachInterrupt()` calls. Because hardware disables interrupts before it enters an interrupt handler, there is no need for the interrupt handler to turn off interrupts. That is, delete `cli()` in `PinA()`. Similarly, delete the `sei()` at the end of `PinA()` because hardware restores interrupt status when a RETI instruction executes.
3. The Arduino software environment defines constants like `B00001100` with binary values that match the name. That is, in the Arduino software environment, constant `B00001100` has the value `0B00001100`. In my opinion, that's a stupid and unnecessary feature; I suggest that in your code you use standard C notation like `0B00001100` when you want to use binary constant values.
4. I regard writing `encoderPos --` instead of `encoderPos--` as a perversion and suggest deleting that unnecessary space.
5. As you haven't shown the `PinB()` interrupt handler, I don't know how you were going to handle the `encoderPos++` case. Judging from the code shown, you are using a method that won't correctly handle bounce and intermittent errors. I suggest using pin-change interrupts and a state-machine method, as illustrated in answers to:
Reading from a KY-040 rotary encoder with Digispark
How to read RPS for fast rotation with status change method in Arduino?
Read RC receiver channels using Interrupt instead of PulseIn
Can external interrupts be OR'd together on the '328 (Uno)?
> 1 votes

# Answer
On the mega, you'd read the pins with PINE.

So your code in PinA would change to:

```
reading = PINE & 0b00110000;

  if(reading == 0b00110000 && aFlag)

  {  encoderPos --;
    bFlag = 0;
    aFlag = 0;
  }
  else if (reading == 0b00010000) bFlag = 1;

```

I found a great discussion talking about the masking required here: https://forum.arduino.cc/index.php?topic=561741.0
> 0 votes

---
Tags: arduino-mega, interrupt, code-review, rotary-encoder, port-mapping
---


title: How to make an arduino wifi repeater?

text:
# Question
Title: How to make an arduino wifi repeater?
I am trying to make a wifi repeater. My router's signals don't come to my study and instead of buying a proper wifi repeater I prefer making one.

I want to learn how to make a simple wifi repeater that:

* repeats/boosts my existing home wifi network by connecting to it.
* Has some kind of a GUI or something that allows me to connect to it first (from some smartphone or PC) to configure it to my home network. It should find and show wifi networks around and then connect to the one I want it to upon my command.

I am new to electronics. Arduino is my preferred platform. If there are other easy to do alternatives that shall work too.

Any kind of help will be appreciated...tutorials, blogs, etc.

# Answer
> 4 votes
An arduino wifi repeater would in theory be very slow. Since you need to record the bit stream to the internal memory, then switch the spi to the transmitter, and send the bit stream, im unsure about what would happen if you miss a few bits in the process.

Arduino Wifi Shield \- the price of a wifi shield 85 usd

Wifi repeater ebay the price of a wifi repeater 22 usd.

This makes me question why one would go through the troubble of making a wifi repeater of an arduino.

Even investing in a raspberry pi and a wifi dongle would be less expensive.

# Answer
> 2 votes
Get a very cheap module called ESP8266, particularly the ESP-01, then flash a program called esp\_wifi\_repeater (which uses the arduino IDE)

https://github.com/martin-ger/esp\_wifi\_repeater

I have tested it several times it is pretty fast and with a ESP to USB adapter it steps down 5vdc from USB to it's usable 3.3v of the module

# Answer
> 0 votes
the network parts are "owned"by the yun side of the board. the yun acts like a mini linux pc, who can seperatly connect trough a bridge library to the arduino. so.. i think you could do it or make it a router that would probaply be easier, but this all wouldnt depend on arduino code, more depend on if there are WRT packages who can do this.. i thinks they should exist as this linux variant is in other routers too.

(better route then repeat btw, repeats puts delays on your entire lan)

---
Tags: arduino-uno, wifi, arduino-yun
---


title: avrdude flash issues

text:
# Question
Title: avrdude flash issues
I want to burn a hex file to a custom ATmega2560 board. I use this USBasp programmer for flashing (firmware version 1.01) on my Mac OS X 10.12.6 system. All hex files are compiled with avr-gcc (GCC) 4.9.2.

I use this command to burn fuses (without bootloader):

```
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -U lfuse:w:0xff:m -U hfuse:w:0xd9:m -U efuse:w:0xfd:m -s -F

```

What is working fine: I can flash smaller (43,266 bytes) programs and they work straight away without bootloader. If I flash **bigger programs (99,986 bytes)** they do not run. I can verify if the program runs because they spit out data via TTL. The smaller program does work but the bigger one does not produce anything.

I turned on "Code verify" and I can see for smaller programs:

```
avrdude: 43264 bytes of flash verified

```

big programs:

```
avrdude: verification error, first mismatch at byte 0x0001
         0x90 != 0x94
avrdude: verification error; content mismatch

```

**Any hints on this side?**

Secondly: after deleting the whole flash, when I flash a custom bootloader (from Atmel Studio - fuses are Ext. 0xFD, High: 0xD2, Low: 0xFF), command:

```
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -U flash:w:ATmega_Example.hex:i

```

and afterwards read the flash, the bootloader ended up in several blocks within the flash.

From the readout hexfile (data blocks):

Line 1

```
>:20000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00

```

All the flash is 0xFF until Line 1921

> :20F0000077C000009BC0000099C0000097C0000095C0000093C0000091C000008FC0000066

Some more data until Line 1995.

> :20F940000895F894FFCF65300000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF31

All the flash is 0xFF until Line 3970.

> :20F0000077C000009BC0000099C0000097C0000095C0000093C0000091C000008FC0000066

Some more data until Line 4044.

> :20F940000895F894FFCF65300000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF31

And so on... I can find similar data 4 times in the file.

**Is this a problem with the flashing or with reading the data from the chip?**

Let me know if you need more information to help me here.

# Answer
> 1 votes
Personally I use AVRDUDESS for uploading sketch on atmega328p and attiny85. Try to use it and run detect. I answer this because AVRDUDESS is very easy to use and it can help you to show more info of your error. I think you maybe have a bad wiring or a defect cable.

# Answer
> 1 votes
I'm not certain that it's going to fix your problem, but few years ago I had similar issue. I was trying to upload program to ATTiny13A using cheap e-bay USPasp and got verification errors. One step of my solution was changing programmer id from "`-c usbasp`" to "`-c usbasp-clone`"

More here: https://www.nongnu.org/avrdude/user-manual/avrdude\_4.html

# Answer
> 1 votes
I am familiar with that issue. I don't have an USBasp but an USBtinyISP but I think the problem is the same.

The USBtinyISP cannot read or write past 64kiB. Since AVR are 8-bit machines with 16-bit addressing they cannot address past 64kiB on their own. A special addressing schema is used on runtime and also during flash. (I think it was larger page sizes during flash.)

I could manage to get around the issue by using an original Atmel AVRISP mkII.

---
Tags: avrdude, atmega2560, avr-gcc
---


# Question
Title: 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)?

# Answer
> 4 votes
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]);

```

# Answer
> 0 votes
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.

---
Tags: esp8266
---


# Question
Title: HC-SR505 PIR Sensor only outputting HIGH
I recently bought an HC-SR505 Mini PIR sensor. I connected its positive to my Arduino UNO's 5v, output to digital pin 2, and ground to ground. I used Adafruit's code to test it, but all the serial monitor displayed was "Motion detected", which meant the PIR was always on a HIGH state. I then also tried powering it using 3V3 but the PIR kept on cycling on a HIGH and LOW state. Any help on getting my sensor to actually work would be greatly appreciated.

# Answer
> 3 votes
The PIR sensor has delay of 8 seconds. So when you turn on arduino, take care that no movement is on the PIR, and then after 8 seconds it should detect no movement. And it has always this delay,every time when detects movement.

# Answer
> 0 votes
The PIR works at 5V but you need to tweak the amount of sensibility and the signal length. Usually when a motion is detected, the PIR keeps sending HIGH until x seconds defined by a potentiometer on the board, when it goes down, the sensor is ready to capture another motion.

# Answer
> 0 votes
I have similar problem with the HC-SR505 sensor. First few seconds it holds 0 on the output pin, and then always 1. I think it was bad batch of sensors. Bad batch in chinese manufacturing means thousands (or hundreds of thousands) bad modules flooded the market.

Meanwhile I decided to choose one of options:

1. Stick with HC-SR501 sensor. It's bigger but works more or less.
2. Buy expensive ($5.90) PIR sensor from seeed.
3. Build my own PIR module by my required dimensions and function (in progress).

**Update:** From 5 sensors received 2 do the job. Supply voltage must be 5V or higher. First 20-60 seconds the output is not reliable and should be ignored. Then it works OK (if it works at all). Since the module has 3.3V LDO onboard the output signal is 3.3V.

# Answer
> 0 votes
Switch to use 5v for Vcc, the sensor will work correctly. I have the same trouble if I use 3.3v for Vcc. The output still 3.3v even your Vcc is higher than 5v.

# Answer
> 0 votes
I'm a noob. I had the same problem.

I connected the signal to pin 7 so I listened to gpio7 which always gave 1. But pin 7 is gpio4... Listening to gpio4 fixed the issue :)

---
Tags: arduino-uno, programming, sensors
---


title: When does a pre/post increment occur?

text:
# Question
Title: 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.

# Answer
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.
> 2 votes

---
Tags: programming, c++, c
---


# Question
Title: Interconnected Arduinos via digital pins and magnets
Before i get too far into the design phase of a project i have in mind, is there a way to connect arduinos in a non-master/slave manner to pass a few different combinations of HIGH/LOW (say 5) or 'information' both ways using digital pins? Perhaps some library i don't know about?

Each of these modules should be identical and be able to connect on any face to any other module. I've included a crude image of what I would like to accomplish.

I've already determined that i can solder to these neodymium magnets without loss of magnetic properties by having the little magnets attached to a stronger magnet during the soldering process. Magnet to magnet connection shows only a very tiny resistance.

If it can't be accomplished, i will need to abandon the project and look for some other means to make my project. Thanks in advance!

~zen

# Answer
While idea looks cool, you need some kind of "locks" because not "any combination" can work.

Rotate second Arduino in bottom row on 180 degree and you will see that GND/5V reversed relatively to first arduino in second row.

You have to account magnet N-S polarities to allow good lock. Probably you can use magnet polarities to achieve proper orientation.
> 1 votes

# Answer
Non-master/Slave is absolutely the best for lots of applications. Why bother with Arduinos? There are much better processors available at low cost. Lots of the STM32 processors allow you to address the serial ports. For instance, from the reference manual of the popular STM32F103 (Blue pill).Quote. Address mark detection (WAKE=1) In this mode, bytes are recognized as addresses if their MSB is a ‘1’ else they are considered as data. In an address byte, the address of the targeted receiver is put on the 4 LSB. This 4-bit word is compared by the receiver with its own address which is programmed in the ADD bits in the USART\_CR2 register. The USART enters mute mode when an address character is received which does not match its programmed address. In this case, the RWU bit is set by hardware. The RXNE flag is not set for this address byte and no interrupt nor DMA request is issued as the USART would have entered mute mode. Unquote. Then use the Embitz compiler, free, use C or C++ if you have to. C++ cannot compete with C for embedded work, proven over and over comparing code size and operating speed. Why use a processor without decent debugger? Embitz and STM32 will give you an unbeatable debugger. The larger STM32 processors also have Canbus, which is the ultimate non-master/slave. Canbus is not difficult to set up, and you will never look back. Alternatively, use ESP32 and Canbus. Regards Johan Smit
> -1 votes

---
Tags: arduino-nano
---


# Question
Title: 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?

# Answer
After much frustration in trying things, I came across this forum post 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.
> 13 votes

---
Tags: uploading, avrdude, linux, upload
---


title: Powering a Tiny Arduino Project

text:
# Question
Title: 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:**

**New Circuit**

**Old Circuit**

---

**Final Circuit**

# Answer
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.
> 3 votes

---
Tags: power, attiny85, lipo
---


title: I need help with U8GLIB library

text:
# Question
Title: 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):

Please help if you have any idea on how to deal with this library as it's driving me insane at the moment!

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

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

> Q: U8g2 requires a lot of memory. How to reduce this? \- 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. 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 directory includes several utilities, including what looks like one that converts OTF fonts to BDF format

Once you get a BDF format font, you use bdfconv 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 votes

---
Tags: arduino-nano, library, display, memory-usage
---


# Question
Title: 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?

# Answer
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.
> 2 votes

# Answer
When the serial buffer (64 bytes) is full the `print` waits until bytes are send away at 9600 baud.
> 1 votes

# Answer
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.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: 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:  Thank you in advance!

# Answer
> 1 votes
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.

---
Tags: arduino-mega, power, pwm
---


title: LED not turning on with following code

text:
# Question
Title: 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);

}

```

# Answer
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.
> 1 votes

# Answer
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);
}

```
> 1 votes

---
Tags: arduino-uno, led
---


title: Displaying characters as bitmaps

text:
# Question
Title: 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!

# Answer
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.
> 1 votes

---
Tags: display, print
---


# Question
Title: 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).

# Answer
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.
> 0 votes

---
Tags: arduino-uno, serial
---


# Question
Title: 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);

 }
}

```

# Answer
> 1 votes
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.

---
Tags: programming, millis, datalogging
---


# Question
Title: 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.

# Answer
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);
}

```
> 1 votes

---
Tags: analogread, mathematics, map, calculation
---


title: Controlling 3 Steppers exactly

text:
# Question
Title: 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 !

# Answer
**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.
> 1 votes

---
Tags: stepper
---


# Question
Title: Soldering Arduino Pro Mini's disaligned pins
I have a couples of Arduino Pro Minis (original from sparkfun) that have those 4 disaligned pin. Unfortunetely, I need to use 2 of them, A4 and A5, because they are the I2C pins and I want to solder them onto a perf board.

Now, I really want to use headers and I do not want to solder any wire directly to it. I also do not want to add headers facing up on the board because I am trying to minimize space. Last, I am not willing to change Arduinos so please do not suggest me to use an Arduino Nano or Pro Micro.

So I would like to know if there is a way to connect those 2 pin to the perf board via headers or is there any alternative pins that I can use to connect and use the I2C interface.

# Answer
That's indeed quite an problem.

If you don't mind losing 2 analog pin, you could solder some jumper-wires between A4 and A2; and between A5 and A3. Then you could connect your I2C lines to pins A2 and A3.

But you have to be careful to never set pins A2 and A3 to OUTPUT in your software. If you want to be super-duper safe, you could cut the trace from the header pins going to the TQFP-chip. See the image below.
> 4 votes

# Answer
Easy! I like these ProMinis and use them in lots of projects. Simply exchange one of the 12 way header pin strips for a 14 way one (cheap to buy long lengths of these strips from eBay) add small neatly soldered wires to extend A4 and A5 to the extra pins you’ve added and job done.
> 3 votes

# Answer
As you are soldering to perf board, perhaps you don't have a printed circuit board specific to your project. If you did, you could modify it, or could make a little intermediate PCB to accept connections from A4 A5 and shift them onto the grid.

If you have some 90°-angle headers, try removing a couple of pins from the plastic former, and 0.05" or 0.15" out from the line of the short side of the L, bend the long leg 90°. Point the jog along the X or Y axis to align the pin with your perf board grid.
> 2 votes

---
Tags: i2c, arduino-pro-mini
---


title: Upgrading NRF module for drone

text:
# Question
Title: 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?

# Answer
> 0 votes
If I search I see plenty of examples of RF with 40 miles, e.g.:

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)

---
Tags: drone
---


# Question
Title: How to Home a stepper and make it move 45 degree after that
I am trying to let a stepper find home (via microswitch) after power up. After that make it move 45 degrees (or the equivalent in steps) and wait for 3 seconds. Below is the code i found/adapted.

The setup part kind of works, but does not run smoothly.

The stepper1() part does not work at all (only jerking movements).

I would also like the motor to be disable when it waits which in my understanding should be achieved by `digitalWrite(M2en,HIGH);`but when I place this at the beginning and end (LOW, HIGH) of stepper1() it never worked. Any ideas would be great.

```
#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.5);
  stepperX.run();
  delay(3000);
}

```

# Answer
You need to call `run` more often. From the documentation:

> You must call this as frequently as possible, but at least once per minimum step time interval, preferably in your main loop. Note that each call to run() will make at most one step, and then only when a step is due, based on the current speed and the time since the last step.

So a single `run` call and then a delay, will make the motor move only one step. So you need to rewrite for example:

```
stepperX.run();
delay(3000);

```

to

```
unsigned long startMillis = millis();
while( millis()-startMillis<3000 )
{
  stepperX.run();
}

```

Secondly, `move` only works on integers, `stepperX.move(22.5);` will actually become `stepperX.move(22);`

Lastly, why are you using a totally different method from the rest, to move the motor 10 steps? I'd use a moveTo(10), like you are using everywhere else.
> 0 votes

---
Tags: stepper
---