title: Arduino Timer Button

text:
# Question
Title: Arduino Timer Button
I am wandering how I would make it so the arduino uno will start a timer when button a is pressed and send "Start" or "Begin" or something like that to the console window. after the timer has started when button b is pressed it will mark the time from start of the timer and put it in the console window. After the timer has started when button c is pressed it will mark the time from start of the timer and put it in the console window. So on and so forth until button e, when button e is pressed i need the time to get logged in the console and they say "End" or "Stop" or something and then pause the sequence until I restart the board. This is for a school project and my only issue really is how to log the times On a timer loop persay.

# Answer
Ordinarily, posters are expected to say what they've tried so far, and to show the code they've written. However, with a problem as difficult as this one, it seems reasonable to illustrate a complete program.

Note, this program assumes that one side of each button goes to Ground and the other side goes to a digital pin with its input pullup turned on. (If you connect one side to +5V instead of to ground, you will need additional circuitry to sense button presses.) The digital pins that are used are selected by changing the values swA, swB, and so forth, in the third line of the program.

```
//  jw - 8 Mar 2016 - Program for buttons demo
// Ref: http://arduino.stackexchange.com/questions/21590/arduino-timer-button
enum { swA=8, swB=9, swC=10, swD=11, swE=12}; // Switchbutton lines
enum { nSwitches=5 };
byte buttonPins[nSwitches]={swA, swB, swC, swD, swE};
byte buttonBusy[nSwitches]={  0,   0,   0,   0,   0};
unsigned long startTime;
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
  // Note, this code assumes one side of button goes to Ground
  // and other side to a digital pin with its input pullup turned on
    pinMode(buttonPins[i], INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Program begins");
}
//--------------------------------------------------------
void doButton(byte b) {
  char *blabels[] = {"A, Start", "B", "C", "D", "E, End"};
  if (digitalRead(buttonPins[b]) && !buttonBusy[b]) {
    // The b'th button has freshly turned on.
    unsigned long now = millis();
    if (b>0 && !buttonBusy[0]) // To ignore B-E if A isn't on
      return;
    buttonBusy[b] = 1;
    if (b==0) startTime = now;  // Button A resets timer
    Serial.print("Button ");
    Serial.print(blabels[b]);
    Serial.print(" at time ");
    Serial.println(now-startTime);
    if (b==nSwitches-1) {   // Last Button ends timing, restarts cycle
      for (byte k=0; k<nSwitches; ++k)
        buttonBusy[b] = 0;  // Clear all the busy-flags
    }
  }
}
//--------------------------------------------------------
void loop() {
  for (int b=0; b<nSwitches; ++b)
    doButton(b);
}

```

*Edit:* Note that triggering messages on button-release instead of button-press would be relatively easy if buttons didn't bounce.

Before explaining that, let's look at why the above code should work. Assume the cycle (buttons A and later E getting pressed, and possibly some of B, C, D too) lasts at least a couple of seconds. Assume we have ordinary button hardware, and that contacts can bounce for several milliseconds at each make or break. When you press a button the Arduino sees a lot of pin-turning-on events, eventually settling at pin-is-on. When you release a button the Arduino sees a lot of pin-turning-off events, eventually settling at pin-is-off. And finally, assume each button press is long enough that at least one `digitalRead()` happens while contacts are closed.

Under those assumptions, the very first time in each cycle that we see a given button closed, we know that button has just been pressed. Also, we can plausibly expect closure of button A to register before closures of other buttons, and can expect the closure of E to register after that of other buttons. So we can ignore bounce.

On the other hand, with on-release triggering we need to distinguish whether a pin-turning-off event is due to contact bounce of a button just pressed, or is actually part of a button-release bounce sequence.

Here's a method worth considering if you want to implement trigger-on-release:
• First, add a `delay(1)` call, in `loop()`. This will make the code timing less processor-dependent, so it can run on a 48- or 72-MHz system as well as on 16-MHz Unos.
• Each time you detect that button b is on, execute `buttonBusy[b] = 40` to start (or restart) a 40-ms timeout. That is, while a button is held down, we keep setting its timeout to 40. (40 ms may be overly conservative. 20 ms should work ok with most switches, and 10 is ok with a lot of them.)
• When you detect that button b is off,
• if `buttonBusy[b]` is zero, do nothing.
• if `buttonBusy[b] > 0`, then decrement `buttonBusy[b]` and test if it now is equal to 1. When it's equal to 1, regard b as released, so do its action.
> 1 votes

---
Tags: arduino-uno, led, arduino-ide, timers, time
---


# Question
Title: why does it use A0 to define analog pin 0 in some case and why use 0 directly?
https://www.arduino.cc/en/Tutorial/AnalogInput

https://www.arduino.cc/en/Tutorial/Knob

For first line of both examples(not in comments), it define the same pin, analog pin 0, but they use different values. why and can use A1, A2, etc. to define other analog pins?

# Answer
> 4 votes
The answer is in the source code. Keep in mind that for this answer, I'm assuming you have a standard Arduino Uno. For other Arduino platforms the values are different but the situation is the same.

If you look at the analog pin definitions in `hardware/arduino/avr/variants/standard/pins_arduino.h`, you'll find these lines:

```
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
...

```

Which tells you that if you call `analogRead(A0)`, it is equivalent to calling `analogRead(14)`. So, really, the question is "How can calling `analogRead(0)` work?"

The answer to that is in `hardware/arduino/avr/cores/arduino/wiring_analog.c`. If you wade through the defines, you'll see that at the top of `analogRead`, there is the following code:

```
if (pin >= 14) pin -= 14; // allow for channel or pin numbers

```

The result is that passing either `0` or `A0` results in `0` being used in the `analogRead` code.

# Answer
> 1 votes
You can use 0 to 5 for `analogRead` of pins A0 to A5. However if you want to do `digitalRead` or `digitalWrite` on those pins then you have to use `A0` through to `A5` in order to avoid confusing them with the digital pins 0 to 5 (on the other side of the board).

> can use A1, A2, etc. to define other analog pins?

Yes.

---
Tags: pins
---


# Question
Title: Brand new to Arduino, and can't even make an LED blink
So I'm going through Getting Started With Arduino. I skipped to making a LED blink when you press a button.

First I wrote the code, then I copied it directly from the .pdf I have, neither has worked.

The code is here:

```
// Example 02: Turn on LED while the button is pressed
const int LED = 13;   // the pin for the LED
const int BUTTON = 7; // the input pin where the
                      // pushbutton is connected
int val = 0;          // val will be used to store the state
                      // of the input pin
void setup() {
  pinMode(LED, OUTPUT);   // tell Arduino LED is an output
  pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
  val = digitalRead(BUTTON); // read input value and store it
  // check whether the input is HIGH (button pressed)
  if (val == HIGH) {
    digitalWrite(LED, HIGH); // turn LED ON
  } else {
    digitalWrite(LED, LOW);
  }
}

```

# Answer
> 2 votes
Other than what what Nick Gammon said that you need the resistor from the board to led, as that will cause your microcontroller pins to get damaged.

The other possible problem is the two breadboards you have put together, the power rails have not been bridged between the two boards. This means that the switch is not providing any logical state to the microcontroller.

Also the only reason why the led is show in the book as a separate thing is that it is meant as an educational exercise to make you build something, the `L` led will do the same thing.

---
Tags: arduino-nano
---


# Question
Title: How do I statements for the various conditions of this function?
I am still new to Aduino and I am trying to use a library's example sketch but I don't understand the following part of the code. I want to trigger an led when the "Pressed" condition is fulfilled. Pardon my ignorance.

```
if (b != ClickEncoder::Open) {
Serial.print("Button: ");
#define VERBOSECASE(label) case label: Serial.println(#label); break;
switch (b) {
  VERBOSECASE(ClickEncoder::Pressed);
  VERBOSECASE(ClickEncoder::Held)
  VERBOSECASE(ClickEncoder::Released)
  VERBOSECASE(ClickEncoder::Clicked)

  case ClickEncoder::DoubleClicked:
      Serial.println("ClickEncoder::DoubleClicked");
      encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
      Serial.print("  Acceleration is ");
      Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
      setMode = true;
       value = 0;
    break;
}

```

}

# Answer
You will have to explicitely expand the case `ClickEncoder::Pressed`. So instead of

```
VERBOSECASE(ClickEncoder::Pressed);

```

you should write something like

```
case ClickEncoder::Pressed:
    Serial.println("ClickEncoder::Pressed");
    digitalWrite(ledpin, HIGH);
    break;

```

Of course then you'll have to turn it off then, but.. Well, that's another problem
> 1 votes

---
Tags: arduino-uno, c++, arduino-ide
---


title: Mounting Arduino in an enclosure

text:
# Question
Title: Mounting Arduino in an enclosure
I've decided to use Sparkfun's Pro Mini boards to make my project into a semi-professional product.

My first thought turned to enclosures - of which the entire internet seems to be bereft. If I ever DO see an enclosure, it's for the Uno sized board and costs about twice the price of the board, which seems incredible to me.

No matter, I have found a way to make quite good enclosures for the Pro Mini pretty easily and cheaply.

HOWEVER, the next problem is mounting the board inside the box. I would like to be able to mount it firmly to the base but in a way which allows it to be removed if necessary. Obviously, there's not a lot of scope for putting screws through the board. It occurs to me that anything which holds it would need to do so by gripping the edges or the corners. Is there such a thing?

If there's nothing that fits the bill, would the board be OK if I were to HOT GLUE it to the base of the enclosure?

# Answer
> 5 votes
What type of box? Howmany times/how easily do you want to remove the Arduino Mini?

**Hot glue**

Hot glue is the way to go in many occasions.

* It does not conduct electricity, so is pretty safe. (Please check your specific hot glue first)
* It sticks quite well, for quite a time. You should also check if it's water resistant or fit for your target environment though.

