# Question
Title: Arduino IDE Based Data Logger - Stops Running
I have created a data logger that writes to a MicroSD on a user defined interval. The data logger also has the ability to use an xBee unit to transmit the data received to a base station.

This is a link to the code and pictures of the data logger.

I use Arduino IDE for prototyping and coding. After compiling the code, I use the temp HEX file and upload it to the boards using AVR Studio 4.

The problem I am experiencing is the data loggers will stop running after a random number of recordings. This can be days or weeks of running before the problem is experienced. This issue rarely occurs when the logger is running in local mode, but occurs often when running with an XBee unit.

A temporary fix I have found for the problem is to add `delay(10);` before and after the SD card writes. I do not know why this fixes the problem and would like to find a more appropriate solution.

# Answer
> 2 votes
This use of String is dangerous. You are growing and shrinking the String in a loop and hoping the memory manager prevents any holes from forming:

```
void clockResetcheck() {

  char clkset[] = "CLKSET.TXT";
  if  (myFile.open(clkset, O_READ)) {

    uint16_t newYr;
    uint8_t  newDay;
    uint8_t  newMo;
    uint8_t  newHr;
    uint8_t  newMin;
    uint8_t  newSec;
    char data;
    String temp;
    int place = 0;

    while ((data = myFile.read()) > 0) {

    if (data == '/' || data == ':' || data == ',') {
      if (place == 0) {
        newDay = temp.toInt();
        temp = "";
      }
      if (place == 1) {
      newMo = temp.toInt();
      temp = "";
      }
      if (place == 2) {
        newYr = temp.toInt();
        temp = "";
      }
      if (place == 3) {
        newHr = temp.toInt();
        temp = "";
      }
      if (place == 4) {
        newMin = temp.toInt();
        temp = "";
      }
      if (place == 5) {
        newSec = temp.toInt();
        temp = "";
      }
      place++;
      if (place == 6) {
        myFile.close();
        break;
      }
    }
    else {
      temp = temp + data;
    }
  }
...

```

The line

```
temp = temp + data

```

is a danger flag. This sort of concatenation is going to reallocate the buffer used by String to make it fit the result. The reallocate will leave behind a hole with the previous smaller string.

String has logic to reuse the buffer if possible. So if you start big, it should not have to reallocate. Something like:

```
String temp("12345678");  // allocates the buffer at largest needed size
temp = ""; // clear out

```

That is a less likely to fragment memory. You have a few other concatenates in code that are similar danger.

The best advice to long running programs I ever received:

> Stay off the heap.

You are using String inside functions. That means that buffers are allocated and freed again and again.

A better pattern is to remove **all** the local String's in functions. Instead use one global String as a temp buffer.

```
String g_temp("                        ");
void function1() {
   g_temp = "";
   g_temp += char
}
void functionB() {
   g_temp = "";
   // do stuff with g_temp
}

```

With this pattern, the allocate happens once when the program starts. If the size is setup large enough, if will **never** need to reallocate. This means your high water mark for memory use is established at the time the program starts. You don't have to monitor for a week to see if some corner case will run out of memory.

---
Tags: programming, atmega328, xbee, sd-card, wireless
---


title: ESP8266 and Arduino Interfacing

text:
# Question
Title: ESP8266 and Arduino Interfacing
I have connected Arduino with ESP8266 with

Arduino pin 2 connected to ESP's Tx Arduino pin 3 connected to ESP's Rx via Voltage Divider Arduino GND connected to ESP's GND Arduino 3v3 connected to ESP's CH\_PD

I have powered ESP8266 using 1117 Voltage regulator

When I initially bought ESP8266 it was working properly(I could even set up a server) but now when I connect it to Arduino an endless stream of garbage values is seen on the Serial Monitor...

The arduino is programmed with the following code

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {
    while(esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }
  }

  if(Serial.available())
  {
    // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
    // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
    // but we want to send everything at the same time.
    delay(1000);

    String command="";

    while(Serial.available()) // read the command character by character
    {
        // read one character
      command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}

```

# Answer
> 2 votes
There is a new command for the ESP8266 in AT version:0.50.0.0 - SDK version:1.4.0 that lets you explicitly set the full UART configuration:

`AT+UART_CUR` – set the current UART configuration This command sets the current UART configuration; it does not write to the flash. Hence there is no change in the default baud rate.

For example:

`AT+UART_CUR=9600,8,1,0,0`

---
Tags: arduino-uno, esp8266
---


# Question
Title: Arduino Not Working as Intended when using barrel jack
I am using an Arduino to control some mechanical components in a project I have. It controls a motor, two servos, a valve, and a compressor. When plugged into the computer, everything works fine and perfectly. However, when I power it through the barrel jack using our power supply, some weird things happen. First of all, our servos, which are powered through the Arduino, stop working. All the other components work except for them. Secondly, at the end of the code we have a 5 second delay. Using the computer it works fine. When powered with our supply the delay doesn't seem to happen at all. Any ideas?

# Answer
> 0 votes
I believe that the problem that you are facing is lack of power. It is likely that your power source cannot supply enough current or voltage to power the equipment AND the arduino. Try to get a power supply that has more amps.

# Answer
> 1 votes
i agree with majenko, maybe you know how to fix it but if you do not know here is a site with good information to make you're own 5 volt Regulated source.

http://www.rakeshmondal.info/IC-7805-Voltage-Regulator

sorry for my bad english and good luck. :D

# Answer
> 0 votes
I had a similar problem recently while powering a servo with a Arduino. It did turn out to be power, our Arduino could only supply about 500ma and with sufficient speed or torque on the servo (a lot of times just the boot sequence) we would it the 500ma at peak, the effect however was baffling at first because when we hit the peak current the Arduino would reboot, this could account for you extra delay at the end.

For us the solution was simple bypass the Arduino when supplying current to the servos, in our case it as a 5v battery, you would probably need to drop the 12v to 6v in your case.

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


# Question
Title: Arduino Mega 2560 not showing up in Serial Port in IDE
I recently purchased an Arduino Mega 2560. As soon as I connected it for the first time with my macbook pro the led was blinking (default blink program). To stop the blinking, I uploaded an empty sketch to Arduino. Now the arduino is not showing up in serial port in any operating system. The LED is constantly on and not blinking. Please help

# Answer
Did you try:-

* Unplugging and reconnecting the board?

or

* Holding down the reset button (on the board) during compile and then letting go when the Ide says "Uploading to ..."? (Make sure the sketch has a setup(){} and loop(){} so is not entirely empty)

If that doesn't work then ...

* The pin13 on all the time with an empty sketch might indicate a hardware problem. Is anything connected to the board apart from the usb cable? Green LED simply means the board has power unless you are talking about the tx/rx Led's?

for windows users ...

* Look in "Control Panel\>Device Manager" to see if there is an exclamation mark against any devices, or "Unknown/Other" devices? If you can see the board but it has an error against it look at the properties to see if you can see what the error is. Re-installing the arduino ide will attempt to install the usb drivers again but they can also be found in the \drivers sub folder below the Arduino Ide.
* If you can see an entry in control panel but it is not showing in the Arduino Ide try changing the port to a different COM number (right click\>properties)
* If you can't see anything in Control Panel try a different usb port on your computer.
* Is the board connected directly to the pc via usb or via a usb hub? Make sure direct connect. If power externally make sure enough power.
> 1 votes

---
Tags: arduino-mega, mac-os
---


# Question
Title: Adafruit TLC5947 breakout board is not working with my Arduino Uno
I am trying to use this board (setup tutorial on left hand nav) with my Arduino Uno. I have tried using their example code, as well as my own simplified code, to turn on a single blue LED.

The simplified code I "wrote" is as follows:

```
#include "Adafruit_TLC5947.h"

#define NUM_TLC5974 1

#define data   3
#define clock   5
#define latch   6

Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch);

void setup() {
  tlc.begin();
}

void loop() {
  tlc.setPWM(0, 4095);
  tlc.write();
}

```

> Scroll to the bottom for reference. (TLC5947)

This compiles and uploads successfully. I have DIN connected to 3, CLK to 5, and LAT to 6. V+ is connected to the Arduino 5V pin, and GND to Arduino ground.

Using this setup, the LED does not turn on when connected to channel 0 on the board. Using a multimeter, I have verified that the voltage between common ground and the channel 0 pin is ~0V. Checking voltage on the board between GND and V+, I see 4.8V, which looks good. Connecting the LED directly to the V+ line lights it up, but obviously isn't switchable.

I have no clue why I'm not seeing anything on channel 0's output when I directly write it to 100% duty cycle.

Why is this not working?

# Answer
> 0 votes
> ... the LED does not turn on when connected to channel 0 on the board. \[...\] Connecting the LED directly to the v+ line lights it up, but obviously isn't switchable.

From this I suspect that you have connected the LED between pin 0 and ground. The problem with doing this is that the TLC594x LED driver outputs are current ***sinks***, and connect the output to ground when on. The LEDs must connect between V+ and the output as shown in the datasheet.

---
Tags: arduino-uno, led, pwm, voltage-level, adafruit
---


title: Counting loops or if..else

text:
# Question
Title: Counting loops or if..else
What I would like to do is, step 1:

```
led1 fades from black(off) to green (max-on 255)
led2 fades from black(off) to red (max-on 255)

```

this happens at the same time. If the max value is reached, then both leds fade out (to black, off) so step 2:

```
led1 fades from green to black
led2 fades from red to black

```

Then step 3, almost same as step 1 but opposite colours:

```
led1 fades from black(off) to red(max-on 255)
led2 fades from black(off) to green(max-on 255)

```

And step 4, both fade to black

```
led1 fades from green to black
led2 fades from red to black

