message:
Serial printf implementation

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

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.


sender: user

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

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

sender: assistant

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


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

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.

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.


message:
Burning the Arduino bootloader without an extra Arduino board

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.

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


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

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

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.


message:
Bot not activating after button press

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

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


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

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

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


message:
New Arduino Motor Shield Short Circuiting my board?

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

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.


message:
Square LED vs Round LED

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.

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


message:
Read frequency to voltage with Arduino

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

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


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

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?

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.


message:
Using same pins number in different arduino?

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

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


message:
Voltage and Current and Arduino

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

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.


message:
how to wrap/scroll text with U8G2

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

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


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

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

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


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

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.

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


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

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 ?

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.


message:
Automatic subtle colour changing on ws2812b with arduino

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.

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.


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

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.

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


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

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

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


message:
What are devices in this picture?

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

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


message:
Problem with PWM interference

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.

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.


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

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

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


message:
Bluetooth data: how to handle these data?

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

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


message:
Not understanding C++ arrays

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.

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.


message:
Newbie Arduino DC motor problem

So I am new to Arduino and new to electronics in general. I've looked up a few tutorials and they all have a simple early tutorial that turns on a DC motor and turns it off again. Something like this:

[![Valid XHTML][1]][1]
<sub>(source: [cloudfront.net](https://d2r5da613aq50s.cloudfront.net/wp-content/uploads/381382.image2.jpg))</sub>

The transistor I am using is a 2N2222 and the motor is a little 3V DC toy motor.

The problem is that the when I use this circuit, the motor barely turns (I need to give it a little help to get it it moving). I know my code is right (motor is on for 5 seconds, off for 1). i can tell this is working but clearly something is not right.

I am powering the Arduino off the USB port.

As a test, I swapped out the 2.2K Ohm resistor for a 560 Ohm resistor and the motor seems to run fine. However, it creeps during the "off" time (the motor is not under any load). Also, the transistor gets very hot after about a minute of running this loop.

So my questions are:

1) Why does the motor not work when I use the 2.2K Ohm resistor when I see that 2.2K Ohm resistor in different circuit diagrams that demonstrate this type of circuit?

2) Why does changing to the 560 Ohm have the effect that it does

3) Why does the motor creep during the off cycle when using the 560 Ohm?

4) Why does the transistor get so hot using the 560 Ohm resistor?

5) Finally, sometimes as a test, to simple try to turn turn the motor on, I will just reroute to pin 9 wire directly to the Arduino 5V on my breadboard (bypassing Arduino control altogether). Is there any reason this is a bad idea?

I am anticipating questions about current draw but my multimeter maxes out at 200mA; I am getting a new one that goes to 10A and will help me see how much I am drawing.

Thanks in advance of any help. I have tried to be clear and concise so hopefully this does not elicit any snark. If there are any resources to point me to, I would be happy to hear them.

Thank you!

Jim

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

body:
I see a couple of issues here, which are related to your questions. I will use numbers here, but these do not necessarily correspond to the numbers you have used when asking.

1. The first thing you need to do when controlling a motor is to know it maximum *stall* current. The stall current is the current that will circulate through the motor (and through the transistor) when you apply an external force to stop the motor's shaft. But it's also the same current needed for the motor to start when it's completely stopped. So, for dimentioning a transistor, you typically will select one that has, as a rule of thumb, a collector current **two times bigger than the motor's stall current.**

2. The 2N2222 has a maximum Ic of 800 mA (best case, since there are 600 mA versions as far as I know). Although you are not specifying much about your particular motor, a typical 3V DC motor may easily be asking for 500+ mA. Some small motors (specially bad quality ones) may have stall currents bigger than 1 A.

3. If your motor is asking for, let's say 300 mA when continuously running, then, you are near enough of the maximum current of the 2N2222.

4. But there is something more important here: dropout voltage in the transistor. The 2N2222 is a bipolar one, so it will have a Vce superior to 1V (probably around 2V), which means that you are dissipating a non trivial amount of power *in the transistor*. That power is not useful for your motor, nor for your transistor. Here, if the motor has a 3V nominal voltage, the 2V dropout in the transistor is even desirable, but I don't see your calculations about the real dropout in your description. So I assume that you are just counting that there will be an approximate 2V dropout. That means that, if your motor is taking 0.5A to work, you are dissipating 2V x 0.5A = 1W (Watt) in the transistor. **But the poor 2N2222 is a 0.5W transistor!** But even if your motor is using much less current, let's say 0.25 A, you are sill using it at its limits. That will explain why it's getting hot.

5. So, my advice is to go for a bigger transistor, if you want to count on its dropout to do not apply a voltage bigger than 3V to the motor (which can really reduce it lifespan **a lot**), AND do some calculations to be sure that at the currents you are using, you will have the Vce that you want.