But, it may have some side-effects:

* It can get quite messy (which does not look really professional)
* It's not that easily removable and has to be "re-glued" when you want to stick it back.
* It might be too sticky (in a carboard box, you won't be able to just rip out the Arduino, withouth damaging the box).

*You could use double sided tape, which might actually work fine. Or atleast better/neater as the hot glue.*

**Sticky velcro**

A neat solution would be sticky velcro. You can easily attach, detach and re-attach the arduino to the velcro. It looks quite fancy and should hold well.

Again, you should check the specific velcro, it might not last 1000+ times of re-attaching (become loose or smh). But will be a good option overall.

**Extra**

You can use mint-boxes as an enclosure. But they're usually made of tin or another conductive material. Please take care and cover the back of your arduino (or box) with electrical tape, to avoid shorts.

Extra-extra, you should (for "replacability") add connectors or headers to your Arduino. Since soldering the leads directly will still give the need to un-solder or resolder your Arduino when replacing.

**Note on making your Arduino project a consumer item**

You might save yourself quite some money by using a barebones arduino. Or actually, an ATmega 328P chip. Which is around 3€. These will be a little more difficult to program, but might also look more professional.

You can also enable "program protection" fuse bits, so that others can't download the code from your arduino/microcontroller.

---
Tags: arduino-pro-mini, enclosure
---


title: Issues with AltSoftSerial

text:
# Question
Title: Issues with AltSoftSerial
I have my arduino connected to my PC and another serial device. This serial device sends a 3 line piece of info on bootup then if I trip a zone it will send information regarding the radio transmission.

When I first power up the device I see the information from the device in the serial monitor (SELFTEST-PASS) however that is the last information I receive from it until I powercycle the device.

I have connected it directly to my PC comport and verified information is being sent via Serial however the arduino seems to quit after the first bit of info... any idea where to proceed from here? PS I have tried both SoftwareSerial and NewSoftSerial
Here is an example of the data sent from the serial device as viewed by hyperterminal:

```
<1234 #3F->0000 1234->FFFF D_ALARM>
<FFFF #3F->1234 FFFF->1234 P_ACK>
<1234 #40->0000 1234->FFFF D_ZREST>

```

Code that is currently not working:

```
 #include <AltSoftSerial.h>
 AltSoftSerial portOne;

void setup() {

                Serial.begin(4800);
                while (!Serial) {; // wait for serial port to connect. Needed for native USB port only
                }
                // Start each software serial port
                portOne.begin(4800);

              }

// the loop function runs over and over again forever
void loop()
{
  if (portOne.available())
  {
    Serial.write(portOne.read());
  }

  if (Serial.available())
  {
    portOne.write(Serial.read());
  }
}

```

# Answer
Device connected to arduino had DTR/DSR. I had to jumper one to the other to convince it to flow data to the arduino.
> 0 votes

# Answer
Try SoftwareSerial rather than AltSoftSerial.

I don't see the point in these lines, I think you can remove them:

```
 if (Serial.available())
  {
    portOne.write(Serial.read());
  }

```

---

> I have connected directly to a pic and verified the radio I'm connecting to does indeed continue to send data.

If that is the case, that it sends data anyway, then you could just use HardwareSerial. Connect the radio to Rx (D0 on the Uno) and leave Tx unconnected. Then just read from Serial, and write to Serial. You should see the results on the Serial Monitor. (Disconnect this wire when uploading new versions of the sketch).
> 0 votes

---
Tags: serial, softwareserial
---


title: IOt application example Error

text:
# Question
Title: IOt application example Error
I have downloaded code from below linkLink of code. I am trying test code from below. I am getting warning for below code.I couldnot able to find how to sort out

```
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

/* ------------------ */
/* SKETCH CREDENTIALS */
/* ------------------ */

const char *deviceId     = "<D56debb6351d9d4e74e000015>";             // * set your device id (will be the MQTT client username)
const char *deviceSecret = "<Y4h+R1NRAxrhFciRhtHLj66ERSv8RExu>";         // * set your device secret (will be the MQTT client password)
const char *outTopic     = "devices/<D56debb6351d9d4e74e000015>/set"; // * MQTT channel where physical updates are published
const char *inTopic      = "devices/<D56debb6351d9d4e74e000015>/get"; // * MQTT channel where lelylan updates are received
const char *clientId     = "<CLIENT-ID>";             // * set a random string (max 23 chars, will be the MQTT client id)

/* ------------ */
/* SKETCH LOGIC */
/* ------------ */

/* Server settings */
byte server[] = { 178, 62, 108, 47 }; // MQTT server address

/* Sample payload published to lelylan */
/* The id is the status property id of the basic light /*
  /* http://lelylan.github.io/types-dashboard-ng/#/types/518be107ef539711af000001/ */
const char *payloadOn  = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"on\"}]}";
const char *payloadOff = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"off\"}]}";

/* Ethernet configuration */
byte mac[] = { 0xA0, 0xA0, 0xBA, 0xAC, 0xAE, 0x12 };
EthernetClient ethClient;

/* MQTT communication */
void callback(char* topic, byte* payload, unsigned int length); // subscription callback
PubSubClient client(server, 1883, callback, ethClient);         // mqtt client

/* Pins configuration */
int inPin = 2; // button
int outPin = 4; // led

/* Button and led logics */
int state = HIGH;     // current state of the output pin
int reading;          // current reading from the input pin
int previous = LOW;   // previous reading from the input pin
long time = 0;        // the last time the output pin was toggled
long debounce = 200;  // the debounce time, increase if the output flickers

/* arduino setup */
void setup() {
  Serial.begin(9600);
  delay(500);

  Ethernet.begin(mac);
  Serial.print("Connected with IP: ");
  Serial.println(Ethernet.localIP());

  lelylanConnection();      // MQTT server connection
  pinMode(inPin, INPUT);    // button pin setup
  pinMode(outPin, OUTPUT);  // led pin setup
}

/* arduino loop */
void loop() {
  lelylanConnection();

  const char *value;
  reading = digitalRead(inPin);  // read the button state

  // if the input just went from LOW and HIGH and we've waited long enough to ignore
  // any noise on the circuit, toggle the output pin and remember the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == LOW) {
      Serial.println("[PHYSICAL] Led turned on");
      lelylanPublish("on");
      state = HIGH;
    } else {
      Serial.println("[PHYSICAL] Led turned off");
      lelylanPublish("off");
      state = LOW;
    }

    time = millis();
  }

  // effectively update the light status
  digitalWrite(outPin, state);
  previous = reading;
}

/* MQTT server connection */
void lelylanConnection() {
  // add reconnection logics
  if (!client.connected()) {
    // connection to MQTT server
    if (client.connect(clientId, deviceId, deviceSecret)) {
      Serial.println("[PHYSICAL] Successfully connected with MQTT");
      lelylanSubscribe(); // topic subscription
    }
  }
  client.loop();
}

/* MQTT publish */
void lelylanPublish(char *value) {
  if (value == "on")
    client.publish(outTopic, payloadOn); // light on
  else
    client.publish(outTopic, payloadOff); // light off
}

/* MQTT subscribe */
void lelylanSubscribe() {
  client.subscribe(inTopic);
}

/* Receive Lelylan message and confirm the physical change */
void callback(char* topic, byte* payload, unsigned int length) {
  // copu the payload content into a char*
  const char *json;
  json = (char *) malloc(length + 1);
  memcpy(json, payload, length);
  json[length] = "\0";

  // update the physical status and confirm the executed update
  if (String(payloadOn) == String(json)) {
    Serial.println("[LELYLAN] Led turned on");
    lelylanPublish("on");
    state = HIGH;
  } else {
    Serial.println("[LELYLAN] Led turned off");
    lelylanPublish("off");
    state = LOW;
  }

  digitalWrite(outPin, state);
  free(json);
}

```

> Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"
>
> C:\Users\Ajit\Desktop\IOT\_Testcode\IOT\_Testcode.ino: In function 'void loop()':
>
> C:\Users\Ajit\Desktop\IOT\_Testcode\IOT\_Testcode.ino:77:26: warning: deprecated conversion from string constant to 'char\*' \[-Wwrite-strings\]
>
> ```
>    lelylanPublish("on");
>
>                       ^
>
> ```
>
> C:\Users\Ajit\Desktop\IOT\_Testcode\IOT\_Testcode.ino:81:27: warning: deprecated conversion from string constant to 'char\*' \[-Wwrite-strings\]
>
> ```
>    lelylanPublish("off");
>
>                        ^
>
> ```
>
> C:\Users\Ajit\Desktop\IOT\_Testcode\IOT\_Testcode.ino: In function 'void callback(char\*, byte\*, unsigned int)':
>
> IOT\_Testcode:124: error: invalid conversion from 'const void\*' to 'void\*' \[-fpermissive\]
>
> memcpy(json, payload, length);
>
> ```
>                            ^
>
> ```
>
> In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:25:0,
>
> ```
>              from sketch\IOT_Testcode.ino.cpp:1:
>
> ```
>
> c:\program files (x86)\arduino\hardware\tools\avr\avr\include\string.h:117:14: error:
> initializing argument 1 of 'void\* memcpy(void\*, const void\*, size\_t)' \[-fpermissive\]
>
> extern void \*memcpy(void \*, const void \*, size\_t);
>
> ```
>           ^
>
> ```
>
> IOT\_Testcode:125: error: assignment of read-only location '\*(json + ((sizetype)length))'
>
> json\[length\] = "\0";
>
> ```
>             ^
>
> ```
>
> IOT\_Testcode:125: error: invalid conversion from 'const char\*' to 'char' \[-fpermissive\]
>
> C:\Users\Ajit\Desktop\IOT\_Testcode\IOT\_Testcode.ino:130:24: warning: deprecated conversion from string constant to 'char\*' \[-Wwrite-strings\]
>
> ```
>  lelylanPublish("on");
>
>                     ^
>
> ```
>
> C:\Users\Ajit\Desktop\IOT\_Testcode\IOT\_Testcode.ino:134:25: warning: deprecated conversion from string constant to 'char\*' \[-Wwrite-strings\]
>
> ```
>  lelylanPublish("off");
>
>                      ^
>
> ```
>
> IOT\_Testcode:139: error: invalid conversion from 'const void\*' to 'void\*' \[-fpermissive\]
>
> free(json);
>
> ```
>         ^
>
> ```
>
> In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:23:0,
>
> ```
>              from sketch\IOT_Testcode.ino.cpp:1:
>
> ```
>
> c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stdlib.h:305:13: error:
> initializing argument 1 of 'void free(void\*)' \[-fpermissive\]
>
> extern void free(void \*_\_ptr);
>
> ```
>          ^
>
> ```
>
> exit status 1 invalid conversion from 'const void\*' to 'void\*' \[-fpermissive\]
>
> This report would have more information with "Show verbose output during compilation" enabled in File \> Preferences.

Kindly let me know how to resolve these warning

# Answer
This code was written and tested using an earlier Arduino IDE version, the author's upload of the source files happened over a year ago.

Within the Arduino 1.6.x branch the preprocessor and compiler behaviour have changed (among other things).

Older libraries will require an earlier Arduino IDE version (i.e. the 1.5.x branch) from https://www.arduino.cc/en/Main/OldSoftwareReleases#previous.

Additionally, we have to keep in mind that there are differences between Arduino.cc and Arduino.org. Those two projects split apart, their IDEs aren't equivalent any more.
> 1 votes

---
Tags: arduino-uno, ethernet
---


# Question
Title: How do you control the amount of times the void loop loops per second?
```
int firstAnalogPin = 0;
int secondAnalogPin = 5;
int firstVal = 0;
int secondVal = 0;
void setup(){

  Serial.begin(9600);          //  setup serial

}

void loop(){

firstVal = analogRead(firstAnalogPin);
   // read the input pin

secondVal = analogRead(secondAnalogPin);
   // read the input pin

Serial.print(firstVal);

Serial.print("\t");

Serial.println(secondVal);

}

```

Basically, I want to know how to convert from the baud rate to the number of times `loop()` runs per second. How do I control the number of `loop()`s per second?

# Answer
> 3 votes
The number of times `loop()` runs every second depends on the time taken for the execution of the instructions *within* `loop()`. For instance, in your code, the time taken for one `loop()` is roughly equal to the time taken for the MCU to execute all the statements in `loop()` (more specifically, the time taken for each operation or function from call to return): in your case, the time taken for the `Serial.print()`s + the time taken for the `analogRead()`s (not considering any interrupts between statements).

That said, you generally don't want to control the interval between `loop()`s; I assume you actually want to control the interval between the execution of certain operations within your `loop()`. Say, you want to set the time between executions of `analogRead(0)` to 500 ms. This can be done like this:

```
#define INTERVAL 500   // time between reads
unsigned long lastRead = 0;

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

void loop(){
  //....your other code....

  if (millis() - lastRead >= INTERVAL){  // if INTERVAL has passed
    val = analogRead(0);
    lastRead = millis();
    Serial.println(val);
    //...anything else
  }

  //...your other code...
}

```

With this code, you now have about 2 `analogRead` samples every second. Of course, this is only useful if `loop()` runs faster than your chosen interval. If there are function calls, or any operations otherwise, in `loop()` (within or outside the IF block) that always take more time than your interval, then this code would serve no purpose.

# Answer
> 1 votes
If your goal is to control how often the sensor is polled and printed to SD card, I would suggest you check out Blink Without Delay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay it would be a much cleaner way than trying to slow down the loop to a specified time.

# Answer
> 0 votes
Marcello Romani's SimpleTimer library was made for this kind of problem. You let `loop()` run as fast as possible but only maintain the timers and do other *short* tasks. The timer library runs your periodic tasks when necessary:

```
#include <SimpleTimer.h>
SimpleTimer timer;         // creates a set of timers

// A timer call-back function - there can be more than one
void onTimer(void){
   ;   // do stuff here, keep it short
}

void setup(void){
   ;   // Serial.begin() and other setup

   timer.setInterval(1000L, onTimer); // set a 1-sec repeating timer
}

void loop(void){
   timer.run();   // updates timers, maybe calls a callback func
   ;              // whatever other loop code
}

```

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


title: Shaft Encoder Accuracy

text:
# Question
Title: Shaft Encoder Accuracy
So, first of all I just want to point out this code is from: Reading Rotary Encoders and is not mine.

I have a magnetic shaft encoder mounted on a regular DC motor, my problem is that I cannot receive the exact angle of the motor. The encoder outputs `+1` each 90 degrees (I then multiply by 90). And is there any relationship between `valx`, `valy`, `valz` and the angle?

```
#define encoder0PinA 2
#define encoder0PinB 3
int rounds= 0;
volatile unsigned int encoder0Pos = 0;
unsigned int tmp_Pos = 1;
unsigned int valx;
unsigned int valy;
unsigned int valz;

boolean A_set;
boolean B_set;

int enA = 9;
int in1 = 10;
int in2 = 11;

void setup() {

  pinMode(encoder0PinA, INPUT);
  pinMode(encoder0PinB, INPUT);
  // encoder pin on interrupt 0 (pin 2)
  attachInterrupt(0, doEncoderA, CHANGE);

  // encoder pin on interrupt 1 (pin 3)
  attachInterrupt(1, doEncoderB, CHANGE);
  Serial.begin( 9600 );

  pinMode(enA, OUTPUT);

  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(enA, 225);
  Serial.begin (9600);
}

void loop(){
//Check each second for change in position

  if (tmp_Pos != encoder0Pos) {
    Serial.print("Index:"); Serial.print(encoder0Pos * 90,DEC);
    Serial.println();
    Serial.print("valx:");Serial.print(valx,DEC);
    Serial.println();
    Serial.print("valy:");Serial.print(valy,DEC);
    Serial.println();
    Serial.print("valz:");Serial.print(valz,DEC);
    Serial.println();
    tmp_Pos = encoder0Pos;
  }
}

// Interrupt on A changing state
void doEncoderA(){

  // Low to High transition?
  if (digitalRead(encoder0PinA) == HIGH) {
    A_set = true;
    if (!B_set) {
      encoder0Pos = encoder0Pos + 1;
      valx=analogRead(0);
      valy=analogRead(1);
      valz=analogRead(2);
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinA) == LOW) {
    A_set = false;
  }
}

// Interrupt on B changing state
void doEncoderB(){

  // Low-to-high transition?
  if (digitalRead(encoder0PinB) == HIGH) {
    B_set = true;
    if (!A_set) {
      encoder0Pos = encoder0Pos - 1;
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinB) == LOW) {
    B_set = false;
  }
}

```

# Answer
If the encoder only gives +1 pulse per 90 degrees, you aren't going to get better than 90 degree accuracy out of it.

In the example code at the link, the val{x,y,z} are measured analog variables of some other thing that are sampled at each encoder lcoation:

> My project is a data loger where three analogue inputs are sampled each time a rotary encoder pulse steps clockwise. On an Arduino, time is of the essence to get this data sampled and saved somewhere (I have not included the 'saving somewhere' part of this project yet.) In order to save some processor cycles, I have slightly redesigned the interrupt system to maintain a pair of boolean states outside of the interrupt loop.

These are not directly related to the positioning of the encoder, and there is no reason to think they provide angle information.
> 2 votes

---
Tags: sensors, interrupt, rotary-encoder
---


title: Simple Arduino Serial Arithmetic

text:
# Question
Title: Simple Arduino Serial Arithmetic
I'm developing a program to calculate static margin of an aircraft through the calculations of mass,moment and arm. Essentially dealing with large numbers.

I'm having difficulty in setting up my code in the way so that the arithmetic is applied correctly to larger numbers. What I have so far works but only when the input is 0-9. The arithmetic fails to calculate digits beyond.

I understand that I'm breaking the digits into separate variables as to convert them from ASCII format to their intended value. The problem is in putting those digits back together.

I know this is probably very simple but I'm picking up arduino again after a long break and I'm very rusty.

Here's my code thus far:

```
long batterymoment,num1,num2,answer;
int batterymass = 720;
int batteryposition;
boolean mySwitch = false;

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
}

void loop() {
  while (Serial.available()){
   batteryposition = Serial.read();

   if(batteryposition>47 && batteryposition<58){
     if(!mySwitch){
       num1=(num1*10)+(batteryposition-48);
     }else{
       num2=(num2*10)+(batteryposition-48);
     }
   }

   answer=num1+num2;
   batterymoment=answer*batterymass;
   Serial.print("Battery moment is: ");
   Serial.println(batterymoment);
   num1=0;
   num1=0;
   mySwitch=false;
  }
}

```

Thanks.

# Answer
> 1 votes
Do you mean to repeat num1=0; in loop()?

It is only reading one character per loop() because loop() happens much faster than Serial.available() and Serial.read().

Do the reporting and clearing when you receive some sort of separator/non-digit character.

---
Tags: arduino-uno, serial, data-type
---


# Question
Title: Read ISO/IEC 14443B (NFC Type B) with PN532
I bought a PN532 from Elechouse (documentation here) because I need to read IDs from `Type B` NFC cards.

My problem is that even if they say the hardware supports `Type B`, the official libraries an examples they provide are not made to.

I have not problem reading `Type A` cards, but nothing happends when I tap `Type B` cards.

After long searchs on internet I found that absolutely every `PN532` sellers have chosen to support only `Type A` cards in their libraries because according to them, a librari supporting both types would have taken too much space in Arduino's memory.

So today my problem is as simple as that: **how to read Type B NFC cards using PN532 on an Arduino UNO?**

I'm a bit new in Arduino so after many hours of searching and trying I couldn't figure out how to do it.

# Answer
> 1 votes
I dont have an exact reply but

1) are you certain the other tags are type b?