```

This is the code that fades led 1/3/5 from red to black and back to red and led 2/4/6 from green to black, and back.

```
#include <FastLED.h>
    #define NUM_LEDS 6
    #define DATA_PIN 3

        CRGB leds[NUM_LEDS];

           void setup() {
               Serial.begin(9600);
       FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
   }

       void loop()
{

  int x = 1;
   for (int i = 1; i > -1; i = i + x){

     leds[0] = CRGB(i,0,0);
     leds[1] = CRGB(0,i,0);
     leds[2] = CRGB(i,0,0);
     leds[3] = CRGB(0,i,0);
      Serial.println(i);
      FastLED.show();
      if (i == 55) x = -1;             // switch direction at peak
      delay(100);

   }
}

```

\****Original question\****

> I am trying to fade a led (WS2812B) from black to green or red, and back to black. (that is working) But now I want the same led fading to blue.
>
> How could I do that? I was trying a if..else but can't figure it out Or should I count the for loops?
>
> This is the starting code I am using
>
> maybe something like
>
> ```
>     if (i==0)
> {
>              leds[0] = CRGB(i,0,0);
>              leds[1] = CRGB(0,i,0);
>              leds[2] = CRGB(i,0,0);
>              leds[3] = CRGB(0,i,0);
> }
>     else
> {
>              leds[0] = CRGB(0,0,i);
>              leds[1] = CRGB(0,0,i);
>              leds[2] = CRGB(0,0,i);
>              leds[3] = CRGB(0,0,i);
> }
>               FastLED.show();
>               if (i == 100) x = -1;
>               delay(100);
>
> ```
>
> But that is not working. Any suggestions?

# Answer
> 1 votes
I would do that based on the clock. This lets you run each one independently.

On the off-chance that your project runs that long, the clock rolls over (resets) every 50 days.

I'm going to assume the 55 in your code should read 255.

I would do something like this (this is a code snippet, but should get you started):

```
const int phase_milliseconds=2500; // each phase lasts 2.5 seconds.
const phase_progress_length=256;   // each phase goes from 0 to 255
const phases=4;                    // numbered from 0 to 3, will repeat forever.

// This is the time since your Arduino turned on
unsigned long time=millis();
// how far we are through the current phase?
int progress= time%phase_milliseconds)*phase_progress_length/phase_milliseconds;

// which phase are we in?
int phase=(time/phase_milliseconds)%phases;

if (phase==0) { // first step
         leds[0] = CRGB(progress,0,0);
         leds[1] = CRGB(0,progress,0);
} else if (phase==1) { // second step
         leds[0] = CRGB(255-progress,0,0);
         leds[1] = CRGB(0,255-progress,0);
} else if (phase==2) { // third step step
         leds[0] = CRGB(0,progress,0);
         leds[1] = CRGB(progress,0,0);
} else if (phase==3) { // fourth step
         leds[0] = CRGB(0,255-progress,0);
         leds[1] = CRGB(255-progress,0,0);
}

```

Since this is time based, it doesn't matter much how often it runs, you don't need a delay (you can still put one in if you like). You can extend this to more steps.

Also note that I rattled this off, off the top of my head, so there may be errors.

---
Tags: arduino-uno
---


title: Human circuit trigger

text:
# Question
Title: Human circuit trigger
The main idea is to create trigger which can be switched on by touching 2 plates on opposite walls. And these should be performed by few peoples holding each other hands.

Obviously human body has big resistance so I couldn't just connect these plates to ground and to one of Arduino pins.

There is a toy that do almost what I what (see it there). But I haven't found any information about how to create it by myself. Do you have any ideas how to create it?

# Answer
I just tried it (using my own method), and I got it working with very good sensitivity (should be fine for two people) using a TIP102 Darlington transistor and some resistors. Here is what I did:

R1, the 1M pulldown resistor on the first pin of the Darlington is necessary to keep the light off when nobody is touching the wires. Without this, the light will turn on and off frantically.

R2, the 1k resistor keeps the Arduino from draining too much current (since that would be bad for the pin) in the case that your A0 is in OUTPUT mode and set to LOW.

R3 keeps the LED (or in my case, an AC relay connected to an actual light) from draining too much current from the Arduino. Note: The LED leads may be backward (reverse polarity) in the provided diagram.

Here is the code:

```
// I release this code under the standard MIT licence;
// (in addition to whatever StackExchange implies);

const short triggerThreshold = 10;// Lower is more sensitive;

void setup() {
  pinMode(A0, INPUT);
  pinMode(A5, OUTPUT);
  digitalWrite(A5, LOW);
  delay(1);
}

void loop() {
  short value = analogRead(A0);
  digitalWrite(A5, (value > triggerThreshold) ? HIGH : LOW);
  delayMicroseconds(10000);// 10ms;
}

```

Note the `triggerThreshold` setting in the code. If you want more sensitivity, try changing the 10 to a 5. I just tried it, and it becomes *extremely* sensitive, yet it still appears to reliably stay off when I don't touch it. Naturally if you use large plates for touching, electrostatic in the air could set it off, so you may need to change this number to be higher to make it less sensitive, depending on your setup.
> 3 votes

# Answer
You can do it with an Arduino ! Use any of the ADC pins There will be change in the ADC i/p when there is some resistance b/w the pins ! Try both +ve \> (people) \> ADC -ve \> (people) \> ADC Just do some trials and probably will notice the change in ADC pin outputs . If you want to make it more sensitive Add a high resistance to the ADC pin if you are giving +ve to touch plates add a resistance from ground to that ADC pin
> -1 votes

# Answer
The idea is intriguing, but you are not limited to use electricity. You could experiment with some other type of signal. Sound, for example. That would be safer.
> -1 votes

---
Tags: arduino-uno, wires, system-design
---


title: Hc Sr 04 Ultrasonic Sensor

text:
# Question
Title: Hc Sr 04 Ultrasonic Sensor
I'm using Hc-Sr 04 ultrasonic sensor for my project and I want to know that if I could or not utilize an slope. Have you an idea?

# Answer
I have a couple of these running right now, and they will often work at a slope when the surface is complex (not flat). However, the detection angle, as it comes from the sensors, appears to be about 30deg from centre in each direction. Hence, the sensors do need to be relatively pointed at the object being detected.

When placing my hand directly above it, it doesn't really matter what angle I tilt my hand, presumably since I have fingers that are not flat. On the other hand, if I put a paper towel in front of it, it will stop seeing it if I angle the paper towel more than 20 or so degrees.

Overall, if you keep the object within 30 degrees from the sensor's fixation point, it will work, granted the object, if flat, is "pointed" at (facing) the sensor flat-wise within about 20 to 25 degrees. For irregularly surfaced objects, it does not seem to matter too much unless the angle is pretty steep, such as 60 degrees.

Here is what I mean:
> 1 votes

# Answer
Slope surfaces may cause reflections so you need to try. I think 30 degree going to make reflection and gives wrong value
> 0 votes

---
Tags: sensors
---


# Question
Title: Arduino clone with ch340G and correct w7 x64 driver cannot connect to IDE
I have an Uno R3 with CH340G which works perfectly at my home w7 x64 notebook.
It worked properly right away with the CH341s64.sys driver. I tried revs from 2009, 2011 and 2014 and it is working with either one.
On my w7 x64 desktop though the drivers somehow do not communicate properly.
If I plug in the device, windows recognized it and a new port (port 8 in my case) shows up in device manager.

When I try to transfer a sketch to the device it fails with error message avrdude: stk500\_recv(): programmer is not responding.
I have tried CH341s64.sys rev 3.3.2011.11 and 3.4.2014.8 without success.
I have no clue how I can troubleshoot this as windows shows the port properly and there are no signs of error on the driver. There are no entries in the event logs.
Is there possibly a log file from the IDE which could shine a light?
I already tried with firewall disabled but no change.
My IDE is the latest 1.6.6 on both systems.

# Answer
> 1 votes
Solved:
The issue was due to an USB Hub which I have at my desktop.
After I connecting the arduino directly to an USB port at my desktop everything was fine.
Unfortunately there is no hint about this in the arduino troubleshooting guide. A hub is only mentioned in conjunction with a MAC.

---
Tags: arduino-uno, clones
---


# Question
Title: None of the programs in Arduino example is compiling
I am new to Arduino. I have connected the Arduino to the computer and I have installed the necessary drivers. But when I am compiling the Blink.ino program and other programs, which is present in the example, I am getting an compilation error. I have the IDE folder in D:\ drive

```
exec: "D:\\Arduino\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino5/ctags": file does not exist
    Error compiling.

