# Question
Title: nRF24L01+ (RF24) radio with Arduino Micro
I purchased several nRF24L01+ (RF24) radios to use with my Arduino Uno and Micro.

Using the GettingStarted sketch and nRF24L01+ connected to my Uno, I get nice debugging info in my serial monitor. However when I connect the nRF24L01+ to my Micro, upload the sketch and open the serial monitor I get no debugging information. There is no info displayed in the serial monitor.

Also the Arduino Uno when set to Transmit, does not see the other nRF24L01+. Any help would be appreciated.

Here is my pinout to connect the nRF24L01+ to the Micro:

```
Line    From Arduino Pin    To nRF24L01+
GND     GND                 1
3V3     3V3                 2
CE      9                   3
CSN     10                  4
SCK     SCK                 5
MOSI    MOSI                6
MISO    MISO                7

```

Here the nRF24L01+

Sketch

```
/*
 Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 version 2 as published by the Free Software Foundation.
 */

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

//
// Hardware configuration
//

// Set up nRF24L01 radio on SPI bus plus pins 9 & 10

RF24 radio(9,10);

//
// Topology
//

// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

//
// Role management
//
// Set up role.  This sketch uses the same software for all the nodes
// in this system.  Doing so greatly simplifies testing.
//

// The various roles supported by this sketch
typedef enum { role_ping_out = 1, role_pong_back } role_e;

// The debug-friendly names of those roles
const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"};

// The role of the current running sketch
role_e role = role_pong_back;

void setup(void)
{
  //
  // Print preamble
  //

  Serial.begin(57600);
  printf_begin();
  printf("\n\rRF24/examples/GettingStarted/\n\r");
  printf("ROLE: %s\n\r",role_friendly_name[role]);
  printf("*** PRESS 'T' to begin transmitting to the other node\n\r");

  //
  // Setup and configure rf radio
  //

  radio.begin();

  // optionally, increase the delay between retries & # of retries
  radio.setRetries(15,15);

  // optionally, reduce the payload size.  seems to
  // improve reliability
  radio.setPayloadSize(8);

  //
  // Open pipes to other nodes for communication
  //

  // This simple sketch opens two pipes for these two nodes to communicate
  // back and forth.
  // Open 'our' pipe for writing
  // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading)

  if ( role == role_ping_out )
  {
    radio.openWritingPipe(pipes[0]);
    radio.openReadingPipe(1,pipes[1]);
  }
  else
  {
    radio.openWritingPipe(pipes[1]);
    radio.openReadingPipe(1,pipes[0]);
  }

  //
  // Start listening
  //

  radio.startListening();

  //
  // Dump the configuration of the rf unit for debugging
  //

  radio.printDetails();
}

void loop(void)
{
  //
  // Ping out role.  Repeatedly send the current time
  //

  if (role == role_ping_out)
  {
    // First, stop listening so we can talk.
    radio.stopListening();

    // Take the time, and send it.  This will block until complete
    unsigned long time = millis();
    printf("Now sending %lu...",time);
    bool ok = radio.write( &time, sizeof(unsigned long) );

    if (ok)
      printf("ok...");
    else
      printf("failed.\n\r");

    // Now, continue listening
    radio.startListening();

    // Wait here until we get a response, or timeout (250ms)
    unsigned long started_waiting_at = millis();
    bool timeout = false;
    while ( ! radio.available() && ! timeout )
      if (millis() - started_waiting_at > 200 )
        timeout = true;

    // Describe the results
    if ( timeout )
    {
      printf("Failed, response timed out.\n\r");
    }
    else
    {
      // Grab the response, compare, and send to debugging spew
      unsigned long got_time;
      radio.read( &got_time, sizeof(unsigned long) );

      // Spew it
      printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time);
    }

    // Try again 1s later
    delay(1000);
  }

  //
  // Pong back role.  Receive each packet, dump it out, and send it back
  //

  if ( role == role_pong_back )
  {
    // if there is data ready
    if ( radio.available() )
    {
      // Dump the payloads until we've gotten everything
      unsigned long got_time;
      bool done = false;
      while (!done)
      {
        // Fetch the payload, and see if this was the last one.
        done = radio.read( &got_time, sizeof(unsigned long) );

        // Spew it
        printf("Got payload %lu...",got_time);

        // Delay just a little bit to let the other unit
        // make the transition to receiver
        delay(20);
      }

      // First, stop listening so we can talk
      radio.stopListening();

      // Send the final one back.
      radio.write( &got_time, sizeof(unsigned long) );
      printf("Sent response.\n\r");

      // Now, resume listening so we catch the next packets.
      radio.startListening();
    }
  }

  //
  // Change roles
  //

  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    if ( c == 'T' && role == role_pong_back )
    {
      printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r");

      // Become the primary transmitter (ping out)
      role = role_ping_out;
      radio.openWritingPipe(pipes[0]);
      radio.openReadingPipe(1,pipes[1]);
    }
    else if ( c == 'R' && role == role_ping_out )
    {
      printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r");

      // Become the primary receiver (pong back)
      role = role_pong_back;
      radio.openWritingPipe(pipes[1]);
      radio.openReadingPipe(1,pipes[0]);
    }
  }
}

```

# Answer
> 1 votes
Perhaps you use the wrong pins. This is really a pitfall link.

You have the Atmega Pins, the consecutive pins of the headers and the pins written on the PCB, i.e. 9 could be 9 on the PCB which is A9.

I have a Chinese 'Micro Pro' and I switched to (2,3) instead of (9,10).

# Answer
> 0 votes
Of course, `9` means `D9` and not `A9`.

Everytime Arduino projects assign a pin with no prefix, it is denoted as data I/O and if the Analog pins are used then it would say `A9`.

The nRF24L01 handles data I/O and not analog input.

---
Tags: rf, arduino-pro-micro
---


title: Bluetooth distorts analog read?

text:
# Question
Title: Bluetooth distorts analog read?
I'm working to make a simple pedometer with Arduino, and after managing to find an algorithm that correctly finds the steps, I added a bluetooth extension (the overly popular and cheap JY-MCU) to check the steps via bluetooth.

I am facing a strange issue, though: when the bluetooth device is powered and waiting for a connection (red led blinking) the analog read function that reads data from the accelerometer goes crazy (thus the pedometer finds a step each second or so). When the bluetooth is powered down or connected to a device such as a mobile phone this doesn't happen.

Did anyone have this problem before? What could be the issue? My setup is easy, you can see it on the image.

I had other sensors as well but since the problem stays even when there are only those two connected I posted the bare minimum setup. At first I thought I could use some kind of pull-ups to stabilise the signal, but I really have no idea on where to tie them and if they can really be helpful at all...

Any help is appreciated.

# Answer
You can try decoupling the power for the bluetooth:

The resistor value should be tiny - 10Ω is a good value to use - don't go much higher than that. The capacitor should be nice and big - I have shown 100µF, but bigger is better - whatever you have that's nice and big. (Make sure you wire it the right way round - check which pin is marked as -) You might also want to add a small capacitor (say 100nF) in parallel with the large one.
> 1 votes

---
Tags: bluetooth, analogread, accelerometer
---


# Question
Title: How can I do this sentence show me in arduino
How can I do this sentence show me in arduino."WARNING: Category 'USB' in library Mouse/keyboard is not valid.Setting to 'Uncategorized'

# Answer
> 1 votes
Your question is unclear.

Note that Mouse and Keyboard libraries are suitable for use with Arduino Due and Zero boards, or with 32u4-based boards like Arduino Leonardo or Micro. They are not relevant when using an Uno.

---
Tags: arduino-uno
---


# Question
Title: Why PJ0 and PJ1 are not reporting as PCINT pins
When the sketch shown at end-of-question is compiled and uploaded to an Arduino board, it is supposed to Serial-print a list of available digital pins, showing for each pin whether it supports PWM or PCINT. (For the latter items, it should indicate whether it has timer-supported PWM, and whether it can cause a hardware-supported pin-change-interrupt.) For example, for an ATmega-2560 board, the program's output includes lines like

```
  Pin# Port Mask  PWM  PCINT
  11   PB5  0x20  PWM  PCINT5  PCINT0_vect
  46   PL3  0x08  PWM
  52   PB1  0x02       PCINT1  PCINT0_vect

```

Using arduino 1.6.3 on my Ubuntu 14.04 system with an ATmega-2560 board, the program's output for pins 14 and 15 is:

```
  14   PJ1  0x02
  15   PJ0  0x01

```

As I understand it, those pins should be shown⁽¹⁾ as supporting PCINT9 and PCINT10, with vector PCINT1\_vect, but the program doesn't report them as such. What is this problem due to?

⁽¹⁾See, for example, table 13.3.9, Alternate Functions of Port J, in doc2549.pdf, the spec sheet for ATmega640/1280/1281/2560/2561. Also see Why is my interrupt code not working?.

Sketch pinsList.ino:

```
/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

```

# Answer
> 2 votes
Majenko was *very close* but seems to have missed the explanatory comment from the source code:

```
// (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me)
// Pins: 10, 11, 12, 13,  50, 51, 52, 53,  62, 63, 64, 65, 66, 67, 68, 69

#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

```

Which seems like it may apply to the fact that the USART3 pins PJ1 (14) and PJ0 (15) are missing.

As for why providing mappings to the hardware USART pins "seems senseless" a little playing with git blame will show that these lines were added to this file in commit f179794 in response to issue 490:

> The SoftwareSerial library defines macros that map Arduino pin numbers to the pin changes interrupts on the pins. We should pull this up into the board-specific pin definition header file so that the SoftwareSerial library can work on any AVR for which those macros (and the pin-change interrupts) are defined.

Which is to say that David Mellis didn't write those lines for generic interrupt use as part of pins\_arduino.h, but rather moved code **originally written as part of the software serial library** to this file to make things more portable (and, though perhaps incidentally, generally usable for other purposes). It's not exactly clear who the original author speaking as "I" in the comment is - the Mega-specific code in question appears to come most immediately from Mikal Hart's extension of Ladyada's Uno-only interrupt soft serial code (which did not have it) but there's also a comment in that seemingly crediting Paul Stoffregen (Teensy boards) for at least some aspect of the macro...