2) hace you tried connecting the reader using a UART USB cable? You could use libnfc, to check if the reader works. And going forward at commands FOR the reader are a good way to debbug.

---
Tags: arduino-uno, rfid
---


# Question
Title: How to use a common anode 7-segment, 4-digit display?
Please take this question as an example to (my own) answer below.

I've got an 7 segment, 4 digit LED display, but I don't have any idea on how to wire it.

I don't understand the difference between common anode/cathode, and I don't have 2 pins per LED, which is strange. Quite recently, a question on a "7 segment 4 digit common anode" got deleted. At that very moment I was typing an answer.

Though, I still want to share my answer with you, or the person who asked it. Please verify/update my answer with more information. Specifically, could someone add working code, I can't at the moment.

# Answer
Just as a complement to Paul's answer, I wrote a short program to show how to drive the 7-segment 4-digit display of his figure:

This is actually a common cathode display, so the program assumes that, as well as the particular wiring of the figure. The interesting part is the `refresh_display()` function, which should be called periodically. The algorithm is as follows:

* drive the 7 anodes with the appropriate signals for one of the digits we want to show
* set `HIGH` the output that controls that digit's cathode through the NPN transistor
* wait for 2.5 ms (for a refresh rate of 100 Hz)
* set `LOW` the cathode-controlling output
* move to the next digit.