```

I don't know what to do. Please help me

# Answer
A couple of things here look odd – but then I don't use Windows very often – I'd suggest that you download a fresh copy of the stock (not development) Arduino IDE. You can get it here.

What's odd looking too me is:

1. The double backslashes, they could be causing the file to appear not to exist, and
2. The `arduino-nightly` component in the path. That suggests to me that you're using a "bleeding edge" version of the IDE where problems are likely to creep in. These versions are for developers and people who like living on the edge (or who want to help with testing new features and the like).

One thing to do to check out the first oddity is to actually try to follow that path (both with and without the double backslashes). If the file is there (without the double backslashes) then it seems like something is odd with the path construction in the IDE.
> 1 votes

---
Tags: arduino-uno
---


title: DHT11 and DHT22 unused pin

text:
# Question
Title: DHT11 and DHT22 unused pin
The DHT11 and DHT22 is a 4 pin temperature and humidity sensor, where one of the pins is labelled as NC (not connected).

I'm curious what the unused pin is used for. Factory calibration?

# Answer
On the DHT11 it's connected to pin 6 of the SOIC14 inside. So it's at least connected to something. But who knows what it's for.

It has a (internal) pull-up resistor to VCC of around 100kOhm on this pin.

I connected my logic analyzer to it, there is no signal, even while reading the sensor. Also connecting the arduino's signal wire to this (incorrect) pin does nothing.

Factory calibration or testing would be my guess too, but who knows.
> 2 votes

# Answer
in this datasheet both 3. and 4. pins are marked GND : https://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf
> 0 votes

---
Tags: temperature-sensor
---


title: XBee + Arduino Problem

text:
# Question
Title: XBee + Arduino Problem
I've been doing some XBee experiments with Arduino Pro Mini 5V. I knew that XBee S2 is 3.3V only, so I've connected its Vcc to 3.3V from external supply, but I had also connected XBee RXTX to arduino TXRX, in this order, and since that i can't use my XBee Explorer to communicate with XCTU on my notebook. The connections with an 5V Arduino RXTX can cause damages to the XBee, even if the XBee was powered with 3.3V?

# Answer
Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, knowledge.digi.com/articles/Knowledge\_Base\_Article/…. I really think that the XBee is gone. One way to avoid this problem is to get one of this regulated breakout board. http://www.hobbytronics.co.uk/xbee-explorer-reg. As it says in the description, it regulates ALL pins to 3.3V, making me believe that I needed to take care of that before making such a mistake. Hopefully this prevent someone from doing this mistake in the future. So, bye-bye XBee.
> 1 votes

---
Tags: power, xbee, arduino-mini
---


# Question
Title: Arduino Nano Atmega328P doesn't work on Macbook
I've bought and Arduino Nano compatible on eBay:

But by the time I connect it to my Macbook Pro (OS X El Capitan 10.11.2) doesn't appear under "Tools -\> Port" in Arduino IDE:

I've followed some instructions by other posts here in StackOverflow:

But none of them worked :(

If someone could help me out with this issue I'll be grateful.

Thanks.

# Answer
I was be able to solve the issue.

By looking for the serial chip my board has: CH340G I found this blog post:

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

So I downloaded the signed driver for my chip and now it works :D

Driver: http://kiguino.moos.io/downloads/CH34x\_Install.zip
> 1 votes

---
Tags: usb, arduino-nano, mac-os
---


title: powering the arduino uno

text:
# Question
Title: powering the arduino uno
I need to power an arduino uno with a battery but for a very long period of time. And I read a lot of thing about this. Some say do not use a 9V battery with a regulator some other say that it is the best way. SO I am really confused and I need to know what's the best solution for this (taking into consideration the fact that I need my board to last a week at least, if it is possible?)

Thanks!

# Answer
The Arduino Uno is not really designed for that. Simply keeping the power indicator LED, regulators and extra circuits on for a week will require in the order of 1500-2000 mAh (10\*24\*7=1680mAh). That is without any application at all on the MCU.

Now it is possible to modify the board and reduce this extra power requirements to less than 1 mA and as low as 0.1 mA. Or even better buy a Pro Mini clone and cut the wiring to the LED and regulator, and power with a 3.7 V/1500mAh battery directly.

Here is a great reference on the subject.

Cheers!
> 7 votes

# Answer
You will definitely not get a week out of a 9V cell - they have very small capacities (and are expensive relative to other types of cell).

Your Uno already has a regulator in it and this regulator wastes a certain amount of energy converting between different voltages. I'm certainly no expert, but from what I've gleaned over the last month or so of owning an Uno, powering it from batteries can be tricky if you want to do it for long periods of time.

It's probably worth trying a 12v sealed lead acid battery - these have capacities measured in Amp Hours, rather than milli-amp hours like most other types of cell. The built-in voltage regulator in the Uno is good up to 20V, just be sure to connect to the barrel jack on the board.

Of course, without knowing more about what you're actually trying to power along with the Uno, it's difficult to make proper recommendations.

I would also suggest looking at building your system with a naked MCU and a voltage regulator tailored to your application. That way you can throw away a lot of the stuff that uses power on the board that you don't need. (Start with a Breadboarduino and take stuff out from there!)
> 4 votes

# Answer
Three main things to do to decrease the Uno's power consumption:

1. Remove the power LED (you can Google for instructions if you're not sure how to do it)
2. Bypass the voltage regulator by providing ~5V of power to the 5V pin. You can arrange three sets of AA batteries in series to get about 4.5V which should be fine except that the crystal may run at a different speed (and you may get incorrect results from the millis() function for example). Obviously if that is unacceptable then you will need to provide a constant 5V voltage either by using the Arduino's regulator (which is quite inefficient) or buying a more efficient third-party regulator. The voltage provided by the batteries will vary somewhat, and over time the batteries will start putting out less voltage and eventually your Arduino may start to behave erratically or not at all. If reliability is of high importance then this may not be acceptable to you.
3. Use sleep modes to the greatest extent possible (see http://playground.arduino.cc/Learning/ArduinoSleepCode). If your Arduino only needs to wake up for a few seconds every hour, you can make a few batteries go a very long way. Note that if you're using a regulator, it will still draw significant power even while the Arduino is sleeping.

Bonus tip: buy a micro instead, or build your own board. (Avamander suggests a Pro Mini 3.3V in the comments below, he's probably right, I don't know much about that board)
> 3 votes

---
Tags: arduino-uno, battery
---


# Question
Title: Can I increase the 10 event limit in Simon Monk's Timer library?
On Dr. Monk's library page here, he states: "You can attach up to 10 events to a timer." I am wondering if this is a hardware limit, or if it was an arbitrary number he chose for his library.

In Timer.h, he defines the maximum number of timed events like this:

```
#define MAX_NUMBER_OF_EVENTS (10)

```

Can you foresee any problems if I changed that to a higher number? My sketch is already approaching the limit of 10 timed events running at the same time, so it would help me if I was able to increase the maximum number of timed events to about 20.

# Answer
I don't see anything that would cause any issue. Just don't exceed 255.
> 1 votes

---
Tags: library
---


title: Can I run a Mega 2560 on 14v?

text:
# Question
Title: Can I run a Mega 2560 on 14v?
I have a Mega 2560 with a ramps 1.4 shield. I noticed when I turn on the 14v power supply the mega would also power up and run.

Am I damaging it running it at 14v? If not is there a solder or jumper somewhere that I can set it to only run the mega/logic on the usb power? The 14v is just for the stepper motors.

# Answer
> 1 votes
You *can*, but you shouldn't, because the the board will heat excessively, as you're out of the recommended range for the input voltage on vin (7-12V).

Unless you have a *switching* regulator (the one on the board is linear), then you shouldn't' have too much of a difference between the operating voltage and vin as an operating principle because of efficiency (and thus heat) issues.

---
Tags: arduino-mega, power
---


# Question
Title: Is there any realy working setup for multicopter with codes
I'm searching pc controlled quadrotor code projects. I tried to do strangedev's project but not works for me. Is any one test this project. PID commands works like relays. suddenley speeds up and down. I tried to tune PID constants with Ziegler nichols but no success. Is there any realy working code and setup. Can you share your experiences?

# Answer
> 2 votes
I've not used the (unmaintained) code you reference, but if a PID is responding much too fast in a new system, cut the parameters down significantly, first focusing on P and later I. Turn off the D, and the I terms, then slow the P down until it is behaving reasonably. Once Proportional control is working then try bringing I up in proportion to the change you did with P.

The https://github.com/strangedev/Arduino-Quadcopter/blob/master/quadcopter/quadcopter.ino#L62 code starts with (P,I,D) values of (0.5,0,1), so back off to (0.25,0,0) or (0.05,0,0) or lower to get the speed or response more as you expect, and then experiment.

Higher P will make it faster and saturate to the PID limit values quicker and make it more-relay like. If your system is in a relay-like bang-bang mode, then Zeigler-Nichols tuning will be hard to do well. Reduce P until you get a non-relay-like response. Show your code and add in some print/debugging to see what sort of pitch values give you what sort of outputs. PID isn't magical, if you want a pitch measurement of -30 to cause a control output of +10, P=10/(-30)=0.3 might be a good starting point.

The way the unmaintained code looks, value of P=20 will saturate at your output limits of +/-20 with only a pitch measurement of +/-1 degrees.

Show your actual code and values in your question, slow down the PID, and add debugging output.

---
Tags: arduino-uno, pwm, pid
---


# Question
Title: How to set address for using more than MPU9250
I am trying to build a project that contains more than one MPU 9250, until now I'm still confused to MPU9250. If I were going to that, does anybody here know how to set addresses to each of the MPU's I am going to use? Thank you for spending time reading my question. I hope someone will help me get through this.

# Answer
> 1 votes
It is possible to have up to two MPU 9250 devices on an I2C bus without any extra logic. Pin 9 (AD0/SD0) defines the lowest bit in the I2C address of the device. Please see Chap 7.2 I2C Interface

If you need to connect more than two devices this can be done by connecting the AD0/SD0 pin of each device to a chip select pin on the arduino. This pin is asserted when addressing the device (This solution was provided by @Gerben, see comments below).

An example with three MPU 9250: Arduino D4-D6 are used as chip select pins. MPU1 AD0/SD0 pin connected to D4, MPU2 pin to D5, and MPU3 to D6. D4..D6 are initiate to HIGH. When addressing a MPU the chip select pin is set to LOW and the lower I2C address is used for access. The other MPUs will be listening for the higher I2C address.

Cheers!

# Answer
> 0 votes
This is the type of information which a Data Sheet is intended to communicate. In I2C mode the AD0 pin selects between two possible addresses,

1101000 for AD0=0 and 1101001 for AD0=1.

In SPI mode you can presumably have as many as you like by giving each its own chip select.

That said, using multiple sensors may not be very useful unless your apparatus is flexible - only the 3 accelerometer axis would be expect to yield different values based on position relative to the center of rotations.

---
Tags: programming, arduino-mega
---


# Question
Title: Having issue using Arduino IRQ handler in nRF51822
Could anyone please help me as I currently using nRF51822-Arduino library with a nRF51822 chip and I couldn't call the interrupt function, `wakeUp()`.

Currently I connect the external interrupt pin to nRF51822 pin: P0\_1 or arduino pin: A0 after pin transform in the nRF51822-Arduino library. Maybe I know what value should I put for the variable `pin` for the function below:

```
attachInterrupt(pin, wakeUp, CHANGE);