6. Another option, probably better, is to replace that bipolar old transistor by a MOSFET, but you will need to provide the apropiate voltage for supplying the motor, since if not you will get nearly all the 5V to the motor (due to the very low Ron on Mosfets, and thus very low dropout voltage), and that will be very bad.

7. Also, please note that the 500mA of the USB port are probably not enough for your setup. But even if you are powering your Arduino from an external power supply through its power jack, you will find a good idea to use common grounds but different Vcc sources for logic and for the motor.

8. Finally a short advice: be sure that the diode protecting the back EMF (the diode connected with its cathode to Vcc in your circuit) is a **fast diode**. A slow, 1Nxxxx diode is usually to slow for effectively protecting your transistor. If you are using for example an 1N4007, you can switch to a UF4007 (Ultra Fast).

9. Regarding your 560R vs 2K2 resistor, this exceeds the answer a bit, so my advice is to read something about base [resistors in transistors, like this][1]. Also something about [open collector configurations][2] may help.

10. Finally, the practice of connecting the base resistor to Vcc in this kind of circuit to test the transistor should be fine. But DO NOT CONNECT the transistor's base directly, use always the resistor.

  [1]: http://www.evilmadscientist.com/2013/base-resistor/
  [2]: http://www.evilmadscientist.com/2012/basics-open-collector-outputs/


