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

Here is my sketch:

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

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

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

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

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

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

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

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

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

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

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

void setup() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

# Answer
# First off

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

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

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

# Second

the line:

```
void tone();{

```

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

# Third

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

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

```

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

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

```

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

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

```

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

# Finally

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

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

---
Tags: arduino-uno, code-review, piezo
---


# Question
Title: Interpreting pull-up values Rp and Rpu in AM3202 (DHT22) datasheet
In the AM2302 datasheet at page 3, table 4, it gives `min`, `typ` and `max` values for `Rpu` (`that the pull-up resistor` as it says verbatim) being `30K`, `45K` and `60K` ohm respectively.

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

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

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

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

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

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

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

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

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

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

---
Tags: temperature-sensor, pull-up, temperature
---


# Question
Title: How to power multiple LEDs with a microcontroller
I currently have a "tiny" setup and want to put a few (~20-30) 0402 LEDs on a 1:87 scale car. My current setup is an ATtiny85 USB Mini Dev Board powered by a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger:

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

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

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

**Question:**

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

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

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

---
Tags: led, attiny85
---


# Question
Title: How to program the Robotdyn Mega 2560 PRO MINI?
I want to program the Robotdyn Mega 2560 PRO MINI which has no USB port.

How do I connect the pins to an FTDI?

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

# Answer
Connect the Arduino to the FTDI in the following way:

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

Use the following settings in the Arduino IDE

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

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

---
Tags: arduino-mega, ftdi, atmega2560
---


title: Motors triggering Interrupt

text:
# Question
Title: Motors triggering Interrupt
I am using a 4wd robotic car to measure straight distances. I have attached two encoders on the front two wheels to measure the distance and I am using the back two wheels to adjust the car and keep it driving straight by using a compass as a reference. The Problem is that when my program is executing the section that drives the back wheels this somehow triggers the interrupt and increments the number of ticks. What is causing this issue?

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

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

  unsigned long num_ticks_l;
  unsigned long num_ticks_r;

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

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

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

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

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

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

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

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

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

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

    // Drive
    drive(power_l, power_r);

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

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

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

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

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

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

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

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

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

  StopCar();
  //Buzzer();
}

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

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

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

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

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

    }

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

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

    }

  }

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

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

    }
  }
}

void countLeft()
{
  enc_l ++;
}

void countRight()
{
  enc_r ++;
}

```

and this is what is on the setup function

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

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

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

      // Buzzer
      pinMode(Buzzer_pin, OUTPUT);

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

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