```

so that when there is an interrupt change, it will call the `wakeUp()` function?

# Answer
> 0 votes
Reading the source code for the attachInterrupt() shows that you should use the Arduino Pin number: https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL\_nRF51822/cores/RBL\_nRF51822/wiring\_interrupter.cpp#L70

The Arduino Pin number for A0 is 19 according to the pin transformation: https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL\_nRF51822/cores/RBL\_nRF51822/pin\_transform.cpp#L64

Cheers!

---
Tags: interrupt, nrf51
---


# Question
Title: invalid conversion from 'char' to 'const char*'
My intention was to overload a function to handle optional parameters. My code looks like

```
void functionA(const char *errorMsg) {
  functionA('0', errorMsg);
}

void functionA(char errorCode, const char *errorMsg) {
    ...
}

```

The line functionA('0',... generates the error

```
invalid conversion from 'char' to 'const char*'

```

How do I fix that?

# Answer
> 1 votes
The compiler needs the prototypes of the functions before the body containing the call to the overloaded function otherwise if starts complaining that the parameters does not match the known function (at this point in the source code).

```
// The function prototypes
void functionA(const char *errorMsg);
void functionA(char errorCode, const char *errorMsg);
...
void functionA(const char *errorMsg)
{
  functionA('0', errorMsg);
}

void functionA(char errorCode, const char *errorMsg)
{
  ...
}

```

Cheers!

# Answer
> 1 votes
What do your prototypes look like? I suspect that the compiler thinks that it is calling the first instance of `functionA()` and is trying to cast `'0'` to a 'const char \*\` and that isn't going to work…

If you don't have prototypes for both signatures, then adding the second one may solve your problem. If you do, I'm puzzled.

---
Tags: data-type
---


# Question
Title: How to connect HC-05 to an arduino Galileo?
I connected a logic analyzer on digital pins 0 and 1 (Rx and Tx). Using `Serial.` functions on Galileo and the integrated terminal on Arduino IDE, I noticed this UART port was not used when chars were received and transmitted, what is sustained by the blocks diagram of Galileo here.

So, if UART1 is used on PC communications, I would like to use UART0 to other things, like a bluetooth adapter. Any tips?

# Answer
> 1 votes
This might answer your questions about the Serial mapping on Galileo. Seems like you should use Serial1 for UART0 and Serial2 for UART1.

Cheers!

---
Tags: uart, arduino-galileo
---


title: Sublime Text Compilation Issue

text:
# Question
Title: Sublime Text Compilation Issue
I've tried searching for this issue but came up empty. Due to the desire to use a better IDE, I installed Sublime Text 3 and Stino. I have installed the Stino package and now have the Arduino menu inside the Sublime Text editor. I have selected the Arduino application folder appropriately. However, when I compile the simple Blink example, I'm presented with the following error. This error comes up when I attempt to compile any Arduino project. Have I forgotten to configure a setting? All videos and tutorials I've seen just follow the same steps as I have and don't seem to include any additional configuration (besides selecting the Arduino application folder).

```
[Stino - Start building "Blink"...]
[  3%] Creating C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o...
"C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD  -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=161 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\examples\01.Basics\Blink" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp" -o "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o"
The filename, directory name, or volume label syntax is incorrect.

[Stino - Exit with error code 1.]

```

# Answer
> 0 votes
As a quick update for anyone who runs into a similar issue (granted, a week later)...

I upgraded to 1.6.5 of the Arduino IDE, making sure to set my Arduino application folder appropriately, and the compilation issue has disappeared. I am able to compile and upload projects successfully.

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


# Question
Title: Can I receive data on the Arduino by sending data to /dev/ttyACM0?
I'm working on a Raspberry Pi connected to an Arduino. When I execute

```
echo 'Hello' > /dev/ttyACM0

```

, the Arduino receives the data, as indicated by its LED. How can I read the data on the Arduino and process it?

# Answer
Use Serial.read() there are plenty of examples that come with the Arduino IDE, just make sure the baud rates on the Raspberry Pi and Arduino match.
> 2 votes

---
Tags: serial, usb
---


title: Light only half of the LEDs

text:
# Question
Title: Light only half of the LEDs
How can I only let half of the LEDs light up, for example, LED 1 on, LED 2 off, LED 3 on...and so on.

I did it this way (this example fades also all LEDs on and off)

```
   int x = 1;
   for (int i = 0; i > -1; i = i + x){
      leds[0] = CRGB(i,0,0);
      leds[1] = CRGB(0,i,0);
      leds[2] = CRGB(i,0,0);
      leds[3] = CRGB(0,i,0);
      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -1;             // switch direction at peak
      delay(10);
   }

```

but that is not so nice if you have 100 LEDs or so.

# Answer
I don't know much about neopixel but as a general coding practice if you want to do something for every other object, you use the modulus operator like so

```
if(i % 2 == 0)
{
  //i is even
  //off
}
else
{
  //i is odd
  //on
}

```

So just wrap your current for loop in another one and to the above with the iterating variable.
> 2 votes

# Answer
```
int x = 1;
   for (int i = 0; i > -1; i = i + x){
     // using modulo
     if(i % 2 == 0){
     leds[i] = CRGB(i,0,0)}else{
     leds[i] = CRGB(0,i,0);}

      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -1;             // switch direction at peak
      delay(10);
   }

```

or

```
int x = 2;
   for (int i = 0; i > -1; i = i + x){
     leds[i] = CRGB(i,0,0);

      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -2;             // switch direction at peak
      delay(10);
   }

```
> 1 votes

# Answer
This is, for the most part, exactly what others have said. However, nobody has managed to actually use a `for` loop properly; they've carried forward your inefficiencies for some unknown reason.

The whole point of a `for` loop is to execute a block of code a predetermined number of times. In your code, you create a loop that loops for a ridiculous length (65,536 times) but each time checks how many loops there have been.

Once the `for` loop has been constructed properly there are two approaches:

```
int NUMBER_LEDS = 100;      // you only ever have to change this
                            // if the number of LEDs change - and it's really
                            // easy to find if you put it at the start of
                            // your code.

for (int x = 0; x < NUMBER_LEDS; x++)
{
    if (x % 2 == 0)
        leds[x] = CRGB(x,0,0);
    else
        leds[x] = CRGB(0,x,0);
    Serial.println(x);
    FastLED.show();
    delay(10);
}

```

The above code is fine if you just want two LED subsets. If you want more than two, you can use a `switch/case` statement:

```
int NUMBER_LEDS = 100;      // you only ever have to change this
                            // if the number of LEDs change - and it's really
                            // easy to find if you put it at the start of
                            // your code.
int NUMBER_SETS = 4;        // this will give four groups.

for (int x = 0; x < NUMBER_LEDS; x++)
{
    switch (x % NUMBER_SETS)
    {
        case (0):
        {
            leds[x] = CRGB(0,0,0);
            break;
        }
        case (1):
        {
            leds[x] = CRGB(x,0,0);
            break;
        }
        case (2):
        {
            leds[x] = CRGB(0,x,0);
            break;
        }
        case (3):
        {
            leds[x] = CRGB(0,0,x);
            break;
        }
    }
    Serial.println(x);
    FastLED.show();
    delay(10);
}

```

You don't have to write a `case` block for every outcome of `x%2`; you might want a certain group of LEDs to stay on for two iterations, for example. More information on `switch/case` can be found here, towards the bottom of the page.

I recommend you read this article on Operators in C++, starting from "Compound Assignement". It helps make code more readable and can considerably decrease the amount of typing you have to do - `i = i + 1` neatly becomes `i++`.
> 0 votes

---
Tags: arduino-uno, neopixel
---


# Question
Title: Arduino Mega 2560 ADC sampling instant and other timings
Hello Everyone (I might be making some mistake in asking this "question", bear with me as I am new to these sites... I honestly think this is the best way to frame my inquiry because it's rather elaborate)

I'd like some help in understanding the "timings" of Arduino MEGA 2560's ADC module, especially with respect to the command *analogRead*.

I read ATmega2560 microcontroller Datasheet

Let's assume, for now, that our conversions are normal ones ( the other type being a "first" conversion, which takes 25 ADC clock cycles instead of 13, due to the time required for the initialization of analog components )

From what I understood, on a normal single conversion, the sample and hold happens after 1.5 ADC clock cycles from the start of the conversion.

Let's say that I set the prescaler to 32 with the following commands:

```
const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

ADCSRA &= ~PS_128;  // remove bits set by Arduino library
ADCSRA |= PS_32;  // set our own prescaler to 32