It should be noted that the waiting is done without blocking the CPU, by using the technique described in the Blink Without Delay Arduino tutorial. Here is the program:

```
const int NB_DIGITS     = 4;  // 4-digit display
const int FIRST_ANODE   = 2;  // anodes a..g on pins 2..8
const int FIRST_CATHODE = 9;  // cathodes, right to left, on pins 9..12

// Digits to display, from right to left.
uint8_t digits[NB_DIGITS];

// Set all the used pins as outputs.
void init_display()
{
    for (int i = 0; i < 7; i++)
        pinMode(FIRST_ANODE + i, OUTPUT);
    for (int i = 0; i < NB_DIGITS; i++)
        pinMode(FIRST_CATHODE + i, OUTPUT);
}

// This should be called periodically.
void refresh_display()
{
    // Our 7-segment "font".
    static const uint8_t font[10] = {
        //abcdefg
        0b1111110, // 0
        0b0110000, // 1
        0b1101101, // 2
        0b1111001, // 3
        0b0110011, // 4
        0b1011011, // 5
        0b1011111, // 6
        0b1110000, // 7
        0b1111111, // 8
        0b1111011  // 9
    };

    // Wait for 2.5 ms before switching digits.
    static uint32_t last_switch;
    uint32_t now = micros();
    if (now - last_switch < 2500) return;
    last_switch = now;

    // Switch off the current digit.
    static uint8_t pos;
    digitalWrite(FIRST_CATHODE + pos, LOW);

    // Set the anodes for the next digit.
    pos = (pos + 1) % NB_DIGITS;
    uint8_t glyph = font[digits[pos]];
    for (int i = 0; i < 7; i++)
        digitalWrite(FIRST_ANODE + i, glyph & 1 << (6-i));

    // Switch digit on.
    digitalWrite(FIRST_CATHODE + pos, HIGH);
}

/***********************************************************************
 * Example usage.
 */

void setup()
{
    init_display();
}

void loop()
{
    uint32_t now = millis();

    // Change the number displayed every second.
    static uint32_t last_change;
    if (now - last_change >= 1000) {
        digits[3] = digits[2];
        digits[2] = digits[1];
        digits[1] = digits[0];
        digits[0] = (digits[0] + 1) % 10;
        last_change = now;
    }

    refresh_display();
}

```

Paul provided a link to a tutorial on Parallax that suggests using the Multiplex7Seg Arduino library. That library is more general than the example code above, as it does not make assumptions about the pins used. But the big difference between the library and this code is in the way the timings are managed:

* The library is driven by the Timer 2 overflow interrupt. This should provide a very steady timing, at the cost of having one timer dedicated to this job.
* The code above relies on the user calling `refresh_display()` often enough. It doesn't require dedicated hardware resources, but it doesn't play well with programs that take too long to `loop()`: it won't like you calling `delay()`.
> 5 votes

# Answer
I'll try and take you through the complete basics of LED's etc. As 4-digit 7-segment displays are a combination of multiple "LED techniques".

**Wiring LED's**

LED's, or Light Emitting Diodes, are one of the fun things of Arduino.

Essentially, they're easy to use, power them up and they'll light up.

They can be annoying, because they have some kind of polarity, meaning that they will only work when you wire them right. If you reverse positive and negative voltage, they won't light up at all.

Annoying as it is, it's also quite usefull.

**Cathode vs Anode**

On a traditional LED, the long lead is the (+), Anode. The other lead being the (-) Cathode.

"Or, if someone’s trimmed the legs, try finding the flat edge on the LED’s outer casing. The pin nearest the flat edge will be the negative, cathode pin." - Sparkfun

Source: https://learn.sparkfun.com/tutorials/polarity/diode-and-led-polarity

**Basic wiring**

I'm not sure if this is correct, since I ripped the image from the internet.