It does kind of make sense that someone writing a software serial library could consider using it on hardware serial pins pointless. But counterarguments could also be made - for one example, the 16u2 core either uses or has experimented with software serial at some baud rates, and for another a software serial implementation could be a plausible way of overcoming swapped RX & TX wiring, or a way of implementing inverted signalling logic when using simplified level shifters or talking to something which expects to.

Given that in its current location the code is no longer necessarily only for software serial use, it seems plausible that a carefully written and fully validated patch to make it more general might be favorably received.

# Answer
> 2 votes
It's because of this entry in the board's pins\_arduino.h file:

```
#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

```

Basically your program isn't reporting what the pins can do - it's reporting *what the Arduino system has been programmed to support for those pins*. Basically it hasn't been programmed to support PCINT on those pins.

---
Tags: arduino-mega, arduino-ide, pins, interrupt
---


# Question
Title: How to use the additional SPIs on Arduino Due
According to the following image it is possible to use a second SPI bus on the Arduino Due by using Serial1 and SCL1 as SCK0 for SPI (or Serial2 and SCK1).

source

However I did not find the code necessary to set up the additional SPI interfaces. I would prefer using these SPI interfaces as they are accessible on the stacking headers in contrast to the default SPI.

Additionally can a SD-Card be accessed using these SPI buses while still using the corresponding Arduino Library?

# Answer
I think the information you are looking for can be found at https://www.arduino.cc/en/Reference/DueExtendedSPI

There are two other alternatives that I can see: if your device supports slave select (which I think they are supposed to), then you can use a different pin to select either device 1 or device 2 (or 3...).

The other options is that if you can connect the clock to only one slave at a time (again, with another pin), you should get the same result - you should be able to use a MOSFET between the Arduino's clock-out and the slave's clock-in, and hook the MOSFET's gate to a spare pin; repeat the procedure, using a separate MOSFET, connected to a different spare pin, to the second slave; then bring one or the other "spare pin" high, to select which way the clock goes. If a slave does not receive a clock, it will not listen for incoming signal. This last one I dreamed up; I don't know if it will work.
> 1 votes

---
Tags: arduino-due, sd-card, spi
---


title: esp8266 not getting programmed

text:
# Question
Title: esp8266 not getting programmed
I am working on an esp8266 and I am connecting it with Arduino Uno. I have programmed the Arduino but when I write AT command on the serial monitor it doesn't show anything.The connections which i have made are:

```
tx uno - rx esp
rx uno - tx esp
gnd uno -gnd esp
vcc and ch_pd - 3.3v supply

```

I am using an external supply and not the 3.3v from the Arduino. I need help with this.

# Answer
Be careful, you could fry your ESP like that. You need to get the signal lines down to 3.3V, not the 5V used by the Arduino Uno. There are many ways to do this, from voltage dividers, to transistors, or you can use a 3.3v Arduino Pro Micro. I would also recommend starting out with just a 3.3v FTDI board, and interface that directly to the ESP to remove the Arduino and its code from the picture.

I would also make sure that your grounds on the external supply and the Arduino are tied together, or just power the ESP from the 3.3v out of the Arduino.

Other than that, double check your baud rate, some come shipped at 9600, some at 115200, and i'm sure that there are others out there too shipping at different baud rates.
> 3 votes

# Answer
Sorry if these are stupid questions but these are the things I would check.

1. Why are you connecting to an Arduino, why not connect directly to the HOST and use a terminal emulator program?
2. What ESP8266 are you using?
3. Are you connecting the Vcc connector of the ESP8266 to 3.3v?
4. I think you need to pull the RST pin high to enable normal running, is it high?
> 0 votes

---
Tags: esp8266
---


# Question
Title: Need help in the project "Arduino for audio processing"
I am following this link from Instructables site:

http://www.instructables.com/id/Arduino-Audio-Input/

My question is:

Instead of using the Microphone Radioshack 33-3038, which is listed in the tutorial, can I use https://www.sparkfun.com/products/9964?

Kindly suggest if there any modifications required in other parts for the circuitry, if I go for Electret Microphone.

# Answer
> 3 votes
The replacement microphone you link to contains all the circuitry in that instructable*. You can do away with the op-amp and all the associated stuff, and just connect it direct to the analog input of the Arduino.

---

*Actually it's better circuitry since they do it right, unlike the Destructable that is a rubbish circuit.

---
Tags: arduino-uno, audio
---


title: Wrong calculation UNO

text:
# Question
Title: Wrong calculation UNO
I've a joystick and a servo connected to my UNO, but for some reason my calculations keep on being wrong? I'm trying to calculate how the rotation should be of my servo (Tower Pro 9g, max value of 180 I think) with my Joystick (Keyes\_SJoys, max value of 1023 on any axis) and example would be:

y = 500;
servo.write(y * 180 / 1023); // should equal to 87.97, but in reality it's 24?

```
#include <Servo.h>

Servo servo;
int d2 = 2;
int a0 = 0;

void setup() {
  Serial.begin(9600);
  servo.attach(d2);
}

void loop() {
  int y = analogRead(a0);
  Serial.print("y: "); Serial.println(y);

  servo.write(y * 180 / 1023);
  Serial.println(y * 180 / 1023);

  delay(100);
}

```

PS. It's a Robotale UNO; I don't know if that makes any difference or not, but.

# Answer
What you are experiencing is a common pitfall. You are probably expecting floating point calculations, but what you are writing are only integer ones.

Try with: y * 180. / 1023. (notice the dots).

This will work only with constants.

To make it work with anything, use a cast: y * 180 / (float) 1023

Happy hacking.
> 2 votes

# Answer
The reason you're getting completely the wrong value (not just losing the decimal portion) is because of a problem called *integer overflow*.

Because the Arduino is an 8-bit device the default integer size is double that. That means that an integer value can store 16 bits, and when signed that's -32768 to 32767.

Any calculations, unless you specify otherwise, have to fit into that range. If you take your calculation step by step you will see how it works:

```
500 * 180 = 90,000

```

Represented in Hexadecimal (for ease of demonstration) 90,000 is 0x15F90. That is 17 bits (4 bits per digit, the left hand is just one bit since it's only the value 1), and 17 is more than the maximum 16 allowed. So we have to "overflow" that value and discard the lefthand-most digit to keep it at 16 bits. So we end up with 0x5F90.

0x5F90 in decimal is 24464. Now we divide that by 1023 and we get:

```
24464 / 1023 = 23.914

```

Because it's integers we have no decimal portion of it, so that just ends up as the 23 that you are seeing.

Solutions? Change the data type.

As @IgorStoppa has pointed out you can use floating point values which gives you big values and the decimal portion. As long as one value in your sum is floating point all the values will be. This is known as *promotion*. There's numerous ways you can force floating values:

1. Represent your literals as a floating point value - that means adding a decimal place. You could have (as Igor shows) things like `1023.`, but I find that a little obscure. It's better to explicitly show a decimal value since it's obvious what it is then, such as `y * 180.0 / 1023.0`.
2. Use a floating point *literal suffix*. You can add certain letters after a number to describe what that number is. `f` is for floating point: `y * 180f / 1023f`.

Floating point is quite heavy weight though and can cause your program to get bigger than you'd like. If you're not interested in the decimal portion you can instead use *long* variables. The best way to do that is with the *long* literal suffix `L`: `y * 180L / 1023L`

*Promotion* means that all the variables are *promoted* to the size of the biggest variable (not greatest value, the variable with the largest storage space). Long and Float are both 32 bits in size, so using either of those will force the other values to both be *promoted* to equivalent types.
> 1 votes

---
Tags: arduino-uno, servo
---


# Question
Title: Beginner here. Which arduino revision should i buy?
I have no idea what difference is there between the revisions and how it affects me. I have a pdf and this pic was in there:

My questions

* which arduino revision is this?
* Does it matter which revision i buy?

# Answer
> 0 votes
That looks like an early-version Uno, rather than an Uno R3 as shown below. (Image is from dxcdn.com and is one of the first few images in a google images for Uno R3 search.)

For a beginner, replacing a DIP ATMEGA328P may be a chip too far. I suggest that rather than looking for an Uno with a replacable chip, get any Uno you like.

Also note that for beginning projects, it makes sense to use the same kind of Arduino – an Uno, a Mega, a Pro Mini, a Nano, etc. – as the guide you are following uses, so that you won't have to adapt any pin numbers and wiring pictures. As you gain experience, it should become easy to adapt designs to different boards.

# Answer
> 0 votes
That looks like an UNO R2, the type with DIP micro controller (you can extract it and replace it with another one, in case of problems). The R3 version is probably the best choice to get started. You might want one that has a connector where this one has only the 3x2 empty pads on the top left (close to the vertical writing AREF). Have a look on ebay/aliexpress/amazon. You can find it for as little as $5-$6. Just search for UNOR3, if you elect to buy this type.

---
Tags: arduino-uno
---


# Question
Title: After moving project from Arduino Mega to Due, pushbuttons now erratically toggle multiple buttons
I've had a project running successfully for months on an Arduino Mega, and today I tried to swap the Mega for a Due to increase the speed. After making the change, the entire project is working successfully except for a strange problem with the pushbuttons.

I have 5 momentary pushbuttons that toggle different controls (they simply send a wireless signal to toggle different AC outlets). After moving the project to the Due, when 1 button is pressed, it ends up toggling 2 other buttons at the same time.

Originally I was using the internal pullups to detect when the buttons were low, but also I've tried connecting them to the Due's 3.3v to detect when they're high, and both times I experienced the exact same behavior.

Is there any reason why there would be this difference in pushbutton-reading behavior between the Mega and the Due? Could it be that the Due is more sensitive to noise? How could I fix this?

The wires connecting to the pushbuttons run about 8 feet. I never had a problem with this setup while running the sketch on the Mega.

Below is the relevant code that detects button presses:

```
#include <Wire.h>
#include <SPI.h>
#include <Ethernet.h>
#include <RCSwitch.h>
#include <Servo.h>
#include <Event.h>
#include <Timer.h>
#include <dht.h>
#include "RTClib.h"

const byte nl1ButtonPin = 40, nl2ButtonPin = 42, nl3ButtonPin = 44,  pumpButtonPin = 5, irButtonPin = 27,

unsigned long buttonPressTime1, buttonPressTime2, buttonPressTime3, buttonPressTime4, buttonPressTime5;  // when the switch last changed state

byte oldButtonState1 = HIGH, oldButtonState2 = HIGH, oldButtonState3 = HIGH, oldButtonState4 = HIGH, oldButtonState5 = HIGH;

const unsigned long debounceTime = 100;

void setup() {
  pinMode(nl1ButtonPin, INPUT_PULLUP); pinMode(nl2ButtonPin, INPUT_PULLUP); pinMode(nl3ButtonPin, INPUT_PULLUP); pinMode(pumpButtonPin, INPUT_PULLUP); pinMode(irButtonPin, INPUT_PULLUP);
}

void loop() {
 byte buttonState1 = digitalRead(nl1ButtonPin);
  if (buttonState1 != oldButtonState1)
  {
    if (millis () - buttonPressTime1 >= debounceTime)
    {
  buttonPressTime1 = millis ();  // when we closed the switch
  oldButtonState1 = buttonState1;  // remember for next time
  if (buttonState1 == LOW) {
    Serial.println("button1 LOW!");
    toggleLight1();
   }
 }
}

   byte buttonState2 = digitalRead(nl2ButtonPin);
  if (buttonState2 != oldButtonState2)
  {
    if (millis () - buttonPressTime2 >= debounceTime)
    {
      buttonPressTime2 = millis ();  // when we closed the switch
      oldButtonState2 = buttonState2;  // remember for next time
      if (buttonState2 == LOW) {
        Serial.println("button2 LOW!");
        toggleLight2();
      }
    }
  }

byte buttonState3 = digitalRead(nl3ButtonPin);
if (buttonState3 != oldButtonState3)
{
  if (millis () - buttonPressTime3 >= debounceTime)
  {
    buttonPressTime3 = millis ();  // when we closed the switch
    oldButtonState3 = buttonState3;  // remember for next time
    if (buttonState3 == LOW) {
      Serial.println("button3 LOW!");
      toggleLight3();
    }
  }
}

byte buttonState4 = digitalRead(pumpButtonPin);
if (buttonState4 != oldButtonState4)
{
  if (millis () - buttonPressTime4 >= debounceTime)
  {
    buttonPressTime4 = millis ();  // when we closed the switch
    oldButtonState4 = buttonState4;  // remember for next time
    if (buttonState4 == LOW) {
      Serial.println("button4 LOW!");
      togglePump();
    }
  }
}

byte buttonState5 = digitalRead(irButtonPin);
if (buttonState5 != oldButtonState5)
{
  if (millis () - buttonPressTime5 >= debounceTime)
  {
    buttonPressTime5 = millis ();  // when we closed the switch
    oldButtonState5 = buttonState5;  // remember for next time
    if (buttonState5 == LOW) {
      Serial.println("button5 LOW!");
      toggleHeater();
    }
   }
  }
}

```

On the serial output, pressing one button shows 2 other buttons as low. So, for example, pressing button2 might show: "Button2 LOW!, Button4 LOW!, Button1 LOW!". There doesn't seem to be any clear patterns with which other 2 buttons get simultaneously pressed. Remember that this exact same code and hardware setup was working perfectly for months on the Mega, which makes me believe maybe it's something related to the Due (maybe 3.3v, maybe stronger PU resistors, etc).

# Answer
I think I can explain this. You have set up a rather complex (and incorrectly wired) network of resistors. Your switch has pull-up resistors, clearly connected together, and then to the "+" pin. The other side of the switches would go to ground.

> Note that I don't have anything connected to the VCC of the switch ...

Right, so your setup looks like this:

Now with no switch pressed they will all read high due to the Due's pull-up (which by the way is around 100 k compared to the Mega's 50 k.)