```

hence 16MHz / 32 = 500 kHz should be the new ADC clock frequency ( or 2 microseconds ADC clock period )

since a normal single conversion takes 13 ADC cycles, the entire conversion should take about 26 microseconds

If I'm not mistaken, (2 microseconds * 1,5) = 3 microseconds after the ADC conversion starts, my analog pin value is set on hold, right?

I measured the elapsed time using the micros() function and, like I'd expect, I found out that there's a little overhead introduced with analogRead function because it takes about 28 \ 32 \ 36 microseconds (these are empirical measures).

analyzing the code in wiring\_analog.c ( which is located in the folder \[...\]/arduino/hardware/arduino/cores/arduino/ ) the actual conversion seems to happen at line 77

```
// start the conversion
sbi(ADCSRA, ADSC);

```

does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?

how can I know how much time passed before that sbi function call is issued?

I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)

Now, considering the so called "first" conversion, which take 25 ADC clock cycles

does this conversion happen just the first time I call analogRead since I powered on Arduino? or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)

Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?

# Answer
> 1 votes
> does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?

Yes. After between 3μs and 5μs. This is because conversion start at the following rising edge of the ADC clock cycle. This rising edge might have just happened, which means you need to wait 31 (main) clock cycles.

> how can I know how much time passed before that sbi function call is issued?

You could copy the original code and create your own `analogRead2` function that measures the time before setting ADSC.

> I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)

A single instruction will take 1 or 2 clock cycles (if I remember correctly). So at 16Mhz that will mean 62.5ns (nano seconds) per clock cycle. Not 4ms

> Now, considering the so called "first" conversion, which take 25 ADC clock cycles
>
> does this conversion happen just the first time I call analogRead since I powered on Arduino? or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)
>
> Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?

This first conversion is after the `ADEN` bit changes from 0 to 1. If you don't unset this bit, all further conversions will take the shorter time.

PS on the first conversion, the sample-and-hold takes place after the extra 12 ADC clock cycles, so between cycle 12 and 13.5.

PPS this info is actually based on the ATMega328, but should be pretty similar in the 2560.

---
Tags: analogread, adc
---


# Question
Title: Handling double (8 byte) in Arduino mega 2560?
I am receiving 8 bytes from serial.

I want to convert and save in double variable.

This is how i tried.

```
union u_data
    {
        byte b[4];
        double fval;
    } u;

double BytesToDouble (byte b8,byte b7,byte b6,byte b5,byte b4,byte b3,byte b2,byte b1)
{
    u.b[0] = b1;
    u.b[1] = b2;
    u.b[2] = b3;
    u.b[3] = b4;
    u.b[4] = b5;
    u.b[5] = b6;
    u.b[6] = b7;
    u.b[7] = b8;
 return u.fval;
}

```

But i am getting 0.00. Because here double size is 4 bytes.

Is there is any other way to do this?

Thanks

# Answer
> 2 votes
In the Arduino there is no such thing as a double. A double is just another name for a float.

So you will have to either:

1. Manually interpret the double format data and calculate that into a float value, or
2. Send the value as some other format, such as float (32-bit), ASCII text, or (a selection of) integer values.

Since you can't actually use anything more than float, sending data with a higher resolution is pointless, so you are probably best off just sending it as a float.

# Answer
> 1 votes
avr-gcc doesn't support binary64. You can use 8 bytes to treat it as an opaque data type, but attempting to manipulate it beyond manually converting to/from binary32 will be naught but pain.

---
Tags: arduino-mega
---


title: Arduino Power - DC adapter

text:
# Question
Title: Arduino Power - DC adapter
I have a 12V 2.5 ampere Dc adapter.Can i use it to power arduino uno board? It says on the arduino website that i can use 9-12V and upto 1 ampere. I am concerned with current limit here..

# Answer
Don't worry about the current limit. The board will only draw what it needs. The spec is telling you that the board can draw as much as 1 amp, so in general the power supply should be able to supply that – more is no problem, but less could be if you have a lot of devices attached to the board that are drawing power as well.

As is pointed out in the comment above the higher the input voltage the more power the on-board regulator will need to dissipate (as heat). If you are using the barrel jack (which you should if you aren't providing power through an external regulator or other stable source) there is a diode (D1 in the reference design) in the input path and the MC33269D-5.0 regulator is spec'd with a max dropout voltage of 1.25 V so you will need an input voltage of at least 6.95 V (assuming a 0.7 V drop across the diode).
> 6 votes

# Answer
Make sure that the adapter you have is the correct polarity for the arduino or it won't work.

The barrel jack is centre positive, so look for this symbol on your adapter:

The barrel jack should have reverse voltage protection so it won't work if it's the wrong way around. The Vin pin doesn't have this protection, so be extra careful connecting things there.
> 4 votes

---
Tags: arduino-uno, power, current
---


# Question
Title: How to extract the last byte out of an IP adress
Newbie question:

I need to pass the last byte of a local IP as a parameter. Eg.: when Ethernet.localIP() returns 192.168.0.100, I need to extract the 100 and put it in a char array or string.

Anyone any ideas? Thx!

# Answer
`localIP()` returns an `IPAddress` object. That object has an operator for `[]` allowing you to access the individual parts of it.

```
IPAddress ip = Ethernet.localIP();
Serial.println(ip[3]);

```
> 2 votes

---
Tags: programming, sketch
---


# Question
Title: Const Array still using dynamic RAM during compile, causing failure
Using win7 and arduino 1.6.7 IDE I have a rather large CONST array of chars and upon compile using atmega2560, it fails and says:

Sketch uses 11,216 bytes (4%) of program storage space. Maximum is 253,952 bytes. Global variables use 8,414 bytes (102%) of dynamic memory, leaving -222 bytes for local variables. Maximum is 8,192 bytes. processing.app.debug.RunnerException: Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint. at cc.arduino.Compiler.size(Compiler.java:319) at cc.arduino.Compiler.build(Compiler.java:156) at processing.app.Sketch.build(Sketch.java:1108) at processing.app.Sketch.build(Sketch.java:1083) at processing.app.Editor$BuildHandler.run(Editor.java:2011) at java.lang.Thread.run(Thread.java:745) Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.

When I delete the CONST array the program compiles successfully, but when I put it back in, the compiler tells me that I'm using too much dynamic RAM. If I am to understand correctly, consts should store in ROM not RAM.

Here's the even weirder part I put the program in Arduino IDE for Linux and it compiles, but it makes my robot act all crazy.

Any help would be much appreciated.

# Answer
> 5 votes
In a Princeton architecture `const` arrays are stored purely within the `text` (i.e., flash / read only / ROM) area.

In a Harvard architecture (which is what the Arduino is) the RAM and Flash both use completely different memory spaces, and instructions that work on RAM don't work on Flash, and vice versa.

Because of that it has to copy the `const` array from Flash into RAM so it can be accessed as normal variables.

To combat this you can use `PROGMEM` to force it to remain only in Flash, but then you have to use special functions to access the data - you can't use it like normal variables.

You can read more here: https://www.arduino.cc/en/Reference/PROGMEM

# Answer
> 2 votes
`Const` data *may* be stored in ROM but the standards don't require it; you usually have to specify in some (non-standard) way that it be placed there. I.e., `const`-ness is a necessary, but not a sufficient, condition for locating into ROM. Placing Data into ROM with Standard C by Dan Saks is a short, well-written paper (as is typical of Saks) describing what the standards do and, particularly, do not say about ROMming of constant data. It is well worth a few minutes to read it.

---
Tags: arduino-uno, constants
---


# Question
Title: NTP Client Library. Set sync provider pointing to public class function. Possible?
I am trying to develop a NTP client library for ESP8266/Arduino to make adding NTP sync an easier task.

Basically, I've thought about a constructor as **`NTPClient(String host, int interval);`** and a **`NTPClient.begin()`** function to register sync function.

My problem is with that registering.

I have a public function: **`time_t ntpClient::getNtpTime()`** that connects to NTP server, decodes the response and returns a `time_t` variable.

Then, inside **`boolean ntpClient::begin()`** function I try to run **`setSyncProvider(ntpClient::getNtpTime)`**. I've also tried to use **`setSyncProvider(this->getNtpTime)`**.

I get a compile error here:

```
ntpClient.cpp:In member function 'boolean ntpClient::begin()
ntpClient.cpp:79:39: error: cannot convert 'ntpClient::getNtpTime' from type 'time_t (ntpClient::)() {aka long int (ntpClient::)()}' to type 'getExternalTime {aka long int (*)()}
  setSyncProvider(ntpClient*:getNtpTime)
Error compiling project sources

```

What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?

# Answer
> What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?

The function should be a static member function. A "normal" member function does not have the right prototype as there is a hidden parameter ("this").

```
static time_t getNtpTime();

```

To solve this you need a single-ton (an instance of the client class) that the static function can use.

```
class NTPClient {
public:
   NTPClient() ...
   {
     ...
     s_client = this;
   }
   time_t getNtpTime();
   ...
   static time_t getNtpTime() ( return (s_client->getNtpTime()); }
   ...
protected:
   static NTPClient* s_client;
   ...
};
...
NTPClient::s_client = NULL;
...
NTPClient ntpClient;
...
setSyncProvider(NTPClient::getNtpTime)

```

Alternatively a global function and a known instance:

```
class NTPClient { ... };
extern NTPClient ntpClient;
...
time_t getNtpTime() { return (ntpClient.getNtpTime()); }
...
setSyncProvider(getNtpTime)