Wiring an LED is quite easy, the Anode (+) connects to positive voltage, preferably through a current limiting resistor. The Cathode (-) connects to ground (with a current limiting resistor, if you didn't have one on the positive side).

The current limiting resistor will avoid the LED from shorting out, damaging the LED or Microcontroller/Arduino.

**Multiple LEDs, matrices, RGB leds**

With multiple LED's you often have them with the positive side connected (+), "common Anode" or all connected to the (-) "common Cathode".

Basically it'll come down to this.

For a common cathode, you supply current to the pins that you want to have on.

For a common anode, you sink the current through the LED.

**Multiplexing (multiple digit, 7-segments)**

You should check out the tutorial of parallax: http://learn.parallax.com/4-digit-7-segment-led-display-arduino-demo

When you've got a lot of LED's, it's often smart to "multiplex" them. Usually you go through "groups" of LED's rapidly, so that it looks like they're all on at the same time.

Usually you sink current from a column of LED's and supply current to individual LED's of a row.

Or, you supply current to a column of LED's and sink current from individual LED's of a row.

So that you can choose which column to activate, and which LED's of that column to light up. Changing these columns/rows rapidly will enable you to control multiple LED's with a lot less pins.

There even are display controllers for this, if you don't want to take care of the switching in your software.

**So when you have a 4 digit, multiplexed 7 segment, common anode**

The diagram will be more like this:

http://www.mytutorialcafe.com/Microcontroller%20Application%20C%207segmen.htm
> 5 votes

---
Tags: led, display, rgb-led, multiplexer, 7-segment
---


# Question
Title: Why can't most servos rotate more than around 180°
I was looking how a servomotor works. I realized that a standard servo can only turn up to 180°, but I didn't understand why. Is it because of the potentiometer?

# Answer
> 6 votes
Fundamentally, because the systems they were designed for convert rotary motion to linear, typically with a range substantially less than 180 degrees (probably more like 120 degrees).

Next, because the control scheme of PWM *position* pulses is not able to convey requests over an arbitrary range - the mapping of pulse width to position must be limited, and it is sensibly set up to map to something related to the useful range.

Because these limitations in task, a fairly ordinary rotary potentiometer of less than 360 degree range can be employed for position sensing.

Given that the useful range is limited, and the potentiometer relatively easy to damage by over rotation, the gearbox is typically constructed with a mechanical rotation stop somewhere outside the normal range of self rotation.

---
Tags: servo, electronics
---


title: RF24 + High speed pwd

text:
# Question
Title: RF24 + High speed pwd
I'm using the arduino to generate a 100kHz pwd using timer 1

```
void setup() {
  // put your setup code here, to run once:

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

```

I used this to test the modules:

```
Receiver
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int LED1 = 3;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();
 pinMode(LED1, OUTPUT);}

void loop(void){
 if (radio.available()){
   bool done = false;
   while (!done){
     done = radio.read(msg, 1);
     Serial.println(msg[0]);
     if (msg[0] == 111){delay(10);digitalWrite(LED1, HIGH);}
     else {digitalWrite(LED1, LOW);}
     delay(100);}}
 else{Serial.println("No radio available");}}

```

Transmitter

```
#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int SW1 = 7;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openWritingPipe(pipe);}

void loop(void){
 if (digitalRead(SW1) == HIGH){
 msg[0] = 111;
 radio.write(msg, 1);}}

```

I'm using this library https://github.com/TMRh20/RF24

And it works ok, now first issue is that both, RF24 and the pwm are using the pin 10 but the library allows you to change it, so now I'm using pin 7 instead. I tested it again and still works fine.

But when I add the lines at the setup to use the pwd the communication doesn't work

```
   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;

```

I try line by line and the issue is here:

TCCR1B = bit(WGM13) | bit(WGM12) | bit(CS10); // Set /1 prescaler

When setting the prescaler at 1.

Which is the dependency of the RF24 on this timer? and which options to I have to make it work

EDIT.

Now I'm using pins 6 and 7 for CE and CS Also removed "| bit(COM1A0) " form the register setting

Still doesn't work

I've this

```
void setup(void)
{

  /// RF settings

  Serial.begin(9600);
 radio.begin();
 //radio.openReadingPipe(1,pipe);
 //radio.startListening();
 pinMode(LED1, OUTPUT);

 /// end RF settings

  //// pwd settings
 DDRB |= bit(DDB1) | bit(DDB2);
   OCR1A  = max_count;       // 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;
   TCCR1A =  bit(WGM11) | bit(WGM10) |  bit(COM1B1); // bit(COM1A0) | Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   TCNT1 = 0 ;

  ////
 }

```

If I put the settings for the PWM before the settings for the RF24 then the PWM doesn't work, the RF settings at first the the communications doesn't work.

radio.begin() must be overwriting the registers but I haven't found how.

# Answer
Maybe doing 100kHz PWM with timer2 instead of timer1 would be good. The registers look similar to timer1, but they are only 8 bit, so you can't go bigger than 255 in the compare and count registers. The prescaler would be the same, and the timer controlled pins would be D11 and D3:

```
  //// pwm settings for 100kHz on Timer 2
  //// Toggle OC2A/D11/PB3 at 50kHz, PWM OC2B/D3/PD3 at 100kHz:
   DDRB |= bit(DDB3); //Enable output
   DDRD |= bit(DDD3); //Enable output
   // WGM2x=0b111 for fast PWM with TOP=OCR2A
   // COM2Ax=0b01 for toggle OC2A at OCR2A
   // COM2Bx=0b10 for set@bottom-clear@match_OCR2B PWM
   TCCR2A =   bit(WGM21)  | bit(WGM20)
            | bit(COM2B1)  // PWM on OC2B
            | bit(COM2A0); // Toggle OC2A
   TCCR2B =   bit(WGM22) | bit(CS20);  // Set /1 prescaler
   OCR2A  = 159;       // 16000000/(PreScaler *Ftimer)-1
   OCR2B  = 10;        // 6.25% PWM
   TCNT2 = 0 ;

```

I haven't tested this on an Uno/Atmega328P, but it looks reasonable per the datasheet (p153-157).

If you don't want both the 50kHz toggle and 100kHz PWM outputs, (as in your posted code,) you could disable one or the other and adjust the frequency as needed.
> 1 votes

---
Tags: pwm, nrf24l01+
---


# Question
Title: Machine installed with arduino suddenly turns on when usb is unplugged
Why is my machine suddenly turns ON when I unplugged the USB on my computer? Does it have connection on the auto reset feature of my arduino board?

```
String input = "";

void setup(){

  Serial.begin(9600);   // Sets up communication with the serial port

  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

  digitalWrite(11,LOW);

}

void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
    int data = Serial.read();
      // convert the incoming byte to a char
      // and add it to the string
    input += (char)data;

    recipe = input.toInt()+'0';    //recipe=0 if not a digit
    if(recipe == '0')
      recipe = data;

    if(data == '\n'){
      //Serial.print("Recipe: ");
      //Serial.println(recipe);
      //Serial.print("String: ");
      //Serial.println(input);
      input = "";
    }
  }

  if(recipe == 's'){
    digitalWrite(11,HIGH);
    delay(1000);
    digitalWrite(11,LOW);

    digitalWrite(6,LOW);
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
  }

  else if(recipe>'0' && recipe<'32'){

    recipe = recipe-'0';
    char binary[7] = {0};   // This is where the binary representation will be stored
    recipe += 32; // Adding 32 so that there will always be 6 digits in the string
    itoa(recipe,binary,2);  // Convert recipe to a string of base 2 and save it in array 'binary'
    char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

  //Serial.print(signals);  // Print out the signals in binary

    int i;
    for(i=0; i<5; i++){
      if(signals[i] == '0')
        signals[i] = '1';
      else
        signals[i] = '0';
      digitalWrite(i+6, signals[i]-'0');    // write to pin; converts the bit of the string to HIGH or LOW
      //Serial.print(signals[i]);
    }

  }
  else
    loop();

}

```

# Answer
Do not call `loop` from `loop`. You will quickly run out of RAM and the sketch will crash:

```
void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
...

  }
  else
    loop();

}

```

---

For the pins that are supposed to be high, I suggest pull-up resistors:

```
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

```

When the Arduino powers up it enters the bootloader for a second or so. Those pins won't be set high yet. A pull-up resistor would make sure they are high until such time as you want to drive them low.

---

If you are saying that the machine powers up when you **disconnect** the power to the Arduino, that is still a good reason for using pull-up resistors, to make sure that it does not operated until commanded to do so.

---

> where will i connect the pull up resistors and how?

Typically pull-up resistors will be around 10k, and are connected from the pin to +5V. Of course, if the Arduino is not powered, then you need another source of the +5V.

---

> please to clarify the "do not call from loop to loop"

Remove these two lines:

```
else
    loop();

```

When `loop` exits, is it immediately re-called. You don't need to do it that way, in fact it is a Bad Idea.
> 1 votes

# Answer
It looks like the this line in your setup:

```
  digitalWrite(11,LOW);

```

... would trigger contact input 211, and do "Start of Program Operation when D11 switches from off to on" every time the sketch starts.

If the arduino resets, it will pull this line low. Autoreset would initiate this.

By changing the line to the following, the code will wait until it gets an 's' before pulling the line low.

```
  digitalWrite(11,HIGH);

```

I don't have an Arduino, but perhaps http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection may help in managing the Auto-Reset issue.
> 0 votes

---
Tags: arduino-mega, electronics, project, home-automation, automatization
---


title: nrf24l01+ with antenna problem

text:
# Question
Title: nrf24l01+ with antenna problem
I just got 4 nrf24l01+ modules with the external antennas, but I'm not able to make them work.

I'm using arduino nanos and MySensors to create a gateway and a sensor.

The funny thing is that when I put a antenna nrf as the gateway and a pcb nrf as sensor, they work just fine, but the other way doesn't.

I also tried two nrfs as gateway and sensor, but the behavior does not look good.

What could it be? Wifi router interference? Channel? Baud rate? Data rate?

# Answer
> 3 votes
It's likely an issue related to the modules' electric supply. The effects can be packet loss (even down to zero bps) or loss of communication with the module.

Two things have to be covered with the nRF modules for them to work:

* current draw (i.e. power),
* decoupling/filtering (i.e. bypass capacitors).

Since you don't mention specific devices, I'm assuming you refer to an 'antenna' module with SMA (or RP-SMA) connector.

The Nordic Semiconductor nRF24l01+ that is typically used in these modules has a maximum power consumption well below 100mW.

A module with power amplifier (PA) draws significantly more power than the nRF chip alone, the total power consumption will be larger than 100mW.

An Arduino can only supply power according to it's onboard regulator capabilities. The Minis (and Micros) feature a smaller regulator that cannot drive both the Atmel AVR microcontroller and the PA.

Solution:

* provide a separate 3.3V regulator for the nRF module(s),
* place a capacitor directly at the modules' connector's supply pins.

Link:

---
Tags: sensors, arduino-nano, nrf24l01+
---


title: Opto Isolator question

text:
# Question
Title: Opto Isolator question
I'm building a CANBUS network based on an arduino to go into an offroad racing truck. The vehicle has two separate battery systems, and I would like to monitor the voltage while still electrically isolating them from the arduino itself. For the voltage monitoring itself, I assume I can use a simple voltage divider into an Analog pin. To electrically isolate the arduino, would an Opto Isolator work? I found this one: https://www.sparkfun.com/products/9118 But it appears that it's designed for low voltage to control high voltage, as opposed to the other way around.

# Answer
> 2 votes
An optoisolator is good for digital signals, but won't transfer an analog signal accurately.

Instead, you could put ADCs on the different circuits and optoisolate their communication with a master Arduino.

# Answer
> 1 votes
1) using current sensors based on Hall effect: https://www.sparkfun.com/products/8882. Their sensing circuit/leads and analog parts are electrically isolated.

The drawbacks are: to calculate the voltage, need to wire some load resistor with known value to batteries, but you can switch on the load circuit by relay during measurement; susceptible to magnetic field, some shielding might be needed.

2) to use isolation amplifiers: please see http://www.analog.com/en/products/amplifiers/isolation-amplifiers.html

---
Tags: electricity, voltage-protection
---


# Question
Title: How do I upload the sensor data from arduino into a database?
I have just connected a Libelium shield to connect many sensors to Arduino UNO, that measure water ph level, temperature,...etc. I really couldn't figure out how do I upload the sensor data into a database(MySQL). I have the code for database connectivity, but still couldn't figure out how(Querying) to upload the sensor data into the database.

The main problem here is how do I make the arduino recognize the sensor data to upload it into database or send to to another Arduino or Raspberry pi through XBee.

Code for database connectivity:

```
void sendData(){

          Serial.println("Connecting...");
          if (my_conn.mysql_connect(server_addr, 3306, user, password)){
            delay(500);
            Serial.println("Starting SQL!");
            Serial.println(INSERT_SQL);
            my_conn.cmd_query(INSERT_SQL);
            Serial.println("Query Success!");
            my_conn.disconnect();
            Serial.println("\n");
          }
          else {
            Serial.println("Connection failed!");
          }
}

```

# Answer
> 1 votes
First you have to create the table in your MySQL database, like:

```
CREATE TABLE IF NOT EXISTS `table_log` (
  `log_id` int(11) NOT NULL AUTO_INCREMENT,
  `log_date` date NOT NULL,
  `log_time` time NOT NULL,
  `log_t1` float NOT NULL,
  `log_t2` float NOT NULL,
  `log_t3` float NOT NULL,
  `log_t4` float NOT NULL,
  `log_vbatt` float NOT NULL,
  PRIMARY KEY (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1;

```

You can execute it in your phpmyadmin page (or create the table manually there). Above we have columns for auto-increment id ('log\_id' - necessary), date & time, 4 temperature values and voltage value (modify these according your requirements).

Than the query to create a new record would be like this:

```
INSERT INTO `table_log` (`log_id`, `log_date`, `log_time`, `log_t1`, `log_t2`, `log_t3`, `log_t4`, `log_vbatt`) VALUES
    (0, '2016-03-04', '01:53:30', 1.0, 2.0, 3.0, 4.0, 3.0);

```