Now you press a switch. The naturally grounds that switch so it reads LOW. However it also pulls down neighbouring switches through the 10 k resistor network. So each switch now is in the middle of a voltage divider. There is 20 k going to ground and a couple of 100 k going to Vcc, like this:

This voltage divider would be enough for that pin to register as LOW, and indeed that would be repeated for each pin.

Adding your carefully calculated resistor between the "-" pin and ground is just changing the voltages a bit.

The correct solution is to connect the "+" pin to Vcc so that it acts as a proper pull-up. And get rid of that resistor in series with ground.

---

It probably worked on the Mega because of the different pull-up resistance when you activated the internal pull-up which would have changed the calculations for the voltage divider.

I've worked out what I think the voltages will be. Note that the supposedly open switches will actually have 1.1 V on them, which as far as I can tell from the datasheet is in the "undefined" territory between LOW (max 0.99 V) and HIGH (minimum 2.31 V).

Reasoning: You can effectively consider that the 4 open switches have 4 x 110 k between them and 3.3 V in parallel. In other words, 27.5 k. With a voltage divider now between that and the 10 k to ground, you have:

```
10 / (10 + 27.5) * 3.3 = 880 mV

```

So, there will be 880 mV on the common point (which is "+" on the board).

Now for each switch you have a voltage divider of:

```
10 / 110 * (3.3 - 0.880) = 220 mV

```

Add to that the 880 mV at the common point and we have:

```
0.88 + 0.22 = 1.10 V

```
> 1 votes

# Answer
I finally got it working. The problem was with this 5-way tact switch being initially incompatible with the Due: http://www.ebay.com/itm/5-Channel-Way-Tactile-Switch-Breakout-Module-Converter-Adapter-Board-Arduino-/141745152805 . As you can see from the picture and the description on that page, the switch includes pullup resistors on the board. I measured those resistors at 10k Ohms. For some reason the switch worked perfectly fine with the Mega's pullup resistors, but didn't work with the Due's.

After much experimentation, I found that the switch will start working if I add a 14.7k resistor between the switch and ground. The Due's internal pullups still had to be activated, otherwise it seemed the switch was firing constantly. When I used a 10k resistor, the center button on the switch wasn't working. And when I used 20k and higher resistors, many of the buttons weren't working.

I posted this as an answer because the switch is finally working the way I want it to. But I'm still curious to know if anyone has a reason why there would be a necessity to have a 14.7k resistor on the ground of this switch in order to make it work with the Due. Note that I don't have anything connected to the VCC of the switch (though I have experimented with it before).
> 0 votes

---
Tags: arduino-mega, arduino-due, button
---


# Question
Title: How to use TimerOne while calculating time?
I'm trying to get warning with buzzer while I get same values on 3 seconds. But first warning doesn't wait 3 seconds. Second warning is correct. Code is attached. BlinkLED1() method is same BlinkLED2. Probably, I'm missing crowning touch. Can you help me? Thanks in advance.

```
void initialsettings(double roll,double pitch){
  if(level==0){
    if(roll>=34 && timerstatus==false){

        Timer1.initialize(3000000);
        timerstatus=true;
        Timer1.attachInterrupt(blinkLED);
    } else{
         Timer1.stop();
         timerstatus=false;
         level=0;
    }

   }else if(level==1){
      if(roll<=-34 && timerstatus==false){

        Timer1.initialize(3000000);
        timerstatus=true;
         Timer1.attachInterrupt(blinkLED2);
      } else{
           Timer1.stop();
         timerstatus=false;

      }

  }else if(level==2){

  }
}

void blinkLED(void)
{
    noInterrupts();
    Timer1.stop();

    //Timer1.restart();
    digitalWrite(buzzerpin,HIGH);
    delay(7000);
    digitalWrite(buzzerpin,LOW);
    timerstatus=false;
    interrupts();
    if(level==0){
      level=1;
      Serial.println("level 1");
    }
  Serial.println("Sag ");
    //Serial.print("\n");

}

```

# Answer
> 0 votes
```
    Timer1.attachInterrupt(blinkLED);

```

...

```
void blinkLED(void)
{
    noInterrupts();
    Timer1.stop();

    //Timer1.restart();
    digitalWrite(buzzerpin,HIGH);
    delay(7000);
    digitalWrite(buzzerpin,LOW);
    timerstatus=false;
    interrupts();
    if(level==0){
      level=1;
      Serial.println("level 1");
    }
  Serial.println("Sag ");

```

---