```

Cheers!
> 0 votes

---
Tags: c++, arduino-ide, library, esp8266, time
---


title: Can I use a UDOO as an Arduino?

text:
# Question
Title: Can I use a UDOO as an Arduino?
I have a UDOO, and I wonder whether or not it is possible to use the Arduino that it has without starting the UDOO's operating system, i.e., I would like use Atmel Studio to load a program within the Arduino at UDOO.

# Answer
> 2 votes
Yes, but you have to erase the flash (and reset the ATMEL SAM3X8E processor) manually before the programming. You can use the J16 and J22 jumpers to do this.

---
Tags: atmel-studio
---


# Question
Title: SD print in script works in setup but not loop
I am a bit of a novice with the Arduino, and have had to learn a lot for my High Altitude balloon launch. I am getting ready to launch this, but for some reason, my datalogger, printing to an SD card, will work in the setup function but not the loop.

If someone could explain what is wrong with my code, and any improvements that could be made to it, it would be very helpful. I am using SPI, SD, I2C, Wire, Sparkfun BMP, and MPU6050 library.

```
    #include <SPI.h>
    #include <SD.h>
    #include <math.h>
    #define thermoPin 0

    #include <SFE_BMP180.h>
    SFE_BMP180 pressure;

    #define ALTITUDE 87.8
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    #include <Wire.h>

    MPU6050 mpu;
    #define OUTPUT_READABLE_YAWPITCHROLL

    #define OUTPUT_READABLE_REALACCEL

    #define analogInPin 3  // Analog input pin that the potentiometer is attached to

    int sensorValue = 0;        // value read from the sensor

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    #define photocellPin 2
    // the cell and 10K pulldown are connected to a9
    int photocellReading;     // the analog reading from the analog resistor divider

    #define chipSelect 4

    void setup() {
      pinMode(A5, OUTPUT);
      pinMode(A4, OUTPUT);
      // Open dataFile communications and wait for port to open:
      if (!SD.begin(chipSelect)) {
        // don't do anything more:
        return;
      }
        File dataFile = SD.open("datalog.txt", FILE_WRITE);
      if(dataFile) {

      // Initialize the sensor (it is important to get calibration values stored on the device).

      if (pressure.begin())
        dataFile.println("BMP180 init success");
      else
      {
        dataFile.println("BMP180 init fail\n\n");
        while(1); // Pause forever.
      }
      // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif
        dataFile.println(F("Initializing I2C devices..."));
        mpu.initialize();

        dataFile.println(F("Testing device connections..."));
        dataFile.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
        // load and configure the DMP
        dataFile.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
    mpu.setDMPEnabled(true);
    mpuIntStatus = mpu.getIntStatus();
    dmpReady = true;
    packetSize = mpu.dmpGetFIFOPacketSize();
    dataFile.close();
      }

    }

    void loop() {
      // make a string for assembling the data to log:
      int valF, valC;
      valF = analogRead(thermoPin);
      valC = analogRead(thermoPin);
      File dataFile = SD.open("datalog.txt", FILE_WRITE);

      // if the file is available, write to it:
      if (dataFile) {

        dataFile.print(F("Millis since Launch"));
        dataFile.println(millis());
        dataFile.print(F(", Analog Val."));
        dataFile.print(valF);

        photocellReading = analogRead(photocellPin);

        dataFile.print(F("  Analog reading = "));
        dataFile.println(photocellReading);     // the raw analog reading
                                          // We'll have a few threshholds, qualitatively determined
      dataFile.println();
      char status;
      double T,P,p0,a;

        dataFile.print(F("provided altitude: "));
      dataFile.print(ALTITUDE,0);
      dataFile.println(F(" meters, "));

      status = pressure.startTemperature();
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);

        status = pressure.getTemperature(T);
        if (status != 0)
        {
          // Print out the measurement:
          dataFile.print(F("temperature: "));
          dataFile.print(T,2);
          dataFile.println(" deg F");

          status = pressure.startPressure(3);
          if (status != 0)
          {
            // Wait for the measurement to complete:
            delay(status);

            status = pressure.getPressure(P,T);
            if (status != 0)
            {
              // Print out the measurement:
              dataFile.print(F("absolute pressure: "));
              dataFile.print(P,2);
              dataFile.print(F(" mb, "));

              p0 = pressure.sealevel(P,ALTITUDE); // we're at 87.08 meters (Home)
              dataFile.print(F("relative (sea-level) pressure: "));
              dataFile.print(p0,2);
              dataFile.print(F(" mb, "));
              dataFile.print(p0*0.0295333727,2);
              dataFile.println(" inHg");

              a = pressure.altitude(P,p0);
              dataFile.print(F("computed altitude: "));
              dataFile.print(a,0);
              dataFile.print(F(" meters, "));
            }
            else dataFile.println("error retrieving pressure measurement\n");
          }
          else dataFile.println("error starting pressure measurement\n");
        }
        else dataFile.println("error retrieving temperature measurement\n");
      }
      else dataFile.println("error starting temperature measurement\n");
      // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            dataFile.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                dataFile.print(F("ypr\t"));
                dataFile.print(ypr[0] * 180/M_PI);
                dataFile.print(F("\t"));
                dataFile.print(ypr[1] * 180/M_PI);
                dataFile.print(F("\t"));
                dataFile.println(ypr[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_REALACCEL
                // display real acceleration, adjusted to remove gravity
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                dataFile.print(F("areal\t"));
                dataFile.print(aaReal.x);
                dataFile.print(F("\t"));
                dataFile.print(aaReal.y);
                dataFile.print(F("\t"));
                dataFile.println(aaReal.z);
            #endif
        }
        // read the analog in value:
      sensorValue = analogRead(analogInPin);
      // print the results to the dataFile monitor:
      dataFile.print(F("  analog Val of OZONE= " ));
      dataFile.println(sensorValue);
      dataFile.close();
      }
      analogWrite(A4, 168);
      delay(3000);
      analogWrite(A4, 0);
      delay(750);
      analogWrite(A5, 0);
      delay(250);
      analogWrite(A5, 168);
      delay(3000);
        analogWrite(A4, 168);
      delay(2000);
      analogWrite(A4, 0);
      delay(1000);
    }

```

Possible problems (correct me if I'm wrong):

* I noticed that the MPU6050 stops transmitting if delays are put into it

EDIT: I have now tried the script but commented out the accelerometer (MPU6050) portion, and it successfully writes to the SD card. could someone explain why the accelerometer portion messes up the rest of the code?

# Answer
I haven't followed all the details of your code, nor looked into all of the libraries being used, so you may need to ignore some of the following comments.

1. You write “my datalogger, printing to an sd card, will work in the setup function but not the loop”. However, you don't say what you mean by “work”, nor how you tell if it works.
2. It looks like your code in `loop()` uses the same filename as in `setup()`. If so, there's no reason to write a file in`setup()` because it will just be overwritten later. (If you have a reason, use a different file name.)
3. Sequences like `status = pressure.startTemperature(); if (status != 0) {... delay(status); ... }` look suspect. The parameter to Arduino's `delay()` function is a number of milliseconds, in an `unsigned long`; is your `startTemperature()` supposed to return a status that's usable as the number of milliseconds to delay?
4. Your `status` is declared via `char status;` and `char` is a signed type. If `status` is negative, the call `delay(status);` will first convert `status` to a signed `long` by sign-extension. Then it will convert the signed `long` to an `unsigned long` with the same bit pattern. This will ensure a delay of at least 7 weeks, which presumably is longer than you mean to wait. \[Ref: See the “Conversions from Signed Integral Types” table in microsoft.com/en-us/library's *Conversions from Signed Integral Types* webpage.\]
5. To avoid those long and tedious sequences of `dataFile.print(...);` statements, you can `#include Streaming.h`, which is a contributed library that adds some “syntactic sugar” to Arduino C. At compile time it converts C++-like `<<` stream operators to `.print()` calls, without increasing code size. If you don't have `Streaming.h` installed, install it via `Streaming5.zip` from arduiniana.org. Then, for example, in place of

dataFile.print(F("areal\t")); dataFile.print(aaReal.x); dataFile.print(F("\t")); dataFile.print(aaReal.y); dataFile.print(F("\t")); dataFile.println(aaReal.z);

write

```
  dataFile << F("areal\t") << aaReal.x << '\t' << aaReal.y << '\t' << aaReal.z << endl;

```
6. Whether using `Streaming.h` or not, writing `F("\t")` instead of `'\t'` uses half a dozen bytes of program memory where one will do, and uses the same amount or more of RAM. That is, while F() saves on RAM usage for long strings, it's of negative value for single characters and short strings.
> 1 votes

---
Tags: programming, arduino-mega, sd-card, mpu6050
---


# Question
Title: Unable to configure Ethernet using Arduino Uno R3
I have purchased an Arduino Uno R3 board and a LAN shield from these locations:

I am trying to configure Ethernet using this sketch:

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x4,0x2,0x45,0x68,0x5E,0x96,0x56
};

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  delay(5000);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  // start the Ethernet connection:
  Serial.println("trying to configure ethernet...");
  while(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP, retrying after 5 sec");
    // no point in carrying on, so do nothing forevermore:
    delay(5000);
    Serial.println("trying to configure ethernet...");
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
}

void loop() {
}

```

It generates this output in the Serial Monitor:

```
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...