body:
***ERROR CORRECTION: Sorry all, I did have one error in my code that explains the creep. I thought I was running a loop to simply turn the motor on and off but actually it was running full on for 5 sec (255) and partial speed (120) of 1 sec, thus the creep. When resetting the code to on on for 5 sec, fully off for 1 sec, with a 560 Ohm resistor, things work as expected. (I still have the problem with the 2.2K Ohm though so most of my question stands.

nbloqs, Thank you ; I will review your answer in detail.

What would so many tutorials show this basic schematic if to has so many issues?

Thanks again!


message:
Reading PushButton status with pyserial

I'm trying to read the status of a PushButton with python via pyserial.

In the loop function of Arduino Uno I have this:

    void loop() {

    if(digitalRead(BUTTON) == HIGH){
    Serial.print("E\n");
    while(1){}
    }

So, if my pushbutton is pressed, it will send this message "E" via serial and then it will enter in an infinite loop so that nothing else happens.

But I want to detect this message in the python code. So this is my python code:

    import serial
    import time

    try:
       arduino = serial.Serial('/dev/ttyACM0', 9600)
    except:
       print "Failed to connect on /dev/ttyACM0"

    try:
       print arduino.readline()

       while True:
          if arduino.readline() == 'E':
            print("Detected!\n")

    except:
       print ("Failed to read!")

The first print before the infinite While is working: it is printing in the ubuntu terminal "Program Initiated", which is a message that I'm sending in the void Setup function of Arduino.

Then, it gets stucked in the line:

     if arduino.readline() == 'E':

I mean, I press several times my pushbutton, and nothing is happening.

Any help?
Thanks!

body:
The string you are sending (`"E\n"`) is not the same one you are checking for: `'E'`.

You could, for example, strip newlines from the string:

    if arduino.readline().strip() == 'E':


message:
Is this example for playing music without delay correct?

I've followed the directions from [this answer][1], to try and play music without delay. This is my code so far:

    #include "pitches.h"

    int melody[] = {
      NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
    };

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

    const int tonePin = 4;
    unsigned long previousMillis = 0;
    int counter = 0;
    int numberOfNotes = sizeof(melody)/sizeof(int);
    boolean outputTone = false;

    void setup() {
      pinMode(tonePin, OUTPUT);
      //Serial.begin(9600);
    }

    void loop() {
      unsigned long currentMillis = millis();
      unsigned long noteDuration = 1000 / noteDurations[counter];
      unsigned long pauseBetweenNotes = noteDuration * 1.30;

      if (counter < numberOfNotes) {
        if (outputTone && ((currentMillis - previousMillis) >= noteDuration)) {
            previousMillis = currentMillis;
            noTone(tonePin);
            outputTone = false;
            counter++;
        }
        else {
            if ((currentMillis - previousMillis) >= pauseBetweenNotes) {
            previousMillis = currentMillis;
            Serial.println(melody[counter]);

            if (melody[counter] == 0) {
              noTone(tonePin);
            } else {
              tone(tonePin, melody[counter]);
            }

            outputTone = true;
          }
        }
      }
    }

`pitches.h` can be found [here][2].

So with this code, the music plays, but slower. The pauses between notes seem longer, and I can't figure out why.

Also, I'm not sure where should I increment my notes counter.

  [1]: https://arduino.stackexchange.com/a/26069/30872
  [2]: https://www.arduino.cc/en/Tutorial/ToneMelody?action=sourceblock&num=2

body:
There's a variable called "pauseBetweenNotes". Try modifying that and see if the pause between notes becomes smaller.

Regarding your counter question, the way the counter is set up looks fine to me.


body:
In this code, your `pauseBetweenNotes` is *in addition to * the duration of the note. In your previous code, IIRC, it included the duration of the note.

Change it to `0.3` times and I think it will behave as you expect.


message:
Need clarification with arduino syntax

I've been learning how to program this fine piece of equipment but i seem stuck. I came upon the "Knight rider" example where you are supposed to blink LED's from one side to another and i can't understand where some of the code comes from. For example:

    byte ledPin[] = {4,5,6,7,8,9,10,11,12,13};
    int ledDelay;
    int direction = 1;
    int currentLED  = 0;
    unsigned long changeTime;
    int pot = 2;
    int i;

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

        for (i = 0; i < 10; i++)
        {
            pinMode(ledPin[i], OUTPUT);
        }

        changeTime = millis();
    }

    void loop()
    {
        ledDelay = analogRead(pot);

        if ((millis()- changeTime) > ledDelay)
        {
            changeLED();
            changeTime = millis();
        }
    }

    void changeLED()
    {
        for (i = 0; i < 10; i++)
        {
            digitalWrite(ledPin[i], LOW);
            Serial.print("i = ");
            Serial.println(i);
        }

        digitalWrite(ledPin[currentLED], HIGH);

        currentLED += direction;

        if (currentLED == 9)
        {
            direction = -1;
        }

        if (currentLED == 0)
        {
            direction = 1;
        }
    }

In this code I don't  know where the "direction" variable is coming from I searched on the arduino reference page but can't find it. Are there other references where I could look or am I misunderstanding something?

body:
It's coming from the program itself:

    int direction = 1;

That means "Create a signed integer called 'direction' and assign it the value 1.


body:
You defined the `direction` variable on the top with:

    int direction = 1;


message:
Why does my LCD screen display white rectangles?

I recently got an Arduino LCD screen. I tried connecting it to the UNO with the 10k potentiometer and all the needed equipment but all I got were white rectangles instead of characters. I have uploaded the hello world code but I saw no changes.

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

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

body: As @Majenko already mentioned, you have to set the right contrast. Use potentiometer to find out what value suits you right.


message:
Using analog in to read a push button

I'm working on a project in which I use a lot of the pins on the Arduino;  I have run out of most of the pins and and I need to read the value of a push button.

Is it possible to read the value of the switch in the analog in pins on the board??

If so how can I implement this?

body:
> Is it possible to read the value of the switch in the analog in pins on the board??

Yes. Analog input pins are also digital IO pins. You can use them exactly the same way as all the other pins on the board.


body:
On ATmega640/ATmega1280/ATmega1281/ATmega2560/ATmega2561 devices (with Arduino Mega using an ATmega640 or 2560), the analog input pins have their analog capabilities in addition to standard digital capabilities.  They can be used to read or write digital values, like other digital pins on the device.

On ATmega48A/PA/88A/PA/168A/PA/328/P devices (with Arduino Uno using an ATmega168- or 328-family device) analog inputs A0 ... A5 have standard digital capabilities, but A6 and A7 do not.  A6 and A7 on an Uno or Nano is limited to analog input.  However, you can use a circuit like the following to multiplex several buttons.  With this circuit attached to A6,  you would get 1 V at A6 when you press S1; 2 V when you press S2; 3 V when you press S3; and so forth.  You get 0 V at A6 when all the switches are open.
[![ladder circuit with 5 switches and 9 resistors][1]][1]

  One would first use a fast analog read (about 13 μs) to decide if any switch is pressed; for example, if the first reading is above 1/2 V.  In some systems, a fast reading may be good enough by itself to decode switch number; if not, take a second reading via ordinary analog read.  In any case, given an analog reading `ar`, and letting `CPS` be the expected step in counts from one switch to the next (in this case either 256/5 or 1024/5 depending upon use of 8 or 10 bits of readings), compute switch number via something like `s = (ar+CPS/2)/CPS;`.

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


body:
Same things happens with me.

Here, it's my code. It's works for me.

    const int kPinBtn = A0;  // Push-Button connected to Analog pin A0
    const int kPinLED = 13;  // LED connected to to Digital Pin 13

    void setup()
    {
      pinMode(kPinBtn, OUTPUT); // Generally, in push-button we take INPUT as a parameter but here we take OUTPUT because ANALOG PIN

      digitalWrite(kPinBtn, HIGH); // Make button condition HIGH

      pinMode(kPinLED, OUPUT);
    }

    void loop()
    {
      // Now, normal push-button operation, LED blink when we press push button

      if(digitalRead(kPinBtn) == LOW)  // If button pressed
      {
        digitalWrite(kPinLED, HIGH);   // Blink LED
      }
      else digitalWrite(kPinLED, LOW); // Else LED is off
    }


body:
> Is it possible to read the value of the switch in the analog in pins
> on the board??

As other answers say, you can use digitalRead on most Analogue pins.  But to answer the question, yes you can read analogue input, which is useful on pins like A6/A7 which cannot be used as digital pins.

You should connect the pin with a pull up resistor - for arduino pins A0-A5 (depending on board, i'm referring to a Nano) this can be done internally using:

    pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5

If you are working on pins A6/A7 you cannot access the internal pull-up resistor, so you need to add your own to prevent a floating input.  A 10K resistor should [go between][1] the input pin and VCC.

Lastly, an example of reading the input:

    const int buttonPin = A7;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    void loop() {
      // read the state of the pushbutton value:
      buttonState = analogRead(buttonPin);

      Serial.println(buttonState);

      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if (buttonState > 512) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
      } else {
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

  [1]: https://learn.sparkfun.com/tutorials/pull-up-resistors/all


message:
How to program an Arduino Uno Pro with a makefile?

I'm using [Arduino Makefile][1] to compile sketches for Uno and Mega boards. I'm now trying to compile a sketch for an [Arduino Uno Pro][2], which is an Uno with a replaced chip to give it features more like a Mega.

When writing a makefile to compile for this board, which `BOARD_TAG` should I use? I don't see this board listed in the official Arduino or Arduino Makefile docs.

  [1]: https://github.com/sudar/Arduino-Makefile
  [2]: http://www.hobbytronics.co.uk/arduino-uno-pro

body:
After you edit your `boards.txt` file to incorporate the Arduino Uno Pro section from near the end of that [Arduino Uno Pro webpage](http://www.hobbytronics.co.uk/arduino-uno-pro) at hobbytronics.co.uk that you referenced, the board tag list produced by `make show_boards` will include the following line:

    uno_pro       Arduino Uno*Pro

indicating the tag should be `uno_pro`.


message:
Arduino Due connection with FLIR Lepton

I'm trying to connect a FLIR Lepton to an Arduino Due. A [thread by pureengineering][1] talks of rerouting some pins. I am not sure what they precisely mean.

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

Does this rerouting mentioned in the link also apply to Arduino Due?

  [1]: https://forum.arduino.cc/index.php?topic=266361.0
  [2]: https://i.stack.imgur.com/rQDOY.jpg

body:
According to the highlighted part of `Due` schematics it'd be better to connect `3.3V` to the `AREF` pin as there might be some significantly big resistor between `AREF` and `3.3V` source. So it might not be needed but one never knows.

Edit: Looking at the DUE board, there is "jumper" resistor, so you can choose 3V3 or AREF, that means AREF is not connected to anything by default. So if you connect 3v3 to AREF, it should be fine (even 5V, if you didn't changed anything on board yet
)

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

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


message:
Demultiplexing Arduino with C++ code

I have been working on a small project recently. I have a circuit like in the image below:

> Hardware Setup Demultiplexer IR Test

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

As you can see I have 8 IR LEDs, which are driven by an MC14051B Multiplexer/Demultiplexer. My goal is to select each IR led individually and send data over the selected IR LED. None of the other LEDs can send signals. Only one LED at a time can be sending IR codes.

---
> Hardware Setup Single IR Test

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

Below is the code I used to send the signal using the IR Library over one LED (no demultiplexer was used in this test).

    // New function to send 'items' codes which are held in the array 'data'
    void sendMulti (const uint8_t& items, const uint32_t* data) {
      for (int i = 0; i < 2; i++) {
        for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex) {
          irsend.sendNEC(data[itemIndex], 32);
          delay(1000);
        }
      }
      delay(5000); //5 second delay between each signal burst
    }

    void loop () {
      static const uint8_t MaxItems = 3;
      uint32_t  data[MaxItems] = {0x1067E21D,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10678877,0x10676897,0x1067A857,0x1067A857,0x10678877,0x1067A857};
      sendMulti(MaxItems, data);
    }

The Single IR Test was a success. However now I want to use the demultiplexer. Any advice or pointers will make me very happy.

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

body:
The most important document you have to read is called a datasheet. [Here][1] you can find the MC14051's.

I assume you already know how a mux/demux work, so... Well, you have eight LEDs, one on X0, another on X1, ... up to X7. The one connected to the pin X, which is your A0 (the pin used on irsend, I assume) is indexed by the three inputs A, B and C.

On page 5 you see the truth table. According to that table, you have to write a 0 on inhibit, and the value on ABC. So, to select led on X0, you have to write 0 on pins 7, 8, 9 and 10. If you want to select led X1, 8 should go high. For led X7, 8, 9 and 10 should be 1, while 7 is low. And this is for all the combinations...

  [1]: http://www.onsemi.com/pub_link/Collateral/MC14051B-D.PDF