```

# Answer
> 1 votes
I think you have 2 problems:

1. The used Hall sensor is an analog device, not a digital one. This means it will not output either Vcc or 0V, but instead an analog (continuous) voltage depending on the magnetic field. With zero magnetic field, it will output about half the supply voltage (in this case 2.5V, since Vcc is 5V for you). For analog signals pullups or pulldowns do not make sense. Digital pins have a hysteris, which means, that they will detect a LOW between 0V and 1.67V and a HIGH between 3.33V and 5V (see this answer). This is also called a Schmitt trigger. I assume, that you just want to measure, that the magnet comes near the sensor (so only one polarity matters). This means, that the voltage will stay - let's say - above 2.5V (depending on polarity) and only going from 2.5V to 5V and back. In this condition the pin state will stay high, since it is set high, but never reaches voltage low enough for setting it to low. No interrupt will be triggered. Depending on what you want and the next problem, you can instead use a comparator (which is a special peripheral of the microcontroller) to trigger the incrementation, when a specified threshold voltage is reached (this also mean it would trigger due to small changes around the threshold), or you can buy or build an external Schmitt trigger, where you can change the threshold voltages for LOW and HIGH changes.
2. Motors send out quite a bunch of electromagnetic noise, which can distort analog Signals nearby. Most likely the noise from the motors is high enough to falsely trigger a state change at the pin. Maybe you should look at the analog signal with an oscilloscope, which can show you, how much noise do you really have in this situation. There are many ways to reduce noise on an analog signal. One is to add a low pass filter to cancel out the mostly higher frequency noise. This only works, if the frequency of your signal is considerably lower (so that you can trim the low pass filter to let your signal pass).

---

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

---
Tags: arduino-mega, motor, interrupt
---


# Question
Title: Connect one HC-05 "master" to two slaves at the same time
Does any one know what `AT+CMODE=2` "slave loop" used for. As I try to connect one HC-05 master to two slaves using it, but it didn't work. i donot know if AT+cmode=2 is used for connecting to multiple slaves or not as i want to know what is used for , i tried to understand what it do from the HC-05 datasheet but i didnot find anything useful about it excpet for what is this image

# Answer
> 0 votes
`AT+CMODE`is mainly used for setting the address pairing purpose. What chrisl stated is exactly true, you cannot connect more than 1 slave to the master at a time. When you set the parameter as `2` you actually set a passive connection, a connection between master and slave to receive the remote Bluetooth master device data and send it back to the master device. It is like a feedback-loop, and is mainly related for testing the connectivity and other features of the PAN (Personal Area Network). So actually whatever is received from the master, is sent back again to the master by the slave.

# Answer
> 0 votes
Based on the documentation :

Slave (slave role)----Passive connection;

Slave-Loop----Passive connection, receive the remote Bluetooth master device data and send it back to the master device;

Master (master role)----Inquire the near SPP Bluetooth slave device, build connection with it positively, and build up the transparent data transmission between master and slave device.

More info here : http://www.linotux.ch/arduino/HC-0305\_serial\_module\_AT\_commamd\_set\_201104\_revised.pdf

So if you want your HC-05 master send : AT+ROLE=1

If you want it to connect to a device safely send : AT+CMODE=0 but you have then to specify what address ( AT+BIND= )

If you want it to connect to all devices available send : AT+CMODE=1

---
Tags: arduino-uno, hc-05
---


# Question
Title: Replace 6 pin on/off switch on Power Bank with 3pin or 2pin?
I'm looking to finish up my project in a box and i'm using a battery bank to power the Leonardo micro pro and other components. The bank has a little on/off which on it which has 6 pins underneath.

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

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

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

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

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

---
Tags: power, battery, switch
---


title: Control Stepper via Serial Monitor

text:
# Question
Title: Control Stepper via Serial Monitor
I would like to control my stepper via serial monitor and unfortunatley the code below did not work. Serial monitor works (Serial.println()), but it does not execute the stepperOne() part. Any ideas why would be awesome. Thank you.

```
#include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

String msg;

unsigned int DEST = 800;
unsigned int SPD = 1600;
unsigned int ACCEL = 1600;
const int TEST = 3;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,HIGH);
  Serial.begin(9600);  // Start Serial

}

void loop() {

if (Serial.available()>0) {
    msg = "";
    while (Serial.available()) {
      delay(10);
      char tmp = Serial.read();
      // msg += tmp;
     if( tmp!='\r' && tmp!='\n' ) msg+=tmp; // Does not work either
    }
    msg.replace(" ","");
    if (msg=="G") {
      stepperOne();
      Serial.println("Stepper turned.");
    }
    Serial.flush();
  }
}

