body:
I am writing my own library for using with my Arduino. In my code, if I set a pointer I have declared to `NULL`, such as

    int *ptr=NULL;

I get the error

    error: ‘NULL’ was not declared in this scope

I need to initialize it to `NULL` as I am using pointers to implement a list.

If I use `NULL` directly in the program in the IDE, I do not get this error. This seems to be happening only when it is a part of the library code.

How do I correct this? Is there any alternative keyword to use? Or do I have to include some library?

Thank you.

title: Setting a pointer to NULL in Arduino library - error: ‘NULL’ was not declared in this scope

Answers: 2

body:
You should make sure your header includes the [`stddef.h`](http://pubs.opengroup.org/onlinepubs/7908799/xsh/stddef.h.html) header, which holds all these standard definitions (hence its name):

    #include <stddef.h>

body:
> I am writing my own library for using with my Arduino.

You should really include Arduino.h, i.e.

    #include <Arduino.h>

Not only will that define `NULL` for you, but you also get the other standard Arduino functions like `digitalRead`, pin number declarations, and various useful macros.


body:
I have 2 buttons.  Button 1 will start/stop the melody while the button 2 will reset the melody. My melody is "Happy Birthday".

How am I going to use the buttons to start/stop/reset the melody?

Here's the code:

    #include "pitches.h"

    int melody[] = {
        NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, NOTE_C4, NOTE_B3,
        NOTE_G3,NOTE_G3, NOTE_A3,NOTE_G3, NOTE_D4, NOTE_C4,
        NOTE_G3, NOTE_G3, NOTE_G4,NOTE_E4,NOTE_C4, NOTE_B3, NOTE_A3,
        NOTE_F4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_C4
    };

    int noteDurations[] = {
        8,8,4,4,4,2,8,8,4,4,4,2,8,8,4,4,4,4,3,8,8,4,4,4,2
    };

    boolean needtoPlay;

    void setup() {
        pinMode(4, OUTPUT);
        pinMode(2, INPUT); //START/STOP
        pinMode(3, INPUT); //PAUSE
    }

    void loop() {
        for (int thisNote = 0; thisNote < 26; thisNote++) {
            int noteDuration = 1000 / noteDurations[thisNote];
            tone(4, melody[thisNote], noteDuration);
            int pauseBetweenNotes = noteDuration * 1.60;
            delay(pauseBetweenNotes);
            noTone(4);

            if (needToPlay == true) {
            }
        }
    }

title: Start/Stop/Reset the melody using buttons

Answers: 2

body: Modify your code so notes will play using timer interrupts instead of delay(). Once your program is inside delay(), no button will be responded. Done that, you just have to read buttons either by polling them with digitalRead or using interrupts.

body:
Easiest way would be to add this to the end of the for loop (inside the loop).  Assuming buttons are pulled up.

    //setting pause with pause button
    if (digitalRead(pauseButtom) == LOW) {
        //it will not play while in this loop
        while (true) {
          //if the button is pressed again, exit the loop
          if (digitalRead(pauseButtom) == LOW) {
            break;
          }
          delay(10);
        }
    }

For the reset, just break;  it will exit the for loop and start again.

Alternately, instead of using a for loop, use a counter and increment / reset it.  You will need to store most variables globally.

    if(!paused) {
      //play note
      if (counter < numNotes) {
        counter++;
      } else {
        counter = 0;
      }
    }

    if (digitalRead(pauseButtom) == LOW) {
      pause = !pause;
    }

    if (digitalRead(resetButtom) == LOW) {
      counter = 0;
    }

You could move those last 2 conditionals to interrupts.


body:
I am using an Arduino 2 which collects data from a set of microphones and stores it in an array of unsigned short of 40000 elements and sends them to the PC via Serial USB.

It is working but I'd like to obtain more speed without any errors.

Can you suggest me the best way to do it? Even changing communication.

Thank you

title: Fastest communication between Arduino and PC

Answers: 2

body: SPI: technically no upper limit so long as both parties can keep up and the wires are good enough. Mbps easily doable.

body:
Switch to using SerialUSB instead and use the other USB port. The baud rate is meaningless then - it runs at the speed of the USB port, which is a lot faster than serial (Linux reports it as 480Mbps, though I can't see an 84MHz chip doing that...).

    void setup() {
        SerialUSB.begin(115200); // The number is irrelevant but it needs something in there
    }

    void loop() {
        SerialUSB.println(millis());
        delay(100);
    }

For greater throughput you could devise some packet-based binary protocol to optimize your data flow to use less bytes.


body:
I'm looking for a very simple wireless, low-power, low-cost switch that can transmit a signal to an Arduino. Ideally, each transmitter would have a signature. For instance, let's say I had 4 different transmitters that are attached to a sensor. When the sensor is tripped, I want to wirelessly send a signal to the Arduino. I've looked at [these][1] 433 MHz modules, but it seems like they would also need a microcontroller to send the data, while that's a possible solution, I'm wondering if there is a even smaller, simpler solution.

  [1]: https://www.amazon.com/UCEC-XY-MK-5V-Transmitter-Receiver-Raspberry/dp/B017AYH5G0/ref=sr_1_3?ie=UTF8&qid=1486572535&sr=8-3&keywords=433MHz modules

title: I need a simple, low power, low cost wireless switch to transmit to Arduino

Answers: 2

body:
There is no such thing as a transmitter that can attach direct to a sensor, since no two sensors in the world work the same way. You need something intelligent between the sensor (to read the sensor value) and the transmitter (to tell it what to transmit).

There are "all in one" modules, like the ESP8266, which have an MCU and WiFi combined in one chip which are closer to what you want, but it is still down to you to program those modules to work how you need them to work for your sensors.

body: You could use an infrared led and an infrared sensor combined with a simple circuit to send a series of flashes that only your arduino can read. The only downside to this is that infrared can only be used indoors and they don't work if you don't have a direct line of sight.


body:
My code is:

    if ((minute == 31) && (hour == 4, 6, 9, 11))
    {
      digitalWrite(8, HIGH);
    }

I want to turn on the LEDs when it is exactly

- 04:31,
- 06:31,
- 09:31,
- 11:31

However, the code above doesn't work.
Might be the multiple values the reason for this?

title: Checking for multiple values in IF separated by commata

Answers: 2

body:
Yes, the list of values `4, 6, 9, 11` [does not mean what you think it does][1].

    if ((minute == 31) &&  ((hour == 4) || (hour == 6) || (hour == 9) || (hour == 11))) {
        digitalWrite(8, HIGH);
    }

  [1]: https://en.wikipedia.org/wiki/Comma_operator

body:
Optionally, you could store the values in an array and go across all of them with some code like this:

    int hours = [4,6,9,11];

    function isInArray(inputValue, array) {
        boolean isIn = false;

        for ( int i = 0; I < array.length; i++) {
            // "isIn |= statement" is shorthand for "isIn = (isIn || statement)"
            isIn |= (array[I] == inputValue);
        }

        return isIn;
    }

    if (isInArray(variable, hours)) {
        //do whatever
    }

    //might be able to do
    if (isInArray(variable, [4,6,9,11])) {
        //do whatever
    }


body:
Has anyone been successful in connecting an ESP8266 to the Initial State IoT platform?

On the platform there is only one example with Cactus ESP. I tried it but it did not work because I have a NodeMCU.

Can you please share your Arduino code?

title: ESP8266 & Initial State

Answers: 1

body:
If you use the Arduino IDE Board Manager to install the support for ESP boards
an ESP8266 can be programmed in EXACTLY the same way as you program an Arduino.

This mean you will now be able to follow the Cactus Micro sample up to the point where you upload CMTempTest.ino.

The problem with the [HubTest.ino][1] code is that relies on having a serial link between the Cactus board's main processor and its ESP8266 network slave processor.  You don't have that so all the AT commands are not going to work.

However you do have a number of examples that come with the ESP addition to the IDE and in there will be a network client example.  You need to look at how that code forms a connection and make HubTest.ino work in that way.  I can't tell you exactly what to do (I don't know) but any lines that are AT related need to be replaced by "proper" networking code.

  [1]: https://github.com/InitialState/piot-athome-arduino/blob/master/HubTest.ino


body:
I posted this on the electrical side of stack exchange and they said it was off topic, so I think it will be on topic here and they confused me even more. So if you guys could clear up my confusion, that would help.I know there are sources for this, but I am still lost.  Anyways, here is the run down. I want to control multiple servos (12 of them) using a sensor shield. I need to know what kind of power supply I need. Here is the servo's I am using:

https://www.amazon.com/gp/product/B01NA80LUR/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1

Here is the sensor shield I am using:

https://www.amazon.com/gp/product/B01ACKVPTW/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1

The servos run at 3-7.2V and 750ma-1000ma full load or another person said they ran only 100-150ma. Also, another question is do I plug that power supply, when I get the right one according to what you say, into the dc jack or the external power on the sensor shield board?

Thank you for your time.

title: Arduino Uno: Sensor shield powering multiple servos

Answers: 2

body:
[Arduino.cc forum topic 229646](http://forum.arduino.cc/index.php?topic=229646.0),  “Arduino Sensor Shield v5 (APC220) manual”, is a thread about lack of documentation for that shield.  However, post #10 in that thread states that pulling off the SEL jumper allows you to use an external power supply to power the devices you attach to the shield.  Also see [*Sensor Shield (Version 5X) Separate 5V for Servos*](http://yourduino.com/sunshop//index.php?l=product_detail&p=407) at yourduino.com.

The [Robotics Stackexchange](http://robotics.stackexchange.com) question [*Wiring & driving TowerPro SG90 servos*](https://robotics.stackexchange.com/q/7472) agrees with the 750–1000 mA current draw of SG90 servos.  You could go with a 5 or 6 V power supply, with say 12 A rating if you expect to drive 12 servos at the same time.  However, as a 12 A supply might be expensive, you probably should attach two or three servos to the shield and measure the current draw.   If, for example, your application rarely draws over half an amp per servo, you might scale back to a 10 A or 8 A supply.

Note that an Arduino Uno or Nano (in general, any based on ATmega328-like MCUs) has six pins that support hardware PWM, so you may need to use a Mega instead, or two Uno or Nano  Arduinos.  (Software-generated PWM signals are another possibility but I doubt it would work well enough if your app is at all complicated.)

---

*Edit 1:*  If the system is battery operated, you probably should use a 2S LiPo RC battery, that is, a battery with the voltage of two lithium polymer cells in series (so, 7.4 volts) and whatever number of cells you wish to pay for in parallel, as often used in radio controlled devices.

Some LiPo batteries support 25C discharge rates, ie, can discharge at 25 times their one-hour-discharge rating.  Thus, a 500 mAh battery might work fine – since 25 times .5 A is 12.5 A – if you only need to run your system for up to 2.4 minutes between battery charges.  Or, for example, a $13.49 [Turnigy 1000mAh 2S 20C Lipo Pack HobbyKing RC Battery](https://www.amazon.com/Turnigy-1000mAh-Lipo-HobbyKing-Battery/dp/B0072AEHIC/ref=sr_1_4?ie=UTF8&qid=1486601844&sr=8-4&keywords=2s+lipo+battery) would work ok, even though only rated for 20C.  It could power a 12 A draw for 1/12 hour, or 5 minutes.

---

For the SEL jumper, look in the lower left corner of one of the pictures from [your amazon.com link](https://www.amazon.com/dp/B01ACKVPTW/?tag=stackoverfl08-20), as below.  With the jumper (the short-metal-strap-and-black-plastic-shell assembly, next to the letters SEL) removed, connect battery+ and battery- to the screw-down terminals at bottom left in the photo.  Battery+ goes to Vcc, battery- to Gnd.

[![top view of shield][1]][1]

---

Regarding a second Arduino, you could split the processing across two of them so that each one only needs to know the current time; or could communicate between them by an SPI, I2C, or RS232 interface; or could move up to a Mega2560 Arduino, which has a lot more PWM channels.

*Edit 2:*  If battery weight is an issue, you may be able to use lower-capacity (hence lighter-weight) batteries if your software only moves a few of the servos at the same time.  For example, if you move three or four at a time, and if most of the servos are idle most of the time, you might be able to use a light-weight cellphone battery.

[Addicore.com](http://www.addicore.com/Addicore-SG90-Mini-Servo-p/113.htm) has some useful current measurements for the SG90:

    Voltage                        4.0V to 7.2V, 4.6V - 5.2V nominal
    Running current with 5V supply (no mechanical load)    220 ±50mA
    Stall current with 5V supply (horn locked)             650 ±80mA
    Idle current with 5V supply                              6 ±10mA
    Weight                                                0.32oz (9g)

However, you probably need to make current measurements on your own to see how big the battery needs to be.

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

body:
two things make servos fairly easy to control:

1. they take a slow pwm input; generating pwm is fairly easy on a mcu;
2. they are generally not that sensitive to the duration of the off state: I have tried from 5ms to 40ms (the longest) and they are fine with that.

so if you combine the two attributes together, it is easy to control multiple servos with from one timer interrupts.

I wrote a few pages on this recently:
1. driving multiple servos on AVR Timer2: https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/

2. driving multiple servos on PIC: using TIMER0 (https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-pic-timer0/) or TIMER1 (https://dannyelectronics.wordpress.com/2017/02/07/driving-multiple-servos-with-pic-timer1/).

The following is a combination of the two: driving 8 servos independently on PORTB with TIMER1 and another 8 servos independently on PORTD with TIMER2.

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

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

the user code is quite simple:

    //set up servo controller 1
    srvo1_init();       //reset the servo module
    srvo1_setpr(1, 1000);     //for 1ms
    srvo1_setpr(2, 1200);     //for 1.2ms
    srvo1_setpr(3, 1400);     //for 1.4ms
    srvo1_setpr(4, 1500);     //for 1.5ms
    srvo1_setpr(5, 1800);     //for 1.8ms
    srvo1_setpr(6, 2000);     //for 2ms
    srvo1_setpr(7, 2500);     //for 2.5ms
    srvo1_setpr(8, 4000);     //for 4ms

    //set up servo controller 2
    srvo2_init();       //reset the servo module
    srvo2_setpr(1, 1000);     //for 1ms
    srvo2_setpr(2, 1100);     //for 1.1ms
    srvo2_setpr(3, 1200);     //for 1.2ms
    srvo2_setpr(4, 1300);     //for 1.3ms
    srvo2_setpr(5, 1400);     //for 1.4ms
    srvo2_setpr(6, 1500);     //for 1.5ms
    srvo2_setpr(7, 2000);     //for 2ms
    srvo2_setpr(8, 4000);     //for 4ms

Once it is set-up, you can just leave it alone and no addition attention is required. You can change the duration of course, or disable / re-enable output on a given channel.

Total CPU drain is about 150K ticks in a second for 16 channel controller.

works on Arduino as well.

edit: if you port the code to TIMER0 (easily done),  you can control 32 servos independently.

and if you combine this code with making timers out of the output compare functionality, you can shrink them all on one timer.


body:
When powering Arduino through Japan Jack at 12V USB communication becomes unstable and frequently interrupts/disconnects. Using Arduino Uno R3 and Linux on the connected computer.

Does anyone have any insight why this might be happening?

title: Powering Arduino through 12V USB communication unstable

Answers: 1

body:
12V is a little on the high end for what the arduino can handle by itself. If I were you I would use a DC step down Buck Converter module to hold the voltage at somewhere around 6v.

http://www.ebay.com/itm/like/400673913185?lpid=82&chn=ps

They're super cheap and pretty easy to use. Simply solder the + and - leads from your 12v power supply to the +in and -in on the buck converter. Then the + out and -out to the + and - for your arduino. Turn the potentiometer until you get somewhere around 6V.

Edit:

Actually I was just reading online, and some people have trouble communicating with the arduino through USB while an external power source is connected. Internet says this problem is related to sharing voltages.

https://forum.arduino.cc/index.php?topic=194598.0


body:
My goal in pseudo code is :

    only LED-6 HIGH for 6 seconds, then only LED-7 HIGH for 2 seconds, then only LED-8 HIGH for 4 seconds, then restart

This is very easy with delay(), but I struggle with millis(). Here is my code. Only led 7 and 8 blinks.

    unsigned long currentTime;
    unsigned long previousTime1 = 0;
    unsigned long previousTime2 = 0;
    unsigned long previousTime3 = 0;
    unsigned long interval1 = 6000;
    unsigned long interval2 = 2000;
    unsigned long interval3 = 4000;

    void setup() {

      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);

    }

    void loop() {

      currentTime = millis();

      if (currentTime - previousTime1 >= interval1){
        previousTime1 = currentTime;
        digitalWrite(6, HIGH);
        digitalWrite(7, LOW);
        digitalWrite(8, LOW);
      }

      if (currentTime - previousTime2 >= interval2){
        previousTime2 = currentTime;
        digitalWrite(6, LOW);
        digitalWrite(7, HIGH);
        digitalWrite(8, LOW);
      }

       if (currentTime - previousTime3 >= interval3){
        previousTime3 = currentTime;
        digitalWrite(6, LOW);
        digitalWrite(7, LOW);
        digitalWrite(8, HIGH);
      }
    }

title: Cycling LED's for specific time period with millis()

Answers: 1

body:
A way to make this work is to use only one `previousTime` variable, rather than three of them.

When the program as shown above starts out, `millis()` is in fact close to 0, so none of the three LEDs should light up in the first 2 seconds.  At the 2 second mark, LED 7 comes on.  `previousTime2` gets set to current time, so the second `if` is not going to be satisfied for 2 more seconds.  At that point, LED 7 and 8 are in a race to see which one turns on second; whichever turns on first at the 4-second mark gets turned off within milliseconds, because when any LED turns on, the code turns off the other two LEDs.  Whenever the condition for LED 6 is met, so is the condition for at least one of 7 or 8; so 6 can't stay on more than 2 seconds at most, and even then is in a race with 7 and 8 to come in third.

With a single `previousTime` variable, code like the following might work.

    current = (millis() - previousTime)/1000;
    if (current < 6) {
      digitalWrite(6, HIGH); // turn on 6
    } else {
      digitalWrite(6, LOW);  // turn off 6
    }
    if (current >= 6 && current < 8) {
      digitalWrite(7, HIGH); // turn on 7
    } else {
      digitalWrite(7, LOW);  // turn off 7
    }
    if (current >= 8) {
      digitalWrite(8, HIGH); // turn on 8
    } else {
      digitalWrite(8, LOW);  // turn off 8
    }
    if (current >= 12) {
      previousTime = millis();
    }

Note, the following code has the same effect.

    current = (millis() - previousTime)/1000;
    digitalWrite(6, current < 6);                 // turn 6 on or off
    digitalWrite(7, current >= 6 && current < 8); // turn 7 on or off
    digitalWrite(8, current >= 8);                // turn 8 on or off
    if (current >= 12) {
      previousTime = millis();
    }


body:
I am very new to Arduino and I have this little bit of code:

    if (R2 <= 200){
      counter=counter+1;
      Serial.print("counter: ");
      Serial.println(counter);
    }

I want it to count every time R2 is less than or equal to 200, but I only want it to count once. Right now it adds to the counter 3-2 times while R2 is less than 200. I'd like it to only count once while in that range before R2 becomes greater than 200.

Any suggestions or links to helpful information would be very appreciated. Thank you!

title: Adding to the counter only ONCE while R2 =<200

Answers: 1

body:
You can set a flag to indicate that R2 is or has been above 200 since it last was low, much as follows.

    // before loop() ...
    byte Rhi = true;  // at outset, say that R2 has been high
    ...

    // in loop() ...
      if (R2 > 200)          // Has R2 gone high?
        Rhi = true;
      if (Rhi && R2 <= 200){ // Has R2 gone low from high?
        Rhi = false;
        ++counter;
        Serial.print("counter: ");
        Serial.println(counter);
      }
      ...


body:
Can someone please help me fix my code?

Basically, a user inputs values that determine how many beeps will play from a breadboard-compatible speaker, and right after the beeps are played, a motor (connected to the breadboard)  is supposed to turn.

The beep-code is mine, and I got the motor code from the Arduino website. Anyway, SEPARATELY the codes work - the beeps play from the speaker, the motor turns fine. However, the codes don't work when I combine them (beeps play, but motor does not run after beeps are played), and I have no idea how to fix it. Any help is appreciated. Thanks so much.

    int pin = 3;
    #include <Stepper.h>

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

    void loop() {
      int bpmeasure, measurespg, bpminute;
      Serial.println("Enter number of beats per measure:");
      while (Serial.available() == 0) {};
      bpmeasure = Serial.parseInt();
      Serial.println(bpmeasure);
      Serial.println("Enter number of measures on page:");
      while (Serial.available() == 0) {};
      measurespg = Serial.parseInt();
      Serial.println(measurespg);
      Serial.println("Enter tempo:");
      while (Serial.available() == 0) {};
      bpminute = Serial.parseInt();
      Serial.println(bpminute);
      float tppg = (bpmeasure * measurespg * 60000.0) / bpminute;
      // time it takes to play a page, in milliseconds
      float tpbeat = tppg / (bpmeasure * measurespg);
      // time between each individual note, in milliseconds
      float t = 0.0;
      for (float t = 0.0; t <= tppg ; t += tpbeat) {
        tone (pin, 30, 50);
        delay (tpbeat+50);
      }
      // speaker is supposed to beep every 'tpbeat' amount of milliseconds,
      // until it reaches 'tppg' milliseconds and then speaker should stop beeping
      const int stepsPerRevolution = 900;
      Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
      int stepCount = 0;
      // number of steps the motor has taken
      if (stepCount = 0) {
        // read the sensor value:
        int sensorReading = analogRead(A0);
        // map it to a range from 0 to 100:
        int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
        // set the motor speed:
        if (motorSpeed > 0) {
          myStepper.setSpeed(motorSpeed);
          // step 1/100 of a revolution:
          myStepper.step(stepsPerRevolution / 100);
        }
      }
    }

title: Help combining code

Answers: 1

body:
The first step with combining any programs together is to forget about combining programs together. Instead you need to do something completely different.

Analyse the existing programs individually. Work out and learn exactly how they work and how they do what they do.

Then think about your program. What do you actually want it to do, and how does that relate to the things the other programs did.

Then, finally, using what you learned from analysing the other programs, you write your own new program that does what you want it to do.

Yes, there may be a certain amount of copy-and-paste from the old programs to the new, but until you have taken the time to learn how the old programs work you won't have a clue which parts of them you may want to copy-and-paste, and which you may want to use as inspiration for writing new portions of code.


body:
Based on [this approach][1] I wanted to implement a function for formatted printing data to the serial monitor. I tried the code below:

    int PIN = 12;

    void _printf(char *fmt, ...) {
      va_list va;
      va_start(va, fmt);
      char buf[vsnprintf(NULL, 0, fmt, va) + 1];
      sprintf(buf, fmt, va);
      Serial.println(buf);
      va_end(va);
    }

    void setup() {
      Serial.begin(9600);
      Serial.println("serial monitor has been set up");
      char buf0[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
      sprintf(buf0, "pin %i configured to output", PIN);
      Serial.println(buf0);
      _printf("pin %i configured to output", PIN);
      char buf1[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
      sprintf(buf1, "pin %i configured to output", PIN);
      Serial.println(buf1);
      _printf("pin %i configured to output", PIN);
      pinMode(PIN, OUTPUT);
      char buf2[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
      sprintf(buf2, "pin %i configured to output", PIN);
      Serial.println(buf2);
      _printf("pin %i configured to output", PIN);
      char buf3[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
      sprintf(buf3, "pin %i configured to output", PIN);
      Serial.println(buf3);
      _printf("pin %i configured to output", PIN);
    }

    void loop() { }

But it gives me some weird output:

    serial monitor has been set up
    pin 12 configured to output
    pin 2263 configured to output
    pin 12 configured to output
    pin 2234 configured to output
    pin 12 configured to output
    pin 2205 configured to output
    pin 12 configured to output
    pin 2176 configured to output

What do `2263` and `2269` mean? Why does it happen only inside the function? What is my mistake and how can I fix it?

  [1]: https://arduino.stackexchange.com/a/479/30652

title: Serial printf implementation

Answers: 1

body:
The problem with your code is that you are mixing the "normal" and "variadic" forms of the printf functions.

Any printf function starting with V takes a variadic argument list pointer as its last variable. Any printf function which doesn't start with V takes a variadic list of individual variables.

When calculating your buffer size from a list of variables in your main loop you are incorrectly using `vsnprintf` - you should be using `snprintf` since you aren't passing it a `va_list`, but individual variables. In your `_printf` function you are correctly using `vsnprintf` to calculate the length of the buffer, but then incorrectly using `sprintf` with a `va_list` instead of individual variables.

So your two forms should actually be re-written as:

    // Inline version
    char buf0[snprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
    sprintf(buf0, "pin %i configured to output", PIN);
    Serial.println(buf0);

and:

    void _printf(char *fmt, ...) {
      va_list va;
      va_start(va, fmt);
      char buf[vsnprintf(NULL, 0, fmt, va) + 1];
      vsprintf(buf, fmt, va);
      Serial.println(buf);
      va_end(va);
    }

Remember: if you have a `va_list` then it goes with a `v*printf` function. If you have individual variables they go with a `*printf` function.


body:
If I don't declare `Serial.begin(115200)`, I can send `AT` commands over serial monitor and it replies me.

[![][1]][1]

But when I declare `Serial.begin(115200)` and send `AT` commands inside program or serial monitor there is nothing happens.

[![][2]][2]

Did I miss something?

  [1]: https://i.stack.imgur.com/XaMuw.jpg
  [2]: https://i.stack.imgur.com/Vu3En.jpg

title: ESP8266 doesn't respond to Serial.println("AT")

Answers: 2

body:
You have connected the tx of the Arduino to the tx of the ESP8266 and the rx of the Arduino to the rx of the ESP8266.

What is happening when you type AT in the Serial Monitor is that you are communicating directly with the ESP8266, and not with the Arduino.

You need to connect the rx of the Arduino to the tx of the ESP8266 and the tx of the Arduino to the rx of the ESP8266.

This has asked and answered a number of times, such as:

https://arduino.stackexchange.com/questions/30689/arduino-uno-and-esp8266-serial-monitor-issue/31929#31929

https://arduino.stackexchange.com/questions/30449/arduino-esp8266?rq=1

https://arduino.stackexchange.com/questions/17590/arduino-nano-v3-0-with-esp8266

https://arduino.stackexchange.com/questions/17666/esp-8266-does-not-respond-at-all

Your ESP8266 definitely uses a baud rate of 115200 (as confirmed by your first screen shot), so you don't need to change that when experimenting.

body:
Thank you for the answer @Holmez, third link was very helpful.
I was just change the code and the RX, TX pins like below and it works perfect now.
I can send commands to the ESP both in program and over the serial monitor.

[![][1]][1]

    #include <SoftwareSerial.h>

    SoftwareSerial wifi(10, 11);

    void setup() {
      Serial.begin(115200);
      wifi.begin(115200);
      Serial.println("Test");
      wifi.println("AT+CIFSR");
    }

    void loop() {
      if (Serial.available()) {
        wifi.write(Serial.read());
      }
      if (wifi.available()) {
        Serial.write(wifi.read());
      }
    }

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


body:
Me and my friend have a project to do and we can't seem to figure out why the code we used for our Arduino Nano Board isn't compiling giving us the `Expected ')' before ';' token` Error

Here is the code:

    // connect motor controller pins to Arduino digital pins
    // motor one
    int enA = 10;
    int in1 = 9;
    int in2 = 8;
    // motor two
    int enB = 5;
    int in3 = 7;
    int in4 = 6;

    void setup()
    {
      // set all the motor control pins to outputs
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);
    }
    void demoOne()
    {
      // this function will run the motors in both directions at a fixed speed
      // turn on motor A
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      // set speed to 200 out of possible range 0~255
      analogWrite(enA, 200);
      // turn on motor B
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      // set speed to 200 out of possible range 0~255
      analogWrite(enB, 200);
      delay(2000);
      // now change motor directions
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      delay(2000);
      // now turn off motors
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }
    void demoTwo()
    {
      // this function will run the motors across the range of possible speeds
      // note that maximum speed is determined by the motor itself and the operating voltage
      // the PWM values sent by analogWrite() are fractions of the maximum speed possible
      // by your hardware
      // turn on motors
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      // accelerate from zero to maximum speed
      for (int i = 0; i ; 256; i++)
      {
        analogWrite(enA, i);
        analogWrite(enB, i);
        delay(20);
      }
      // decelerate from maximum speed to zero
      for (int i = 255; i (&gt);= 0; --i)
      {
        analogWrite(enA, i);
        analogWrite(enB, i);
        delay(20);
      }
      // now turn off motors
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }
    void loop()
    {
      demoOne();
      delay(1000);
      demoTwo();
      delay(1000);
    }

We could really use some help.

title: Expected ')' before ';' token Error

Answers: 1

body:
Well, for example `for` doesn't have four parts but three

    for (int i = 0; i ; 256; i++) // => for (int i = 0; i < 256; ++i)

Next one doesn't look much better:

    for (int i = 255; i (&gt);= 0; --i) // =>  for (int i = 255; i >= 0; --i)

There might be more, but these are really obvious. Like you copied it from some website with some characters translated into the html entities.


body:
Is there any way to burn the Arduino bootloader on a standalone Atmega328 (internal clock 8MHz) from the Arduino official website without using an extra Arduino board to burn the bootloader?

I mean, is it possible to burn the bootloader on the Arduino and then remove the ATmega chip from the Arduino board and use it in a breadboard?

Thanks.

title: Burning the Arduino bootloader without an extra Arduino board

Answers: 2

body:
Yes, use an ISP programmer. I personally use [Atmel ICE][1], [Arduinos as ISP][2] and [USBasp][3].

AVRISP is another popular option:

[![enter image description here][4]][4]

This tutorial might be useful: [Sparkfun][5].

  [1]: http://www.atmel.com/tools/atatmel-ice.aspx
  [2]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [3]: http://www.fischl.de/usbasp/
  [4]: https://i.stack.imgur.com/he0Pu.jpg
  [5]: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader

body:
If you don't want to go the route of a dedicated programmer, you could try ArduinoISP where you can program an Arduino board (with a Mega on it) to be a programmer for another AVR device (e.g. another Mega). The instructions can be found at https://www.arduino.cc/en/Tutorial/ArduinoISP and allows you to do something like this:

[![arduinoisp][1]][1]

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


body:
I broke the USB connector on an Arduino Nano and I am trying to use my Uno board as a USB/serial adapter to be able to upload sketches. The broken Nano came with a customized bootloader (*avrdude -c arduino* compatible), which I do not have a copy of. The content in the HEX files I have is encrypted, it has to go through the bootloader for the plain code to be flashed. This rules out ISP.

I came up with this:

[![Uno board to broken Nano][1]][1]

Please note that the ATMega on the Uno board is **removed**. As I am proxying the Nano through the Uno board, I am wiring RX to RX and TX to TX.

The problem I face is that it seems the Nano board is not receiving data from the PC. Everything else works:

  - pressing the reset button on either board resets the Nano
  - TX from the Nano goes back to the PC (the current sketch on the Nano prints some stuff on boot), TX leds blink accordingly on Nano and Uno boards
  - RX led on the Uno board blinks when PC sends something, *but RX led on the Nano board does not blink in that case*
  - connecting the RX/TX Nano pins to a USB/serial cable lets me send and receive data to/from the sketch

I tried with another, non-broken, Nano (standard bootloader) and I have the same issue, so I think the broken Nano is fine. If I upload a sketch that continuously writes to the serial port, the PC receives it. If I upload an "echo" sketch, I do not get anything back (the "echo" works well over direct USB connection).

I am a software guy, my apologies if I am doing something obviously wrong. I read several pages on the topic, I couldn't spot a fix. The boards are not official Arduino products, but I am not sure this is relevant. I wonder if part of the answer is related to the fact that the USB/serial conversion is [handled by a Mega16U2 chip rather than something like a CH340][2], now useless on the broken Nano.

Some links that I checked:

  - [Arduino UNO as USB to serial TTL converter](http://www.princetronics.com/arduino-uno-as-usb-to-serial-ttl-converter/)
  - [Arduino Uno as an FTDI RS232 to Serial Adapter](https://codeseekah.com/2014/09/09/arduino-uno-as-an-ftdi-rs232-to-serial-adapter/)
  - [Using an Arduino or Seeeduino for its FTDI chip](http://hackaday.com/2010/10/09/using-an-arduino-or-seeeduino-for-its-ftdi-chip/)
  - [Use an Arduino UNO as a USB-to-Serial converter](http://forum.arduino.cc/index.php?topic=138832.0)

  [1]: https://i.stack.imgur.com/RBFBj.png
  [2]: https://electronics.stackexchange.com/questions/77562/arduino-uno-rx-tx-pins

title: Arduino board as USB/serial for a Nano with broken USB

Answers: 1

body: As explained in comments by Chris Stratton, both the Mega16U2 on the Uno and the USB/serial chip on the Nano are competing for the signal level. Removing the resistors on the RX/TX lines between the USB/serial chip and the ATMega on the Nano board will prevent it from interfering with the signals exchanged with the Uno.


body:
This bot is supposed to begin moving forward when the button is pressed, and stop after counting 3 lines of tape on the ground. Currently it is set up to scan the color of the floor at the beginning and count any major differences as a line of tape. Unfortunately I can't test its tape-sensing capabilities due to not being able to get it to actually start. It will only move if I hold the button down continuously, and stops as soon as I release it. Here is the code and images (It uses the Arduino Pro Mini 3.3v):

    #include <SFE_ISL29125.h>
    SFE_ISL29125 RGB;
    unsigned int master2;
    unsigned int detect2;
    boolean isOn = false;
    unsigned int accumulator = 0;

    void setup() {
      RGB.init();
      pinMode(7, INPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      master2 = RGB.readGreen();
    }

    void loop() {
      if(isOn) {
        if(accumulator < 3) {
          detect2 = RGB.readGreen();
          digitalWrite(8, HIGH);
          digitalWrite(9, LOW);
          if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
            accumulator++;
          }
        } else {
          accumulator = 0;
          isOn = false;
          digitalWrite(8, LOW);
          digitalWrite(9, LOW);
        }
      } else if(digitalRead(7) == HIGH) {
        isOn = true;
      } else {
        digitalWrite(8, LOW);
        digitalWrite(9, LOW);
      }
    }

[![top-down view][1]][1]
[![bottom view][2]][2]

  [1]: https://i.stack.imgur.com/0eBY5.jpg
  [2]: https://i.stack.imgur.com/P0F20.jpg

title: Bot not activating after button press

Answers: 1

body:
I strongly suspect the main problems with your code are in these lines:

      if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
        accumulator++;
      }

If I understand correctly, with this code you are attempting to tell whether you have been over a line of tape, which will be indicated by a change in reading from `RGB.readGreen();` - say high, low, high.  If so, `accumulator++`.  (I have no opinion on whether this is a valid way of sensing it, or how well your sensor will work.)

This is definitely broken in one way, and probably broken in another.

First the definitely-broken way:

You want to sense down-up-down-up-down-up (or up-down-up-down-up-down).  Your code senses simply three higher or lower readings.  Your `loop()` takes no time at all, so when your buggy moves onto the tape, it will immediately read (say) high, then loop round, read high again, loop round and read high again, and again. `accumulator` is now 3 and we stop the motor.

Second, the maybe-broken way:

What value does `master2` have?  Consider that it is an *unsigned* integer.  You are subtracting 10 from it.  What do you get if its value is `5`?  It can'be be `-5` because it is unsigned.  How you solve this depends on the possible range of values from `RGB.readGreen();`.  The [implementation][1] looks like it could give a value anywhere in the range, so we have to be careful.

Here's my reworking of your code.  It assumes the *concept* of checking for values which vary by 10 from the original value is sensible - I've no idea if it is.  (I don't understand what this "middle" values means, but you say you've "already tested the components individually" which I don't believe because your code could never have worked but, assuming you saw something similar working...)  It also makes a very big assumption that the value will change cleanly - from higher to lower exactly once per edge of strip, with no wobbling.  Log out some values to find whether it really does.

    #include <SFE_ISL29125.h>
    SFE_ISL29125 RGB;
    int master2;
    boolean isOn = false;
    int changes = 0;

    #define BUTTON 7
    #define MOTOR_A 8
    #define MOTOR_B 9

    #define LOWER 0
    #define HIGHER 1
    int last_state = 0;

    void setup() {
      RGB.init();
      pinMode(BUTTON, INPUT);
      pinMode(MOTOR_A, OUTPUT);
      pinMode(MOTOR_B, OUTPUT);
      master2 = (int)(RGB.readGreen()/2);
    }

    void loop() {
      if(isOn) {
        // Wait for 6 changes: up-down or down-up, three times.
        if(changes < 6) {
          int detect2 = (int)(RGB.readGreen()/2);
          digitalWrite(MOTOR_A, HIGH);
          digitalWrite(MOTOR_B, LOW);
          // Count _changes_ in state only
          if(last_state == HIGHER && detect2 <= (master2 - 5) {
            last_state = LOWER;
            changes++;
          } else if (last_state == LOWER && detect2 >= (master2 + 5)) {
            last_state = HIGHER;
            changes++;
          }
        } else {
          accumulator = 0;
          isOn = false;
          digitalWrite(MOTOR_A, LOW);
          digitalWrite(MOTOR_B, LOW);
        }
      } else if(digitalRead(7) == HIGH) {
        isOn = true;
      } else {
        digitalWrite(MOTOR_A, LOW);
        digitalWrite(MOTOR_B, LOW);
      }
    }

  [1]: https://github.com/sparkfun/ISL29125_Breakout/blob/master/Libraries/Arduino/src/SparkFunISL29125.cpp


body:
I simulate Arduino UNO on proteus 8 Pro. I use Arduino software for writing a program.

Is it possible to trace or know the data that are stored in valuables while running the code on Proteus?

I would like to know how the code is running step by step so that I can find logical errors.

Thank you,

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

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

title: Can I monitor data of variables while simulating Arduino on Proteus?

Answers: 1

body:
It is possible. By using several tools on "Virtual Instruments Mode" such as SPI-Debugger, I2C-Debugger, Virtual Terminal, or Logic Analyser.

> I would like to know how the code is running step by step so that I can find logical errors.

For example, you can use Virtual Terminal and print the value of variables you want to examine
[![enter image description here][1]][1]

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


body:
I want to create a network with 10 routers/end devices and one coordinator with my Xbee Pro S2C devices. For That I know I have to do it in API mode. I configured one as a coordinator (DH=0, DL=FFFF, CE=1, AP=1) and one as a router (DH=0, DL=0, CE=0, AP=1) and then I tried making them communicate with the xbee-library for Arduino.

I used this for the coordinator:

    XBee xbee = XBee();
    uint8_t *payload= "Hello!";

    //XBeeAddress64 CoordinatorAddr64 = XBeeAddress64(0x0013A200, uint8_t *payload= "Hello!";0x40C8CA96); //Put the address of the node explicitly.
    //XBeeAddress64 CoordinatorAddr64 = XBeeAddress64(0x0013A200, 0x4125f767); //The address DH:DL = 0 for coordinator always
    XBeeAddress64 CoordinatorAddr64 = XBeeAddress64(0, 0); //The address DH:DL = 0 for coordinator always
    XBeeResponse response = XBeeResponse();
    ZBRxResponse rx = ZBRxResponse();
    ZBTxRequest zbTx = ZBTxRequest(CoordinatorAddr64, payload, 7);
    ZBTxStatusResponse txStatus = ZBTxStatusResponse();
    ModemStatusResponse msr = ModemStatusResponse();

    void setup()
    {
      Serial.begin(9600);
      Serial1.begin(9600);
      xbee.setSerial(Serial1);

      Serial.println(("ZB Node-" + String(NODE_TYPE)+ " FW Version:"+ String(NODE_VERSION)));
      Serial.println(("Arduino Setup Finished on " + String(NODE_NAME) + ". Console should show up!"));
      Serial.println("------------------------------------------------------------------------------");
    }

    void loop()
    {
      // put your main code here, to run repeatedly
      String sample;          //Our incoming messages from coordinator will be collected in this variable.
      uint16_t senderShortAddress;

      xbee.send(zbTx);

      delay(5000);
    }

And for my router, I'm simply trying to receive the data and I'll send data to the coordinator when I am able to read data.

    XBee xbee = XBee();

    uint8_t *payload= "Hi!";

    //XBeeAddress64 CoordinatorAddr64 = XBeeAddress64(0x0013A200, 0x40C8CA96); //Put the address of the node explicitly.
    XBeeAddress64 CoordinatorAddr64 = XBeeAddress64(0x0013A200, 0x4125f755); //The address DH:DL = 0 for coordinator always
    XBeeResponse response = XBeeResponse();
    ZBRxResponse rx = ZBRxResponse();
    ZBTxRequest zbTx = ZBTxRequest(CoordinatorAddr64, payload, 4);
    ZBTxStatusResponse txStatus = ZBTxStatusResponse();
    ModemStatusResponse msr = ModemStatusResponse();

    void setup()
    {
      // put your setup code here, to run once:
      pinMode(STATUS_LED, OUTPUT);
      pinMode(ALIVE_LED, OUTPUT);

       //initialize timer-1 (16 bit timer) for normal timer overflow mode
      Timer1.initialize(500000); //defined in value/1000000 toggleStateFn called every 500 milliseconds.
      Timer1.attachInterrupt(toggleStateFn);

      Serial.begin(9600);
      Serial1.begin(9600);
      xbee.setSerial(Serial);

      Serial.println(("ZB Node-" + String(NODE_TYPE)+ " FW Version:"+ String(NODE_VERSION)));
      delay(3000);
      Serial.println(("Arduino Setup Finished on " + String(NODE_NAME) + ". Console should show up!"));
      Serial.println("------------------------------------------------------------------------------");
    }

    void loop()
    {
      uint16_t senderShortAddress;
      xbee.readPacket();

      if(xbee.getResponse().isAvailable()){
        Serial.print("Available ");
        Serial.println(xbee.getResponse().isAvailable());
        Serial.print("Api ID: ");
        Serial.println(xbee.getResponse().getApiId());

        XBeeAddress64 senderLongAddress = rx.getRemoteAddress64();
        senderLongAddress = rx.getRemoteAddress64();
        Serial.print(senderLongAddress.getMsb(),HEX);
        Serial.println(senderLongAddress.getLsb(),HEX);

        //Get the 16bit address of source node from incoming packet.
        Serial.print("Source Node short address:0x");
        senderShortAddress = rx.getRemoteAddress16();
        Serial.println(senderShortAddress,HEX);
      }
    }

When I run the code I get nothing on the router.

- I checked my connections (OK, Tx1 for MEGA connected to DIN, pin3, and Rx1 connected to DOUT, pin 2);

- I verified that the signal is getting to the Xbee

- Verified the packet. Connected it to serial 1 and just printed it to the serial console and I see that the packet goes correctly to the Xbee (7E 00 15 10 01 00 7D 33 A2 00 41 25 F7 67 FF FE 00 00 48 65 6C 6C 6F 21 00 63) and I can see that the same packet is going in the signal

- When I first got the modules I just started printing from one side to the other and it worked. It was in transparent mode and not in API mode.

The thing is that I can't even get one coordinator and one router to communicate and I want to create a coordinator-10router network. Which means I'm in trouble. Could there be something wrong in my configuration? Is there something wrong in my code? Perhaps I'm using the wrong XbeeAddress64? Is it a problem with the library I'm using?

title: Can't communicate my 2 Xbee modules using API mode

Answers: 0


body:
I just got this today, plugged it in my arduino, and the arduino light starts dimming until you cannot see it any more over the course of 5 seconds. The Computer disconnects the arduino when the light is off (Ding Dong Sound). I found pulling the VIN Connector Jumper/Power Jumper will stop the short circuit and work, but that defeats the purpose, as the board wouldn't even powered.

Here is the video:
[YouTube][1]

Is the motor board broken? If so in what way? are the wires on the board simply broken? Is it due to bad soldering?(I checked solder, looks fine).

Arduino Model: Arduino UNO by Elegoo
Motor Driver Model: L293D Driver Board
[Ebay Listing For Item][2]
(I tried using this with a MEGA also, would short it as well).

  [1]: https://www.youtube.com/watch?v=aEzPjXHXiL4
  [2]: http://www.ebay.ca/itm/L293D-Motor-Drive-Shield-Expansion-Board-for-Arduino-Duemilanove/162163308212?_trksid=p2050601.c100085.m2372&_trkparms=aid=111001&algo=REC.SEED&ao=1&asc=20140211132617&meid=747824cb304b49b88d66ab2cc3ebd836&pid=100085&rk=1&rkt=4&sd=162163308212&clkid=2477980637705759209&_qi=RTM2247625

title: New Arduino Motor Shield Short Circuiting my board?

Answers: 1

body: Thanks to @jwpat7, I have discovered that the reason it is not working is that the seller has messed up and sent me 3 of the same chip, 74HC595N. After doing some research, I have purchased the LM293D Chips.


body:
I'm trying to choose between square or round LEDs.  I would like to select an LED that will "project" light and I cannot find any information comparing the two types.

Which style of LED will project light better?

Projection, for the purposes of this question, means casting light "in-line" with the LED.  For example, an LED right out of the box with straight leads plugged into a breadboard on a flat table will stand vertically.  In this case, I would like to project as much light onto the ceiling as possible.  I hope this makes sense.

If it matters, I'd like to use water clear blue LEDs.

title: Square LED vs Round LED

Answers: 1

body:
Many of the square or rectangular LEDs with leads  – that is, not surface mount devices (SMD)  –  that I've seen are intended for use as panel indicator lights, so are not very bright.   On the other hand, among SMD devices square, rectangular, and round lights run the whole gamut of brightness.  Of course many white LEDs, square or round, are extremely bright because of being intended for illumination.

For projecting a beam against a ceiling, adding optics to the LED may be the best approach.  For example, buy some 99¢ flashlights like “Waterproof 3500LM Pocket LED Flashlight Zoomable LED Torch Mini Penlight Light” on ebay, and either add a blue filter in front of the lens or replace the LED with an ultrabright blue LED, using the zoomed-out flashlight lens to concentrate the light.  Also, search for 10° or 15° “PMMA LED lens” on ebay, Amazon, aliexpress, etc.

Note, for determining if any given LED will project a tight bright beam, look at the angles of its beam pattern.  [![beam diagrams, 30 and 70 degrees][1]][1]  This diagram (from [Led Buying tips at sunriseled.us](http://www.sunriseled.us/Led-Buying-tips.php)) contrasts the intensity of a 30°-beam LED with that of a 70°-beam LED.  The diagram at left below (from [dimmable-gu10.com](http://www.dimmable-gu10.com/sale-114159-180-to-260v-ac-high-lumen-white-20w-140-degrees-beam-angle-cri-80-led-downlight.html)) is typical of intensity-vs-angle diagrams, which usually are shown on a polar plot like that, with a narrower oval corresponding to a tighter beam.  The diagram at right below shows the same information, in a perhaps more easily comprehended form.
[![typical LED goniometer chart][2]][2]

  [1]: https://i.stack.imgur.com/fs8tR.jpg
  [2]: https://i.stack.imgur.com/PL1y2.jpg


body: How to read frequency into voltage with Arduino with an external source of frequency of 0-1Khz max?

title: Read frequency to voltage with Arduino

Answers: 1

body:
In the past I used the LM2917 for this purpose:

http://www.ti.com/lit/ds/symlink/lm2907-n.pdf

That IC is a frequency to voltage converter, so it perfectly suits your need. According to some quick calculations I made it can go to some tens of kHz, so if your signal is up to 1kHz it should be fine.

Now, this is the answer to your question. But... You can easily read the frequency directly with the arduino... If your purpose was to read the frequency, I suggest you to read something about [the X-Y problem](http://xyproblem.info/)


body: I see frequent errors where the network connection to my Arduino Uno WiFi drops when I am requesting a web page. I wrote a simple REST server, and some of the pages will load as expected, but others will fail after loading half of the the text, and I notice that the network connection drops in the middle of these events. Why is the network connection dropping like this?

title: Why does the Arduino Uno WiFi network connection drop when requesting a page?

Answers: 1

body:
I saw this error when I was running low on RAM. The Arduino Uno WiFi appears to drop the network connection in low memory situations. One fix that made a significant difference for my program was to wrap all of the string literals in the F() macro. This moves the strings from ram to flash storage, and in my case quickly freed 500 bytes of SRAM (25% of the available RAM on this board).
For example, replace:

    client.println("HTTP/1.1 200 OK");

with

    client.println(F("HTTP/1.1 200 OK"));
Some other memory optimization may also be necessary.
Another possible cause of these symptoms would be low voltage, possibly from trying to draw too much power from the board to power external devices, but in my case there were no external connections, and I confirmed it was a low-memory issue.


body: I'm new beginner in programming arduino, and I want ask a question about arduino code, this is the problem " i used two arduino to build a robot, but i don't know how to set the code that for two arduino uno that pins in first arduino i used them all and now i wanna use the pins in second arduino, and how write code for the second arduino, which it is the same pin number i used  in first arduino, how to creat a code? thanks a lot guys for answer my question... (sorry for my bad english)...

title: Using same pins number in different arduino?

Answers: 2

body:
The notion that “both Arduinos are in the same sketch” is slightly off.  Each of the Arduinos will contain a program; their programs might be identical if you do some fancy programming, but it is simpler to write one sketch per Arduino.

Thus, your first Arduino will run a sketch designed to control the devices it is connected to, and your second Arduino will run a sketch designed to control the devices that it's connected to.  Conceivably, you might have some devices that both Arduinos connect to.

Calling the two sketches S1 and S2, the device on pin number *n* as referred to in S1 will typically be a different device than the one on pin number *n* as referred to in S2.  Most but not all of the pin usage assignments for each pin number will be different in one sketch versus the other.

It's likely the two Arduinos will need to communicate with each other.  For a range of methods, see for example  *[How to have an Arduino communicate with 3 other Arduinos](https://arduino.stackexchange.com/q/9709)*.  For additional detail see *[Arduino-to-Arduino serial communication](http://robotic-controls.com/learn/arduino/arduino-arduino-serial-communication)* and *[How to network many Arduinos with sensors using I2C](http://www.techbitar.com/how-to-network-many-arduinos-with-sensors-using-i2c.html)*.

If you decide to use I2C, then also see [MasterWriter Tutorial](https://www.arduino.cc/en/Tutorial/MasterWriter) and [Wire Library](https://www.arduino.cc/en/Reference/Wire) webpages at arduino.cc.

body:
To expand on my comment, if you begin your sketch with conditional definitions, you can compile it for different sets of pin assignments just by changing the `#define ARDUINONUMBER xxx` statement:

    #define ARDUINONUMBER 1

    #if ARDUINONUMBER == 1
    #define FRONTMOTORPIN 7
    #define REARMOTORPIN  8

    #elif ARDUINONUMBER == 2
    #define FRONTMOTORPIN 12
    #define REARMOTORPIN  13

    #else
    #error Board number must be 1 or 2.
    #endif

    void setup(void)
    {
       pinMode(FRONTMOTORPIN, OUTPUT);
       pinMode(REARMOTORPIN, OUTPUT);
       ; // etc
    }

    void loop(void)
    {
       ;
    }


body:
I put a LED into 3.3V of the arduino and Ground, and it blew my LED violently, smoke was everyone, the whole half top of the led blew up across my room.

However, when i program the arduino with Pin13 HIGH per say, it will not blow up. Will be lit brightly. (Both using no resistors). However, if I plug mroe stuff in the board, for example, a lcd screen, rotary switches, and pushbuttons for my program, the LED dims to such a low brightness I cannot see.

Why is this? How Do I fix it?

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

Note, that i am using a mega, and some of it is slightly changed, and LED is being powered from A0 (Or Pin 54 on Mega)

  [1]: https://i.stack.imgur.com/L48SJ.gif

title: Voltage and Current and Arduino

Answers: 2

body:
>“I put a LED into 3.3V of the arduino and Ground, and it blew my LED violently ... the whole half top of the led blew up ...” –

Current through the LED was so high that a tiny interconnect wire blew up.  In typical LEDs, an almost-invisible wire connects from the anode lead frame to the LED chip on the cathode lead frame (at left and right, respectively, on each of the three lead frames pictured below).  That wire acted like a fuse and blew up.  With such a fine wire, it doesn't take particularly much current to pop it.

The diagram below shows how current through an LED increases exponentially as voltage across it rises.  The diagram is from ["mikesflightdeck.com LED dimmer" webpage](http://www.mikesflightdeck.com/led_dimmer/leds_and_dimming.html), a page which may be useful in helping you understand why LEDs need series resistors or some other form of current limiting, eg a constant-current circuit.

[![LED voltage vs current graph][1]][1][![LED lead frame][2]][2]

When an LED is powered by an Arduino port output, the port's internal resistance is enough to limit LED current to non-lethal (to the LED) values.  (However, the port itself may get burned out by delivering current beyond its 40 mA absolute max current rating.)

> “However, if I plug more stuff in the board ... the LED dims to such a low brightness ...” –

The stuff being plugged in apparently is drawing enough current to drop the system voltage.  This can happen if your Arduino is powered by a low-power source like a 9-volt transistor-radio battery, or a laptop USB port that can't deliver the 500 mA that a standard USB port is rated at.

If either of those causes is behind the problem, use an external power supply, plugged into the power jack or connected to Vin and Ground.  You can buy suitable “wall-warts” online, or at an electronics store, or quite cheaply at second-hand or thrift shops.

But if neither of those causes is the problem, you may have a clone of an Arduino using substandard parts, and unable to deliver reasonable current through its regulators.  In this case, find a well-regulated 5 V supply to connect between +5V and Ground or to the USB's power pins.  Such supplies are available not only at the aforementioned venues, but also whereever USB phone-chargers are sold, since 5.0 V is what a USB phone-charger should deliver.

  [1]: https://i.stack.imgur.com/jC2rW.jpg
  [2]: https://i.stack.imgur.com/6aaCG.jpg

body:
You *must* use a resistor. See [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html)

> How Do I fix it?

Use a current-limiting resistor.


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

Thank you!

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

title: how to wrap/scroll text with U8G2

Answers: 1

body:
You can do something like

 void loop(void) {
  u8g2_uint_t x;

  u8g2.firstPage();
  do {

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

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

  } while ( u8g2.nextPage() );

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

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

this is taken from [here][1].

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

Of course on ESP32 it is faster.

Used for small OLED 0.98" screen

  [1]: https://github.com/olikraus/u8g2/blob/master/sys/arduino/u8g2_page_buffer/ScrollingText/ScrollingText.ino


body:
I'm writing a small program for my arduino which allows me to send two int values over serial to be interpreted. The first is a frequency Hz value and the second is a a length milsec value.

The code works, and plays the correct tone for the correct amount of millis, but only for single digit integers. If a double or more digit integer is sent then the arduino loops through the code several times and plays the wrong tone.

Here is my code:

    const byte LED = 13; /* LED Pin */
    const byte SPK = 12; /* Speaker Pin */
    const int BAUD_RATE = 19200; /* Baud Rate of Input */

    void setup(){
      pinMode(LED, OUTPUT);
      pinMode(SPK, OUTPUT);
      Serial.begin(BAUD_RATE);
      Serial.setTimeout(0);
      tone(SPK, 1000);
      delay(200);
      noTone(SPK);
      Serial.println("System ready for data");
    }

    void loop(){
      Serial.println("tone");
      while(Serial.available() == false){
        delay(0);
      }
      int toneToPlay = Serial.parseInt();
      Serial.println("delay");
      while(Serial.available() == false){
        delay(0);
      }
      int delayValue = Serial.parseInt();

      tone(SPK, toneToPlay);
      delay(delayValue);
      noTone(SPK);
    }

Expected result is the ability to enter any tone and delay and the arduino plays it then asks for another tone and delay.

Any help is much appreciated.

EDIT: Here is my new code. It does what I want, the only issue is there is a pause after I type the tone value before it asks for the delay value, and a pause after the delay value before it plays the tone. I can't have this delay as data will eventually be sent by a piece of software to the arduino. How can I fix this delay? New code:

    const byte LED = 13; /* LED Pin */
    const byte SPK = 12; /* Speaker Pin */
    const int BAUD_RATE = 19200; /* Baud Rate of Input */

    void setup(){
      pinMode(LED, OUTPUT);
      pinMode(SPK, OUTPUT);
      Serial.begin(BAUD_RATE);
      tone(SPK, 1000);
      delay(200);
      noTone(SPK);
      Serial.println("System ready for data");
    }

    void loop(){
      Serial.println("tone");
      while(Serial.available() == false){
        delay(0);
      }
      int toneToPlay = Serial.readString().toInt();
      Serial.println("delay");
      while(Serial.available() == false){
        delay(0);
      }
      int delayValue = Serial.readString().toInt();

      tone(SPK, toneToPlay);
      delay(delayValue);
      noTone(SPK);
    }

title: Arduino serial controlled tone generator only working with single digit ints?

Answers: 0


body:
I need to be able to see if the volume controls and the middle button of Apple earphones are pressed.

I am using an Arduino Uno. I was thinking about using the `analogRead` function.

I tried connecting the ground of the audio jack to the ground of the Arduino, the micro of the audio jack to the analogPin 0 on the left and right of the audio jack to the 3.3 volt output of the Arduino, but the results of the `analogRead` are not really useful. They are constantly changing.

---

So guys i have this code that constantly gives a bunch of numbers. They are never constant.

    int analogPin = 0;
    int ledPinBlue = 8;
    int ledPinRed = 9;

    int val = 0;
    int times = 0;
    int clickTimes = 0;

    void setup()
    {
      pinMode(ledPinBlue, OUTPUT);
      pinMode(ledPinRed, OUTPUT);
      times = 0;
      Serial.begin(9600);
    }

    void loop()
    {
      val = analogRead(analogPin);
      if (val == 0) {
    times = times + 1;
      }
      else if (!val == 0) {
    times = 0;
      }
      if (times == 500) {
    times = 0;
    digitalWrite(ledPinBlue, HIGH);   // sets the LED on
    delay (500);
    digitalWrite(ledPinBlue, LOW);    // sets the LED off
    Serial.println("Click");
      }
    }

When I press the button of the microphone (the middle button) of the apple earphones, the numbers change to a constant 0.

But when I press the volume buttons, nothing seems to change. Any ideas?

[![This is my connection to the arduino.][1]][1]

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

title: How can I see if volume buttons of Apple earphones are pressed?

Answers: 3

body:
Have you tried searching Apple Earphones Schematic or something similar? You probably won't find a schematic, at least not from Apple, but I did find [this discussion][1] of someone's attempt to figure out what the buttons do, on some kind of Apple earphones or other (you didn't say which ones you have). There must be others who have also experimented with this.

  [1]: https://forums.macrumors.com/threads/how-does-iphone-headphone-remote-circuit-work.841431/

body:
Since you say that an Android headset would be an alternative....

Google have published the [specs][1] for how headset controls work on Android: in short, (up to) four different values of resistor connected between `mic` and `gnd` represent the four buttons.

If you just need to read the controls, use a potential divider between Vcc and ground, and read the mid point with an analogue input to tell you which (if any) key is being pressed.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/YxiR8.png)

<!-- End schematic -->
(Wow, that's big... Dunno how to make it smaller :-) )

  [1]: https://source.android.com/devices/accessories/headset/plug-headset-spec.html

body:
Here is an article that explains the inner working of the Apple headphones:

http://tinymicros.com/wiki/Apple_iPod_Remote_Protocol


body:
I bought this Pro Micro on eBay a while back, and I never really got around to using it. But now that I do my iMac won't recognize the board. I plug it into my iMac and open Arduino and go to the board tab, and it doesn't even have a Pro Micro choice, so I just choose Micro.

In ports it isn't showing up like my other boards do. Is it my computer, because my Chinese clone Uno and Mega weren't being recognized a while ago? I downloaded the CH340 chip driver for them because they used the CH340 chip and now they are recognized and work perfectly!

The thing is the Pro Micro does not use that chip so is there something else I have to do like another driver to download? It is not the cable because I have tried 5 cables and some had the symbol with the circle triangle and square connected on them, which is the usb serial symbol I think, so they aren't just power cables. If anyone knows what the problem is, that would be awesome! Here is the error it gives me when I try to upload it.

     Arduino: 1.6.9 (Mac OS X), Board: "Arduino/Genuino Micro"

    failed MSpanList_Insert 0x31dea0 0x29ab70fa1fa 0x0
    fatal error: MSpanList_Insert

    runtime stack:
    runtime.MSpanList_Insert(0x2c70d0, 0x31dea0)
 /usr/local/go/src/runtime/mheap.c:692 +0x8f
    runtime.MHeap_Alloc(0x2c6d20, 0x6, 0x10000000034, 0xf989)
    runtime.MCentral_CacheSpan(0x2d10d8, 0x30c270)
 /usr/local/go/src/runtime/mcentral.c:85 +0x167
    runtime.MCache_Refill(0x308000, 0xc200000034, 0x30c270)
 /usr/local/go/src/runtime/mcache.c:90 +0xa0

     goroutine 1 [running]:
     runtime.switchtoM()
 /usr/local/go/src/runtime/asm_amd64.s:198 fp=0xc2082b7468          sp=0xc2082b7460
     runtime.mallocgc(0x2200, 0x19ff80, 0x0, 0xc2080d68e9)
 /usr/local/go/src/runtime/malloc.go:178 +0x849 fp=0xc2082b7518     sp=0xc2082b7468
     runtime.newarray(0x19ff80, 0x20, 0xa5ca)
 /usr/local/go/src/runtime/malloc.go:365 +0xc1 fp=0xc2082b7550    sp=0xc2082b7518
     runtime.hashGrow(0x1b4300, 0xc2080dc150)
 /usr/local/go/src/runtime/hashmap.go:744 +0x86 fp=0xc2082b7580    sp=0xc2082b7550
     runtime.mapassign1(0x1b4300, 0xc2080dc150, 0xc2082b7698, 0xc2082b7688)
 /usr/local/go/src/runtime/hashmap.go:456 +0x568 fp=0xc2082b7620  sp=0xc2082b7580
      arduino.cc/builder/props.PropertiesMap.Merge(0xc2080dc150,      0xc2082b7748, 0x1, 0x1, 0x3)
 /Users/jenkins/jenkins/workspace/arduino-builder-     macosx/src/arduino.cc/builder/props/properties.go:162 +0x153     fp=0xc2082b7718 sp=0xc2082b7620
     arduino.cc/builder/props.PropertiesMap.Clone(0xc20803ce40, 0xb2f5f)
 /Users/jenkins/jenkins/workspace/arduino-builder-    macosx/src/arduino.cc/builder/props/properties.go:170 +0xad fp=0xc2082b7770     sp=0xc2082b7718
     arduino.cc/builder.(*RecipeByPrefixSuffixRunner).Run(0xc20801e300,     0xc208068000, 0x0, 0x0)
 /Users/jenkins/jenkins/workspace/arduino-builder-    macosx/src/arduino.cc/builder/recipe_runner.go:53 +0x2c4 fp=0xc2082b78e8    sp=0xc2082b7770
    arduino.cc/builder.runCommands(0xc208068000, 0xc2082b7af8, 0x1c, 0x1c,     0xc208038001, 0x0, 0x0)
 /Users/jenkins/jenkins/workspace/arduino-builder-   macosx/src/arduino.cc/builder/builder.go:181 +0x139 fp=0xc2082b7978    sp=0xc2082b78e8
     arduino.cc/builder.(*Builder).Run(0xc2082b7ce0, 0xc208068000, 0x0,   0x0)
 /Users/jenkins/jenkins/workspace/arduino-builder-  macosx/src/arduino.cc/builder/builder.go:116 +0xe8e fp=0xc2082b7cc0   sp=0xc2082b7978
     arduino.cc/builder.RunBuilder(0xc208068000, 0x0, 0x0)
 /Users/jenkins/jenkins/workspace/arduino-builder- macosx/src/arduino.cc/builder/builder.go:212 +0x49 fp=0xc2082b7ce8  sp=0xc2082b7cc0
     main.main()
 /Users/jenkins/jenkins/workspace/arduino-builder-   macosx/src/arduino.cc/arduino-builder/main.go:316 +0x171b fp=0xc2082b7f98    sp=0xc2082b7ce8
     runtime.main()
 /usr/local/go/src/runtime/proc.go:63 +0xf3 fp=0xc2082b7fe0   sp=0xc2082b7f98
     runtime.goexit()
 /usr/local/go/src/runtime/asm_amd64.s:2232 +0x1 fp=0xc2082b7fe8    sp=0xc2082b7fe0
    arduino-builder returned 2
    Error compiling for board Arduino/Genuino Micro.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

title: Why won't my iMac recognize my Mega32u4 Arduino Pro Micro board (I've tried several cables)?

Answers: 1

body:
From what you say here:

> I plug it into my iMac and open Arduino and go to the board tab, and it doesn't even have a Pro Micro choice, so i just choose Micro.

and from the dump you provide:

> Arduino: 1.6.9 (Mac OS X), Board: "Arduino/Genuino Micro"

It looks to me like you're selecting the wrong board. Instead of just picking a "similar" board from the Tools menu, what you should do is add the Sparkfun board manager package and then select the Pro Micro from it.

[Here][1] you can find the procedure step by step. Follow it and you should be all set.

**EDIT:**

If you tried to upload a sketch with a wrong board selection, then your your Pro Micro may have become "bricked". In order to unbrick it, follow [this procedure][2] (same link as above, different section).

Once you unbrick it, upload the specific blink example code for Pro Micro that you can find in another section of the same link.

If it keeps not working, READ THE ENTIRE ARTICLE linked and try out all troubleshooting instructions before anything else.

  [1]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#installing-mac--linux
  [2]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/all#ts-revive


body:
I'm trying to understand how serial communication for ESP8266 in NodeMCU actually works. I found a quote saying that normal `Serial` is mapped to ports GPIO 1 (TX) and GPIO 3 (RX). They are even labeled on the board like this, so I believe this is true.

However I'd like to understand the relationship between those pins and serial communication over USB. Does this work the same way as in normal Arduino where you can use either communication over USB or hardware serial on pins 0 & 1?

I did some tests and if I run simple program like:

    Serial.begin();
    //.......
    Serial.println("Hello world");

I can see that in serial monitor on my PC. How does that impact serial communication on GPIO 1 & 3 ?

title: NodeMCU serial port - use with computer and device at the same time

Answers: 1

body: Yes, it is the same as Arduino. The TX and RX pins connect to a CH340G chip to convert the serial into USB. If you use USB serial you can't use the pins for anything else.


body:
I'm creating a wordclock and I'd like to change the ws2812b led strip color slowly, so that it fades from one colour to another. However, I'm new to arduino and I can't get it done and I also could not find anything on this anywhere (probably because of using the wrong keywords)

Currently I have a colour hardcoded like this:

    void SwitchLED(int MyArray[], int n) {
         for (i = MyArray[0]; i < MyArray[0]+n; i++) {
              leds[i].setRGB((161,57,0);
         }
    }

(The array in this code are the LEDs that will light up depending on the time I get from a ds3231).

So I would like a (random) starting colour to slowly change to another colour and so on. This in such a way that you will notice it only after a couple of minutes, so very slow and subtle.

I'm using the FastLED libary. I bit of help on this would be appreciated very much.

title: Automatic subtle colour changing on ws2812b with arduino

Answers: 1

body:
For the color, you can use the time (`millis()`) as a hue parameter.

<!-- language: lang-cpp -->

    void SwitchLED(int MyArray[], int n) {
        CRGB color = CHSV(millis()/1024, 255, 255);
        for (i = MyArray[0]; i < MyArray[0]+n; i++) {
            leds[i] = color;
        }
    }

I used 1024 here to scale the time, so it takes 4 min 22 sec, to go through the hue cycle. And a power of two, should solve a visual glitch on `millis()` overflow.


body:
I am doing some work for both Arduino Mini Pro and for a NodeMCU style ESP8266 board. Within the Arduino IDE I tell it what board I am compiling for and downloading to.

How do I access which board in my scripts?

Some sections are for one or the other exclusively. Right now I'm using a `#define` at top of the script, but changing this to switch between boards not the best. For example, version control keeps on thinking I'm in a new branch when I'm not.

title: How to have compiler know whether Arduino or ESP8266?

Answers: 1

body:
There are a number of macros defined to help you with this:

<!-- language: lang-cpp -->

- `__AVR__` for any board with AVR architecture.
- `ARDUINO_AVR_PRO` for the **Arduino Pro or Pro Mini** selection in the **Tools > Board** menu.
- `ESP8266` for any ESP8266 board.
- `ARDUINO_ESP8266_NODEMCU` for the **NodeMCU 0.9 (ESP-12 Module)** or **NodeMCU 1.0 (ESP-12E Module)** selections in the **Tools > Board** menu.

This allows you to do things like this:

<!-- language: lang-cpp -->

    #if defined(__AVR__)
    // AVR specific code here
    #elif defined(ESP8266)
    // ESP8266 specific code here
    #endif


body: I have made a 8*8*8 led cube using arduino. I have found two different codes from different developers having different animations in them. i wanted to combine them and get to run all the animations at once. Both the codes have some similar function names and some are different as well. I wanted to know if i can keep both these separate from each other yet run them one after another. Almost all parameters are different including setup() of both codes. Please help

title: Is there any way that the two 'different' programs of arduino can be run one after another keeping each one separate?

Answers: 1

body:
You can achieve this fairly simply by using **namespaces**. Inside a namespace, symbols are relative to that space. So you could put all of your first sketch into the namespace sketch1, and all of the second sketch into the namespace sketch2 (assuming it all fits, of course).

Now you can call the first sketch's setup and then loop, by qualifying it with the namespace name as illustrated below.

    // FIRST SKETCH

    namespace sketch1
    {

      // FUNCTION PROTOTYPES

      void func1(int a, int b);
      void func2();

      void setup()
      {
        Serial.begin (115200);
        Serial.println ("Inside sketch1 setup");
        func1 (5, 6);
      }

      void loop()
      {
        Serial.println ("Inside sketch1 loop");
        delay (1000);
        func2 ();
      }

      void func1(int a, int b)
      {
        // some function
      }

      void func2()
      {
        // some other function
      }

    } // end of namespace sketch1

    // SECOND SKETCH

    namespace sketch2
    {

      // DECLARE FUNCTIONS BEFORE CALLING THEM

      void func3(int a, int b)
      {
        // some function
      }

      void func4()
      {
        // some other function
      }

      void setup()
      {
        Serial.begin (115200);
        Serial.println ("Inside sketch2 setup");
        func3 (7, 8);
      }

      void loop()
      {
        Serial.println ("Inside sketch2 loop");
        delay (1000);
        func4 ();
      }

    } // end of namespace sketch2

    // MAIN LOOP AND SETUP

    void setup()
    {
      pinMode (10, INPUT_PULLUP);
      if (digitalRead (10) == HIGH)
      {
        sketch1::setup ();
        while (true)
          sketch1::loop ();
      }
      else
      {
        sketch2::setup ();
        while (true)
          sketch2::loop ();
      }
    }   // end of setup

    void loop()
    {

    } // end of loop

In my example I am testing a pin (10) to see if sketch1 or sketch2 should run.

---

>  yet run them one after another

Yes, well sketches normally keep running inside `loop` forever, so you would need a way of deciding when to exit the sketch and run the other one. My example shows how you can choose between one or the other based on a digital input.

---

> I tried it but it is showing that the functions are not declared in this scope.

## Important note re function prototypes

It looks like the IDE's automatic generation of function prototypes doesn't work inside namespaces. Thus you need to do either:

* Make your own function prototypes (that is the function declaration without the actual function code) - see sketch 1 above; or

* Declare a function before it is used (sketch 2 above)

If this is someone else's code you may find it easier to just add the function prototypes as required. When you get the error message, find the function it is referring to, copy the "declaration" part, eg.

    void foo (int a, int b)

Add a semicolon, eg.

    void foo (int a, int b);

Then put that **before** it is called. Make sure it is still inside the namespace.

---

> can I call the setup if first namespace then some func. respective to that namespace then call the setup of second namespace and call func. from that namespace and keep all this in an infinite loop?

Well, you *can* do that, but you need to realize what each sketch is doing. For example if sketch1 turns some pins to output, but sketch2 assumes they are still inputs, then you need to undo that.

> And what is it to wrapup a function and 'how' to do it.

You need to inspect the sketches and see what they have done, so you can "undo" it. For example:

    void wrapup ()
      {
      // set all pins to inputs and LOW
      for (int i = 0; i < 20; i++)
        {
        pinMode (i, INPUT);
        digitalWrite (i, LOW);
        }
      // if Serial used
      Serial.flush ();  // flush output
      Seral.end ();    // stop serial hardware

      // and so on

      }   // end of wrapup


body:
I don't know the name of those. Please advise me.

Thanks very much.

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

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

title: What are devices in this picture?

Answers: 2

body:
It's a [Seeeduino Lotus][1] (or a clone of it).

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

  [1]: http://wiki.seeed.cc/Seeeduino_Lotus/
  [2]: https://i.stack.imgur.com/d78xp.jpg

body:
Item all the way to the right are [these Excellway ET25 2/3/5 Pins Spring Terminal Block Electric Cable Wire Connectors][1]

  [1]: http://www.banggood.com/5Pcs-235-Pins-Reusable-Spring-Lever-Terminal-Block-Electric-Cable-Wire-Connector-p-1103030.html?rmmds=search-left-hotproducts


body:
I have a following code

      #include <Servo.h> //library for servo drive
      int MotorAPinA = 9;   //pin number for DC drive
      int MotorAPinB = 10;  //pin number for DC drive
      Servo myservo; //create object myservo, class servo from Servo library

    void setup() {
      // put your setup code here, to run once:
      pinMode(MotorAPinA, OUTPUT);
      pinMode(MotorAPinB, OUTPUT);
      //myservo.attach(6); //pin number for servo output
      myservo.write(65);
    }

    void loop() {
      analogWrite(MotorAPinA, 240);
    }

This very code works only partly.

If I comment line

    myservo.attach(6)

 then I got my DC drive working.

If I uncomment this line, my Servo goings crazy (effect looks like myservo.write(0) constantly), until I comment line

    analogWrite(MotorAPinA, 240);

and then I got my servo working properly.
While myservo.attach(6) is uncommented, DC drive doesn't work (with uncommented analogWrite).

So, basically, I can have or PWM or Servo working simultaneously, but not both

Any ideas? Arduino Uno R3, Arduino 1.8.1.

title: Problem with PWM interference

Answers: 1

body:
Well, your PWM outputs are both on `16b` `Timer/Counter 1` and the servo is attached to the `8b` `Timer/Counter 0`. So my guess is that `8bit` counter has too low resolution for driving the servo and it uses `Timer/Counter 1` in full `16b` mode for better precision instead (PWM uses just `8bits` from 16). Also `Timer/Counter 0` is used for counting millis, so its settings can't be changed anyway.

For the confirmation you can either:

* use pins `5` and `6` (`TC0`) or/and pins `3` and `11` (`TC2`) and for the servo use pin `9` or `10`
* You can read the values of `TC1` configuration registers and according to the datasheet you can figure out what mode is currently used.

EDIT:
So on the Uno board is used Timer/Counter 1 for timing purposes:

      if(timer == _timer1) {
        TCCR1A = 0;             // normal counting mode
        TCCR1B = _BV(CS11);     // set prescaler of 8
        TCNT1 = 0;              // clear the timer count
        TIFR |= _BV(OCF1A);      // clear any pending interrupts;
        TIMSK |=  _BV(OCIE1A) ;  // enable the output compare interrupt
        timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);
      }

So no `PWM` on the `OC1A` nor `OC1B` in normal mode and the channel A is taken by Servo.


body:
My project is very complicated, but here is a visual synthesis

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

The input actually comes from a kinect, that detects a person position through Processing, which I connected via Serial to Arduino.
Whenever my trigger is activated, a character is sent to arduino.
What I need to make everything work properly is, upon the said input, some lines of code have to be executed once and for a specific amount of time. And upon repeated input, these lines must not be executed until the input changes.

A semplified version would be: I press a button, led turns on for one second and then turns off (even if i'm still pressing it). led doesn't turn on again until i stop pressing and press again. Obviously in my project the input is the character received via serial and the output is the motor to turn on for some time, and then turn off.

I wanted to make the serial thing specific because i think it makes the thing a little bit trickier than the led example.

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

title: Make something happen on a continous input just once and for a specific amount of time

Answers: 2

body:
you want something along the lines:

    bool continuing;
    #define trigger 't'
    void loop(){
      if( Serial.avaiable()) {
        char c;
        c=Serial.read();
        if (continuing) {
           if (c==trigger) { //do nothing, ignore it
           } else {
           continuing=False; }
       } else {
         continuing=True;
         motors.start();
         the_time=milis();
       }
     };
     if (the_time+timespan>milis()) {motors.stop();};
    }

body:
Well, te problem is actually the same provided that you write correctly the first program.

How did you solve the button problem? My suggestion is to use a simple state machine:

    const byte ledPin = 13;
    const byte buttonPin = 2;

    const int onTimeMs = 1000; // The time the led should be on

    // In this state the board waits
    // for the user input
    #define STATE_WAITING 0
    // In this state the button was
    // pressed (so the led is on)
    #define STATE_PRESSED 1
    // In this state the board is waiting
    // for the button to be released
    #define STATE_WAITREL 2

    byte currState;
    unsigned long pressTime;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
      currState = STATE_WAITING;
    }

    void loop() {
     switch (currState)
     {
     case STATE_WAITING:
      if (digitalRead(buttonPin) == LOW)
      {
       digitalWrite(ledPin, HIGH);
       pressTime = millis();
       currState = STATE_PRESSED;
      }
      break;
     case STATE_PRESSED:
      if ((millis() - pressTime) > onTimeMs)
      {
       digitalWrite(ledPin, LOW);
       currState = STATE_WAITREL;
      }
      break;
     case STATE_WAITREL:
      if (digitalRead(buttonPin) == HIGH)
       currState = STATE_WAITING;
      break;
     }
    }

In this case you can be in three states: waiting for the button press, waiting for the led to turn off (after one second) and waiting for the user to release the button.

So... The states remain the same even for the serial input, you just have to trigger the transitions in another way. The only problem is that the serial input is not continuous, so you have to determine what you mean by "stop sending". In my opinion, you can just set a timeout. The simplest way to achieve this is with this code, IMHO:

    const byte ledPin = 13;
    const char cmdChar = 'x';

    const int onTimeMs = 1000; // The time the led should be on
    const int timeoutCmdChar = 50; // The time the char should be off

    // In this state the board waits
    // for the user input
    #define STATE_WAITING 0
    // In this state the character was
    // received (so the led is on)
    #define STATE_RECEIVED 1
    // In this state the board is waiting
    // for the char to be absent
    #define STATE_WAITABS 2

    byte currState;
    unsigned long recvTime;

    unsigned long lastTimeCmdChar;

    void setup() {
     pinMode(ledPin, OUTPUT);
     Serial.begin(9600);
     currState = STATE_WAITING;
    }

    void loop() {
     bool cmdCharReceived = false;
     while (Serial.available())
     {
      if (Serial.read() == cmdChar)
      { // Received the character
       cmdCharReceived = true;
       lastTimeCmdChar = millis();
      }
     }

     switch (currState)
     {
     case STATE_WAITING:
      if (cmdCharReceived)
      {
       digitalWrite(ledPin, HIGH);
       recvTime = millis();
       currState = STATE_RECEIVED;
      }
      break;
     case STATE_RECEIVED:
      if ((millis() - recvTime) > onTimeMs)
      {
       digitalWrite(ledPin, LOW);
       currState = STATE_WAITABS;
      }
      break;
     case STATE_WAITABS:
      if ((millis() - lastTimeCmdChar) > timeoutCmdChar)
       currState = STATE_WAITING;
      break;
     }
    }


body:
I'm reading a BLE device and my api return me this struct

    typedef struct {
      LGATTAddress bd_addr;
      int32_t rssi;
      uint8_t eir_len;
      uint8_t eir[256];
    } LGATTDeviceInfo;

I try to print some eir_len and eir[256] and this is the result

      for(int i = 0; i < 255; i++)
      {
        Serial.print(info.eir[i], HEX);
      }
      Serial.println();

      Serial.print("Advertising data lenght: ");
      Serial.print(info.eir_len);
      Serial.println();

        21613FF4C0CE8E1B87D83CB43431A739F4496E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
        Advertising data lenght: 23

        2167FF4C0102B00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
        Advertising data lenght: 11

        216320A0109524543414D3532474A5830313235315125005002A0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
        Advertising data lenght: 33

I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?

According to bluetooth specs..

The data is 240 octets and consists of a significant part and a non-significant part. The significant part contains a sequence of data structures. Each data structure shall have a length field of one octet, which contains the Length value, and a data field of Length octets. The first n octets of the data field contain the extended inquiry response (EIR) data type. The content of the remaining Length - n octets in the data field depends on the value of the EIR data type and is called the EIR data. The non-significant part extends the extended inquiry response to 240 octets and shall contain all-zero octets.

[![Here is the eir][1]][1]

How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?

**update**

Let's take for example this response

[LGATTC ino]dev address : [8:46:be:ca:2c:2] rssi [-63]

    2 1 6 9 8 69 53 65 6E 73 6F 72 20 9 FF BE CA 2C 2 46 2 5F 5D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    Advertising data lenght: 23

I try to convert the hex to string and this part `69 53 65 6E 73 6F 72` is the sensor name (iSensor).

This is a bluetooth sensor that change in this way

    <be ca 2c 02 46 02 58 56> - > open
    <be ca 2c 02 46 00 59 55> - > close
    <be ca 2c 02 46 02 5a 58> - > open
    <be ca 2c 02 46 00 5b 57> - > close
    <be ca 2c 02 46 02 5c 5a> - > open
    <be ca 2c 02 46 00 5d 59> - > close
    <be ca 2c 02 46 02 5e 5c> - > open
    <be ca 2c 02 46 00 5f 5b> - > close

These are the manufacturer data: the first part `be ca 2c 02` is the unique identifier of the device, the `02/00` identify the status of the sensor...

By the way I negin to understand... I notice now the match between the lenght and the eir!

I must now extract the name in char, the status and the device code!

**edit 2**
I found the specs of my sensors...

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

  [1]: https://i.stack.imgur.com/wi393.png
  [2]: https://i.stack.imgur.com/ymwd8.jpg

title: Bluetooth data: how to handle these data?

Answers: 1

body:
> I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?

The hex numbers may be one or two digits long.  The way the values are being printed does not enable you to discern between `1 2 3`, `12 3` and `1 23`. Try this:

    for(int i = 0; i < 255; i++)
    {
      Serial.print(info.eir[i], HEX);
      Serial.print(" ");
    }

(Someone already [told you this][1].)

---

> How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?

This works for the only example of the data you have given.  If I have guessed correctly how further data will follow, it'll work for them too.  (If I haven't, it won't.)  I have assumed that the name always starts in the same place, ends with a space, three bytes of stuff we don't care about, and that the data is groups of 8 bytes.  It's very likely that some of the other bytes give details of the data to follow, but with only one example and no spec, it's basically impossible to tell.

    // Let's assume the sensor name always starts at element 5...
    char *sensorName = &(info.eir[5]);
    // ...and ends on a 0x20 (space) - which is probably a risky assumption
    char *end = strchr(sensorName, ' ');
    if (end)
    {
        *end = '\0';
        // Sensor name is now in sensorName

        // Let's assume the data starts exactly 4 bytes after the end of the name
        uint8_t *dataItemStart = (uint8_t*)(end + 3);
        uint8_t *dataEnd = info.eir + info.eir_len - 1;
        while(dataItemStart < dataEnd)
        {
            // We have a data item here, as 'dataItemStart'.
            // You can get bytes within it using, for example
            //   dataItemStart[5]
            // to get the 6th item (the 00 or 02 in your examples)

            // Each data item is 8 bytes long, so the next one starts 8 bytes later
            dataItemStart += 8;
        }
    }

  [1]: https://forum.arduino.cc/index.php?topic=454644.0


body:
I'm attempting to re-write a library for the CD74HC4067 multiplexer.  There is a library available for this device on the Arduino Playground, however, it's limited in its functionality.

I have this as a private data member in the class header file:

    uint8_t channelSelects[16][4];

And this in the class constructor:

    CD74HC4067::channelSelects[16][4] = {
        { 0,0,0,0 }, // channel 0
        { 1,0,0,0 }, // channel 1
        { 0,1,0,0 }, // channel 2
        { 1,1,0,0 }, // channel 3
        { 0,0,1,0 }, // channel 4
        { 1,0,1,0 }, // channel 5
        { 0,1,1,0 }, // channel 6
        { 1,1,1,0 }, // channel 7
        { 0,0,0,1 }, // channel 8
        { 1,0,0,1 }, // channel 9
        { 0,1,0,1 }, // channel 10
        { 1,1,0,1 }, // channel 11
        { 0,0,1,1 }, // channel 12
        { 1,0,1,1 }, // channel 13
        { 0,1,1,1 }, // channel 14
        { 1,1,1,1 }  // channel 15
    };
And I'm getting this error:

    cannot convert '<brace-enclosed initializer list>' to 'uint8_t {aka unsigned char}'
Could someone please explain what I'm not understanding here ?

Many thanks in advance.

title: Not understanding C++ arrays

Answers: 3

body: You need `,` at the channel 15 line too.

body:
If you have in your constructor this:

    CD74HC4067::channelSelects[16][4] = ...

then you are trying to assign something into the element at position `[16][4]`. Thats why it's telling you

> cannot convert '<brace-enclosed initializer list>' to 'uint8_t {aka
> unsigned char}'

Anyway - you don't even need that second dimension. You can use binary representation like  `0b00001000` ...

And if you'll think about previous line, you don't even need any array, you can do it with simple counter value and getting its bits.

However if you want to rely on this array, the constructor should look like:

    CD74HC4067::CD74HC4067() :
      channelSelects {
        { 0,0,0,0 }, // channel 0
        { 1,0,0,0 }, // channel 1
        { 0,1,0,0 }, // channel 2
        { 1,1,0,0 }, // channel 3
        { 0,0,1,0 }, // channel 4
        { 1,0,1,0 }, // channel 5
        { 0,1,1,0 }, // channel 6
        { 1,1,1,0 }, // channel 7
        { 0,0,0,1 }, // channel 8
        { 1,0,0,1 }, // channel 9
        { 0,1,0,1 }, // channel 10
        { 1,1,0,1 }, // channel 11
        { 0,0,1,1 }, // channel 12
        { 1,0,1,1 }, // channel 13
        { 0,1,1,1 }, // channel 14
        { 1,1,1,1 }  // channel 15
      }
    {
       // constructor code
    }

(maybe one more {} enclosure, I'm not sure right now exactly)

**EDIT**: I'd go this way (if you need only one or two instances):

<!-- language: lang-js -->

    // ADC READ channel + Address selection pins
    template <uint8_t ADC_Chan, uint8_t Addr0, uint8_t Addr1, uint8_t Addr2, uint8_t Addr3>
    class Mux16b {
    public:
      void initPins () {
        pinMode(Addr0, OUTPUT);
        pinMode(Addr1, OUTPUT);
        pinMode(Addr2, OUTPUT);
        pinMode(Addr3, OUTPUT);
        pinMode(ADC_Chan, INPUT);
      }

      int readMux(uint8_t channel) {
        digitalWrite(Addr0, channel&1 != 0);
        digitalWrite(Addr1, channel&2 != 0);
        digitalWrite(Addr2, channel&4 != 0);
        digitalWrite(Addr3, channel&8 != 0);
        // maybe some delay to stabilize voltage at the ADC_Chan input ??
        return analogRead(ADC_Chan);
      }

      // not necessary but it's easier to use   mux(10) than mux.readMux(10)
      int operator()(uint8_t channel) { return readMux(channel); }
    };

    // analogRead from A0, Address pins: 4 9 5 2
    Mux16b<A0,4,9,5,2>  mux;

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

    void loop() {
      Serial.println(mux.readMux(15));

      Serial.println(mux(12)); // using overloaded operator ()

      delay(5000);
    }

body: I moved the initialization to the header file where it was first declared...  It compiled without errors.