You need to create this string dynamically (with real values) and use instead of INSERT\_SQL.

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


title: Problem running WiFiWebClient example

text:
# Question
Title: Problem running WiFiWebClient example
I'm running the WiFiWebClient example which comes preloaded with Arduino IDE 1.6.7. I'm using Arduino Uno board with WiFi Shield Model R3.

```
/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using a WiFi shield.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * WiFi shield attached

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */

```

```
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>

char ssid[] = "Vanilla Sky"; //  your network SSID (name)
char pass[] = "mypass";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80) == 0) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: keep-alive");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

It gets my WiFi shield connected to `Vanilla Sky` but doesn't fetch the HTTP request (see image below). What is getting wrong here?

# Answer
> 1 votes
Let's break it down :)

> Please upgrade the firmware

Visit here to upgrade the firmware of your board. Your original post doesn't show the fw version, but could have outdated library references and has been noted many times that outdated fw will not work.

https://www.arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading

Also add this to your project to help us determine your firmware:

```
  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());

```

My guess is that it is less than 1.1.0. If the Arduino IDE is out of date, and the board is newer, the NOT EQUAL TO(!=) may suggest that the firmware is newer than the library which could also be an issue.

Just b/c it connects to your router, doesn't mean that it can still communicate correctly.

One last side note, some versions of Arduino IDE have proven to be problematic with uploading a sketch to a wifi shield. A quick search with your Arduino version followed by the Wifi Shield not connecting could point you in the right direction. eg- Arduino x.xx wifi shield not connecting

Hope this helps!

---
Tags: wifi
---


# Question
Title: Why does the Arduino UNO have a separate power port if USB also powers it?
Can you power the Arduino off a USB cable alone, without using the regular power connection? If so, what's the point of the additional power connection: to provide extra power? Also Why not just have two usb ports one for power one for connecting to the computer, or a micro usb.

# Answer
As Hyperbola pointed out, the USB port function is primarily to allow for programming the board. Now, since the USB port has the power cables too, it is convenient to power the device from the USB port.

The main drawback of USB port powering, however, is that it can supply a limited current: usually the USB2 ports can deliver up to 500mA before shutting down. In order for the arduino board to be compliant with this, consequently, a 500mA fuse was put on the board just after the 5V usb input.

Now, what if your final circuit requires more than 500mA? Will you have to change board? Of course not! you can just use the external power input to power the arduino board and all the other circuitry without worrying about the 500mA limitation. Of course the onboard regulator has limits too, but you have more flexibility.

Moreover portable applications run on batteries. No battery can supply exactly 5V (usually alkaline ones deliver 1.5V per battery, while lithium have usually 3.7V/cell, but this varies over time). Consequently they put an onboard regulator for providing 5V from any 6.5V+ source.

Summarizing: the USB power is convenient, since you will usually power it from the PC when programming. An external connector, however, is very important because it gives you more flexibility when choosing the power supply. You don't have to use both: you can just choose the most suitable for your needs.
> 1 votes

# Answer
> Can you power the Arduino off a USB cable alone, without using the regular power connection?

You can use the USB cable alone to power the board.

> If so, what's the point of the additional power connection: to provide extra power?

You can use either to power the board. By using just the power plug you can make your Arduino portable by using a battery box or power it via a wall plug.

> Also Why not just have two usb ports one for power one for connecting to the computer, or a micro usb.

Only ONE USB is needed to power and program.
> 4 votes

# Answer
Arduino, in its very esence, is an embedded system and can be used as a standalone device. The USB port is provided for:

1. To power up the device.
2. To **program** it through a computer i.e. dump the sketch on it which one can program in the Arduino IDE.

Once you have dumped the program on it, it will stay on it forever unless you change/erase it and hence you can use the Arduino anywhere without actually bringing a computer (USB port) along.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Bluetooth Arduino control (was Speech recognition arduino control)
How to I control arduino with voice. I got an Android app but it works only with Internet connectivity. So I was an Android app with works offline when I connect to my Bluetooth HC-05. Please suggest me some ideas

# Answer
You might find your answer with someone else who has done the same thing on Instructables:

Arduino Voice recognition Via Bluetooth HC-05 - http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/

Hope this helps!
> 1 votes

---
Tags: bluetooth
---


title: Arduino port recognition

text:
# Question
Title: Arduino port recognition
New Arduino Uno, Arduino 1.6.3, MBP running 10.10.5.

The Arduino IDE is running, I connect to the laptop via usb. The green LED is on the amber light is on but it's not blinking.

I attempted to upload the blink file from File\>Example\>Basic\>Blink. It compiles without issue but won't upload. I get the can't open device "/dev/cu.usbmodem1421" : No such file or directory...

I have attempted using the reset button, changing ports, cycling the IDE and the computer. The killer is that I've had an Arduino on this laptop before.

Any suggests for getting the Arduino linked and operational.

# Answer
> 1 votes
Sorry to dredge up an old thread (well, really only replying to one that got robo-dredged :), but maybe this will help someone someday.

A /dev/cu.\<something\> is a unix port designation. "cu." meant a port used for modems, back in the mists of time but probably isn't relevant today. But what we do learn from it is that the OP is probably using a Mac, and for sure, not Windows.

"/dev/cu.usbmodem1421" is a typical device name for an Arduino as seen by a Mac on a particular one of its USB ports - the numeric part varies according to which Mac USB port the Arduino is connected to each time.

Arduinos & FTDI devices do not need additional drivers on Mac OS (that may not be true for other, non-FTDI USB-to-serial devices).

In this case, the OS already reports seeing (what looks like) an Arduino. The suggestion already put forward, checking the board-type and port selections in the IDE's 'Tools' menu, is the place to start.

# Answer
> 0 votes
I think you may not install arduino hardware and ftd drivers, Follow the steps given here and then check,

1. Download the latest version of Arduino software and install it.
2. Open windows device manager - You can open windows device manager by right clicking on 'My Computer' and choosing Properties. In the new Window, Click on Device Manager
3. Now Scroll Down the List of Devices in the Device Manager till you come to a Device or expand Ports (COMM).
4. Now you should see Arduino hardware with warning icon or without.
5. Now do right click on arduino hardware name. Now, Windows will provide you two options, Choose the one that says “Locate and install drivers manually from a specific Location.”
6. By browsing locate arduino installed folder, then update.

If you previously done these procedure or now, then open arduino software

1. Go to tools and choose board as what you have like (arduino uno, mega, due etc....)
2. then in tools menu you should choose serial port (example comm 10, comm 21, comm 8 etc...) in which the arduino board connected, some time the board name displays with serial port otherwise you can observe from device manager ports list.
3. now upload blink example and check.

---
Tags: arduino-uno, uploading, port-mapping
---


title: Combining 2 State Machines?

text:
# Question
Title: Combining 2 State Machines?
I want to gain from recent advice from this forum by re-doing my project using 'state machine' logic if possible, in an effort to reduce wasted processor time and variables usage.

I'm starting from Nick Gammons '*state machine to process input from the serial port*' example http://www.gammon.com.au/statemachine, which shows all the different possible combinations for all the special control character 'events' against all the possible machine states - essentially a 2-dimensional grid.

I've refined my goal to the processing of serial input in a format of "**command \[parameters\] \[options\]**", similar to a DOS command-line format, eg: **DIR "c:\program files" /w /s**. This would free me from needing large Buffer\[\] and Header\[\] string, and avoides any parsing,

Therefore my event control characters are space, comma, single-quote, double-quote, forward-slash, Carraige Return, and my 'states' are **NULL, COMMAND, PARAMETER, OPTIONS**

The OPTIONS state adds characters to a temporary option\[\] string until a comma or space delimiter or Carraige Return causes that option to be processed as appropriate, perhaps saving its value to a recognised variable.

The COMMAND and PARAMETER 'states' add characters to their corresponding command\[\] and parameters\[\] strings, including the special control characters if they are contained within either single or double quotes (thereby allowing quotes as part of a string if used within a pair of the other type).

So there appears to be a second state machine needed for **NoQuotes, SingleQuotes and DoubleQuotes** to modify the operation of the COMMAND, PARAMETER and OPTIONS states.

This is where I run out of neurons, because all I see is an impossibly complex 2-machine-state 3-dimensional grid with too many possible permutations.

But I suspect there must be a very practical way to implement this, because it lies at the heart of almost all command-line utilities dating back to a time when processor power and memory availability were scarcer than hens teeth, and those old DOS command-line utilities needed to be as mimimal as was possible, including their command-line parsing.

So can anybody suggest a feasible model (machine-state or otherwise) for getting command-line type format from input?

UPDATE

Oh dear... I've just seen another complication I hadn't spotted before, which is that '/' options are not necessarily always at the end, which means that except if the options state changes by carraige-return, options state change by delimiter have to return to the state prior to the options state change (phew, I hope that makes some sense). Anyway, I think it's back to drawing board because this approach seems likely to be too complicated, as the 2 answers already suggest.

# Answer
Personally I don't think Nick advised to do command line pattern parsing with a state machine. His example is about changing a state machine based on command line input.
I have written some command line parsers and I never used a state machine to do so. I would not advice to use a state machine to do so.
Simple string parsing is far easier.

**Edit To answer the remark below:**
I would not advice to go byte by byte. I'd advice to go the line by line way. I have written a library to do read line by line and an article on how that one works. http://blog.baeyens.it/#post16
Here a link to the lib https://github.com/jantje/libraries/tree/master/SerialCommunicator.
Here is a parcing code example. It is not so interesting for you as I have it done in a stage by stage way in a very high level way of coding. https://github.com/jantje/libraries/blob/master/SerialBridgeCommunicator/SerialBridgeCommunicator.cpp#L21

Basically the algorithm is=
1 Take the first word;
2 identify the word.
3 If the command is complete -\>do it
else Send the rest of the string to a specialized piece of code. (which has the same algorithm)
> 2 votes

# Answer
Suggestion: - don't try to "moosh" (that's a technical-term!) the state-machine heirarchy down into one large, flat state-machine. That way lies madness. Keep your { NULL, COMMAND, PARAMETER, OPTIONS } state machine, for instance, and, wherever you need something more than simple string collection in one of those states, call a parser SM appropriate to the kind(s) of input you expect at that point - a number, a quoted string, an option specifier, etc.
> 2 votes

---
Tags: serial, programming
---


# Question
Title: Humidity values returned by DHT22 sensors failing after some time
I've built a weather station using Arduino that measures temperature/humidity and pressure using an Adafruit 8266 HUZZAH. Temperature and Humidity are measured using a DHT22 sensor a ordered from AdaFruit. The project was completed about 4 months ago and for the first three months has returned what appears to be good data. Eventually, the humidity values started returning garbage, values around 1%.

I replaced the DHT22 sensor with another, this time from a random eBay seller. This also worked fine for about a week (humidity values appear to look good in the 20-60% range).

Then all of a sudden, they dropped to 1% again.

If I run the DHTtester program (instead of my program) against the sensor and my Uno development board, the result is also 1% humidity for this sensor.

```
 DHTxx test!
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F