* Don't do serial prints inside an interrupt service routine (ISR).
* Don't use `delay()` inside an ISR.
* Don't turn interrupts on or off inside an ISR.
* Variables shared between an ISR and the main code should be `volatile` (I can't see from your snippet whether they are or not).

Reference: Interrupts

---
Tags: arduino-mega, c++, timers, buzzer
---


title: Web Server Options

text:
# Question
Title: Web Server Options
I want to give my project a simple web GUI to change config options. I know I could get a shield and write some horrible HTML in C but I'm wondering if there is a better way. Is there another IC I could get to help with this? What's the recommended solution for an embedded web server?

# Answer
> 1 votes
I'm currently using the ESP8266 modules. They are available for little money on eBay and the like and they provide a pretty nice Wifi-Module. You can even (and I would recommend that) be programmed by the Arduino IDE using some clever core that a few people built here: https://github.com/esp8266/Arduino

Using that you got a Wifi-Server built into the delivered Libraries that can provide basic functions. It can also output files from an SD card if available, there is an example for that.

Aside from that the module has a lot of Flash and you might not even need the Arduino if you don't need a lot of I/O, if you need a lot of I/O then you might want to communicate across a serial link. You will need to make sure to lower the voltage for the ESP, either use a 3.3V Arduino or build a level converter between the Arduino and the ESP, like this: http://www.hobbytronics.co.uk/mosfet-voltage-level-converter

It's not as easy as using a Wifi-Shield but it's very cheap to use.

# Answer
> 1 votes
The Arduino in combination with a wifi/ethernet module will not give you a lot of options to work with. There are currently no libraries that will give you features like including stylesheets, AJAX or websockets. If your project allows it, due to the number of I/O pins you need etc: replace your Arduino with a ESP8266

If you want to produce something fancy: go with the ESP8266. Getting everything setup and working will be a bit harder than with the Arduino, but it will be worth the effort. You can program it in Lua, but that will only give you access to some basic functions. Just write your program in C like you did on the Arduino. There is a thing called Sming framework which allows you to import Arduino libraries with only changing in few lines of code. The Sming framework also includes a HTTPserver with AJAX, websocket, POST/GET, pre-processing, and style/js-file inclusion features.

The web framework is easier than it is in most webframeworks for the pc! The hard part is installing the toolchain and uploading your first bit of code, but once you've got that done it will be easy to figure out the rest. The Sming framework also contains examples for everything you think of.

If you are planning on buying an ESP8266 I recommend you get a few. The basic ESP-01 cost around $2,40 on ebay, but get a fancier one too with a few extra IO pins. I have also got a development version which can be programmed with a USB cable. It is really usefull for developing your program since you don't have to connect a USB-serial device every time just plug a USB cable. When I think my program is done, I upload it to a more basic and replaceable version of the ESP8266 and fix it in my project.

So a summary: It will be harder to figure everything out, but once you've got everything done it will be worth the effort! Here are a few links:

This will show you the power of a ESP8266: ESP8266 oscilloscope with websockets video

The Sming framework: Sming framework github repo

# Answer
> 0 votes
You can buy an ethernet shield of any kind, ENC28J60, wifi module etc etc, and NOT do the html on the chip, just set it up as a server (usually specific the the shield/module you use).

Then you can actually create a local html file on your computer, or even use any webserver on your network or even online. As long as you send the commands to the local address of your arduino.

So if your Arduino ethernet module has the IP-address: 192.168.1.123 then the following form will send a command to the arduino that you can handle in the arduino code:

```
<form action="http://192.168.1.123/acommand=1">
<input type="submit" value="click to send command">
</form>

```

So if you create a simple web form to send a command to the arduino you can put this page anywhere, as long as the action is pointing at your arduino IP-address. If you want to go into the whole jquery standard it might be a bit different, unsure how asyncronious submits are handled.

I want to point out that IF you put your simple html page online you dont need to and SHOULDNT open anything in your firewall or router. The code will work as long as the device you are accessing the page from is on the same network as your arduino.

# Answer
> 0 votes
I personally find that one of the simplest solutions to a web server is one of the two following options.

1. Buy a serial cable, and transmit data using the Serial port on your Arduino. You can transmit data to a PC, and use PHP to read the serial port and display the data you would like.
2. Buy a Raspberry Pi. You will be doing the same as step 1, however you don't need a serial cable to use serial between Pi and Arduino. However you might need a 3.3V / 5V converter, which depends if the arduino serial port outputs data at 3.3V or 5V.

# Answer
> 0 votes
**GENERAL IDEA:**

I would recommend getting a simple Wi-Fi and/or Ethernet module.

Then simply set up routes to **receive** and **send** data to Arduino (assuming `arduino_ip` to be your Arduino's IP), and `GET` and `POST` being HTTP verbs:

Receive data from Arduino:

`GET http://arduino_ip/data`

Send data to Arduino:

`POST http://arduino_ip/data`

Now use any Web development Framework/Language (`PHP`, `Node.js`, `Python`) to receive and send data.

**NO ADDITIONAL MODULES SOLUTION:**

The above method will allow the arduino and server to communicate if they're on the same network. However, if you can constrain the server to be connected by `USB` to Arduino, you can use `Node.js`, `Python` (even `PHP`) to directly communicate to Arduino.

**ANOTHER SOLUTION**:

Add a **Raspberry Pi**, have it connected to Arduino by USB (Arduino's `Serial`), and the use Raspberry's Ethernet to bring in networking (Raspberry Pi can host a server itself)

---
Tags: web-server
---


# Question
Title: Upload Assembly to AVR on a breadboard using Arduino as ISP
I try to learn assembly and use an arduino uno R3 to act as a programmer. i have build a standalone circuit with an atmega328p, can upload usual sketches (written in c) and have also sucessfully burned the bootloader to the external chip with the arduino as an isp but i cant bring my assembly code onto the chip on the breadboard. i tried it with avrdude and the following command

```
avrdude -C avrdude.conf -p atmega328p -c avrisp -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

```

and also

```
avrdude -C avrdude.conf -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

```

but the code is always uploaded to the chip on the arduino - not to the one on the breadboard. can anyone lead me how to upload my assembly programm to the standalone chip on the breadboard using the arduino as isp? is this possible anyway?

EDIT This command worked for me

```
avrdude -C avrdude.conf -v -v -v -v -p atmega328p -c stk500v1 -P /dev/ttyACM0 -b19200 -Uflash:w:test.hex:i

```

# Answer
> 1 votes
Try uploading the blink sketch to the standalone atmega328 first.

Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).

---
Tags: arduino-uno, assembly
---


title: does INPUT_PULLUP uses power?

text:
# Question
Title: does INPUT_PULLUP uses power?
When using a digital pin as input, one has the option of using the internal arduino resistor, which is connected to VCC; that is setting the digital pin as INPUT\_PULLUP, and then the pin reads HIGH. Does this uses electricity?.

I mean the resistor is connected directly to VCC and I presume electricity is constantly flowing through the system, no?. as oppose to having the pin as just INPUT?

# Answer
Only the leakage current on the input itself is constantly consumed if there is no external connection. This is usually much less than the waste caused by having the input floating.

> If a voltage between 0.8 V and 2 V is applied to the input for a prolonged period of time, this situation becomes critical and should not be ignored, especially with higher bit count and more dense packages \[...\]. For example, if an 18-bit transceiver has 36 I/O pins floating at the threshold, the current from VCC can be as high as 150 mA to 200 mA.
> 2 votes

# Answer
The pullups have a value between 20k and 50kOhm. If the input is connected to ground (button pressed), between 0.1mA and 0.25mA is flowing through the resistor. So bare anything.
> 2 votes

# Answer
See Deviation of power consumption between datasheet and real world? \- there we established that leaving the pins input consumed considerably more power than input\_pullup. That was with the pins not connected to anything.
> 1 votes

---
Tags: resistor, input
---


title: A question about including libraries

text:
# Question
Title: A question about including libraries
I'm a beginner in creating my own libraries so the following might contain some stupid stuff.

Anyways, I'm using NRF24L01+ modules for wireless communication and I've been utilizing the magnificent RF24 library (https://github.com/TMRh20/RF24) to operate these modules using Arduino. I wanted to clean up my code and decided to write my own library that uses the R24 library. My own library would contain all the subroutines that handle TX and RX functions.

Problem is that the RF24 library is initialized using e.g.

```
/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);

```

To begin using the NRF24L01+ one would the use the RF24 library like for example:

```
byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
Serial.begin(57600);
printf_begin();
radio.begin();

radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();

```

Well, now I would like to make a library that would allow me just to call setup to handle all of the above. My library would be called RadioComm so I would call in my main code:

```
RadioComm rComm();

setup() {
rComm.setup();
}

```

The problem is that how do I use the RF24 library and all its functions in my library? To initialize the RF24 library in my own library I would have to call somehow this

```
RF24 radio(7,8);

```

and use all the radio. commands. How do I tell my own library that everything starting with "radio." is related to RF24 library because right now I'm getting this:

```
RadioComm.cpp: In member function 'void RadioComm::setup()':
RadioComm.cpp:20:18: error: 'radio' was not declared in this scope
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

```

Below are my .h .cpp and .ino files

Lib\_test.ino

```
#include <RadioComm.h>
#include <RF24.h>
#include <SPI.h>

RadioComm rComm;

void setup() {

rComm.setup();

}

void loop() {

}

```

RadioComm.h

```
#ifndef RadioComm_h
#define RadioComm_h

#include "Arduino.h"
#include <RF24.h>

struct dataStruct{
unsigned long id;
float value1;
float value2;
float value3;
float value4;
};

class RadioComm
{

public:

RadioComm();
void setup(void);

private:
int pin1;
int pin2;

};

#endif

```

RadioComm.cpp

```
#include "Arduino.h"
#include "RadioComm.h"
#include <RF24.h>
#include "printf.h"

RadioComm::RadioComm(void)
{}

void RadioComm::setup()
{
byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10
Serial.begin(57600);
printf_begin();
radio.begin();
radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();
}

```

Any help is appreciated.

Thanks.

# Answer
> 1 votes
Firstly, to address your compilation error:

```
RadioComm rComm();

```

That is not a constructor, that is a function prototype. When you have no parameters to a constructor you *must not* include the brackets or it confuses the poor little compiler.

```
RadioComm rComm;

```

Now - to address your main question. Well, there's many ways of doing it, but the way I always tackle this is to have your sketch define the RF24 object and pass it to the library for later use.

In the class definition, in the `private` section, add:

```
RF24 *radio;

```

Then change the constructor to have:

```
RadioComm(RF24 &r);

```

The constructor itself would then read:

```
RadioComm::RadioComm(RF24 &r) {
    radio = &r;
}

```

Now throughout your library, instead of working with `radio.whatever` you need to work with `radio->whatever` since you are now using a pointer to an object not the object itself.

Then in your sketch you need to adjust your constructor to be:

```
RF24 myRadio(7, 8);
RadioComm rComm(myRadio);

```

The beauty of this is it decouples the configuration of the RF24 class from the RadioComm class, so you can use the same library in a different situation on a different board with different pins without having to change the library - just change the RF24 constructor in your sketch.

It also gives you direct access to the RF24 class in your sketch so you can do any advanced manual tweaks outside the library should you wish to.

---
Tags: arduino-ide, library
---


title: Burned Arduino?

text:
# Question
Title: Burned Arduino?
I have an arduino that I programmed a PWM signal on pin 5. When I power the arduino with 12v or USB5v, pin 5 has the PWM signal. Iam checking it with a oscilloscope. Oddly enough the arduino is not recognisable to a windows PC or MAC, the device never shows up on the usb. The LED on the device seem to give all the right signals. The Green ON LED is on. And the L LED is also on. The program is not using serial so the RX and TX are not on.

When I try another Arduino it works fine.

What could I have broke? I am guessing the ATmega328 is fine?

# Answer
Just a guess, if anything else work fine, my (first) guess would be the serial to usb adapter. I damaged one a while ago on a breadboard but also dont know how. But it could also be almost everything else. The pwm sketch, in which language is it written and burned? Does the Atmega have a bootloader on it?
> 1 votes

---
Tags: arduino-uno, power, usb
---


title: Wrong analog reading

text:
# Question
Title: Wrong analog reading
I am making a simple Li-Ion battery Tester. Basically its two 5R1 resistor in series and a relay (used to cut off the battery when it reaches cutoff voltage). Arduino is connected with ground to the battery and with A3 to the end of the resistors. But when I try to read the analog value, I receive something like 870, which is about 4.24V. BUT the real voltage is about 3.90V (according to my multimeter). How is that possible? Thanks for any suggestions.

# Answer
> 0 votes
I have found the answer. I am not an arduino-newbie, but I was thinking that probably I am making a stupid mistake somewhere. But the problem is in **my arduino**. I tried setting pin D13 (and then all other pins) to HIGH, and I only measured **4.60V**! I measured my USB port and it outputs 5.00V exactly, so there must be a problem in the arduino. So the solution - **the ADC takes 4.60V as 1023, and therefore if you calculate it you get that the real voltage is 3.90V**, which is exactly the same as my DMM said. Thanks Majenko, you were pointing the right way :) By the way, I was using a cheap Arduino Nano from China, I bought it only for 2.2 USD from Ebay. When I used original Arduino, the code and circuit perfectly works. Do you think that this can limit the functionality of my board?

---
Tags: analogread, voltage-level, battery
---


# Question
Title: Help understanding code to build circuit for plant reader
I'm working a design project that measures the tiny changes of conductivity in a plant. (To visualize how a plant reacts to its environment) I'm working with Arduino to realize that. Two wires are hooked up to the plant to measure the changes and are connected to the Arduino. I haven't worked with Arduino before but a friend got me the code from his plant reader (he got help too and doesn't know how to build it anymore). I do understand most of it but I just don't manage to translate the code he gave me into a circuit on the Arduino bread board. I use processing to visualize the measurements afterwards.

Who can help me building the circuit. I don't get what's happening at pin13. Thank you for helping me :)