```

I have captured the LED indicators on video on YouTube, it shows Tx and Rx LEDs glowing occasionally, see Arduino not detecting the ethernet connection.

It looks like the Arduino is not able to connect to the Ethernet... I am using the Arduino IDE 1.6.5 on Windows 7.

Is there any debug tool for Arduino that can be used to figure out this issue?

# Answer
> 2 votes
I use more or less the same code to do my networked widgets and it has been quite reliable in my experience. Do you know if you have a DHCP server on the network segment that the Arduino is on? The absence of a server or a configuration that won't respond to the Arduino seem like the most likely explanation for the problem you're seeing.

The way to troubleshoot this would be to get another machine on the same network segment and watch the traffic with `tcpdump` or Wireshark or a similar tool. If you're running on a "third party" machine (e.g. not the DHCP server) then you'll be able to see the Arduino's side of the DHCP exchange, but I'm not sure if you'll be able to see the server (the Arduino will be broadcasting since it can't know the address of the DHCP server, but I think the server's response is unicast). If you've got a Linux box or some other machine that you can log into where you could run the DHCP server you can watch both sides of the negotiation. But even if you can't get to the server it will help to see if the Arduino is starting the DHCP negotiation.

If you need a fixed IP address on the Arduino, the way to do it is to configure the DHCP server to reserve an address for the Arduino. That way you can have a known address on the Arduino without having to hard code an IP address (which will eventually bite you).

# Answer
> 0 votes
I never used the DHCP feature to assign an IP address for the Ethernet shield, but somewhere in there you have to list the IP of the router that assigns the DHCP.

In everyday use of the shield, you don't want your router to assign an IP address to your device because every time it connects it might get a different IP address. That means if you want to communicate with it, you need to discover the IP address each time. And communicating with it from the WAN side through a port you open in your router would be impossible.

Try one of the fixed IP address sketches, but select a free IP address in your router's IP range that *isn't*, also, in the router's DHCP IP range (that way the fixed IP address won't interfere with the IP addresses given out automatically).

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


# Question
Title: "No more addresses" when using multiple DS18B20 sensors
I want to build a scheme to get data from several DS18B20 sensors and write their temperature to serial. Before I connected them using parasite mode and using 2,7k resistor (because I didn't have 4,7k at home). Back then, it worked for 1 device, if I plug in another, it won't detect any of them (it writes "No more addresses"). Now I replaced 2,7k resistor with 4,7k and it doesn't detect any device connected. But if I do one little thing, which is replacing 4,7k resistor back with 2,7k, it will detect one device.

How to fix it?

Here is exactly how it is all connected now:

and here is the default sketch I am using:

```
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(10);  // on pin 2 (a 4.7K resistor is necessary)

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

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for ( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44);        // start conversion, use ds.write(0x44,1) with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

```

Is there anything I am doing wrong? Because I somehow managed to get it working some time ago.

# Answer
A problem with what you are doing on the breadboard is that you show no bypass capacitors.

What makes the pull up "strong" is the ability to provide current to move the data line from zero back to one. The load on the data line is its capacitance. To move the data line from 0 to 1, you have to charge that capacitor. Working on a bread board, you are correct that you have a larger capacitive load. So you require more current to move the data line from zero to one quickly.

You are correct that the lower 620 ohm resistor will provide more current. The large current will move the capacitance load of the data line more quickly. But you are not paying attention to the other side of the resistor, the 5V rail.

The layout you have has inductance in the wires from the Arduino power supply out to the bread board. An inductor has a voltage drop across it proportional to the rate of change of the current through it:

```
V = L  di/dt

```

The analogy is that inductance is a flywheel: if it is not spinning, it will take force to get is moving. Similar, once it is spinning, it will take force to stop it.

So when the resistor starts conducting to pull up the data line, the inductance in the wires and breadboard cause a voltage drop. The +5 side of the resistor voltage drops. This inductance in the wires leading to the resistor prevents it from rapidly charging the data line back to 1.

That is the role of *bypass* capacitors. You place 1 or 2 right at the resistor between the +5 and GND strips on the bread board. Now when the resistor draws current, it initially pulls from the energy stored in the capacitors. After a short time, the current will start pulling from the +5 wire. Thereby, you have **bypassed** the inductance of the +5 supply, hence the name.

Add a 0.1 microFarad ceramic capacitor on your breadboard where the wires connect to the contact strips. You will see this on schematics for anything that has a DC supply off board. Right next to the power connector will be 2 or 3 capacitors, usually one big 2-10 uF tantalum and one smaller 0.1 uF or so. Similar across circuit boards you see bypass caps placed at the supply voltage pin of every chip, commonly two: a 0.1 uF and a smaller 10 nF.

It might seem pointless to place a small capacitor in parallel with a larger capacitor. The values just add, yes? But again, the time response is different. Capacitors are not perfect and have internal series resistance. A big 10 uF electrolytic capacitor may store a lot of energy, but it is not fast in terms of how quickly it can start providing current. A little 100 nF ceramic monolithic capacitor is very fast, but doesn't have much energy.

So with two bypass caps in parallel, you have the small one for the initial burst of current, the larger cap for the heavy lifting, and last and slowest the 5V wires and traces to supply to steady current.
> 1 votes

# Answer
A strong-pullup seems to be the key to having multiple sensors in parasitic mode, as described in the datasheet for the DS18b20 devices. Though they suggest using a MOSFET to pull up the 1-wire bus, I've had good results (3 meters of wire, 3 devices more than 2 meters out) by tying an output port directly to the 1-wire bus, bypassing the 4.7K resistor.

```
// One wire bus strong-pullup:
//
//    +------------+     +5v            +---------+     +---------+
//    |    MCU     |      |             | DS18b20 |     | DS18b20 |
//    |            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
//    | Strong-    |      |             +-o--o--o-+     +-o--o--o-+
//    | Pullup   > o------o               |  |  |         |  |  |
//    |            |      |               +--|--+         +--|--+
//    |            |      |               |  |            |  |
//    |    Data <> o------o---------------|--o------------|--o------ - - -
//    |            |                      |               |
//    +------------+                      V               V

```

Initialize the strong-pullup port by setting the port as an output and HIGH, the disable and enable it by changing the port mode, not the output value. (Setting the port mode to input floats it, rather than grounding it as setting it LOW would do. This technique was suggested to me by Dave Tweed in Electrical Engineering Stack Exchange.)
> 0 votes

---
Tags: arduino-uno, temperature-sensor, 1-wire
---


# Question
Title: How to add hysteresis to threshold values?
This code compares the analog input value against two thresholds, having three voltage regions. Then it will turn on an LED according to what region the read voltage is in.

The problem is that when the voltage read is very close to the threshold, the noise will disturb the output, resulting in an uncontrolled switching between LEDs.

I would need to add some sort of HYSTERESIS around my thresholds to avoid the uncontrolled switching, but I have no idea how to write this into the code language. Would anyone be able to help me writing the threshold bit?

This is the full code:

```
// these constant won't change:
const int BatteryVoltagePin = 14;   // the pin that battery voltage is attached to
const int GreenLedPin = 3;           // the pin that the green LED (On charge) is attached to
const int OrangeLedPin = 4;          // the pin that the orange LED (no risk) is attached to
const int RedLedPin = 5;             // the pin that the red LED (low battery) is attached to

// Variables will change:
int currentVoltage ;         // current voltage value
int previousVoltage ;     // previous voltage value

void setup() {
  // initialize the battery voltage pin as a input:
  pinMode(BatteryVoltagePin, INPUT);
  // initialize the green LED as an output:
  pinMode(GreenLedPin, OUTPUT);
  // initialize the orange LED as an output:
  pinMode(OrangeLedPin, OUTPUT);
  // initialize the red LED as an output:
  pinMode(RedLedPin, OUTPUT);
}