```

So at this point, I know the problem is not with my program (happens with both my program and the DHTtest program), not with my Arduino (happens with both the 8266 in "the field" and my Uno on my couch). So something must be happening to the sensors in the field, where they work for a week to a few months, and then fail?

Any ideas?

I'm beginning to think some bug/critter is eating or doing something to the sensor (maybe they are attracted to it because it's warmer), but anyway is there a good way to shield if this is the case without affecting the values? Any other way to see what is going on?

```
 // Example testing sketch for various DHT humidity/temperature sensors
 // Written by ladyada, public domain

 #include "DHT.h"
 #define DHTPIN 2     // what pin we're connected to

 // Uncomment whatever type you're using!
 //#define DHTTYPE DHT11   // DHT 11
 #define DHTTYPE DHT22   // DHT 22  (AM2302)
 //#define DHTTYPE DHT21   // DHT 21 (AM2301)

 // Connect pin 1 (on the left) of the sensor to +5V
 // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
 // to 3.3V instead of 5V!
 // Connect pin 2 of the sensor to whatever your DHTPIN is
 // Connect pin 4 (on the right) of the sensor to GROUND
 // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

 // Initialize DHT sensor.
 DHT dht(DHTPIN, DHTTYPE);

 void setup() {
   Serial.begin(9600);
   Serial.println("DHTxx test!");
   dht.begin();
 }

 void loop() {
     // Wait a few seconds between measurements.
     delay(2000);
     // Reading temperature or humidity takes about 250 milliseconds!
     // Sensor readings may also be up to 2 seconds 'old'
     float h = dht.readHumidity();
     // Read temperature as Celsius (the default)
     float t = dht.readTemperature();
     // Read temperature as Fahrenheit (isFahrenheit = true)
     float f = dht.readTemperature(true);

     // Check if any reads failed and exit early (to try again).
     if (isnan(h) || isnan(t) || isnan(f)) {
         Serial.println("Failed to read from DHT sensor!");
         return;
     }

     // Compute heat index in Fahrenheit (the default)
     float hif = dht.computeHeatIndex(f, h);
     // Compute heat index in Celsius (isFahreheit = false)
     float hic = dht.computeHeatIndex(t, h, false);

     Serial.print("Humidity: ");
     Serial.print(h);
     Serial.print(" %\t");
     Serial.print("Temperature: ");
     Serial.print(t);
     Serial.print(" *C ");
     Serial.print(f);
     Serial.print(" *F\t");
     Serial.print("Heat index: ");
     Serial.print(hic);
     Serial.print(" *C ");
     Serial.print(hif);
     Serial.println(" *F");
}

```

# Answer
This is how it looks when they fail.

The DHTxx are very low cost sensors, optimised for cheap volume production.

We don't know under what condition you actually use your sensors. Also, there's the phenomenon of knock-offs and low-grade selling.

In his comprehensive test, Robert J. Smith found a failure rate of 33% and concludes a mean life expectancy of one to two years.

A slightly more expensive alternative is the SHT series of temperature and humidity sensors. My personal experience is that they tend to tolerate some abuse (i.e. complete submersion in water) and don't age as quickly.

Link:
> 3 votes

# Answer
I have had the exact same experience using a DHT11 with Huzzah. I found that the problem tends to happen after high humidity conditions (\>85% relative), my solution was to place silicone caulk and heatshrink tubing around the connections to prevent dew buildup. That solved my problem with my third replacement. It has been two months now with no issues.
> 2 votes

# Answer
Can't really help as I have the same problem ! , DHT22 on an ESP8266 has failed twice , while a DHT11 on a similar system has worked faultlessly for months (Thingspeak 27272) , DHT11 is inside the house while the DHT22 is below the house in the carport, Only thing I have come up with is that the DHT22 MAY be failing due to exhaust/hydrocarbon fumes from the car startups

Art
> 0 votes

---
Tags: sensors, c++
---


title: How to sync multiple arduinos?

text:
# Question
Title: How to sync multiple arduinos?
I'm making a posture control experiment in which a series of images (stimuli) are presented to a person and I'm trying to measure the displacement of this person as a result of these stimuli. To do so I'm planning to use 3 Arduinos:

1) "Arduino Tx 1": an Arduino nano with an Xbee shield and an MPU unit attached for sensing displacement. This implementation has to be wireless because the subject must be able to move freely.

2) "Arduino Tx 2": an arduino uno for reading an analog signal that indicates when an image (stimulus) is presented to the person

3) "Arduino Rx": an arduino uno connected to a computer and reading data from both "Arduino Tx 1" and "Arduino Tx 2"

I want to make sure that signals coming from "Arduino Tx 1" and "Arduino Tx 2" are synchronised. That is: if an image is presented at *t=t0* (signal sensed by "Arduino Tx 2") then I want to be able to tell that the displacement sensed by "Arduino Tx 1" at *t=t0+dt* corresponds to this stimulus.

My question is: is it possible to ensure that signals coming from "Arduino Tx 1" and "Arduino Tx 2" are synchronised when read by "Arduino Rx"?

# Answer
> 0 votes
Have TX2 also emit an infrared pulse that initiates the timing reported by TX1. TX1 should report dt rather than t\_tx1.

The common real-time clocks for for Arduino report at 1 second resolution, which does not sound as if it is accurate enough for your needs.

# Answer
> 0 votes
IMHO the delays are negligible if you are detecting times in the range of milliseconds. Just give us some more info (e.g. what is the maximum error you can tolerate).

In any case you can implement a round-trip-time estimator. For instance

* RX sends a packet (or even just a single byte) to one TX to set it in "RTT measuring mode".
* TX reads the packet and sends an ack. This is required for avoiding errors when the TX is busy doing something else.
* When the ACK is received, the RX sends a message and starts measuring the time.
* When TX receives the message, immediately sends back a reply
* When RX receives the reply, stops the timer. The communication delay is half the time measured

Just repeat this procedure for both TX1 and TX2; this way you will have an estimate on how long it takes to receive a message from each of them. Then, when you receive a packet, you know how much time passed since it was transmitted (and so you can synchronize them)

---
Tags: arduino-uno, arduino-nano, xbee
---


# Question
Title: Is it possible to infer the length of a neopixel string using 1-wire protocol?
I'have been looking at the AdaFruit NeoPixels recently and am trying to understand how the addressing scheme works.

All of the examples I've seen explicitly identify the length of the string (number of neopixel units) and are typically set using an array of 24-bit values to control the color of a particular neopixel.

My question is two fold:

1. How do the neopixels know where they are in a string to allow for addressing?
2. If the neopixels know where they are in the string, would it not be possible to potentially feed the output of the last neoxpixel back to a microcontroller to determine the number of neopixels in the string?

**OP Note** (this is my interpretation and may be suspect, but it is more or less my take away)

Thank you for all the answers on this - it has been very enlightening from ALL of the answers. General take away, the NeoPixel is not "directly" addressable in the sense that you can pick pixel "X" of "n" pixels. The string of NeoPixels acts essentially as a gigantic shift-register (as stated in one of the answers) so to "address" a particular pixel you have to update a buffer that represents the state of the entire string and then shift it down the wire. This is why micro-controllers, such as an Arduino, would have limitations on how many NeoPixels it could control. This is also why it is more practical to define the number of pixels in the string and allocate memory to represent that state.

# Answer
> 3 votes
As noted in Chris Stratton's answer, “Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain”.

This behavior is spelled out clearly in WS2812.pdf and WS2812B.pdf datasheets from http://www.world-semi.com :

> The data transfer protocol use single NZR communication mode. After the pixel power-on reset, the DIN port receive data from controller, the first pixel collect initial 24bit data then sent to the internal data latch, the other data which reshaping by the internal signal reshaping amplification circuit sent to the next cascade pixel through the DO port. After transmission for each pixel, the signal to reduce 24bit. pixel adopt auto resha-ping transmit technology, making the pixel cascade number is not limited the signal transmission, only depend on the speed of signal transmission.

This means that each WS2812 unit in a chain picks off the first 24-bit data packet, latches that data into an internal register, and passes the rest of the data on out, through reshaping circuitry. Hence, if you put *m* packets of data into a chain and *k* packets come out, the chain length is *m-k* or more. (The chain length may be more than *m-k* when *k* is zero.)

# Answer
> 4 votes
Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain. Although the data wire may look continuous it isn't - the signal is electrically re-driven from each unit to the next.

For the RGB ones, they are logically three monochrome pixels of different colors, so they peel off three words rather than just one.

At any point in the chain you can determine how many logical pixels potentially remain to be updated, by counting the words you are passing on. You can't of course tell if they are actually there, or if there are further pixels for which no data is being provided. And you can't tell how many pixels preceded, other than to bound it by the amount of gap time from the previous update you received.

# Answer
> 4 votes
It is possible to do this by feeding the end of the strip back into the arduino. bunnie Huang blogged about doing this a few years ago: http://www.bunniestudios.com/blog/?p=3345

He has schematics and firmware which uses a modified neopixel library that can measure the length of the strip.

# Answer
> 2 votes
As far as I can make out (eg. NeoPixels Revealed: How to (not need to) generate precisely timed signals) the NeoPixels are not in fact addressed, but are like a long shift register. Thus if you have 10 pixels, you have to send out 10 lots of RGB colours and then latch them. This is why you need to know how many pixels you have, so that you send out the right number of RGB bytes.

I don't think it would be particularly practical to try to detect how many pixels are in the chain, because the individual ones "reshape" the timing pulses.

# Answer
> 1 votes
This is certainly possible as I have now confirmed.

The code below will detect the length of a string of NeoPixels up to 10000 long.

```
/*
 *
 * Find length of NeoPixel string.
 * Author: Nick Gammon
 * Date:   11 March 2016
 */