# Answer
> 2 votes
Pin13 is attached to the onboard LED.

So when you see a reference to it, it means that the program is turning the light ON/OFF. You do not need to do any wiring with it.

But the logic seems strange: it turns the LED off only when the analog reading is out of range (and it resets the stress).

It seems to imply that once the plant is stressed, it will stay stressed :-)

Btw, as side note: posting the code in ASCII form would allow people to quote/comment on it. The screenshot is not very good for that purpose.

What cannot be figured out from the code, is how to instrument your plant. If your friend has a working setup, you could try to replicate it. At least post a few pictures.

---
Tags: arduino-uno
---


title: Can't upload my sketch from arduino IDE

text:
# Question
Title: Can't upload my sketch from arduino IDE
I am using arduino uno and window7 64bit.I can't upload my program to arduino uno.When I upload it the warning message is show me.The warning message is"WARNING:Category 'USB' in library keyboard and mouse is not valid. Setting to 'Uncategorized'.What can I do?

# Answer
> 1 votes
Arduino IDEs v.1.6.x have recently been causing such kind of trouble on windows and mac systems. These problems seem to be caused by Java issues. Arduino IDE comes with java suit for it to work, installing java separately will cause problems. I suggest you uninstall java completely(by that i mean even the residue files that are not removed after uninstalling. For removing java completely you can use third party java remover like JavaRa ( https://singularlabs.com/software/javara/ ). After doing so you can install the IDE again (i suggest to use .zip download of the IDE). If it does'nt help it check this out http://forum.arduino.cc/index.php?topic=341144.0 its possible that problem is caused by out dated executables after updating the IDE.

Hope it helps.

---
Tags: arduino-uno
---


# Question
Title: MPU-9250 : How to convert pitch (+90/-90) to 360 degree?
I'm using Arduino Uno with MPU-9250 to find roll, pitch and yaw.

Everything works fine but I want to covert pitch from (+90/-90) to 360 degree.

I'm using this code:

```
vec.setX(atan2(2.0 * (m_data[2] * m_data[3] + m_data[0] * m_data[1]),
        1 - 2.0 * (m_data[1] * m_data[1] + m_data[2] * m_data[2])));

vec.setY(asin(2.0 * (m_data[0] * m_data[2] - m_data[1] * m_data[3])));

vec.setZ(atan2(2.0 * (m_data[1] * m_data[2] + m_data[0] * m_data[3]),
        1 - 2.0 * (m_data[2] * m_data[2] + m_data[3] * m_data[3])));

m_data[0] = scalar;

m_data[1] = x;

m_data[2] = y;

m_data[3] = z;

```

What should I do?

# Answer
I assume you want to map the range `-90...-1` to `270...359` and the range `0...90` to `0...90`?

It's simple enough:

```
if (angle < 0)
    angle = 360 + angle;

```

Note that you are *adding the negative value* to 360, which is the same as *subtracting the positive value*.

*Or* do you want to map it so that -90 is 0 and +90 is 360? In that case you need to offset and scale it:

```
angle = angle + 90; // Angle is now 0..180
angle = angle * 2; // angle is now 0...360

```

Or in one line:

```
angle = (angle + 90) * 2;

```
> 0 votes

# Answer
The equations in you example convert a quaternion representation of rotation into euler angles correctly; The "pitch" euler angle only has a valid range of +90/-90 and changing it will make your angular representation invalid.

Euler angles specify an arbitrary rotation by 3 consecutive turns. You may want "apparent angle with the horizon", which is not the same thing, and does not define a sequential set of turns to get from rotation A to B.

To get pitch and roll with the horizon from a quaternion, I think you want something like:

```
float x = 2*m_data[1]*m_data[3] - 2*m_data[2]*m_data[0];
float y = 2*m_data[1]*m_data[0] + 2*m_data[2]*m_data[3];
float z = 1 - 2*m_data[2]*m_data[2] - 2*m_data[1]*m_data[1];

float pitch = atan2(y,z);
float roll  = atan2(x,z);

```

I got this by rotating the vector \<0,0,1\> by the quaternion and then measuring the angles of the result around x and y axis. This kind of freaks out when one of the angles is close to 90 degrees though; there are probably better equations out there.

"Yaw vs the horizon" doesn't make any sense, and people usually want the same "style" of yaw you are getting from the euler angle equations, so that shouldn't change.
> 1 votes

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


title: Connect 2 LSM9DS0 to Flora

text:
# Question
Title: Connect 2 LSM9DS0 to Flora
So I'd like to connect two of these sensors to an Adafruit Flora (https://www.adafruit.com/products/2020). In the product page it says you can only connect one but in the forum an admin said that you could do it but it required a bit of hacking. I'm new to arduinos and circuits in general. Can someone tell me how I could do this, or at least point me in the right direction?

**Edit**

I decided to use this multiplexer to use LSM9DS0's with the Flora. https://www.adafruit.com/products/2717

# Answer
Adafruit's rectangular 9DOF device, unlike their round 9DOF, brings several more signals out to pads. When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0\_G can be set low or high to modify the device address:

> The SDO/SA0 pins (SDO\_XM/SA0\_XM or SDO\_G/SA0\_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).

Controlling that signal should let you put multiple 9DOF's on one system. (See my answer to question 13830 for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.

If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22¤ of the LSM9DS0 to Vcc on *one* of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground. This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.

It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.

¤ Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner. See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet. That figure shows the underside of the chip.
> 1 votes

---
Tags: i2c, adafruit
---


# Question
Title: A knob that can be turned by hand, have the position read, and turned by software to another position?
I'd like to be able to change variables on the Arduino by adjusting a set of knobs. When I get to a desirable setting I'd like to be able to save those settings on the Arduino... and then I'd like to be able to load those settings back, and have the knobs turn themselves back to the correct positions. Specifically I'm thinking of using this with a synthesizer.

I understand how to do all of this, except, I don't know if there are knobs that allow this type of behavior.

# Answer
> 2 votes
If you attach a knob to the Analog Feedback Micro Servo, either directly or via gears, then you can use the pot output to measure the current position and use the normal servo control protocol to turn it under software control.

# Answer
> 2 votes
Not a knob, but depending on your application, would a motorized slider like this be applicable?

You would read it just as you would a potentiality, and you have a motor that you can use to drive it to a specific position when you make a change in your software.

As for knobs, I have seen very few if any *motorized knobs*. What I would recommend here would be a continuous rotation encoder so that the position of the knob actually doesn't matter.

# Answer
> 1 votes
Alternatively, just add an LED/LCD display on top of each knob (or have a larger LCD showing info for all the knobs) to show the value. Then you can have the knobs implemented with an optical rotary encoder.

Each knob is unmarked and doesn't need to be reset.

This solution doesn't put any mechanical part under strain.

# Answer
> 0 votes
If you can't get a motorised potentiometer could you use a rotary encoder, a motor, a shaft and some cogs. Press the shaft and rotate manually then release and it disengages the manual cog and moves back to the motor cog.

---
Tags: arduino-uno, hardware
---


# Question
Title: What is the relationship between the gain on the receiver and the delay time
I was conducting some research on wireless communication between a simple transmitter and receiver module using an Arduino. Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%. I am not quite sure why the data would result in this. I think it possibly has something to do with the gain on the receiver and the delay time. Some sweet spot perhaps? Can anyone offer me some ideas/explanations? Also, sorry for any confusion in this question. I am happy to clarify.

Part 2:

Hey Everyone,

I also had a question regarding what purpose each of the following delay serves in wireless communication.

```
// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);// line in question ---------------------
  b >>= 1;
}

```

and the delay used in the regular blink program.

**The regular delay used in the blink programs was what set the 2 microsecond delays.**

Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method?

# Answer
> Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%.

Microsecond resolution delays on an Arduino are tenuous at best. They aren't that accurate. Simply because you're hitting the limit of the speed of the CPU.

At 16MHz you have a clock period of 1/16000000 seconds. That's 63ns. That's the *granularity* of the delays you can achieve - and that can only be achieved by inserting a precise number of `NOP` assembly instructions.

So for the best 1µs delay possible you would need (0.000001 / 0.000000063) 15.87 `NOP` instructions. Of course, you can't have that many, so you have to round it either up or down. Normal integer truncation would result in 15. So that would actually be a delay of 945ns, which is an error of 5.5%.

2µs would be (0.000002 / 0.000000063) 31.74 `NOP` instructions, which would round to 31, so 1.953µs, or an error of 2.35%. As you can see increasing the length generally reduces the error.

*HOWEVER*

The delay function on the Arduino for microsecond accuracy (`delayMicroseconds()`) is maybe not as accurate as it could be. Simply because it's impossible to just have an exact number of NOP instructions for a delay since you can't know how long the delay should be until the function is called with a parameter detailing how long the delay should be. So it has to perform a number of calculations and *make a number of assumptions*. It tries to come close, but it was written for one specific version of the compiler and compilers change. Things may have been changed in how the function gets called, and how long parts of it take (what registers are pushed and popped may change with different compiler versions, for instance). So it's not a perfectly reliable delay.

For more detail you can look at the source code of it (it's in `wiring.c`) and you can see how for small delays it's very hard to get it right. For instance, this couple of lines highlights the problem nicely:

```
    // for a one-microsecond delay, simply return.  the overhead
    // of the function call yields a delay of approximately 1 1/8 us.
    if (--us == 0)
        return;

```

Note the use of the word *approximately* there...

Also you need to note that the delay functions are just that - a delay *at that specific moment in time from the start of the call to its finish*. It doesn't take into account anything else that's going on in your code, so a delay of 1µs in a loop of code that does other things will end up in a loop that takes `X + 1µs` where `X` is the amount of time that the rest of the code takes to execute.

And that's where the `tunedDelay()` function comes in. It has been specially written to be used in that specific circumstance to provide a delay that *takes into account the time the rest of the loop takes to run*. That is, the loop's time plus the `tunedDelay` time equate to the final period you want for the whole loop. For asynchronous serial communications the timing accuracy is important. Since there is no separate (or even embedded) clock to get the timing from both ends have to agree what speed the communication happens at (the baud rate), and any deviation from that can cause communication errors. So the timing has to be as close as possible. A normal `delayMicroseconds()` function call just wouldn't cut the mustard - they needed it more precise than that. Manually tuned to have specific delay values that are as precise as possible, and that was done for specific baud rates on specific speed chips. Each supported frequency has a table such as this:

```
static const DELAY_TABLE PROGMEM table[] =
{
  //  baud    rxcenter   rxintra    rxstop    tx
  { 115200,   1,         17,        17,       12,    },
  { 57600,    10,        37,        37,       33,    },
  { 38400,    25,        57,        57,       54,    },
  { 31250,    31,        70,        70,       68,    },
  { 28800,    34,        77,        77,       74,    },
  { 19200,    54,        117,       117,      114,   },
  { 14400,    74,        156,       156,      153,   },
  { 9600,     114,       236,       236,      233,   },
  { 4800,     233,       474,       474,      471,   },
  { 2400,     471,       950,       950,      947,   },
  { 1200,     947,       1902,      1902,     1899,  },
  { 600,      1902,      3804,      3804,     3800,  },
  { 300,      3804,      7617,      7617,     7614,  },
};

```

That's the value to send to the `tunedDelay()` function in the four different situations where its used for each of the baud rates at that specific clock frequency (16MHz in that example).

`tunedDelay()` itself is written in assembly code and is a very tight loop for the number of iterations specified in the parameter. The shortest possible piece of code with the minimum of overhead to get the maximum accuracy and finest granularity (least number of clock cycles for one iteration) out of it.
> 1 votes

# Answer
> I am looking at the read and recv methods in the software serial library and I don't see any checks for start bits, so what's the point of writing one in the write method?

The start bit is absolutely essential in serial comms. In the graphic below, the start bit is marked "B" - which distinguishes it from "idle" data which is "A". Once received, the receiver then waits 1.5 bit times and starts clocking in the remaining bits. (Starting at "C" in the diagram, and then moving on for a total of 8 bits).

Without a start bit, how would the receiver know when the byte started? Imagine you wanted to send 0xFF (all 1 bits). Without a start bit that would be indistinguishable from the idle state.

In the graphic, "D" is the stop bit. Why have a stop bit? We need one (which is a "1" bit), so that we can detect the transition from the stop bit in the previous byte (a "1") and the start bit in the next byte (a "0").

In the graphic, "E" is the start bit for the next byte.

---

> I don't see any checks for start bits ...

SoftwareSerial has a pin-change interrupt set up to detect that the receiving pin has changed state (to a zero usually). **That** is your start bit. You don't see it in the loop, because it has already arrived, otherwise you wouldn't be in the receive loop in the first place.
> 1 votes

---
Tags: arduino-uno, communication, softwareserial
---


# Question
Title: Arduino and 127/220 Volts: Relay and Isolation
I am new to Arduino, also, I am not fluent in english.

I wish to create a controller for several circuits. All of those circuits are "in parallel" with additional circuits.

My question is:

* Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

Suppose the following:

The retangular boxes are "parallel switches" connected to the devices.

```
R = Power Supply Phase

S = Another Power Supply Phase

N = power Supply Neutral

Arduino, C2 and C3 are 127 Volts, (S+N)

C0 and C1 are 220 Volts (R+S)

```
* Are the Shields safe from oscilations from the eletrical supply?
* What / Where / How should I look on what to ground? Local regulations state that I cannot let R and/or S be grounded.

# Answer
> 1 votes
> Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

A relay provides *galvanic isolation* in the circuit. The mains power is electrically isolated from the rest of the circuit since the device that performs the actual switching (the contacts in the relay) have no physical connection to the rest of the circuit - they are merely acted upon by magnetism.

That doesn't mean that it's *safe*, however. There are a number of things you still need to deal with:

* The Arduino cannot directly drive a relay - it can't provide enough current. You must use a drive circuit.
* Back-EMF from the relay coil as the magnetic field collapses can damage sensitive semiconductors - good snubber circuit design is important here.
* Mains electricity is dangerous and must be treated with respect. Proper circuit design is paramount to ensure that the mains is kept away from the rest of the circuit. Proper connectors must be used and exposed high voltage points must be rendered inaccessible, either by the project housing or by the addition of plastic insulating shielding.
* Relays as they turn on and off cause sparks. Sparks cause EMI. EMI causes induced currents. Induced currents cause damage to electronics. Minimizing the spark generation not only prolongs the life of your relay but the life of everything else around. Ensure your relays can switch fast enough for the currents you are dealing with, or consider using *solid state relays* (SSRs) that don't suffer from this issue.

---
Tags: arduino-mega, power, hardware, relay, system-design
---


# Question
Title: Why I cannot connect directly Arduino UNO and Xbee S2?
I'm connecting Arduino UNO to Xbee S2 Zigbee module directly, and X-CTU cannot find Xbee module via arduino. i'm not using shield, it finds with non-arduino board connecter, but not by arduino UNO board.

i checked all parameters like baud rate, etc.., wirings, and it seems no problem at all, but it keeps msg like 'reset your radio module' and even i swtiched pin 5 and GND, it doesn't works.

what i have to do?

# Answer
If you want X-CTU to see the Xbee while it's connected to the Arduino, you have to connect the Arduino's reset pin to ground. This bypasses the Arduino's MCU and allows the Arduino to act as a USB to serial adapter.

Also don't forget to connect the Arduino's Tx to the Xbee's Tx when it's connected like this, and likewise with the 2 Rx's.
> 1 votes

---
Tags: xbee
---


# Question
Title: ATMega328 + Bluefruit LE stops working soon after power on (not consistently)
Now I am Running Arduino code for Bluefruit LE on bare ATMega328 with 8MHz internal clock, with Bluefruit connected, pin 0 and 1 RX/TX unused, and AT42QT1011-based capsense circuits (logical input to pins 1, 2, 3).

There appeared one problem: when I try to switch the device ON (with 4.5 V batteries, but the same with 5 V USB power), it happens only after three or more attempts. Each time "loop" stops after a second of what appears to be correct operation. For example, if I touch one of the capsensors on the first second of operation, and LED is on, it stays ON, which means, the "loop" is not run.

I have tried to put back the Serial (it was in use in the original echoDemo example), tried to put pollACI after digitalWrite to LED pins. See pin assignments defined in the sketch, those were re-checked with actual circuit.

Measured power supply current and voltage - there were no significant changes in it, even if both LEDs were on. BLE module at startup or while transmitting, was not causing any brownouts. In addition, checked input current and voltage with oscilloscope, and there were no anomalies as well.

NB, this is atmega328, without "p", so for the record I am using 0x07 efuse, 0xE2 lfuse and 0xD9 hfuse.

Also, if the device starts up, it will work fine for at least an hour.

What could be other reasons for such random early failure? (in average, about four attempts to switch on, sometimes starts even on first, second time)

The sketch in question:

```
/*********************************************************************
This is an example for our nRF8001 Bluetooth Low Energy Breakout

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/1697

Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!

Written by Kevin Townsend/KTOWN  for Adafruit Industries.
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in any redistribution
*********************************************************************/

//#define F_CPU 8000000

#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2     // This should be an interrupt pin, on Uno thats #2 or #3
#define ADAFRUITBLE_RST 7

#define REDLED 8
#define BLUELED 9
#define LEFTPAD A2
#define RIGHTPAD A3
#define BADPAD A1

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

unsigned int leftcnt, rightcnt;

void setup(void)
{
  pinMode(REDLED, OUTPUT);
  pinMode(BLUELED, OUTPUT);
  pinMode(LEFTPAD, INPUT_PULLUP);
  pinMode(RIGHTPAD, INPUT_PULLUP);
  pinMode(BADPAD, INPUT_PULLUP);
  digitalWrite(BLUELED, LOW);
  digitalWrite(REDLED, LOW);
  delay(300);
  BTLEserial.setDeviceName("MYUART"); /* 7 characters max! */
  BTLEserial.begin();
  digitalWrite(REDLED, HIGH);
  delay(300);
  digitalWrite(BLUELED, HIGH);
  leftcnt = 0;
  rightcnt = 0;
}

aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;

void loop()
{
  BTLEserial.pollACI();

  if (digitalRead(LEFTPAD)) {
    leftcnt++;
    digitalWrite(BLUELED, LOW);
  } else {
    leftcnt = 0;
    digitalWrite(BLUELED, HIGH);
  }
  if (digitalRead(RIGHTPAD)) {
    rightcnt++;
    digitalWrite(REDLED, LOW);
  } else {
    rightcnt = 0;
    digitalWrite(REDLED, HIGH);
  }

  aci_evt_opcode_t status = BTLEserial.getState();

  if (status == ACI_EVT_CONNECTED) {
    boolean inp = false;
    while (BTLEserial.available()) {
      char c = BTLEserial.read();
      inp = true;
    }
    if (inp) {
      if (leftcnt > 5) {
        BTLEserial.print("LEFT");
      }
      if (rightcnt > 5) {
        BTLEserial.print("RIGHT");
      }
      if (digitalRead(BADPAD)) {
        BTLEserial.print("CENTRAL");
      }
    }
  }
}

```

**UPDATE**: MCU's reset pin is pulled-up by a resistor. Bluefruit's RST connected to PD7 on atmega328 (also known as arduino digital pin 7). Also, 3.3 uF capacitor on the power lines near MCU's IC. (there are more near capsense circuits).

When I disconnect Bluefruit's power, the rest of the circuit (LEDs showing cap sensors state) works without failures after startup. So it looks like under some circumstances, control never leaves BLE code to return to the loop?

**UPDATE 2**: Found long list of reset causes (not sure yet whether relevant here): Arduino/AVR ATmega microcontroller, random resets, jumps or variable/data corruption ...

**UPDATE 3**: Added two 100nF bypass capacitors near GND / VCC pins on both sides. The problem is still there.

**UPDATE 4**: Performed all kinds of experiments, placing BLE module's power lines in different places, with different capacitors. Only in the case of separate power (common ground) the problems were different (but may be due to different times of turning module and MCU on).

**UPDATE 5**: May be relevant or not, but when I run MCU on 1MHz (8 MHz internal clock, divided by 8 - lfuse 0x62), success rate is better than 70%. The speed seem to be enough for my application, but of course near 100% turn-on success should be achieved.

**MAY BE IMPORTANT**: I have added watchdog to sketch (thanks to the "Make: Sensors" book by Karvinen & Karvinen, Valtokari):

```
  WDTCSR |= (1<<WDCE) | (1<<WDE);
  WDTCSR = 1<<WDP0 | 1<<WDP3;
  WDTCSR |= _BV(WDIE);
  MCUSR &= ~( 1 << WDRF);

```

And in the respective ISR red led is turned on or off once in about 8 seconds or so. And ISR code works (thus, MCU works all the time too, right?), even though the "loop" runs no longer.

Can this still be attributed to trouble with power or is it more likely control flow is stuck somewhere in the BLE library?

**UPDATE**: Well... As advised here, while trying out Serial (via microbot USB adapter), I understood, that it does not work reliably (if at all, sometimes eats characters, prints garbage, ...). Not sure whether SPI is sensitive to clock accuracy, but if it is, it may be the problem. Also, the circuit turns on always when powered from USB3 port 5V.

# Answer
> 0 votes
The main problem cause was inaccurate internal clock. As soon, as external 8MHz crystal has been attached to XTAL pins (with a pair of 22pF capacitors to GND), problems with turning the board on disappeared.

Also, I found

```
while(1);

```

loop in the Adafruit's nRF8001 library, which runs whenever problems with the Bluefruit LE board are encountered. That is possibly why interrupts worked fine, but the whole MCU never returned to the main loop.

---
Tags: bluetooth, atmega328, adafruit
---


# Question
Title: Json gets corrupted after first HTTP request
I'm a web developer and I started building a small environment logger that will post to my website\`s API. I'm really new to this kind of coding so bare with me.

Since yesterday, the whole Arduino started to acting funny. After the first or second request to the server(with already tested code), I started sending corrupted JSON data.

```
{
  ":12": "module3",
  "10-7 18:26": {
    "1": {
      "": 21.50,
      "26:12": 55.50,
      "measured_at": "2015-10-7 18:26:12"
    },
    "2": {
      "": 21.10,
      "26:12": 55.70,
      "measured_at": "2015-10-7 18:26:12"
    }
  }

```

Where it should be

```
{
  "modulename": "module3",
  "environments": {
    "1": {
      "temperature": 21.40,
      "humidity": 55.60,
      "measured_at": "2015-10-7 18:25:52"
    },
    "2": {
      "temperature": 21.20,
      "humidity": 55.80,
      "measured_at": "2015-10-7 18:25:52"
    }
  }
}

```

The second JSON is from the initial request to the server. The first one is the corrupted one. I tried stopping all kinds of parts from the code, without any luck, except when I enter the measured\_at manually (without getting the data from the RTC.)

```
#include <DHT.h>

#include <elapsedMillis.h>

#include <DS3231.h>
#include <Wire.h>
//Json Library
#include <ArduinoJson.h>

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

#include <LiquidCrystal.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
EthernetClient client;

const String module_name = "module3";

DHT dht1;
DHT dht2;

DS3231 clock;
RTCDateTime dt;

// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

elapsedMillis timer0;
const long interval = 10000; // READING INTERVAL

int connected_sensors = 0;
float t1 = 0;  // TEMPERATURE VAR
float h1 = 0; // HUMIDITY VAR
float t2 = 0;
float h2 = 0;

int nc = 0; //Network connection simulation INI

byte temp[8] = { //icon for thermometer

  B00100,
  B01010,
  B01010,
  B01110,
  B01110,
  B11111,
  B11111,
  B01110
};

byte humi[8] = { //icon for water droplet
  B00100,
  B00100,
  B01010,
  B01010,
  B10001,
  B10001,
  B10001,
  B01110,
};

byte sconnect[8] = { //icon for connection
  0b00000,
  0b11111,
  0b10001,
  0b10001,
  0b11111,
  0b00100,
  0b11111,
  0b00000
};

void setup() {
  Serial.begin(9600);
  clock.begin();
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  Serial.println("Terrarium Serial");
  // Print a message to the LCD.
  lcd.print("Weather v0.1");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("Sensor loading...");

  lcd.clear();
  lcd.print("Network check...");

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP"); //There is a problem with DHCP
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("DHCP ERROR");
    lcd.setCursor(0, 1);
    lcd.print("Please Restart");
    for (;;)
      ;
  }
  nc = 1;

  delay(2000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(Ethernet.localIP());
  lcd.setCursor(0, 1);
  lcd.println("Ready!");

  Serial.println(F("Connected!"));
  Serial.println(Ethernet.localIP());

  delay(4000);
  lcd.clear();

  lcd.createChar(1, temp);
  lcd.createChar(2, humi);
  lcd.createChar(3, sconnect);

  dht1.setup(15);
  dht2.setup(16);

  h1 = dht1.getHumidity();
  t1 = dht1.getTemperature();

  h2 = dht2.getHumidity();
  t2 = dht2.getTemperature();

  delay(2000);

  //Display the statics on the display
  lcd.setCursor(2, 0);
  lcd.print(module_name);
  lcd.setCursor(9, 1);
  lcd.write(2);
  lcd.setCursor(15, 1);
  lcd.print("%");
  lcd.setCursor(2, 1);
  lcd.write(1);
  lcd.setCursor(8, 1);
  lcd.print((char)223);

  timer0 = 0; // clear the timer at the end of startup

}
void CheckSensors() {

  if (timer0 >= interval) { // READ ONLY ONCE PER INTERVAL
    timer0 -= interval;

    dt = clock.getDateTime(); //get current time

    h1 = dht1.getHumidity();
    t1 = dht1.getTemperature();

    h2 = dht2.getHumidity();
    t2 = dht2.getTemperature();

    DataSend(); //send data
  }
}

//Print the changeable values on the display
void LcdPint() {
  lcd.setCursor(0, 0);
  if (nc == 1) {
    lcd.write(3);
  } else if (nc == 0) {
    lcd.print(" ");
  } else if (nc == 2) {
    lcd.print("E");
  }

  lcd.setCursor(10, 1);
  lcd.print(h1);

  lcd.setCursor(3, 1);
  lcd.print(t1);

}

//Construct the JSON response
JsonObject& prepareResponse(JsonBuffer& jsonBuffer, String measured_at) {

  JsonObject& root = jsonBuffer.createObject();
  root["modulename"] = module_name;

  JsonObject& environmentsObject = root.createNestedObject("environments");

    JsonObject& environmentsOne = environmentsObject.createNestedObject("1");
    environmentsOne["temperature"] = t1;
    environmentsOne["humidity"] = h1;
    environmentsOne["measured_at"] =  measured_at;

    JsonObject& environmentsTwo = environmentsObject.createNestedObject("2");
    environmentsTwo["temperature"] = t2;
    environmentsTwo["humidity"] = h2;
    environmentsTwo["measured_at"] =  measured_at;

  return root;
}

void writeResponse(EthernetClient& client, JsonObject& json) {

  char buffer[256];
  json.printTo(buffer, sizeof(buffer));

  if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
    client.println("POST /v1/sensors HTTP/1.1");
    client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/json");
    client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
    client.println("Connection: close");
    client.print("Content-Length: ");
    client.println(strlen(buffer));
    client.println();
    client.println(buffer);

    nc = 1;
  } else {
    nc = 2;
    Serial.println("connection failed");
  }

  while (client.connected())
  {
    if ( client.available() )
    {
      char c = client.read();
      Serial.print(c);
    }
  }
  Serial.println();
  client.stop();
  //End  post request

}
void DataSend() {

    //This is the part that I think crashes my entire code. I tried using the helper with the RTC library that I use
    //but that made things worse.

    String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& json = prepareResponse(jsonBuffer, measured_at);
    json.prettyPrintTo(Serial);

    writeResponse(client, json);

}

void loop() {
  CheckSensors();
  LcdPint();
}

```

# Answer
> 2 votes
You have used 461 out of 2048 of your RAM bytes for string literals alone. At the very least, use the `F()` macro where you can, eg.

```
client.println(F("POST /v1/sensors HTTP/1.1"));
client.println(F("Host: api.terrariums.eu")); // SERVER ADDRESS HERE TOO
client.println(F("Content-Type: application/json"));
client.println(F("Authorization: Basic bW9kdWxlMzoxMzIxMzI="));
client.println(F("Connection: close"));
client.print(F("Content-Length: "));

```

Ditto for `Serial.print` and `lcd.print` where you are printing strings.

After that, what Majenko suggested is a good idea. Using a custom library is well and good, but JSON is easy enough to output directly. Just make a small function to do it for you.

---

> Problem now is the Content-length... How do I calculate it ?

Do you absolutely need it? If you do, instead of building up the entire content first, I suggest two passes.

First pass outputs to a dummy class which simply calculates the length, second pass actually outputs. Something like this:

```
// outputting class that just counts output
class DummyOutput : public Print
{
private:
  unsigned long length_;

public:
  void begin ()
    {
    length_ = 0;
    }
  virtual size_t write (byte c)
    {
    length_++;
    return 1;
    }
  unsigned long getLength () const { return length_; }

};  // end of DummyOutput

DummyOutput countOutput;  // instance of DummyOutput

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting");

  Print * outputter;  // where to write to

  for (int pass = 1; pass <= 2; pass++)
    {
    randomSeed (1);
    switch (pass)
     {
     case 1: outputter = &countOutput;
             countOutput.begin ();
             break;

     case 2: outputter = &Serial;
             break;
     } // end of switch

    // generate some output
    for (int i = 0; i < 25; i++)
      {
      outputter->print (random (5000));
      outputter->print ('\n');
      }

    switch (pass)
     {
     case 1: Serial.print (F("Content-length: "));
             Serial.println (countOutput.getLength ());
             break;

     case 2: break;
     } // end of switch

    }  // end of for loop
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

Output:

```
Starting
Content-length: 121
1807
249
73
3658
3930
1272
2544
878
2923
2709
4440
3165
4492
3042
2987
2503
2327
1729
3840
2612
4303
3169
2709
2157
4560

```

By generating the same output in two passes you can first just calculate the length (without outputting) and the second time you can output that length first, and then output the actual data.

# Answer
> 1 votes
In all probability you are either running out of memory, or the libraries you are using (and the fact that you are abusing String objects) is fragmenting your heap to such an extent that your whole 2KB of RAM is being used and you are ending up with a stack-and-heap collision.

You have to remember that the Arduino Uno only has 2KB of RAM. It's not a computer, and has no OS, and as such you have to unlearn much of what you know about programming and do things slightly differently.

The first problem you have is with your String abuse. This line:

```
String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

```

will be doing horrible things to your heap. The String class dynamically allocates memory on the heap to store the string content. The operations you have there inadvertently create a rather alarming number of temporary Strings which are then thrown away at the end. Every temporary String dynamically allocates RAM on the heap and can potentially lead to heap fragmentation.

For instance the numeric value `dt.second` is first converted to a String and memory allocated to store the content. Every concatenation results in a new String with its dynamic allocation, etc. Quite messy really.

Secondly, who knows what dynamic memory the `ArduinoJSON` library is using - quite a lot would be my guess - every tag, every value, etc, would need to be stored in memory somewhere, and unless they statically allocate a huge chunk of RAM (wasting most of your precious resource) they will be doing dynamic allocation - and that will make matters much worse.

So how would you get around it? It's actually quite simple - you need to think more about spoon-feeding a baby instead of preparing a 5 course banquet.

Instead of building up big objects with lots of data in them and sending them all out in one big chunk you need to just send little bits at a time. There is absolutely no reason to use things like ArduinoJSON if all you are doing is sending data.

For instance to send the JSON data you could do something like this:

```
  if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
    client.println("POST /v1/sensors HTTP/1.1");
    client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/json");
    client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
    client.println("Connection: close");
    client.println();

    client.println("{");
    client.println("    \"modulename\": \"module3\",");
    client.println("    \"environments\": {");
    client.println("        \"1\": {");
    client.print("            \"temperature\":
    client.print(t1);
    client.println(",");
    client.print("            \"humidity\":
    client.print(h1);
    client.println(",");
    client.println("        },");

```

Etc. You get the drift.

You notice I removed the `Content-length` header? That's because you don't know how long the content will be now (one drawback), so to signal the end of the transmission you will have to close the connection (I don't recall if `client` has a way of only half closing - just the TX portion) to signal to the web server that you have finished. However, if you know how long your numbers will be (say you format them to a specific number of characters) then your body size would always be the same and you can hard code a `Content-length` header.

Also - do you really need to send the time and date? Surely the computer has a better idea of what the current time and date is than the Arduino - just use the computer's internal clock.

---
Tags: arduino-uno, c++, ethernet, rtc
---


title: Measure total microcontroller current?

text:
# Question
Title: Measure total microcontroller current?
So I have a Duemilanove board and am utilizing 7 output pins, I power a Pixy camera and pan/tilt servos from the ICSP header, i also power an HC-SR04 sonar snsor directly from the board.

Of those 7 output pins, 4 are PWMs for the motors (don't ask why), 3 are for servo control (tower pro mg-995)

when I try to output these 7 pins simultaneously things don't work, i get "components at a time" behavior. Like servos turn first, then the motors spin (servos stopped).

Initially we thought it must be a power supply problem (8 1.2v NiMh bat series) which powers the l298n h bridges (two of them) and also powers the board and servos. But now im starting to fear that it's the board itself and that it can't handle simultaneous outputs.

I've read from here (method #10) that taxing the board more than 200mA is a problem. But what exactly happens if you do just that? And is my case exactly like this one? If so, how to fix it?

* Edit +

Here's how the circuit looks.

**Edit:**

Yes i do think there is a need for decoupling capacitors but im not sure where to put them. They dont seem to work. The bounty goes to the best answer on the proper decoupling of this circuit.

**Edit:**

Here's some images on the Pixy camera

**Edit:**

Actually from the original problem I noted when I posted this question, things don't work as expected. WHen the big servos move, the pan/tilt camera don't move when they are supposed to, or the motors briefly stop. I'm wondering if is also an Arduino idiosyncrasy because when I don't run the `servo.attach(servo_pin)` code everything works fine.

# Answer
My experience of high power draw from an Arduino is that it endlessly re-boots so maybe not the issue for you.

The Servo library and PWM pins are probably sharing the same timer therefore motors stop while servos are running.

You could try a different Servo library.

This article is useful to understand the timer/pwm/pin relationships
> 2 votes

# Answer
Here are a few suggestions that might help:

1. **Provide its own power supply to Arduino UNO**, so that no voltage drop can occur on the board itself due to high energy consumers as servos and DC motors. As someone suggested in an answer, a voltage drop on Arduino MCU may trigger the Brown-Out Detection (BOD) which will stop the MCU until voltage rises up again, above a given threshold. You could for instance power the UNO with a 9V battery (or the equivalent 7.2V rechargeable pack). Those batteries don't have much energy but it should be OK as long as they are not used for powering motors. Of course, then you'll have to remove the `Vin` wire to your 8-batteries pack.
2. **Add decoupling caps** (between **V+** and **GND**) as near as possible to every energy consumer: that means adding decoupling for each **motor driver** power-in pins, for each **servo** power pins, and ALSO for the **HC-SR04** sonar sensor (in my experience, it can drop voltage a lot, more than you could expect); note that you may also need decoupling for the **camera**, but I'm not sure on this one, because I have never used one yet.

**Note on decoupling caps**:

The value of caps to use depend on many factors, which would be too long to explain here (and I admit that I don't necessarily understand each of these); but typically, you would use **a small cap (100nF)** when you expect **fast (and short) voltage drops**, and **a bigger cap (\>=10uF)** when you expect **longer voltage drops**.

When you don't know, you can just experiment and see what works best.

Using both kinds of caps at the same time (in parallel) does no harm (I have done this in several situations).

For higher caps, you will have to use an **electrolytic cap**, which is polarized: **do make sure that you wire them correctly (+/+, -/-) otherwise they may blow up**.

Also, choose a **breakdown voltage** for the cap that is much above (I'd say 50% above is fine) your power voltage; **16V** is a common value that would fit your needs; of course, you can use higher breakdown voltages as well.
> 1 votes

# Answer
From the Servo library documentation:

> On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

This is, as has been suggested, because of conflicting usage of the timers. You should just move your DC motors to other PWM-capable pins.
> 1 votes

# Answer
I know this is after the fact but "Back EMF " is more than likely the issue with the starting and stopping of the servo's and most likely the DC motors. The power supply could receive a pulse 4 to 5 times its supply voltage. The cpu could be scrambled or reset. Or pulses sent to servos corrupted. Divert the energy of a motor's collapsing magnetic field back into itself with a diode, cathode to the positive supply rail. Basically any time you stop or start a motor its magnetic field has to go somewhere.Digital hates that.
> 0 votes

# Answer
When power goes through a wire, it heats up the wire. The more current you draw, the more it heats up. The "wires" inside a chip such as the one that adjusts the power aresmall, which means it heats up more, and also it takes less to burn it out.

A fuse is essentially a very thin wire. If you draw too much current (amps) through it, it will burn out (melt the wire). Wires inside a chip or on a PCB are much the same, It may recover when it cools down, or not. Some devices have protection, some do not - you may find the arduino shuts itself off to protect itself, to restart after a period. Or it may not.

As has been suggested, you can bypass the board to power the h-bridge - there should be one or two pins to power the h-bridge separate from the signalling, specifically for this reason.

Also, if the board is powered by batteries, the batteries may not be able to supply the current, causing one or more parts not getting enough power.

If you do bypass the voltage regulator and use power directly from the power source, remember that you are using a different voltage - the voltage from the power source, not +5v.

If you are powering your board from USB, then be aware that there are limitations to the power able to be supplied via USB - the USB specs say 150milliamps; any higher power has to be negotiated with the host (PC), so you may get different answers for a laptop vs. a desktop vs. a mains power adapter.
> -1 votes

---
Tags: battery, current, arduino-duemilanove
---