void stepperOne() {

  AccelStepper stepper(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper.setMaxSpeed(SPD);
  stepper.setAcceleration(ACCEL);
  stepper.move(DEST);
  if (DEST > 0) {
    while ( stepper.distanceToGo() > 0 ) {
      stepper.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }

```

# Answer
I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. But in case someone encounters the same problem R3 did it for me.
> 0 votes

---
Tags: stepper
---


# Question
Title: Using an external pull-up resistor vs INPUT_PULLUP
When would one would prefer to use an external pull-up resistor vs the internal:

```
pinMode(fanPin, INPUT_PULLUP);

```

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

However, the ATmega32U4 datasheet's Table 29-1 says that RPU or "I/O Pin Pull-up Resistor" is between 20K and 50K ohms.

This question asks about internal vs external pull-ups for a simple button, but I'm asking in the general case.

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

What are the considerations for preferring one over the other?

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

# Answer
There is no OUTPUT\_PULLUP that I am aware of. Use INPUT\_PULLUP for most things.

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

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

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

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

---
Tags: pull-up
---


# Question
Title: How to perform two tasks in one loop in Arduino?
I am trying to make a weather monitor using Arduino. I want my weather monitor to send me a message of the weather data every 5 hours using GSM sheild. Also, there is an LCD on my weather monitor which shows live weather conditions. The problem I am facing is that the delay of 5 hours in my code also applies to the LCD which updates the LCD every 5 hours and not every second as it should. Please tell me how to run these two functions simultaneously.

# Answer
> 1 votes
Consider using a finite state machine to track multiple tasks. Specifically, the state in which you send your message once every 5 hours. And, the state you update your LCD, perhaps once every second.

As your tasks are associated with time, consider using the built in Arduino call to millis() to find how many milliseconds the Arduino program has been running. This will not block your program. Instead it will immediately return with a number you then need to manage.

To create a delay, use the above number from millis() and add the number of milliseconds for the desired delay. Call millis() repeatedly until it returns the calculated number or a number greater than the calculated number. Use this to drive your state machine. Perhaps you only use millis() to count seconds and use software to count up to 5 hours (5 x 60 x 60 seconds).

Note, millis() will eventually roll over as it is of type "unsigned long". That is, it will roll over once about every 50 days. If you want to keep accurate timing when this happens, you will have to account for the roll over in your program.

# Answer
> 0 votes
Something along the lines of this pseudocode should help you.

```
unsigned long weatherUpdate; // Use unsigned longs for millis times
unsigned long screenUpdate;  // You need to worry about wraparound less often
unsigned long timeNow;

setup {

  unsigned int interval1 = 0; // 0 Should be whatever delay you need
  unsigned int interval2 = 0; // 0 Should be whatever delay you need

  updateScreen();
  screenUpdate = millis();

  updateWeather();
  weatherUpdate = millis;

}

loop {

  timeNow = millis();

  /*
     These if statements are true when the interval between the current time
     and the last time the if ran is greater than the required interval. For
     organization purposes, maybe create separate functions for when you
     update your screen and weather functions instead of just replacing
     the function stubs I've included.
  */

  if((timeNow - screenUpdate) > interval1){

    updateScreen();  // Do what you need
    screenUpdate = millis();  // Update time since last run

  }

  if((timeNow - weatherUpdate) > interval2){

    updateWeather();  // Do what you need
    weatherUpdate = millis();  // Update time since last run

  }

}

```

---
Tags: arduino-uno, lcd, gsm
---


# Question
Title: NodeMCU Ping working on one but not another
Update 2: Have tested by pinging various devices on different subnets / vlans and did a pcap on the wifi AP
I can see the icmp requests going through for each request except for ones on the 4.x subnet, almost like the arduino doesnt like that IP address and refuses to send those packets?

Update 1:

Have tested the following

Turned on logging on firewall and noticed the following actions:

* Ping router from Arduino - See logs in firewall, arduino gets response. (Red line)
* Send external web request from arduino - See logs in firewall, arduino gets response. (Orange Line)
* Send web request to internal server - Arduino queries internal DNS and gets IP of web server, but no request send (Nothing in firewall logs) (Yellow and Blue)
* Send ping to internal server - Arduino queries same dns server, gets ip, but no request sent (Firewall logs again) (Yellow and Green)

however, sending the ping and web request from desktop, shows both the firewall log blocking the ping request, and the rule allowing the web request.(Brown Purple Pink)

Have attached diagram again to help visualize whats going onAnd can attach router logs or rules if required

https://imgur.com/a/g4TipmZ

Also have set a windows PC with the same IP address, and can ping the web server, so I know it's something wrong with the arduino's requests to the web server in particular, and not the firewall?

### End Update

I have two Node MCUs which I'm using for a project. A while ago they were working fine, but i recently changed some network settings on my home network and found that it broke the script I had running on them. I finally figured out where it went wrong and fixed it, but now I have another interesting problem.

One of my nodes runs this script fine, where as the other gets stuck on the ping stage. I have uploaded the same script to both nodes and swapped over the IP address assigned and it follows the device not the IP. So I know its not a networking issue.

I know the WiFi is working on the funny node, as it gets a IP address. but it doesn't go any further

Any ideas?

Script attached below:

```
    #include <DHT.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    #include <ESP8266Ping.h>

    // WiFi credentials.
    const char* WIFI_SSID = "SSID";
    const char* WIFI_PASS = "******";
    WiFiClientSecure wifiClient;
    bool connection = false;
    WiFiClient client;
    const char* dbServer = "webaddress";

    void setup() {
      //Open Serial
      Serial.begin(9600);
      Serial.setTimeout(2000);

    //Connect to Wifi
      bool pingtest = false;
      Serial.print("Connecting to WiFi");
      WiFi.begin(WIFI_SSID, WIFI_PASS);
      //Wait for connection
      int wificount = 0;
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      if (WiFi.status() == WL_CONNECTED) {
        connection = true;
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        while(!pingtest){
          Serial.println("Pinging Server");
          if(Ping.ping(dbServer) == true){
            pingtest = true;
          }else{
            Serial.print(".");
            delay(1000);
          }
        }
      }

    }

void loop() {
  Serial.println("Hello");
  delay(2000);
}

```

Update (Cross posted from another forum): I have an Arduino which pings a server on a different VLAN / subnet as part of its code. It was working a while ago, but I changed some settings on my firewall to restrict stuff down, and that broke the Arduino code. I found it was because I was blocking ICMP across VLANs. So I created a rule to allow ping requests between the two VLANs tested on my desktop (on same net as Arduino) and works fine. Went to test on Arduino and wasn't getting any response.

So I put the router IP in and tested it on the Arduino, works fine. I can even ping the Arduino from my desktop, and ping my desktop from the Arduino

So I figured I must have some other firewall rule allowing my desktop to have special access. (not that I could find it) so gave the arduino the same Ip address and no luck, yet can still ping the router

I have attached a crude drawing here. Hopefully it helps to visualize my problem.

# Answer
If a ping doesn't work over a routed connection it could be.

1. Default gateway on the Arduino device, add a `Serial.println(WiFi.gatewayIP().toString());` to print the default gateway.
2. DNS issue, I presume that the `const char* dbServer = "webaddress";` indicate a FQDN.
3. Firewall is blocking the ICMP on either the inbound or outbound path.
> 1 votes

---
Tags: arduino-ide, nodemcu, networking
---


# Question
Title: Issue with code for SDA/SCL TC9548A Multiplexer and HMC5883L sensors
This is my first time posting on this forum, so I hope my question is appropriate here. My team is working with the Adafruit TCA9548A 1-to-8 I2C Multiplexer Breakout board to try and read from six HMC5883L Breakout sensors, and I am in the process of trying to look at their code to solve a problem. For some reason, code does not run at all unless you comment out a certain line in the code. Once it is commented out, the code runs as expected.

Now, we have to initialize it in setup(), but the statement tcaselect(0) statement was commented out so it doesn't initialize the 0th sensor in setup(). We can keep the other part, the if(mag0.begin()) statement, and it works as expected. However, if we uncomment out tcaselect(0) in setup, the entire code crashes, and all we see are 'HM' in the display window. A very basic schematic is shown below:

simulate this circuit – Schematic created using CircuitLab

I ran some tests with my team, and when all six HMC5883Ls and the single TCA9548 multiplexer were connected on the same breadboard according to the schematic, they worked when tcaselect(0) in setup() was not commented out. Next, we had an apparatus to hold the six sensors, and we had it connected with long lengths of wire, the same as the schematic. We hooked it up to the same breadboard, and the code would not run unless tcaselect(0) in setup was commented out. This seems strange to me that they would work when connected on the breadboard, but when spread out and connected to the breadboard via long wires, they would not work unless that code was commented out.

https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout?view=all

https://learn.adafruit.com/adafruit-hmc5883l-breakout-triple-axis-magnetometer-compass-sensor/overview

EDIT: Someone mentioned that wires might have problems with the SDA/SCL bus, so the wires that we're using are 4-pin ribbon cables, 2.54 mm pitch. A very rough schematic of the container that we're using is shown below:

simulate this circuit

Sorry for the roughness. It's the best I can do to show how the container is assembled. There's an 8x8 in. box where the components are stored, so the sensors go from various locations in the apparatus to the center box where the Pi, Arduino, and breadboard are placed. The nodes in the schematic represent the locations of the sensors. Given the rough dimensions, the longest distance for one of the sensors is around 56.8 inches (or approx. 1.45 meters) accounting for some extra wiring.

Code:

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_HMC5883_U.h>

#define TCAADDR 0x70

/* Assign a unique ID to this sensor at the same time */
Adafruit_HMC5883_Unified mag0 = Adafruit_HMC5883_Unified(0);
Adafruit_HMC5883_Unified mag1 = Adafruit_HMC5883_Unified(1);
Adafruit_HMC5883_Unified mag2 = Adafruit_HMC5883_Unified(2);
Adafruit_HMC5883_Unified mag3 = Adafruit_HMC5883_Unified(3);
Adafruit_HMC5883_Unified mag4 = Adafruit_HMC5883_Unified(4);
Adafruit_HMC5883_Unified mag5 = Adafruit_HMC5883_Unified(5);

//Display details of sensor here
void displaySensorDetails(Adafruit_HMC5883_Unified *mag){
  sensor_t sensor;
  mag->getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value);         Serial.println(" uT");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" uT");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" uT");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

//Given sensor i, select and write to it
void tcaselect(uint8_t i) {
  if (i > 7) return;
  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}

    void setup() {
  Serial.begin(9600);
  /* Initialise the 0st sensor */
   //tcaselect(0);
   if(!mag0.begin())  {
    /* There was a problem detecting the HMC5883 ... check your connections */
    Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");
   }

  /* Initialise Sensors 1-6 */
  tcaselect(1);  if(!mag1.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(2);  if(!mag2.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(3);  if(!mag3.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(4);  if(!mag4.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }
  tcaselect(5);  if(!mag5.begin())  {  Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");  }

}

void loop() {
  /* Get a new sensor event */
  sensors_event_t event0;  sensors_event_t event1;
  sensors_event_t event2;  sensors_event_t event3;
  sensors_event_t event4;  sensors_event_t event5;

  tcaselect(0);  mag0.getEvent(&event0);  tcaselect(1);  mag1.getEvent(&event1);
  tcaselect(2);  mag2.getEvent(&event2);  tcaselect(3);  mag3.getEvent(&event3);
  tcaselect(4);  mag4.getEvent(&event4);  tcaselect(5);  mag5.getEvent(&event5);

  /* Display the results (magnetic vector values are in micro-Tesla (uT)) */
  Serial.print(event1.magnetic.x); Serial.print("  ");
  Serial.print(event1.magnetic.y); Serial.print("  ");
  Serial.print(event1.magnetic.z); Serial.print("  ");

  Serial.print(event2.magnetic.x);      Serial.print("  ");
  Serial.print(event2.magnetic.y);      Serial.print("  ");
  Serial.print(event2.magnetic.z + 37); Serial.print("  ");

  Serial.print(event3.magnetic.x); Serial.print("  ");
  Serial.print(event3.magnetic.y); Serial.print("  ");
  Serial.print(event3.magnetic.z); Serial.print("  ");

  Serial.print(event4.magnetic.x); Serial.print("  ");
  Serial.print(event4.magnetic.y); Serial.print("  ");
  Serial.print(event4.magnetic.z + 37); Serial.print("  ");

  Serial.print(event5.magnetic.x); Serial.print("  ");
  Serial.print(event5.magnetic.y); Serial.print("  ");
  Serial.print(event5.magnetic.z); Serial.print("  ");

  delay(500);
}

```

EDIT: Big news, I tried using only two sensors and 1.5m cables and adding 10k pullup resistors from VCC to SDL/SCA on the respective sensors; with these changes, they seem to work even with tcaselect(0) not commented out in setup, though I only used two sensors rather than six. The HMC5883L sensor breakout board contains 10k pullup resistors already, so with another 10k resistor per line, it would make it 5k. Would this value be too much, or is it fine? I looked at the datasheet of the sensor itself, but I can't find anything on what value the input impedance would be for SCL/SDA.

Also, on another related note, one of my sensors had wires crossed deliberately, so SCL and SDA are separated by GND and VCC in the cable. I'm still running tests to see if I need to do this, but is it recommended to do so even if it is not necessary for correct operation? Someone mentioned that having SCL/SDA next to each other would be bad if they cause problems with crosstalk/interference.

# Answer
I'm sure you have, but have you connected the grounds together?

Have you tried 1 sensor on SD/C0 and then moving it to SD/C1 it should stop working, so the fault has to be with SD/C0.

Looking at your code, is there a reason you haven't initialised sensor 0?

```
 /* Initialise Sensors 1-6 */

```

So it looks to me as the fault is caused by you not calling `begin()` on `mag0`
> 1 votes

# Answer
Try bumping the empty to the last slot and changing your for loop to only iterate the first 7.

Serial prints along the way help debugging
> 0 votes

---
Tags: arduino-uno, wires, multiplexer, magnetometer
---


# Question
Title: Latest datasheet for Leonardo's ATmega32U4
What is the authoritative source(s) for the ATmega32U4 (or any Arduino chip for that matter) datasheet?

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

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

---
Tags: atmega32u4
---


title: Code causing Servo motor not to work!

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

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

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

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

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

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

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

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

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

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

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

int tonePin = A3;        //variable for buzzer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

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

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

That is clearly reported in the docs:

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

And also:

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

---
Tags: arduino-uno, servo, arduino-motor-shield, code-review, stepper
---


title: What is mean of 700,150 number?

text:
# Question
Title: What is mean of 700,150 number?
```
 if ((leftsensor >= 700) && (rightsensor >= 700))
   forward();
       else if((leftsensor <= 150) && (rightsensor <= 150))
   backward();
   else if((leftsensor <= 150) && (rightsensor >= 700))
   turnright();
   else if((leftsensor >= 700) && (rightsensor <= 150))
   turnleft();

```

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

This was already answered by @MaximilianGerhardt in the comments.

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

---
Tags: arduino-uno
---


# Question
Title: How can big Arduino programs be analyzed easily?
I have an Arduino project code, but the problem is it has multiple functions and flow of control.

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

Any software or online website?

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

To do it manually:

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

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

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: Get image from Arduino Ethernet Shield sd card
I have a code that uploads the temperature and humidity from a dht22 to a website.

Now i want to add an image to the "add to homescreen" button in safari on ios.

Apple has a html code for this:

```
<link rel="apple-touch-icon" href="/custom_icon.png">

```

Now I want the "custom\_icon.png" to be a link or some other method to a file "Icon.png" on the ethernet shield sd card.

I think I need something like this:

```
client.println("<link rel=\"apple-touch-icon\" href=\"/Icon.png\">");

```

But this doensn't work. It doesn't give an error, but its just the wrong way to acces that file.

I tried using the SD.h library but I am not able to use the library for my code. This is my code.

```
#include <dht.h>
#define dht_apin A0

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

File root;
// initialize the library with the numbers of the interface pins

byte mac[] = {I HIDE THIS};   // physical mac address
byte ip[] = {I HIDE THIS};                        // ip in lan (that's what you need to use in your browser. ("I HIDE THIS")
byte gateway[] = {I HIDE THIS};                   // internet access via router
byte subnet[] = {I HIDE THIS};                  // subnet mask
EthernetServer server(10000);                          // server port
String readString;
dht DHT;
int Temp;

void setup() {
  // set up the LCD's number of columns and rows:
  Serial.begin(9600);
   while (!Serial) {
    ;
  }
  delay(100);
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");

  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

    Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

 Serial.println("done!");

}

void loop() {

  EthernetClient client = server.available();    // Create a client connection
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (readString.length() < 100) {    //read char by char HTTP request
          readString += c;
         }

         if (c == '\n') {      //if  HTTP request has ended
          Temp = 0;
  switch (Temp){
  case 0:
           DHT.read22(dht_apin);
           Serial.print("Vochtigheid = ");
           Serial.print(DHT.humidity);
           Serial.print("%  ");
           Serial.print("Temperatuur = ");
           Serial.print(DHT.temperature);

           delay(500);

           File dataFile = SD.open("Icon.png");

           client.println("HTTP/1.1 200 OK"); //send new page
           client.println("Content-Type: text/html");
           client.println();
           client.println("<HTML>");
           client.println("<HEAD>");
           client.println("<TITLE>Home Damian</TITLE>");
           client.println("<meta http-equiv=\"refresh\"content=\"1 \">");
           client.println("<meta name=\"apple-mobile-web-app-title\" content=\"Home\">");
           client.println("<link rel=\"apple-touch-icon\" href=\"/Icon.png"/>");
           client.println("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
           client.println("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
           client.println("</HEAD>");
           client.println("<BODY bgcolor=\"#273B46\">");
           client.println("<br />");
           client.println("<p><font color=\"white\">Temperatuur = </p>");
           client.println(DHT.temperature,1);
           client.print("&#176C");
           client.println("<p></p>");
           client.println("<p><font color=\"white\">Vochtigheid = </p>");
           client.println(DHT.humidity,1);
           client.print("%");
           client.println("<br />");
           client.println("</BODY>");
           client.println("</HTML>");

           delay(1000);
           Serial.println("OK");
           Temp = 0;
           client.stop();

         }
       }
     }
   }
  }
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

```

# Answer
> 1 votes
The Arduino uses the 8.3 File Format. meaning that your filename must not be more than 8 characters and the file extension must not be more than 3 characters.

eg: picture1.png 12345678.123

Hope that helps.

I have been toying with this for the last few days, and managed to find out that it uses the 8.3 format.

Also the index.html must also be in the 8.3 format. so index.htm

Hope that helps.

# Answer
> 0 votes
You are reading the HTTP request into `readString`. You need to parse that request to see *what* is actually being requested.

If the URL being requested is "icon.png" then you need to open the file on the SD card and send the data back as a properly crafted HTTP response - something in the form:

```
HTTP/1.1 200 OK
Content-type: image/png
Content-length: <file size here>
Connection: close

<Raw PNG data>

```

The first line of the `readString` will contain the request:

```
GET HTTP/1.1 /icon.png

```

You needt to split that up and find what the request is. You could trap specific entries (/, /index.html, etc) and serve those as specifically crafted responses, and all other unmatched requests you could forward on to your SD card reading code. You should, though, extract the file extension and match it to a MIME time so you can set the Content-Type header correctly.

---
Tags: arduino-uno, ethernet, sd-card
---


# Question
Title: What functions are disabled with noInterrupts()?
The Arduino page for `noInterrupts()` says:

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

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

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

Which functions are definitely disabled when interrupts are disabled?

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

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

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

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

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

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

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

```

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

---
Tags: interrupt, communication
---


title: Issues with I2C and Wire.Available()

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

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

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

    uint16_t data;

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

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

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

    return data;
}

```

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

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

Any ideas what could be causing such and issue?

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

---

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

```
uint16_t FDC2214::read16FDC(uint16_t address) {

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

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

```

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

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

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

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

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

```

Remove the Wire.endTransmission at the end.

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

```

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

---

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

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

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

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

---
Tags: serial, i2c, arduino-due, wire-library
---


title: Slow refresh rate on I2C OLED screen

text:
# Question
Title: Slow refresh rate on I2C OLED screen
I'm trying to create a small handheld console with 6 buttons and an I2C 0.96" OLED display: https://i.stack.imgur.com/gWqZP.jpg

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

Here is the code:

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

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

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

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

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

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

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

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

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

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

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

  return a;
}

```

What is slowing the execution down?

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

# Answer
> 2 votes
Solved by updating the Adafruit sdd1306 library and the Adafruit GFX library

EDIT: Why am I being downvoted?

---
Tags: arduino-uno, i2c, performance
---


title: SPI Connections to DAC

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

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

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

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

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

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

To use DSPI you need to first define an SPI object

```
DSPI0 SPI;

```

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

Start it

```
SPI.begin();

```

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

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

```

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

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

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

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

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

---
Tags: spi, adc, digital-analog-conversion
---