#include <SPI.h>

const unsigned long LIMIT = 10000;  // maximum pixels to test

// Note: Connect NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega)
//       Connect the other end of the NeoPixels to D2 (External Interrupt 0)

void sendByte (byte b)
  {
    // send one byte to the Neopixels - note that the "off" gap is partly handled by the loop overhead
    //   gaps measured empirically to be 1.7 µs to 2 µs, so we don't need to add any more of our own
    for (byte bit = 0; bit < 8; bit++)
      {
      if (b & 0x80) // is high-order bit set?
        SPI.transfer (0b11111100);  // 1 bit - 750 ns on + 250 ns off (acceptable "on" range 550 ns to 850 ns)
      else
        SPI.transfer (0b11100000);  // 0 bit - 375 ns on + 625 ns off (acceptable "on" range 200 ns to 500 ns)
      b <<= 1; // shift next bit into high-order position
    } // end of for each bit
} // end of sendByte

void ledsetup()
{
  SPI.begin ();
  SPI.setClockDivider (SPI_CLOCK_DIV2);
  SPI.setBitOrder (MSBFIRST);
  SPI.setDataMode (SPI_MODE1);   // MOSI normally low.
} // end of ledsetup

void sendPixel (const byte r, const byte g, const byte b)
  {
  sendByte (g);
  sendByte (r);
  sendByte (b);
  } // end of sendPixel

void show()
  {
  delayMicroseconds (7);
  } // end of show

volatile bool triggered;

void myISR ()
  {
  triggered = true;
  } // end of myISR

void setup()
  {
  ledsetup();
  Serial.begin (115200);
  Serial.println (F("Starting ..."));
  attachInterrupt (0, myISR, RISING);
  } // end of setup

unsigned int increment = 1000;
unsigned int counter = increment;

void loop()
  {
  noInterrupts ();
  triggered = false;
  EIFR = bit (INTF0);  // clear flag for interrupt 0

  for (unsigned int i = 0; i < counter; i++)
    sendPixel (5, 0, 0);
  TIMSK0 = bit (TOIE0);  // throw away timer overflow interrupt
  interrupts ();
  show ();  // latch the colours - handle the interrupt meantime

  if (triggered)
    {
    if (increment <= 1)
      {
      Serial.print (F("There are "));
      Serial.print (counter - 1);
      Serial.println (F(" NeoPixels in the string."));
      Serial.flush ();
      exit (0);
      }
    else
      {  // binary search
      counter -= increment;
      increment /= 2;
      } // end of if
    } // end of if triggered

  counter += increment;

  if (counter > LIMIT)
    {
    Serial.print (F("Could not find any NeoPixels after trying "));
    Serial.print (LIMIT);
    Serial.println (F(" pixels."));
    Serial.flush ();
    exit (0);
    }

  } // end of loop

```

It works by sending out increasingly long strings of 24 bits, and waiting for one to "shuffle off" the other end of the string.

Connect the Data In of the NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega) as this sketch uses SPI to generate the timed sequences. Connect the far end of the NeoPixels (Data Out) to pin D2 which is External Interrupt 0.

The sketch pumps out batches of pixels, and waits for an external interrupt. When that occurs it indicates that the last pixel in the chain was reached, and passed the pixel data out Data Out to the non-existent pixel past the end of the chain.

The number of pixels needed to do this is then noted.

The sketch does a "binary search" to speed things up for long strings of pixels. The worst-case scenario (where you have either 10000 pixels, or none at all) takes 6 seconds to execute. With less pixels it will be faster. I had under a second execution time for 3 pixels in my test string.

The sketch outputs a dull red (intensity 5) so you should see the pixels light up in red if all is well. If you wanted to do it unobtrusively, you could output black (as that still results in bits being sent down the string).

Example output:

```
Starting ...
There are 3 NeoPixels in the string.

```

---
Tags: neopixel
---


# Question
Title: How to properly process large arithmetic
just a question that requires a simple answer. How do I process a large number of arithmetic steps in arduino efficiently and precisely?

For example I have this code function setup:

```
void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;

}

```

Now I've properly setup up data types for all of these variables and they are a combination of float, int and long. I don't think it's a problem with the data type. What I'm getting when I print final answer in the serial is the same number regardless the input the user enters.

I'm guessing I need to format the code in such a way that it performs each line step by step and verifies the answer before proceeding to the next arithmetic line. If so would I need a function for each arithmetic step? Or is there a simpler way to process this that I'm missing.

Any guidance is appreciated. Thanks.

Here is the code in its entirety:

```
unsigned long batterymoment,num1,num2,input,totalmoment;
double buoyancymoment,wheelmoment,cgwheels,mainmass,nosemass,maindistance,nosedistance;
double mainmoment,nosemoment,netmoment,netcg,staticmargin,answer;
double centrebuoyancy = 14.164;
double mainarm = 14.3;
double adc = 11.4;
double meanadc = 22.65;
double nosearm = 1.8;
int totalmass = 12404;
int batterymass = 720;
int buoyancymass = 4401;
int batteryposition,wheelweight;
boolean mySwitch = false;

void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
 }

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
 }

void loop() {
  while (Serial.available()){
    batteryposition = Serial.read();
    if(batteryposition>47 && batteryposition<58){
      if(!mySwitch){
         num1=(num1*10)+(batteryposition-48);
      }else{
         num2=(num2*10)+(batteryposition-48);
        }
       }

if(batteryposition==61){
  input=num1+num2;
  calc();
  Serial.print("Static margin is: ");
  Serial.println(answer);
  num1=0;
  num1=0;
  mySwitch=false;
  }
 }
}

```

So depending on the user input, the calculations will change the final output answer. For example if a 5 should be entered the output should be -4.22 based on my calculations in excel.

# Answer
You're getting the same value every time because that is the value that is being calculated.

I think you have something wrong with how you have implemented your formula. If you start from "answer = " and repeatedly substitute the variables with the formulae or values that make up those variables you end up with this:

> answer = (11.4 - (((4401 * 14.164) + ((((12404 - 4401)\*(1-((14.3 - (12404 - 4401))/((14.3 - (12404 - 4401))+(12404 - 4401 - 1.8)))))/2) * 14.3) + ((((12404 - 4401)\*(1-((12404 - 4401 - 1.8)/((12404 - 4401 - 1.8)+(14.3 - (12404 - 4401))))))/2) * 1.8)) / 12404)) / 22.65

There's nothing variable about that at all.

Your input value is being used to calculate `batterymoment`. `batterymoment` us being used to calculate `totalmoment`. `totalmoment` is being used to calculate `wheelmoment`. `wheelmoment` is being used to calculate `cgwheels`. **`cgwheels` is never used for anything**.
> 3 votes

# Answer
Per your comments, the calc() function is not acting as expected.

Change calc() to be:

```
void calc() {
  Serial.print("input:");Serial.println(input);
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
  Serial.print("answer:");Serial.println(answer);
 }

```

and see if it gets the expected inputs and works as expected. Then add debugging statements in-process until you discover the mismatch.

I'd turn in into more of a function, or a series of better defined functions, and then test them individually.

As your code is there is interaction between global variables, serial parsing, and calculations. If you break it into distinct pieces, you can isolate where the problem is.
> 0 votes

---
Tags: arduino-uno, serial, data-type
---


# Question
Title: Why does the Pro Mini 5 v and 3.3 v version have different clock frequencies?
It looks like the 5 volt version used the 16MHz external crystal while the 3.3V one uses the 8MHz crystal. I need to use 3.3v as my operating voltage.

Can I just remove the linear regulator and bring in 3.3V. I still have to select the 5V 16MHz version in the Arduino IDE, right?

https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf

# Answer
> 2 votes
The ATMega328p is not rated to operate at 16 MHz on a 3.3v supply.

In practice it may sometimes work, but cannot be considered reliable.

The data sheet will show the actual clock rate vs. voltage tradeoffs, so there might be an intermediate value that is workable for you.

The Arduino toolchain needs to know the CPU clock frequency for the serial baud rates, timing delay code, and any time-based use of the timer peripherals to come out right.

There is a special case where if the configured clock rate and the actual clock rate differ by a factor of two, you may be able to cover that by selecting a similarly wrong baud rate - however, the baud rate in the bootloader was set in comparison to the *expected* clock frequency when it was compiled before flashing, and the baud rate *expected* of the bootloader is set in the boards file, so less readily changed than it is in something like the serial monitor.

---
Tags: arduino-pro-mini, oscillator-clock
---