void loop() {
  // read the voltage across the battery voltage pin:
  currentVoltage = digitalRead(BatteryVoltagePin);

  // compare the current voltage value to its previous value
 if (currentVoltage != previousVoltage)

 delay(10);

    // value above maximum threshold
    {
     if ((( ( analogRead(BatteryVoltagePin) ) > ( 699 ) ))
        {
        digitalWrite(GreenLedPin, HIGH);
        }
        else
        {
          digitalWrite(GreenLedPin, LOW );
        }
    }

    //value between two thresholds (middle region)
    {
     if (( ( ( analogRead(BatteryVoltagePin) ) <= ( 699 ) ) && ( ( analogRead(BatteryVoltagePin) ) >= ( 628 ) ) ))
        {
        digitalWrite(OrangeLedPin, HIGH );
        }
        else
        {
          digitalWrite(OrangeLedPin, LOW );
        }
    }

    // value below minimum threshold
    {
     if (( ( analogRead(BatteryVoltagePin) ) < ( 628 ) ))
        {
        digitalWrite(RedLedPin, HIGH);
        }
        else
        {
          digitalWrite(RedLedPin, LOW );
        }
     }

  // save the current state as the last state,
  //for next time through the loop
  previousVoltage = currentVoltage;
 }

```

# Answer
> 7 votes
Adding hysteresis behavior to your code is not difficult. You just need to store the state you're in and make the thresholds for transitioning into another state dependent on that.

You can use an enum to store the state:

```
enum BatteryStates {
  Red, Orange, Green
};

```

Then, instead of defining and checking against one threshold value, define two thresholds for each transition, separated by so much that you don't observe the undesired flip-flopping behavior.

For example, when transitioning from Green to Orange you could do something like this:

```
if ((state == Green) && (battery < 690))
  state = Orange;

```

And the other direction would use a slightly higher threshold

```
if ((state == Orange) && (battery > 700))
  state = Green;

```

so that small fluctuations of the voltage do not cause flip-flopping.

(Note that my code assumes

```
int battery = analogRead(BatteryVoltagePin);

```

The variable `state` should be declared and initialized like so:

```
enum BatteryStates state = Green;

```

Instead of an `enum` you could use a simple `int` and map each state to a number (e.g. red = 1, orange = 2, green = 3), but using `enum` makes the code easier to read and write. (In fact `enum` does use integer numbers.)

I might also use a `switch` statement instead of an `if` chain to implement the transitions, but that's a matter of taste.)

# Answer
> 2 votes
This includes hysteresis and uses some loops and arrays to simplify and compact the code, since the logic for each range is essentially the same. More ranges are easy to include by extending the Cutoffs and LedPins arrays (one more led than cutoff).

```
const int VoltagePin = 14;
const int Cutoffs[] = { 628 , 699 };
const int NumCutoffs = sizeof(Cutoffs)/sizeof(int);
const int Hysteresis = 5;

const int LedPins[NumCutoffs+1] = {5,4,3};

int Level = 0;
int Voltage = 0;

void setup()
{
  for (int i=0; i<=NumCutoffs; ++i) {
    pinMode(LedPins[i],OUTPUT);
  }
}

void loop()
{
  Voltage = analogRead(VoltagePin);

  while (Level < NumCutoffs && Voltage >= Cutoffs[Level]) {
    ++Level;
  }

  while (Level > 0 && Voltage < Cutoffs[Level-1] - Hysteresis) {
    --Level;
  }

  for (int i=0; i<=NumCutoffs; ++i) {
    digitalWrite(LedPins[i], i == Level);
  }

  delay(20);
}

```

# Answer
> 2 votes
Here is what I do. I detect whether the voltage is rising or falling and adjust the threshold based on that.

```
int ledPin = 13;   //pin 13 will be connected to the MOSFET SS relay

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

void loop() {
    int sensorValue = analogRead(A0); // This is the main battery voltage sensor
    int RLA1;   //this will be connected to the MOSFET SS relay
    float threshold; //  To enable some hysteresis and prevent the relay from chattering, we move the threshhold, depending on whether we are going up or down

    float Vmainold;  //  Used to detect whether we are going up or down
    float  Vmain;   // Main battery voltage.
    float Vaux;     // Auxillary battery voltage

    Vmain = sensorValue / 204.6 + 9.8;   // Add back the ~10V that the zener shifts for higher resolution

   if (Vmain > Vmainold) threshold = 13.2;  // If the voltage is rising, set threshhold to 13.2
   else
    if (Vmain < Vmainold) && (Vmainold > 12.8) threshold = 12.8 // If the voltage is falling and previous voltage is above TH, set theshhold to 12.8
    else
        if (Vmain = Vmainold) threshold = 13.2;  // If the voltage is stable, set threshhold to 13.2

   if (Vmain >= threshold) RLA1 = 1; //  Charging

   else
    if (Vmain < threshold) { RLA1 = 0;  Vmainold = Vmain; }  // Not connected

   delay(1000);
   Serial.print(Vmain);
   Serial.print("  Main  ");
   Serial.print(Vmainold);
   Serial.print("  old  ");
   Serial.println();
   Vmainold = Vmain;
   digitalWrite(ledPin, RLA1);
}

```

\`

# Answer
> 2 votes
The state machine is a solid approach.

For this simple case, you can also solve this by implementing small dead bands around the change levels. When the value is in a range near the transition threshold, do nothing. Only when the value is certainly above or below the transition, make the change. Your code would be:

```
// Variables will change:
int currentVoltage = 0;         // current voltage value
int previousVoltage = 0;     // previous voltage value

void loop() {
  int deadband = 5;
  // on very first loop, start with no dead band
  // this is necessary in case starting voltage is in
  // middle of a transition range
  if (0 == previousVoltage) {
    deadband = 0;
  }

  // read the voltage across the battery voltage pin:
  currentVoltage = analogRead(BatteryVoltagePin);

  // test the voltage against the three ranges
  // value above maximum threshold
  if ((699+deadband) < currentVoltage) {
    digitalWrite(GreenLedPin, HIGH);
    digitalWrite(OrangeLedPin, LOW );
    digitalWrite(RedLedPin, LOW );
  }

  //value between two thresholds (middle region)
  if (((628+deadband) < currentVoltage) && (currentVoltage <= (699-deadband))) {
    digitalWrite(GreenLedPin, LOW);
    digitalWrite(OrangeLedPin, HIGH);
    digitalWrite(RedLedPin, LOW);
  }

  // value below minimum threshold
  if (currentVoltage < (628-deadband)) {
    digitalWrite(GreenLedPin, LOW);
    digitalWrite(OrangeLedPin, LOW );
    digitalWrite(RedLedPin, HIGH);
  }

  // Note that at this point, none of the if cases above
  // might have been true.  When the voltage is right near the
  // thresholds, do nothing.  Only when the voltage is definitively
  // in the range does the LED state change.

  // save the current state as the last state,
  //for next time through the loop
  previousVoltage = currentVoltage;
  delay(10);

  return;
}

```

In function, this will achieve the same result as hysteresis.

---
Tags: arduino-uno, programming, sketch, analogread, compile
---


# Question
Title: how to use the decoded raw value to send IR signal in arduino
I am IR library from Ken Shirrif at https://github.com/z3t0/Arduino-IRremote/releases/download/MAJOR/IRremote.zip

It is good and I have used the examples to receive and send and to playback IR signals from the library. And they are working good.

To send Unknown signals we should use sendRaw() method with a list of integers got from the receiver.

My question is when I use the receive program, I get the decoded hexadecimal value for even the Unknown signals. And can I use this small decoded signal to send signals apart from the long list of integers.

I am trying to send these codes from android. It would be quite easy to send and store the small hexadecimal decoded value.

Is there a way to use the decoded value to send for raw signals with some encodings at arduino?

# Answer
If the signal is reported as "unknown" the library couldn't identify the protocol (RC5, RC6, NEC, SONY, etc). If the library doesn't know the protocol, the decoded number is meaningless. Simply put, an IR remote transmission has a frequency; a header; some data (the actual remote command); and a footer. Without knowing the protocol the library doesn't know the length and shape of each section, so the purpose of the decoded number is only to show quickly if the decoding is receiving the same code at each keypress. You can verify this yourself. Every time something makes an already known remote code be reported as "unknown", the code received is different from a real code, so simply guessing (or knowing beforehand) the protocol is not going to help anyway.
> 2 votes

---
Tags: arduino-uno, ir
---


# Question
Title: problem on implementation of the ultrasonic circuitry
I used an Arduino Uno on my project to produce a frequency greater than 35000Hz and the output of digital pin was connected to the ultrasonic transmitter circuitry:

However, it's not working on the transmitting side. Here's the Arduino code:

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

void loop()
{
    pinMode(13,OUTPUT);
    pinMode(12,OUTPUT);
    int pirSenses = analogRead(A1);
    int pirOuts=11;
    pinMode(pirOuts,INPUT); /*PIR sensor 1*/
    int pirSense = analogRead(A0);
    int pirOut = 10;
    pinMode(pirOut,INPUT); /*PIR sensor 2*/
    Serial.println(pirSense);Serial.println(pirSenses);

    if (pirOut || pirOuts == HIGH)
    { /*tone produces ultrasonic frequency*/
        delay(8000);
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else if (pirOut||pirOuts==LOW)
    {
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else
    {}
}

```

And the transmitter (model "MCPCT-G5100-4139") specification:

Please help me with this problem. Thanks!

# Answer
Your ultrasonic Transducer driver circuit isn't doing a very good job. At most you are getting only a few milliwatts output to the transducer. Your circuit is applying 12 volts through a 2.2K resistor to the transducer, and your Q1 transistor is merely shorting out the Transducer.

From viewing the data sheet on your transducer, it looks like a tiny loud speaker and not a Piezo device. But that is OK.

Try the following push pull driver circuit. I have tried to keep it simple, but you would need to come up with a PNP transistor (in addition to your existing NPN transistor).

The V2 square wave is your 5 volt output from Arduino.

Also, notice that I have shown the driver circuit using 5 volts, not 12 volts. Using this circuit, if you use 12 volts supply, the output doesn't get any more powerful, and just causes more heating in the transistors.

EDIT 1 : IMPORTANT : Don't leave your output pin in the HIGH state. This turns on transistor Q1 and causes sustained current in the Transducer. To alleviate this, insert a 47uf capacitor in series with the transducer.

EDIT 2 : Changed schematic to include output capacitor.
> 1 votes

---
Tags: arduino-uno, frequency
---


# Question
Title: Arduino Christmas light project with dimmer
I have an existing project using an Arduino Yun that controls Christmas lights with relays to turn them on/off. There are currently 13 separate rows of lights on the (60 foot) tree, each plugged into a wall wart that's controlled by its own relay.

I'm considering adding the ability to dim the lights, so I wanted to figure out the best way to do it. The lights can all be dimmed "in unison" - there's no need for 13 seperately controlled dimmers. But I have to be mindful not to cause any "buzzing" in the audio equipment on stage where the tree is.

I've read about PWN, zero cross, and other terms and saw the zero cross tail from powerswitchtail.com that seem useful in the typical project. I'd like to be able to pull this off with no more than 2 "dimmers" for the whole project, if possible.

Where do I start, and how do I do it?

# Answer
I can think of a couple of ways to approach this:

1. Use a DMX dimmer, something like this 4-channel dimmer, or
2. Use an household X10 dimmer.

DMX is used for stage lighting and there is some information on controlling DMX devices with an Arduino in the Playground where there is also some information on the hardware interface and shields, it looks pretty simple. DMX is a differential RS485 interface.

X10 is used for home automation, the signaling is done over the AC line. There is some information on using X10 and an Arduino library in the Tutorials.

Both seem like viable approaches, if you're working in a theater it is likely that they might already have DMX equipment and it would be as simple as hooking up to the gear in the house. Then you'd only need to add a shield or build the interface hardware.
> 0 votes

---
Tags: arduino-yun
---


# Question
Title: How to send a group message to multiple receivers using GSM900 and Arduino Mega2560?
I'm working on a project and it can send to one receiver only. What I need is to send a message to multiple receivers. I need a code sample that would satisfy my needs. Please help! I need to finish this ASAP.

# Answer
Simply change the number in the AT command and send the message again.
> 0 votes

---
Tags: programming, arduino-mega, gsm, coding-standards
---