# Question
Title: How to apply a programme to all values in a list simultaneously
I'm attempting to turn on a set of LED's one at a time and then switch them all off at the same time, I am stuck however on turning them off at the same time.

That is my code:

```
int ledpins[] = {2,3,4,5,6,7,8,9}; //creates a list of the pins in use

void setup() {
  for (int i = 0; i < 8; i++){
    pinMode(ledpins[i], OUTPUT);  // iterates over the list led pins from the 0 pin to the pins before the eigth
  }
}

void loop() {
  for (int i = 0; i < 8; i++){
    digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  }

  delay(100); //when all on will wait 100 ms
  digitalWrite(ledpins[0,7], LOW); //turns off all the leds at once
  delay(100);
}

```

The annotations are for my own understanding. I just need help turning all the LED's off at once which I dont know the command for.

# Answer
> 3 votes
You have already done it twice, why are you struggling the third time?

```
for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
}

```

> // turns all the pins of one at a time

Except that it is happening so fast you can't see then doing it individually. So just do the same but set them to LOW:

```
for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], LOW); // turns all the pins off one at a time
}

```

Now you might want to add a delay into the loop that turns them on so you can see them turn on individually instead of all at once:

```
for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  delay(50);
}

```

# Answer
> 1 votes
There is another approach that is to use direct port manipulation. It is a lot faster than using `digitalWrite` in the sense that it requires less clock cycles to execute and allows you to change one port at a time (the UNO has 3 ports called D, B and C). You can find an introduction to port manipulation on this page: https://www.arduino.cc/en/Reference/PortManipulation

Here is an example that toggles the LED you chose:

```
void setup()
{
    DDRD |= B11111100; // Pin 2 to 7 as outputs
    DDRB |= B00000011; // Pin 8 to 9 as outputs
}

void loop()
{
    // Pin 2 to 7 HIGH
    PORTD |= ( 1<<2 ) | ( 1<<3 ) | ( 1<<4 ) | ( 1<<5 ) | ( 1<<6 ) | ( 1<<7 );
    // Pin 8 to 9 HIGH
    PORTB |= ( 1<<0 ) | ( 1<<1 );

    _delay_ms( 500 );

    // Pin 2 to 7 LOW
    PORTD &= ~( 1<<2 ) & ~( 1<<3 ) & ~( 1<<4 ) & ~( 1<<5 ) & ~( 1<<6 ) & ~( 1<<7 );
    // Pin 8 to 9 LOW
    PORTB &= ~( 1<<0 ) & ~( 1<<1 );

    _delay_ms( 500 );
}

```

---
Tags: arduino-uno
---


# Question
Title: Powering multiple servos on external battery
I am working on a project with my school's 3D Printing Club where we are making a humanoid robot and I am attempting to wire the arm at the moment, and program the hands to translate text to sign language. The portion of the arm I am currently working with uses six TowerPro 5010 servos, one for each finger, and another for the wrist, and I am controlling it with an Arduino Uno. I have a 9v wall plug that I am powering the Arduino with, and a 4xAA battery pack (wired in series for 6v, last measured at 5.7) that I would like to use for the servos.

Initially, I wired the servo ground pins to the Arduino GND output, and the servo power pins to the battery pack's 6v output, I connected the ground on the battery to the ground on the Arduino, and I attached the servo motors to their IO pins. This approach worked perfectly for two servos, barely for three, and not at all for four. Even with most of the motors staying still (I was only moving one at a time with three and four servos, but I can move two simultaneously no problem with nothing else connected). Not sure how to describe the load on them quantitatively, but they are pulling on fishing line that has a good deal of resistance, but nothing excessive, or near their limits.

I have been googling around for hours, and I found some tutorials where a similar battery was powering eight servos at a time, and so I am unsure why mine was cutting out so soon.

I tried to reduce the load of the servos, but nothing I tried worked. At one point I tried wiring the servos on a shift register to only power the ones I needed, but then I realized this was a dumb idea because my shift register would never be able to output enough current to power even one servo. I have some 5v voltage regulators, but I don't think they will help since the servo takes from 4v to 6v, and I looked through all my transistors, but they are all designed for very small currents. I have a relay which should be able to switch that voltage that voltage easily, but only one of them. If possible I would like to try and do this without purchasing any additional components such as motor controllers or specialized batteries, but I understand that if I need to I need to.

If anyone has any advice on how to proceed I would greatly appreciate it. Thanks.

# Answer
If you dont mind to use a bit of space for a dedicated board that controls your servo and power them, I would suggest to use http://www.adafruit.com/product/815 which is very good.

Your issue might become a power draining where the batteries cant keep up to give enough amper to use 3 or 4 servos at the same time.

I am not sure what kind of batteries you are using, probably not rechargeable ones but I would suggest to get an ampermeter to get the real draining on your circuit.

After that you will understand a bit better what is going on and why this issue is happening on your configuration.

I cant find the power consummation of this servo so I Cant give much more information.
> 1 votes

---
Tags: power, servo, battery, current, electronics
---


title: Arduino with seven segment

text:
# Question
Title: Arduino with seven segment
Can anyone help me regarding the output of this program?

What is the function of `Num_Write`?

Here is the code below:

```
int num_array[10][7] = { { 1,1,1,1,1,1,0 }, // 0
{ 0,1,1,0,0,0,0 }, // 1
{ 1,1,0,1,1,0,1 }, // 2
{ 1,1,1,1,0,0,1 }, // 3
{ 0,1,1,0,0,1,1 }, // 4
{ 1,0,1,1,0,1,1 }, // 5
{ 1,0,1,1,1,1,1 }, // 6
{ 1,1,1,0,0,0,0 }, // 7
{ 1,1,1,1,1,1,1 }, // 8
{ 1,1,1,0,0,1,1 }}; // 9

void Num_Write(int);

void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  for (int counter = 10; counter > 0; --counter) {
    delay(1000);
    Num_Write(counter-1);
  }
  delay(3000);
}

void Num_Write(int number) {
  int pin= 2;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

```

# Answer
> 2 votes
Num\_Write will map the output pins to display a number on the 7-segment display.

*Please note that the schematic below is not the best, nor the proper way to connect a 7 segment display. It's intended to show the connection for illustrating purposes, not for actual wiring. Each segment lead should have it's own resistor. Also, depending on if you have a Common Anode or Common Cathode 7 segment, wiring will differ.*

When the number 0 is being displayed (check in the num\_array) all segments are lit, except for the last segment (segment G).

```
void Num_Write(int number) {                 //Write a number to the 7-segment display.
  int pin= 2;                                //Take the starting (output) pin.
  for (int j=0; j < 7; j++) {                //Loop through all the segments of the given number.
    digitalWrite(pin, num_array[number][j]); //Write the output pin according to the pattern in the "num_array" for the given number.
    pin++;                                   //Go to the next pin.
  }
}

```

So by looping through the pins, and looping through the array (while setting the pins) we can display a number on the 7 segment display.

Extra: The output will be somewhat like this, but then reversed (9 to 0) and withouth the A, B, C, D, E and F.

---
Tags: arduino-uno, led
---


# Question
Title: Most efficient way to store number in EEPROM?
I would like to store temperature readings in eeprom, the value from -55.00 to 125.99. What is the most space efficient way to store these numbers with two significant digits along with epoch timestamp?

Thanks

# Answer
> 5 votes
My best off-the-top-of-my-head figure is 6 bytes.

4 bytes for the timestamp (assuming a 32-bit value). Two byte for -32768 to +32767.

Multiply the temperature by 100 to make it into the integer range -5500 to +12599. That then fits comfortably inside a 16-bit signed integer.

*However*, there are other tricks you can use.

For instance, if you know the time of one reading you don't need to store the time of the next - only how much later it is. One byte can then store up to 255 "whatevers" later than the previous entry - be that seconds, minutes, hours, whatever.

Similar with the temperature. You can just store the difference from the previous reading as a single byte if you know that successive readings will never deviate by more than +/-1.27 degrees.

Also, you can check to see what the last saved temperature was, and only save a new temperature if it has changed from before.

Another thing is the resolution of your data. You say 2 decimal points, but if the values are all multiples of 0.05 then what is the point of storing at 0.01 resolution? Just store how many 0.05s there are (divide by 0.05) then multiply it out again afterwards to get the original temperature. Most useful when coupled with a temperature difference to increase the storage range.

There's many tricks, you see, and which work best depend exactly on what you want to do with the data.

---
Tags: eeprom
---


# Question
Title: 4 Digit, 7 Segment Display Wiring (14 pin)
I purchased this 4 digit, 7 segment display from Adafruit:

Product: http://www.adafruit.com/products/865

Data Sheet: http://www.adafruit.com/datasheets/865datasheet.pdf

Everything I have searched for on the net either has 12 pins or 16 pins and most of those are only using 4 resistors. This one has 14 pins. I'm trying to wire it up to an Arduino but I'm not sure which pins should have resistors and which shouldn't. If I wire it up like in the product picture with 1k resistors, I get 8.8.:8.8. and as I remove resistors from 5V, I can see the different sections that are lit/not lit.

Is that the correct way of doing it? Can I now just wire those to the Arduino?

# Answer
It's just a 12 pin display, but with two extra pins for the colon.

Removing connections can help you better understand what it going on.

Resistor should be added to the anodes (pins 1,2,3,4,5,8,9,12,13) just like on the website. Pin 8 should be a different value, to match the brightness of the other (multiplexed) leds.

The other end of the resistor can be put into the Arduino. Depending on the resistor value you may need to add some transistor to drive the other pins (cathodes) on the display. Lower value resistors means a brighter display, but too much current for the Arduino to drive all 8 leds of a digit at the same time.

1k resistors, would mean about 3mA of current per segment. So if all segments are on in one digit, that would be 8\*3, so 24mA. Which is approaching the maximum current an Arduino pin can source.
> 0 votes

---
Tags: led, display
---


# Question
Title: using seek() in Arduino to go to the end of a variable-sized file
Anyone know how to use the seek() function of Arduino SD Library to position pointer at the end of a file?

If programming in Windows do something like:

```
void fileInsert(char *file, void *data, size_t len) {

    FILE *filePtr;

    if ((filePtr = fopen(file, "rb+")) == NULL) {
        printf("Arquivo %s não pode ser aberto.", file);
        exit(EPERM);

    } else {

        fseek(filePtr, 0L, SEEK_END);
        fwrite(data, len, 1, filePtr);
        fclose(filePtr);
    }
}

```

But the Arduino does not have the SEEK\_END

# Answer
> 3 votes
You can only seek to an absolute position from the start of the file. Fortunately there is the `size()` method that can tell you where the end is, though.

```
file.seek(file.size());

```

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


# Question
Title: Why does a light bulb activate an infrared sensor? Is there a way I can filter this out?
I've made 3 programs. One is written in python, c++ processing and bash.

Everything seems to be okay but then sometimes I get a signal from the arduino that activates the function to lower down the volume on the python code listening for serial data. This is sometimes random but it seems that I can reproduce the same behavior when I turn the light on. I can cause the same disruption if I wave my hands over it quickly.

How can I filter this? I know that IR is part of the electromagnetic spectrum in which the visible light takes part. The sensor is facing upward for a type of omnidirectional receptor. I've placed a TV IR blackish cover over it but with the same results. Do I need to use the function to hash decode the incoming signal? I suppose that it needs a simple circuit as any other sensor.

I want to discard the possibility of a random activation in my code.

Edit:

Taken into consideration the answers until now I can confirm that this is part of a physical phenomena due to the distance between my light and the device.

As for the solution to my volume problem It seems that I used "0" in the same statement as the ir code I remapped in the python code. It turned out to be part of the IRlib library of the arduino code that returns a "0" when it encounters an unknown signal. (due to protocol specification? - out of useful range? )

The thing is that I can change the if statement value for other than "0" but that won't stop it from returning "0" and that's a disadvantage. The solution that came to me is simply intercepting the signal and use continue to skip this.

Is there any alternative to this?

# Answer
Yes, a light bulb will put out some infrared light.

Decoding remote control signals isn't that hard - there is a tutorial at instructables - http://www.instructables.com/id/The-Easiest-Way-to-Use-Any-IR-Remote-with-Ardiuno/?ALLSTEPS

This also means you can tell the difference between different buttons.

P.S. - when posting in this forum, it helps to include your code and your wiring.
> 1 votes

# Answer
What kind of light bulb is it? Try using e.g. an LED instead of incandescent; you might get less IR signal.
Having a more complicated signal that is decoded by the receiver reduces your false positives.
> 1 votes

---
Tags: ir
---


title: Connect arduino to beaglebone black

text:
# Question
Title: Connect arduino to beaglebone black
I want to exchange some date between arduino and beaglebone, as far as I know, most arduinos works with 5v levels, so I need to convert 5v into 3.3v beaglebone in order to communicate with it.
Unfortunatly I have no pro mini 3.3v now, only 5v arduinos.
So I need to convert levels.
I have several questions.

1. I have UART TTL CP2102 converter, I am using it to programm my Arduino pro mini, can I use it directly with beagle bone without converter ? http://ecx.images-amazon.com/images/I/410n8%2BHhdNL.*SY300*.jpg like this.
2. I can buy this cable with pl2303 inside http://i01.i.aliimg.com/wsphoto/v0/32250361345/Free-postage-1pcs-PL2303-PL2303HX-USB-to-UART-TTL-Cable-module-4p-4-pin-RS232-Converter.jpg
3. Is it possible to power my arduino pro mini 5v with 3.3v supply and use it directly with beaglebone

4. Can you provide simple level converter schematic to solder it quickly

All in all I need just to communicate with beaglebone via uart from pc with USB-UART converter or from arduino it doesn't matter, just to communicate and send some data.

Please suggest what is the best way to follow.

# Answer
> 1 votes
The simplest way is just to plug the Arduino in to the BBB.

The BBB has USB. The Arduino has USB. Connect the two together and you have both power and data immediately available.

Depending on the Arduino and its version it will either be there as `/dev/ttyAMA0` or `/dev/ttyUSB0`

You can even use `avrdude` to upload new software to the Arduino direct from the BBB.

---
Tags: serial, usb, uart
---


# Question
Title: Possible configure ESP8266 as wifi shield for Arduino?
I know there's sketch to make ESP8266 becoming a simple web server. ESP8266 is cheap, small and consume less power compared to a Arduino Wifi shield.

Due to a more complex functionality requirement, I wish to place the web server code inside the Arduino itself (UNO, Nano or Pro Mini maybe). Is it possible to do this by configuring ESP8266 as a wifi bridge/shield to the Arduino? Or some mechanism methods which can route network traffics from ESP8266 to/from Arduino?

**Updated**
It connected to 4 relays & one I2C RTC DS1307.
It needs to sync RTC time with NTP server, and implement a web server which allows on-demand turn on/off each individual relay or by scheduling (e.g: turn on/off different relay at particular time of day). If RAM spaces allows, would like to implement a password access scheme for the web server as well

# Answer
The ESP has 40 kb of ram and the average SPI flash rom used by ESP modules have 1 ~ 8 MB of code space. The average Arduino has much less of both. Uno R3 has the ATMega328, with 2kb of SRAM and 32kb of code space. Your trying to drive a truck with a mini cooper engine.
> 2 votes

# Answer
I can't comment on Passerby's answer so here is an answer to that question in the comments: What ESP8266 are you using? The simple ESP-01, the one with just 8 pins, does not have four I/O ports. However if you have a more advanced ESP8266(for example the ESP12 on a breakout board) you do have 4 I/O pins and you could just threw out the Arduino entirely. The ESP8266 is better suited to serve as a webserver than your arduino. So as Passerby suggested try just using your ESP8266 alone instead of combined with your Arduino. Have a look at this. It is a tutorial on how to build a webserver controlling two LED's. All you would need to do is replace the LED's with the relays and add another two outputs. Note that you do need another powersupply for your ESP8266 than the Arduino. The arduino can only supply about 40mA, while the peek current of an ESP8266 can be around 250mA. Good Luck!
> 0 votes

---
Tags: wifi, esp8266
---


title: LED matrix appears dead

text:
# Question
Title: LED matrix appears dead
I recently purchased a 1.2 8x8 yellow matrix from Adafruit, along with a HT16K33 backpack for it. I joined the matrix and the backpack, connected everything to the arduino, followed the instructions on the site and got it to work. During animation certain rows would not light up and upon later examination I realized that I had to solder up the pins to the backpack because some pins would not completely make contact with the backpack. After soldering the matrix to the backpack, I fired up arduino and uploaded the matrix8x8 sketch that comes with the library to test the matrix and nothing happens.

I don't have a multimeter yet, but tried to check whether electricity is reaching the backpack which turns out to be true. (used a led and connected it to both + and -, and data and clock pins on the backpack.) in both cases the led lights up.

How can I check the health of the backpack and/or matrix?

# Answer
I hate to say it, but a multimeter would really come in handy for you. Harbor Freight has some for under $10.

That said, without knowing anything specific about what you are using, you could try using the same LED you used to test power and put it in parallel with one of the LEDs on the matrix. I'm guessing you don't have power at the LEDs though because it seems unlikely that all the LEDs would fail. Check your solder work and make sure you have not shorted anything. Also, you could have overheated a component when soldering causing it to fail. Good luck.
> 0 votes

---
Tags: arduino-mega, led
---


# Question
Title: Why cannot I input arrays as digitalWrite arguments?
I am making my own "7 segment LED driver". I know there is a lot of examples on the internet, I just want to try my own. But I have a piece of code that does not work and I don't know why. Can somebody explain to me why it is not working?

When I put in this, it works:

```
digitalWrite(pins[0], one[0]);
digitalWrite(pins[1], one[1]);
digitalWrite(pins[2], one[2]);
digitalWrite(pins[3], one[3]);
digitalWrite(pins[4], one[4]);
digitalWrite(pins[5], one[5]);
digitalWrite(pins[6], one[6]);

```

So of course I tried using for():

```
for (byte i = 0; i >= 6; i++)
  {
    digitalWrite(pins[i], one[i]);
  }

```

And this does not work. But why? I think it should. Btw. *pins* is const byte array and *one* is const bool array.

Thanks in advance for any suggestions!

# Answer
You've written the `for` loop incorrectly.

```
for (byte i = 0; i >= 6; i++)   <-- ERROR HERE
  {
    digitalWrite(pins[i], one[i]);
  }

```

That first line should be `for (byte i = 0; i <= 6; i++)`. `i` begins at zero, which is less than six, and the loop only runs while `i` is greater than 6.
> 0 votes

---
Tags: digital
---


title: Power Supply for 30 Servos

text:
# Question
Title: Power Supply for 30 Servos
I am now constructing something with 30 servos (each one will control an individual joint separately, so I guess I can't get away from this), how can I determine how much current do I need, I have a 5V 6A power supply, will that be working just fine? Many thanks in advance!

# Answer
> 1 votes
Get one of the servo's working at full load & measure the current flowing through it, multiply that by 30.

That's a lot of servos :D

# Answer
> 1 votes
You'll need to look up for your particular model of servo what it is rated for.

From this random datasheet I got values of about 5mA while idle and 150mA while running. Your 6A supply will be fine (if your servos don't draw significantly more than these) even if you run them all at once (which in practice, you might not).

Note that if you stall the servos they will draw more current, but it seems unlikely that you'd stall all of them at once.

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


# Question
Title: Is there a good XMPP (Jabber) library for Arduino?
I have a few sensors plugged in and getting some data from them. I want to use XMPP protocol to push the sensor data to my main server. Is there a good XMPP library available which I can use?

# Answer
A quick search pulls up https://github.com/adamvr/XMPPArduino which hasn't been touched since it was first created five years ago, and may or may not work. XMPP is a very heavy protocol that is very burdensome for a microcontroller to try and run. You could try and get the above library to work, or I would recommend one of the following alternatives:

* Load an XMPP client onto the OpenWRT side of the Yun and send commands from the Yun to control it. (Although glancing through the list of packages, there does not appear to be a pre-existing one. So this might not be an option unless you are up for cross compiling one. Looks like there is at least one: BitlBee via https://github.com/arduino/openwrt-packages-yun)
* Have the Arduino communicate using a lighter weight protocol (e.g. HTTP or MQTT) to another server or application that you write, which in turn sends your XMPP message using a readily available library.
> 1 votes

---
Tags: arduino-yun
---


# Question
Title: Execute Code While Refreshing a 7 Segment LED Display
I'm using the following library to drive a 4 digit, 7 segment LED display:

http://playground.arduino.cc/Main/SevenSegmentLibrary

The display is showing the temperature which it gets from a DS18B20 temperature sensor. Since the LED display constantly needs to be refreshed, when the code runs to get the current temperature, the display temporarily turns off because the LEDs are not being refreshed. The code I am using is below. Is there anyway to prevent the LED display from turning off while the temperature request code runs?

```
#include <SevSeg.h>
#include <OneWire.h>
#include <DallasTemperature.h>

SevSeg sevseg;

unsigned long timer; // the timer
unsigned long INTERVAL = 30000; // the repeat interval (30 seconds)

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {A2, A3, A4, A5};
  byte segmentPins[] = {8, 10, 6, 4, 3, 9, 7, 5};

  sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
  sevseg.setBrightness(90);

  // Get the initial temperature and show it on the LED display
  sensors.begin();
  sensors.requestTemperatures();
  sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  timer = millis(); // start timer
}

void loop() {
  if ((millis()-timer) > INTERVAL) {
    // Reset the timer and get/display the current temperature
    timer += INTERVAL;
    sensors.requestTemperatures();
    sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  }

  sevseg.refreshDisplay(); // Must run repeatedly to refresh the LED display
}

```

# Answer
> 1 votes
The problem here is that the display is driven using a timer interrupt. The temperature sensor, being a one-wire device, has to have very careful timing to communicate with it. As a result it disables interrupt so it has exclusive use of the CPU and can properly predict its timing while it's communicating. And so the display can't refresh at the same time.

So what can you do? Well, nothing really. You can't have perfect timing for the temperature sensor while at the same time interrupting it for displaying the value.

So there's really two main options:

1. Change the temperature sensor. Use an SPI or I2C temperature sensor that has a real hardware interface to communicate with it so you don't have to use big-banging.
2. Change the display. A non-multiplexed display or a display with its own built in driver (most often with some serial protocol like I2C or UART) would mean you don't have to use interrupts to update the display.

Basically you have two technologies that won't sit together well on the same chip.

---

Update:

I missed the `sevseg.refreshDisplay()` function call since the website had scrolled it off the bottom of the code block. Bah!

Ok, so it's not using an interrupt. That could be a good thing, or it may be meaningless. It takes time to do the temperature reading, and it's that getting in the way of the refreshing.

There's a chance you may be able to push the update "into the background" by attaching it to a timer interrupt, but if the OneWire communication does disable interrupts then the problem will still persist (I don't have OneWire to hand to look at the code right now).

---
Tags: led, display
---


title: Detect USB activity from a host

text:
# Question
Title: Detect USB activity from a host
I am testing a WinCE device that loses all USB communication infrequently. I need to detect when the USB fails on this device. When it fails, the power is intact at the port, just no data at all on D+ and D- (I verified this with an oscilloscope). This host device is basically a black box to me so I can't do anything to it but check it's state.

My proposed solution: Use an arduino of some type (preferably an UNO since I have one already) programmed to detect USB activity to let me know when USB is failing on the host device I am testing.

Is this possible? The arduino seems like a good solution for me because I assume it is a USB client, which I need in this scenario. Any example or pointing me in the right direction would be of great help. Thanks!

# Answer
> 0 votes
If all you are interested in is the voltages on the D+ and D- lines you could wire those direct into two ADC inputs on the Arduino and wire +5V and GND into the +5V and GND pin. The Arduino can then sample the voltages and compare them to valid or invalid ranges.

---
Tags: usb
---


title: Arduino Uno R3 board dead

text:
# Question
Title: Arduino Uno R3 board dead
I have an arduino uno Rs board and when connected to USB the board is dead. Yet when connected to the external supply the board will come to live. Power LED on and led near pin 13 blink on and off all time. I tried another computer and other new usb lead. Still computer will not see the board. When usb lead is on checked the 5 volt on the board and it is ok. Even checked the usb lead with multi meter and all four connection are ok Can you give me some advice

---

1.Yes I bought the new board from different source but still waiting for it to arrive. 2. My clone board Arduino uno using microcontroller Atmega329P-PU and interphase chip Atmega16U2\] 3 but the video link is still of help as my new board is as the one shown in the video. Will use it late. Great!!! There should be a similar explanation for the one I have in the picture

# Answer
> 1 votes
Does the Arduino show up at all in device manager or in mac/linux.(not sure what you are using)Is your board authentic or a clone? Did this happen the first time you plugged the arduino in or after uploading sketches etc? I had screwed up my firmware for my board that acted similar to what you describe.(I was trying to flash a different firmware) Eventually i ended up reflashing the right firmware and it went back to working again.Maybe it's that, maybe it isn't.

# Answer
> 1 votes
I had a similar problem. though it was easily solved but not obvious.

I couldn't connect my nano to the computer, but other devices worked fine. After a while other devices started to be faulty such as portable hard-drives and my CC3D flight controllers. After a cable replacement all the items started working again even the Arduino that i otherwise had discarded as broken.

It might not be the solution you are looking for but im leaving it here in case others comes for a solution.

# Answer
> 0 votes
You are happy the lead is ok. Good.

Can you test another Arduino on the PC? (Is it a driver issue?)

Can you connect to the serial pins on the Arduino and read the console output, is anything coming out on USB? (Is the USB socket on the board broken?)

Have you selected the right board type on the ide? (I know it's a dumb question but...)

---
Tags: arduino-uno
---


title: cannot read from softwareserial

text:
# Question
Title: cannot read from softwareserial
I am able to use AT command from the Serial monitor however when I run the following code nothing is sent or received from the ESP8266. Can someone advise what could be the problem.

```
#include <SoftwareSerial.h>;

SoftwareSerial esp8266(0,1); // 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
```
SoftwareSerial esp8266(0,1)

```

You can't use pins 0 and 1 for software serial since they are the hardware serial `Serial` than you use for communication with the PC.

Pick two other pins to use.
> 2 votes

---
Tags: softwareserial
---


title: Arduino Mega 2560 bootloader delay

text:
# Question
Title: Arduino Mega 2560 bootloader delay
I need to make my program run immediately on a reset or power up. However, the bootloader delays program startup by around 2.5 seconds. How can I get over this? Is there a way to turn off the bootloader wait period?

# Answer
Yes. You remove the bootloader completely and program the Arduino using a hardware programmer.

If you could "turn off" the wait period you would never be able to get into the bootloader to program the board, so the bootloader would be completely useless. So either way you would then need a hardware programmer to do anything constructive with the board.

A hardware programmer could be another Arduino, or a real hardware programming adapter.
> 0 votes

---
Tags: arduino-mega, bootloader
---


title: How to use Induino R3 on Ubuntu 14.04

text:
# Question
Title: How to use Induino R3 on Ubuntu 14.04
I have just got Induino R3. I have installed Arduino on my Ubuntu. I tried blink example but it shows error `serial port COM1 not found`

I think i need to select proper option from *serial port*. But i can't click on it!

P.S. I am completely new to Arduino

# Answer
> 1 votes
Not 100% sure of the specific differences between your board and a normal Arduino\[clone\], but I've never seen serial devices referenced in Ubuntu via COM# labels(Granted I've only used or needed to use serial type devices in the last year, so I could be a bit under experienced).

Anyhow, usually I find serial devices available at /dev/ttyXXX. On my Lubuntu 14.04 installs, my USB connected Arduinos all show up as /dev/ttyACM#. I have an FTDI programmer I usually use on wifi routers which generally shows up as /dev/tty#.

Rule of thumb in Linux, everything is a file somewhere.

# Answer
> 0 votes
Did you by any chance, download the Windows version of the Arduino IDE and install it under Wine? Then I would expect it to seek a COM# serial port. In which case you will have to create a symbolic link from the relevant /dev/ttyUSBx to COMx for your Arduino IDE to work.

The right way is to download the Arduino for Linux tar.gz file and extract it to a path of your choice in your Home folder.

---
Tags: serial, ubuntu
---


# Question
Title: Why does the PIN 13 LED of Uno R3 blink every time I upload some code?
I was driving a relay from Arduino Uno R3 Pin 13. I observed that every time I upload some code the led on the board designating pin 13 would blink. I'm curious why this is so. I understand that the serial LED blinks cause there's a serial transmission but why an IO pin?

# Answer
See What happens when code is uploaded using the bootloader? \- the flashing is by design.

Probably the reason is to confirm that the bootloader has started.
> 4 votes

# Answer
It's driven by the bootloader, which is performing the flashing (I suppose you are flashing through the USB port).
> 1 votes

# Answer
To show that the bootloader is functioning satisfactorily to the hobbyist. Boot loader helps to upload new sketch on the chip.
> -1 votes

---
Tags: arduino-uno, digital
---


title: Ping sensor with three or four pins?

text:
# Question
Title: Ping sensor with three or four pins?
I bought a Ping Ultrasonic Range Finder. It has four pins that you connect to the Arduino. I see in Internet that they have three pins. What does represent each pin and where to connect it to? I have an Arduino Uno Starter Kit.

# Answer
You have 4 *pins*.

* Vcc: +5V supply voltage (it stands for Collector Voltage)
* GND: Ground.
* Trig: Causes an ultrasound pulse to be generated (it stands for *Trigger*)
* Echo: Tells you when an echo has been received.

You can see how to wire and use it here: http://www.instructables.com/id/Easy-ultrasonic-4-pin-sensor-monitoring-hc-sr04/
> 0 votes

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


# Question
Title: Algorithms to reduce measurement error from analogue sensors
When reading analogue sensors - e.g. load cells, accelerometers - via a microcontroller's Analogue to Digital Converter, there are many sources of potential measurement error including:
a) Warm-up time for electronics
b) Mechanical inertia and resonance
c) Spurious random readings (due to e.g. vibration, electrical interference).

My current software hack for a) and b) is to simply add a suitable time delay before reading the sensors; however there must be a more robust way of detecting and screening for resonance...

My hack for c) is to take the mean of a given number of consecutive readings, but discard any individual readings which exceed a given percentage range from the current mean (pseudocode example below). The trouble with this approach is that it requires an inital \`baseline' sensor reading, and if this happens to be spuriously high or low, it can cause subsequent correct readings to be rejected. Another approach might incorporate a weighted moving average, but this would still be skewed by spurious random readings.

Are there any robust and elegant approaches / algorithms for the above which are commonly applied in commercial devices (e.g. domestic or laboratory weighing scales) that I could include in my code to improve the accuracy and reliability of measurements?

Many thanks in anticipation

```
// Take mean of multiple sensor readings excluding outliers:

# define SAMPLES 100 // number of samples to take mean of
# define TOLERANCE 0.1 // % range of allowable deviation
                       //between current mean and new values, expressed as decimal

n = 1; // loop variable
total = analogRead(analogPin); // Running total for calculation of mean & baseline reading
mean = total; // mean of all current data

while (n < SAMPLES) {
    new = analogRead(analogPin);
    if (new < (1 + TOLERANCE) * mean) and (new > (1 - TOLERANCE) * mean){
        total += new; // if new reading is within range, calculate new mean
        n += 1;
        mean = total / n;
        }
    // (else ignore new reading)
}
Serial.print mean;

```

# Answer
> 1 votes
I use something very similar to what you are proposing to measure RSSI in an antenna pattern generator. Say you have an array of 16 samples. You start filling the array with samples but don't actually output a result until the array is full. This will give you a startup period of 16 samples where no decisions are made.

After the array is loaded, set a semaphore that indicates that results may now be used to make decisions. New samples overwrite the oldest sample in a recirculating buffer. You will now get decision outputs at the same rate as the sample rate with a lag, i.e. when the inputs go to zero abruptly, it will take 16 sample periods for the output to catch up. I call this a 16 sample rolling average.

For relatively stable inputs, simply take the mean of the array and output that result.

For inputs that are glitchy such as RSSI take the mean of the array and then find the sample(s) that is (are) the farthest away from that mean. You then recalculate the mean without that sample included. Note: Do not discard that sample, simply ignore it for that cycle. I call this a 15/1 outlyer average. For my RSSI measurements, this gives me the equivalent of a 48 sample rolling average. You can do an 8/1, 16/2 system etc requiring 9 and 18 samples per sample respectively, tuning the counts to your particular application. I am able to get nearly anaechoic chamber results in the middle of a radio noisy office.

Again, note that the outlyers are NEVER discarded as they may represent a real trend.

# Answer
> 1 votes
Thank you John! Your solution is what I was looking for: it resolves my conflict between preserving all the data and excluding the skewing effects of outliers; is simple enough to implement on a microcontroller; and seems to work perfectly. I'm guessing that the rolling mean will also smooth out any potential swings due to mechanical resonance.
I know this is an Arduino forum, but I find it quicker and easier to write interactive code in Python, so I've written a crude \`test bed' implementation of your algorithm in Python so that I could get a feel for how it works in practice, with user keyboard input simulating real-life sensor readings. I've avoided any libraries or esoteric Python syntax, so this should be easy to adapt to C++/Arduino. I'm posting it here in case it is of interest to the community.
I've used the formula for Sample Std Deviation (n-1) rather than Population SD (n) which I think is correct in this context, but please let me know if not:
in LaTeX: $SD=\sqrt{\frac{\sum\_{(i=1)}^{n}(x\_{i}-\bar{x})^{2}}{n-1}}$

If there are any other algorithms or solutions to my post, I'd be very interested to know. Thanks again.

```
#===================================================
def SampleSD(data,bufLen):
    datasum = 0.0 # NB declare as float to prevent integer rounding error
    diffsum = 0.0 # NB declare as float to prevent integer rounding error
    for m in range (0,bufLen):
        datasum += data[m]
    mean = datasum / bufLen
    for m in range (0,bufLen):
        diffsum += (data[m] - mean) ** 2
    sd = (diffsum /(bufLen-1)) ** 0.5
    print "n: %d\tSum: %f\tMean: %f\tSD: %f" %(bufLen,datasum,mean,sd)
    return mean,sd

#=====================================
def addData(data,bufLen):
    print "\n------------------------------"
    new = input ("Sensor reading: ")
    for m in range(bufLen-1,0,-1):
        data[m]=data[m-1]
    data[0]=new
    return data

#======================================
bufLen = input ("Buffer Length: ")
print
data = [0] * bufLen # Declare an array of suitable length in Python
n = 0

# Fill buffer with initial data
while n < (bufLen):
    new = input ("Initial sensor reading: ")
    data[n] = new
    n +=1
print "\nBuffer initialised."
print "Data: ",data

while True:
    addData(data,bufLen)
    print "Data: ", data
    mean,sd = SampleSD(data,bufLen)
#===========================================
# Recalculate Mean only using data within range +/- 1 SD of mean
    if sd != 0: # Error trap to avoid divide by zero error if sd = 0
        print "\nChecking for outliers:"
        newSum = 0.0 # NB declare as float to prevent integer rounding error
        newLen = 0
        n=0
        while n < (bufLen):
            if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))):
                print "Data [%d] = %d Included" % (n, data[n])
                newSum += data[n] # sum of data which is within +- 1SD of original mean
                newLen += 1 # number of data whic are within +/- 1SD of original mean
            else:
                print "Data [%d] = %d Excluded: Out of range" % (n, data[n])
            n+=1
    CorrMean = newSum / newLen
    print "New n: %d\tNew Sum: %f\tCorrected Mean: %f" %(newLen,newSum,CorrMean)

```

# Answer
> 1 votes
... and here's my minimal working example for the Arduino. Feel free to adapt it for your own requirements, and please post any improvements or corrections to my script; or any alternative algorithms for the above.

Just noticed that my approach of using the SD to define and exclude outliers is a little more (? unnecessarily) complex than John's algorithm, which defines outliers in terms of the highest and lowest values from the mean; but both methods seem to work nicely.

Cheers!

```
#define BUFFER 5 // Buffer size (number of readings to use in rolling Mean)
#define SENSORPIN 3 // Analogue input pin from sensor
int data[BUFFER]; // Make an array of appropriate size for Buffer

void setup() {
  pinMode(SENSORPIN, INPUT);

  // Fill buffer with initial data
  int n = 0;
  while (n < BUFFER) {
    data[n] = analogRead(SENSORPIN);
    n++;
  }
}

void loop() {
  // Calculate Raw Mean & SD
  float datasum = 0;
  float diffsum = 0;
  for (int n = 0; n < BUFFER; n++) {
    datasum += data[n];
  }
  float mean = float(datasum / BUFFER);
  for (int n = 0; n < BUFFER; n++) {
    diffsum += ((data[n] - mean) * (data[n] - mean));
  }
  float sd = sqrt(diffsum / (BUFFER - 1));

  // Recalculate Corrected Mean only using data within range +/- 1SD of Raw Mean
  if (sd != 0) {      // Avoid divide by zero error if sd = 0
    float newSum = 0; // Sum of readings within acceptable range
    float newLen = 0; // Number of readings within acceptable range
    int n = 0;
    while (n < BUFFER) {
      if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))) {
        newSum += data[n];
        newLen ++;
      }
      n++;
    }
    mean = newSum / newLen; // Corrected Mean
  }

  // Add your code here to do stuff with variable float 'mean' = the (Corrected) Mean

  // Read new sensor reading, append to buffer and delete oldest reading
  for (int n = (BUFFER - 1); n > 0; n--) {
    data[n] = data[n - 1];
  }
  data[0] = analogRead(SENSORPIN);
}

```

---
Tags: sensors, adc, algorithm
---


# Question
Title: How to wait Arduino ready with ANY method?
Recently I knew, that Arduino restarts any time somebody accesses it's serial port. I was trying to use this feature so that for each request Arduino restarts and give answer on request. Unfortunately, I found this is impossible with shell script, because shell script can't keep port open all time I send requests and wait responses: Arduino restarts on each port touch.

So, I wrote simple C++ program:

```
#include <iostream>
#include <fstream>

using namespace std;

void help() {
    cout << "bmp180dims usage:" << endl <<
            "bmp180dims port command" << endl;
}

int main(int argc, char* argv[]) {

    if( argc != 3 ) {
        help();
        return 0;
    }

    fstream port;
    string answer;

    port.open(argv[1], std::fstream::in | std::fstream::out);

    port << argv[2] << endl;

    port >> answer;

    cout << answer << endl;

    port.close();

    return 0;

}

```

Since this program has explicit `open` and `close` statements, I was thinking, this program will wait for Arduino answer, because of stream reading functions. But I failed again: this program returns nothing as if it is not waiting.

Why?

Apparently, the only way to communicate with Arduino, is to have daemon program, which always listen it's port. Is this really so?

Arduino-side code is here: How can program/arduino restarted by IDE?

# Answer
> 2 votes
Again, you're *not waiting for the bootloader to complete* before sending your text:

```
port.open(argv[1], std::fstream::in | std::fstream::out);
// Board resets and enters bootloader

port << argv[2] << endl;
// You send argv[2] to the bootloader

port >> answer;
// The bootloader doesn't understand what you sent so doesn't reply with anything

```

You *must* wait for the bootloader to complete *before* sending ANYTHING to the Arduino.

The two ways you can do that are:

1. Insert a `sleep(3);` immediately after opening the port to give the bootloader a chance to time out and start running your sketch, or
2. Provide an initial "I Am Ready" message from your sketch that your C++ program waits for *before* sending the text you want to send to elicit an answer.

---
Tags: usb, linux
---


title: Send numbers bigger than 256 by SPI

text:
# Question
Title: Send numbers bigger than 256 by SPI
How can i send numbers like 300 or 1024 ?

I'm using the recommendation of the atmel's manual.

```
void SpiTransmitir(unsigned char data)
{
   SPDR = data;
   while(!(SPSR & (1<<SPIF)));//{Serial.println("While");}
}

```

I imagined that one bit shift could be the solution, but it still fails.

# Answer
You need to send two bytes - a high byte and a low byte.

There are two things you need to know with SPI:

1. You must wait for one byte to finish transmitting before you send the next
2. The whole transaction needs to be wrapped with a digital *chip select* signal.

So you have:

1. Chip Select idles HIGH
2. You lower Chip Select
3. You send one byte
4. You send the other byte
5. You raise chip select

At the receiver you:

1. Wait for chip select to go low
2. Receive one byte
3. Receive a second byte
4. Chip Select rises
5. You combine the two bytes together into one integer.
> 1 votes

# Answer
Try to join the numbers as follows:

```
#define NUMERO 342

void setup() {
  Serial.begin(9600);
  Serial.println(NUMERO, BIN); // Mostra valor do número em binário

  uint8_t MSB = 0, LSB = 0; // Dois números de 8 bits

  uint16_t junta = 0; // Valor junto em 16 bits

  MSB = NUMERO >> 4;
  LSB = NUMERO << 4;

  junta = (MSB << 4) | (LSB >> 4) ;

  Serial.println(junta, BIN);
}

void loop() {}

```
> 0 votes

---
Tags: spi
---


title: How to change i2c address for mpu9250?

text:
# Question
Title: How to change i2c address for mpu9250?
I'd like to connect 12 mpu9250 sensors to one arduino board.

I can't find documentation on how to change the addresses of mpu9250 boards. (i read through the reference ). Some tutorials talk about changing addresses for other device so i assume it is possible for mpu9250. I found this map of registers but can't figure out how to change the address.

I realize that mpu9250 might be too specific, so general guidance on how to solve these problems would be highly appreciated.

mpu9250 is similar to more popular mpu9150 and mpu6050. It is also known as GY-9250

# Answer
> 2 votes
Page 23 of the manual you linked:

> The MPU-9250 always acts as a slave when communicating to the system processor. The LSB of the of the I2C slave address is set by pin 9 (AD0).

It seems you can only choose between two addresses as listed in the table on page 12.

# Answer
> 4 votes
Might be a little late, but you can string more than two of these on one I2C bus, with a little ingenuity.

You connect the AD0 pin of each MPU to a different I/O pin of the processor, then take low the address of the one MPU you want to talk to.

Then that MPU has one address, all the others have the other address, and being slaves will not respond.

Provided you don't have more than one MPU selected at once, works a dream.

---
Tags: i2c, communication, accelerometer, mpu6050
---


# Question
Title: It is possible to control brightness of an LED strip (connected using a relay and having a seperate power supply ) using output from an arduino?
The circuit contains a relay interfacing with 12v power supply and LED strip. Can the brightness for this strip of LEDs be controlled using the `analogWrite` command? This works perfectly for a single LED, but when i replace the LED with a relayed LED strip with its own adapter, it doesnt produce any perceivable output

# Answer
> 1 votes
As Gerben said relays are only for on/off control. If you need to fade led you should use transistor.

* `What kind of transistor?`

It depends on power consumption (how many LEDs).

* `How to connect Arduino, LEDs, transistor?`

This is schematics how to connect the strip. As i assume resistors are already on the strip.

And little bit simpler image :)

# Answer
> 0 votes
Yes!

In the simpler image replace R2 with a 10 Ohm resistor and Q1 with a N channel Logic Level FET. This will allow you to switch (PWM) amps with R1 removed.

My LED strips pull about 3 amps at 12V. Depending on the FET you use you may have to add a heat sink. You will need to connect the low side (Ground) on the Arduino power supply to the low side on the power supply for the LED strip. The Arduino can then operate at 5 volts and the LED at 24V or whatever depends on the rating of the MOSFET. I would suggest using one of the PWM outputs, they will work fine with this circuit. This works for motors but additional parts will need to be added.

Enjoy.

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


# Question
Title: Processing printing sensor readings and raising NaN exception at the same time
I am using pressure sensor with Arduino Uno within Processing. Given these variables:

```
Serial myPort;              //the serial port
float sensorValue = 0;      //the value form the sensor

```

Arduino is printing float numbers on Processing console, according to the snippet below.

```
(...)

void serialEvent (Serial myPort){
//get the ASCII string
String inString = myPort.readStringUntil('\n');

if (inString != null){
//trim off any whitespace:
inString = trim(inString);
//convert to an int and map to the screen height
sensorValue = float(inString);
println(sensorValue);
sensorValue = map(sensorValue, 0, 1023, 0, height);
//println(sensorValue);

```

However, I am getting a `NaN` exception:

`sensorValue = map(NaN, 0, 1023, 0, height);`

how is this possible? printing numbers that aren't numbers?

# Answer
//convert to an int and map to the screen height sensorValue = float(inString);

You can't convert a String to a Float just like that by casting. You have to interpret the characters within the String. Oh, and a float isn't an integer.

All you're doing there is trying to cast the address of the String object to a float, which it really doesn't like, hence you get NaN.

Try:

```
int sensorValue;
sensorValue = inString.toInt();

```
> 1 votes

---
Tags: arduino-uno, processing-lang
---


# Question
Title: Android stops reading from bluetooth module
I am trying to read from a bluetooth module connected to arduino Uno. My application is a simple counter where the values are displayed on the arduino and the android app. The problem is that my android application get readings for some time (40-50 sec) and then stop at a random reading. When I check on the arduino serial monitor, the counter keeps counting and doesn't stop. Can someone please help?

Note: Ignore the buttons that I created :D

Java code:

```
package com.example.ibm.bluetooth_3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.ibm.bluetooth_3.R;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String TAG = "bluetooth2";

    Button btnOn, btnOff;
    TextView txtArduino;
    Handler h;

    final int RECIEVE_MESSAGE = 1;      // Status  for Handler
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder sb = new StringBuilder();

    private ConnectedThread mConnectedThread;

    // SPP UUID service
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // MAC-address of Bluetooth module (you must edit this line)
    private static String address = "00:06:66:68:30:D6";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnOn = (Button) findViewById(R.id.btnOn);                  // button LED ON
        btnOff = (Button) findViewById(R.id.btnOff);                // button LED OFF
        txtArduino = (EditText) findViewById(R.id.txtArduino);      // for display the received data from the Arduino
        h = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case RECIEVE_MESSAGE:                                                   // if receive massage
                        byte[] readBuf = (byte[]) msg.obj;
                        String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                        sb.append(strIncom);                                                // append string
                        int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                        if (endOfLineIndex > 0) {                                           // if end-of-line,
                            String sbprint = sb.substring(0, endOfLineIndex);               // extract string
                           sb.delete(0, sb.length());                                       // and clear
                            txtArduino.setText(sbprint);                                    // update TextView
                        }
                        //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                        break;
                }
            };
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
        checkBTState();

        btnOn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                btnOn.setEnabled(true);
                mConnectedThread.write("1");    // Send "1" via Bluetooth
                //Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
            }
        });

        btnOff.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                btnOff.setEnabled(true);
                mConnectedThread.write("0");    // Send "0" via Bluetooth
                //Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        if(Build.VERSION.SDK_INT >= 10){
            try {
                final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            } catch (Exception e) {
                Log.e(TAG, "Could not create Insecure RFComm Connection",e);
            }
        }
        return  device.createRfcommSocketToServiceRecord(MY_UUID);
    }

    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "...onResume - try connect...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

    /*try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }*/

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d(TAG, "...Connecting...");
        try {
            btSocket.connect();
            Log.d(TAG, "....Connection ok...");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to server.
        Log.d(TAG, "...Create Socket...");

        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
    }

    @Override
    public void onPause() {
        super.onPause();

        Log.d(TAG, "...In onPause()...");

        try     {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
    }

    private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) {
            errorExit("Fatal Error", "Bluetooth not support");
        } else {
            if (btAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    private void errorExit(String title, String message){
        Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
        finish();
    }

    private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                } catch (IOException e) {
                    break;
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(String message) {
            Log.d(TAG, "...Data to send: " + message + "...");
            byte[] msgBuffer = message.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
            }
        }
    }
}

```

Android XML:

```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:focusable="true">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="On"
        android:id="@+id/btnOn"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="52dp"
        android:enabled="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Off"
        android:id="@+id/btnOff"
        android:layout_below="@+id/btnOn"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:enabled="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/txtArduino"
        android:layout_below="@+id/btnOff"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="65dp" />

</RelativeLayout>

```

Android Manifest:

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ibm.bluetooth_3" >
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

```

Arduino code:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial (3, 2);
void setup()
{
  Serial.begin (57600);
  mySerial.begin (115200);
}

void loop()
{
  for (int i=0; i < 1000000; i++)
  {
    mySerial.println (i);
    Serial.println (i);
    delay (100);
  }
}

```

# Answer
I am not sure if you have found the answer. Here are my observation. Those who are searching for same problem can refer to these...

1. Change your Android device. Devices will have different bluetooth stack provided by bluetooth chip makers. Cheap ones will have problems. I had this. When I tested with another couple of devices, they seem to have handled it very well. It is all in the bluetooth stack on Android device!
2. Though I have not had problems with Arduino bluetooth device, try changing that.
3. Disable all logging on Android app. This will reduce burden on device.
4. Disable Serial communication on Arduino used for debugging purpose. This way you can make sure that only one serial communication channel is active communicating with Android.

If you follow this, surely you will have solved your problem as I have solved the same.

-Sachin
> 1 votes

# Answer
On the Arduino side, try increasing the delay or decreasing the baud rate. I have an application that dumps a stored history to a Bluetooth module talking to Bluetooth Terminal/Graphics on a Google Nexus 7. At 57600 baud, I've seen the same thing happen. My solution was to delay for 50ms after every 100 lines of output. While your Arduino code should be sending even slower than mine does, your Android system including your application code, might need an even slower input.
> 0 votes

---
Tags: arduino-uno, bluetooth, android
---


title: Problem in receieving message

text:
# Question
Title: Problem in receieving message
I'm working on a project in which when I press reset button the arduino should send longitudes and latitudes to my phone. I'm a beginner and tried to join two codes, first code can send the message and the second code can get the lon and lat printed on the serial monitor.

First code--

```
int timesTosend=1;
int count=0;
char phone_no[]="+917771914436";
void setup()
{
  Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay(200);
}
void loop()
{
  while (count<timesTosend)
  {
    delay(1500);
    Serial.print("AT+CMGS=\"");
    Serial.print(phone_no);
    Serial.println("\"");
    while(Serial.read()!='>');
    {
      Serial.print("Hii If this message is sent then its a huge sucess for me");
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
    }
    count++;
  }
}

```

Second code--

```
#include <SoftwareSerial.h>
#include <TinyGPS.h>

long lat,lon; // create variable for latitude and longitude object

SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
TinyGPS gps; // create gps object

void setup(){
  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
}

void loop(){
  while(gpsSerial.available()){ // check for gps data
   if(gps.encode(gpsSerial.read())){ // encode gps data
    gps.get_position(&lat,&lon); // get latitude and longitude
    // display position
    Serial.print("Position: ");
    Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
    Serial.print("lon: ");Serial.println(lon); // print longitude
   }
  }
}

```

My code which is not working--

```
#include <SoftwareSerial.h>
#include <TinyGPS.h>
long lat,lon; // create variable for latitude and longitude object

SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
TinyGPS gps; // create gps object

void setup()
{
  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
    Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay(200);
}

int timesTosend=1;
int count=0;
char phone_no[]="+917771914436";
void loop()
{
  while (count<timesTosend)
  {
    delay(1500);
    Serial.print("AT+CMGS=\"");
    Serial.print(phone_no);
    Serial.println("\"");
     while(Serial.read()!='>');
    {
      while(gpsSerial.available())
      {
        if(gps.encode(gpsSerial.read()))
        { // encode gps data
    gps.get_position(&lat,&lon); // get latitude and longitude
    Serial.print(lat,lon);
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
        }
      }
    }
    count++;
  }
}

```

Please help me out by correcting my mistake in the code.

# Answer
> 0 votes
```
Serial.print(lat,lon);

```

That doesn't do what you think it does. That is trying to print the latitude encoded in base "lon", which just isn't going to work.

Instead you need to send it as separate operations:

```
Serial.print(lat);
Serial.print(",");
Serial.print(lon);

```

Also you should separate out the GPS and GSM routines. Create a function that gets the latitude and longitude, and another function that sends the two values as a text message. Then you can keep things as discrete obvious steps and not get confused with what is happening when.

---
Tags: arduino-uno, gsm, gps
---


title: Lego Technic Servo Motor - 9V PWM

text:
# Question
Title: Lego Technic Servo Motor - 9V PWM
I want to control Lego Technic Servo Motor 88004.

The way it works is - Lego has a 4 cable connector. Two of them supply power (+9V & GND) and the other are optionally +9V and they are called C1 and C2.

Servo turns right or left max 90 deg when you supply PWM to either C1 ("left") or C2 ("right"). (or the other way round, but it doesn't really matter)

That basically means that what I need is a 9V PWM and be able to supply it to either C1 or C2. What is more the frequency has to be 1150 Hz.

Now the question is how do I achieve this goal?

I'm already using the L298N motor controller and happen to have one engine slot free.

1) If I can supply PWM from Arduino to "LNA" input in L298N - will it also cause the output to be PWM? Because L298N has a transistor I have a feeling that the output is also going to be PWM unless there's something else there i.e. capacitor

Even if it's not does that matter at all - meaning is it going to still work?

2) How do I produce PWM with 1150 Hz from Arduino? My Arduino is 16MHz so I suppose that it should be possible to switch output with order of magnitude smaller frequency.

If what I'm trying to do makes no sense please try to point me to the right direction.

# Answer
1. Yes, the output will be a pwm. You can see it from the schematics.
2. you have few options, with different precision and complexity:
    1. Configure one of the PWM HW blocks
    2. Do it by sw in a loop
    3. Use a timer to trigger a sw function - but it might be simpler to just configure the PWM HW block.
    4. Use some existing library that will implement one of the methods I listed

I would recommend Option 1: it's not so difficult, you will learn something of the AVR internals and it will be the solution with the least overhead. You can have a look at this tutorial. There are also many others floating around.
> 1 votes

---
Tags: servo
---


# Question
Title: Help with button library, hold>2s doA else doB
I'm using JChristensen's Button Library to debounce my buttons and provide extra functionality. I'm trying to use his press & hold function to do something if the button is pressed and held for greater than 2 seconds. If it is just pressed momentarily it should do something else. His example use switch cases, and I couldn't get it to work. Here is my example that currently doesn't work.

```
    #include <Button.h>
    #include <SPI.h>
    #include <printf.h>

    // Keypress state setup
    byte clearPin = 16; // Clear pin

    #define PULLUP true
    #define INVERT true // Since the pullup resistor will keep the pin high  unless the
    #define DEBOUNCE_MS 20 // A debounce time of 20 milliseconds usually works well for tactile button switches.
    #define LONG_PRESS 2000 // We define a "long press" to be 2000 milliseconds.
    unsigned long ms; // The current time from millis()
    Button clearBtn(clearPin, PULLUP, INVERT, DEBOUNCE_MS); // Declare the button
    int score=1;

void setup ()
{
  pinMode(16, INPUT_PULLUP); // Pin for clear button
  Serial.begin(9600); // Radio Setup
}

void loop()
{
 clearScore(); // sets both home and away scores to 0 or enters settings menu
}

void clearScore()
{
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button

  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
     Serial.println("Settings Menu");
     while (clearBtn.read()!=1) {

     } // End While
   return; // Hopefully not proceed down to the next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }

}

```

Can anyone help please? My serial output repeats "Settings Menu" over and over. Once I let go of the button ~~variable1~~ always gets set to 0.

# Answer
The `loop()` and `clearScore()` code that you have is like the following.

```
void loop() {
  clearScore(); // sets both home and away scores to 0 or enters settings menu
}
void clearScore() {
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button
  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
    Serial.println("Settings Menu");
    while (clearBtn.read()!=1) {
      // do stuff
    } // End While
    return; // Don't proceed to next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

```

When you reset the Arduino and then hold down the clearBtn, `clearScore()` will be called repeatedly. `clearBtn.pressedFor(2000)` will not be satisfied during the first two seconds of holding the button down, and `clearBtn.wasReleased()` will not be satisfied either, so `clearScore()` will do nothing during the first two seconds.

After the first two seconds, "Settings Menu" will be sent repeatedly: `clearBtn.pressedFor(2000)` is true, so the first `if` succeeds each time `clearScore()` runs, and it will run repeatedly because it is called from `loop()`. The `while` test, `clearBtn.read()!=1` \[which in more-idiomatic C would be written as `!clearBtn.read()`\] fails until the clearBtn is released, so the `while` loop does nothing. Also, `clearBtn.wasReleased()` will be false, so the other `if` does nothing.

When the button finally is released, `clearBtn.pressedFor(2000)` goes false, so the first `if` fails and the second executes one time.

Here is some code that should act more like what you want, as expressed in your comment,

> It's supposed to work like this: 1) hold button down for 2 seconds to enter settings menu. While in settings menu I'll code other stuff. Stay in settings menu until the clear button is pressed momentarily again. Once you press clear button again from being in the settings menu, the score should NOT be reset, and it should just return to the main loop. 2) if the clear button was not pressed for more than 2 seconds, just clear the score.

```
void clearScore() {
  ms = millis(); //record the current time

  while (clearBtn.read()) {
    if (clearBtn.pressedFor(2000)) {
      Serial.println("Settings Menu"); // Announce Settings menu
      while (clearBtn.read()) {}       // Await button release
      while (!clearBtn.read()) {       // Await button press
        // do  Settings menu stuff here
        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }
    return;
  }

  if (clearBtn.wasReleased()) { // See if released, after short press
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

```

*Edit edit:* To avoid resetting the score at every settings exit, in the above code replace

```
        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }

```

with

```
      }
    }
    while (clearBtn.read()) {} // wait for the settings-exit clearBtn release
    clearBtn.read(); // Do another read to avoid clearing score on next clearScore()

```

That is, right before the `return`, wait for clearBtn release, and read it again to be sure later reads won't register a release. The latter `read` might not be needed, because `clearScore()` does a `read` when it tests the first `while` condition; you could experiment.
> 0 votes

---
Tags: c++, button, debounce
---


title: Esp8266 V12 Wiring

text:
# Question
Title: Esp8266 V12 Wiring
I have tried a Google search and cannot find any place that tells me exactly how to wire the version 12 esp8266 ,

How should it be wired for normal operation and for flashing ?

I am designing a diy pcb and need to know the specifics,to wire a switch for flashing purposes etc.I am using just a esp8266 version 12 standalone without a typical arduino micro-controller attached and will be flashing it to take the arduino ide ,any help with this would be great as I'm sure someone has already come across this problem.

# Answer
> 1 votes
You could find the solution, on the first hit for googling "ESP8266 ESP-12".

> You need to connect a few GPIO pins on the ESP-12 to 3.3V or Ground, to set it in the right mode for communicating with it. Here are the connections you need to make :
>
> VCC ----\> 3.3V Power supply (Vout of LM1117)
>
> GND ----\> Ground of power supply
>
> CH\_PD ----\> HIGH (3.3V)
>
> GPIO2 ----\> HIGH (3.3V)
>
> GPIO15 ----\> LOW (GND)
>
> GPIO0 ----\> HIGH or Floating for AT Mode (3.3V) \[ * if you want to flash completely different firmware then you must connect it to ground \]

You need to connect `GPIO0` to `GND` for flashing and to `VCC` for normal operation.

---
Tags: arduino-ide, pins, hardware, esp8266
---


# Question
Title: SMD Voltage Regulator 662k very hot, how to repair it?
I think I made a mistake. Now, the 662k on my Arduino Uno very hot about 90°C.

I test it, it can be programmed and can run blink program normally.

There is a switch for voltage choose. Now, run in 3.3v mode get 2.8v and in 5v mode get 4.8v.

What should I do?

If 662k be replaced, can I use that Arduino normally in the future.

# Answer
> 3 votes
From the picture I guess it is a roboduino. The only voltage regulator is the 662k, it is **too small** compared to other voltage regulators!!! (have a look at the size and sink of the official arduino), so it is normal that the temperature is high. (arduino uno can get up to 1A and the regulator is bigger)

To reduce temperature just **use the lowest input source** (for instance, for arduino 5 volts, use 7 volts source, not 12 volts source). The bigger input voltage, the higher temperature in the regulator.

Solutions.

* replace the 662K with another 662K one.
* use a bigger voltage regulator. Since 66K space is tight (SOT-23) and no sink space I suggest to solder a TO-92 like voltage regulator. Not nice solution, but handy.

---
Tags: arduino-uno, voltage-level
---


# Question
Title: The Time are functions do not work correctly when the processor clock speed is set at 128K
How can I change The timers to work correctly when The processor clock is set to 128K instead of 16 M? At present, using the delay function does not work correctly, The delay is far too long.

# Answer
> 2 votes
Add a new entry in boards.txt with the new value for `f_cpu`. Note that the timing functions will become far less precise at so low a speed.

# Answer
> 1 votes
A commonly-used approach is writing an intermediate or surrogate delay function that your application calls. That delay routine needs a way to know if the clock is slow (128 KHz) or fast (16 MHz). If the clock is slow, divide the delay counts by 125 (the ratio of 16 MHz and 128 KHz) before calling the built-in `delay()`. \[Or, adjust all your application calls to use numbers scaled down by a factor of 125, and in the surrogate scale them back up if the clock is fast. This may give you better control than just rounding, truncating, or truncating up will do.\]

For example, if you call the intermediate routine `vDelay()` and change your app calls from a `delay(x)` form to a `vDelay(x)` form, in the function `vDelay(unsigned long ms)` you will say something like `if (ClockIsSlow) delay((ms+124)/125); else delay(ms);`

---
Tags: arduino-uno, oscillator-clock, fuses
---


# Question
Title: Can one supply an Arduino Zero's VIN pin with 5v?
The title pretty much says it all. I know that most Arduinos can do this, but I couldn't find very much information for the Zero. Any help would be very much appreciated.

# Answer
> 0 votes
Yes you can. If you look at the schematics on the Arduino website you can see that the 3.3 volt regulator is connected to the 5 volt regulator. That means that if you feed 5 volts straight into the 5 volt pin it will go through the 3.3 volt regulator to supply the main chip. Note that this is going into the 5 volt pin not the VIN pin which goes into the 5 volt regulator and would thus require a higher voltage than 5 volts.

---
Tags: power
---


# Question
Title: Failed to read DHT22 sensor using Arduino Uno
why do I end up with the display "Failed to read from DHT sensor!" in the serial monitor in most cases when I run the code given below?? In case I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false......Any help would be highly appreciated...

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

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

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

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

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

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

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

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

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

```

# Answer
> 3 votes
I suggest you to modify the following lines of code to check which reading has issue.

```
if (isnan(h) || isnan(t) || isnan(f)) {
   Serial.println("Failed to read from DHT sensor!");
   return;
}

```

# Answer
> 1 votes
Have you put a 4.7kOhm resistor between data pin and Vcc on the dht22? i had problems with a reading until i did. see this HTH

---
Tags: arduino-uno, temperature-sensor, code-review
---


title: Advanced Line Follower robot

text:
# Question
Title: Advanced Line Follower robot
I know about line follower mainly the grid solving robots i know the basics actually. Actually they have to trace the path of the grid in an arena and then reach back to starting point in a shortest distance. Here my doubt is regarding the line follower in this link I have attached.Advanced Line Follower Robot for maze solving

My doubt is what are the procedures to do it? They have mapped the path and used Dijkstra algorithm to solve the path. But how do they transfer the code(i.e) where it has to turn which direction it has to turn. how are they generating the what function should be passed? Please explain i need the procedure alone. am going to try it with python.

# Answer
> 2 votes
Any language will do, as long as it is supported by your HW platform. If you want to use python, you need a board that can run python. That could be an Arduino Yun, for example. Or an Intel Quark. Or an Intel Edison with an Arduino shield. But these will be expensive.

You could, alternatively, use C/C++ and an Ardino UNO (or micro, nano, mini pro), which is far cheaper.

Googling for something as simple as "Arduino line following kit" gives as first answer this, which seems to be exactly what you are looking for.

---
Tags: arduino-uno, arduino-ide, robotics, python
---


# Question
Title: How to use serial.read a sentences and serial.print after that enter to new line
This is my code but it doesn't work. I don't no why . I hope someone can explain the problem. Tks

```
unsigned char InTransfer;
char buffer;
void setup()
    {
  Serial.begin(9600);
}

void loop()
{
  /* when get the sentences and print it*/
   while ( Serial.available())
  {
    buffer=Serial.read();
    Serial.write(buffer);
    InTransfer=1;    // detect
  }
  /* After done enter one time */
  if (Serial.available()==0)
    if(InTransfer==1){
      Serial.println("");
      InTransfer=0;
  }
}

```

# Answer
Your code works perfectly, I don't see a problem with it. It's doing *exactly* what you're telling it to.

The problem lies in a fundamental lack of understanding about how serial communications work on your part, so you are telling it to do the wrong thing. Until you fix that aspect no program you try and write in this way will be a success.

You should start by learning how serial communication actually works. A good starting point is an article I wrote ages ago: http://hacking.majenko.co.uk/reading-serial-on-the-arduino
> 1 votes

---
Tags: serial
---


# Question
Title: Difference in bootloader of ATmega with 16MHz external crystal and 8MHz external crystal
I have used your bootloader for ATmega2560-16AU with 16MHz external crystal and it works like a wonder.

In my new project I have a 3V power supply. Therefore, I am planning to use a low frequency external crystal in order to operate the ATmega at a low frequency so that the voltage will be able to go as low as possible.

However, I have a number of issues/questions:

1. I uploaded the bootloader using an 8MHz external crystal and it went successfully but I am not able to upload a sketch.
2. Can I run an ATmega2560-16AU with an 8MHz crystal and will it work at 3V, without any risk?
3. As I do not have an ATmega2560-8AU right now, I am not able to test this. Will your bootloader work with Atmega2560-8AU and an external 8MHz crystal or, before burning bootloader, do I need to make any changes?

Sorry to ask you such a long query, but I have really spent lots of time looking at this and finally today I made a post everywhere.

# Answer
> 1 votes
Yes, the ATmega328 will run fine at 8MHz, at 3 volts.

The formulas for clock speed vs. volts are:

* Below 1.8V - cannot operate
* Below 4 MHz - use at least 1.8V
* Between 4 MHz and 10 MHz you require: Volts = 1.8 + ((M - 4) * 0.15) (Where M is Megahertz)
* Between 10 MHz and 20 MHz you require: Volts = 2.7 + ((M - 10) * 0.18) (Where M is Megahertz)
* You can supply an absolute maximum of 5.5V

Plugging 8MHz into this formula: volts = 1.8+((8-4)\*0.15) = 2.4 volts minimum (5.5 volts maximum). Note that, as batteries are used, their voltage goes down gradually, so the 0.6 volts difference will mean that your project will run a little longer.

Since your supply is \> 2.7V, we can reverse the second formula: 3V=2.7+(M-10)\*0.18); 0.3=(M-10)\*0.18; 0.66=M-10, so you can run it at 10.66MHz at 3V (but it is likely to stop as soon as the battery starts to drain).

Your second question, I think, is the most relevant one - the bootloader is written for 16MHz, and some things will not work at other speeds - serial communications used for programming for example. The same, for that matter, applies to the program - if you put in a `delay()` instruction in your code, it will `delay()` for twice as long as it should.

You can get around the programming side by ditching the bootloader altogether - once your code is ready, select file-\>upload using programmer. This will still affect the speed your sketch runs at (anything time-related - serial communications, `delay()`, etc). To change this, you will need to add a custom entry to the `boards.txt` file. See \[HOWTO:\] Anatomy of the boards.txt file for custom boards.

---
Tags: arduino-mega, uploading, sketch, bootloader, frequency
---


# Question
Title: Communicating Arduino with Intel Galileo
I'm doing a project where I have few sensors on Arduino Uno. Now I am trying to send some data to the internet where i figured using my GSM shield with the Galileo board I have is the best solution.

The problem I am facing is that software serial is not working on Galileo so I have to use the Serial1 of Galileo board (Pin 0 and Pin 1) and I am out of serial ports. I was thinking of using serial communication between Arduino and Galileo but Galileo seems to have only pin0 and pin1 as serial and they are occupied by the GSM shield.

Is there any part I am getting wrong or any suggestions?

(other than using the sensors on Galileo and getting rid of the Arduino Uno :) )

# Answer
You could use SPI/I2C as interface between Arduino and Galileo. They are better than plain serial.
> 0 votes

---
Tags: serial, gsm, arduino-galileo
---


# Question
Title: Relay module and internal pull-up resistors
I'm currently assembling a prototype of the lightning infrastructure (*based on several MEGAs interconnected via RS485, as described in this other post*)

The prototype consists of three MEGAs, a couple of wall-push-button and the two relay modules here below:

Obviously I've:

* connected one endpoint of each push-buttons to Arduino INPUT-PIN; the other endpoint to ground;
* connected the relay-module control-pins to Arduino OUTPUT-PIN (and ensuring a properly connected ground).
* connected lamps to relay-modules power connectors.

My question relates to "**pull-up resistor**": I've read in **lots** of places that when involving push-buttons, "pull-up resistors" are needed in order to prevent shorts between ground and input-pin. As such, there are **lots** of tutorial/videos on the web, showing a nice resistor added in the push-button circuit.

Further investigating, I've also learnt from the official documentation that "*...There are 20K pullup resistors built into the Atmega chip that can be accessed from software....*", by setting the `pinMode()` as `INPUT_PULLUP` or setting it to `INPUT` and the forcing a `digitalWrite(<PIN>,HIGH)`.

So, I ended:

* directly connecting the two relay-modules to MEGAs INPUT-PINs and...
* ...activating the internal pull-up, with `digitalWrite(<INPUT_PIN>,HIGH)`;

Nothing more.

This is the second evening I'm "testing" my Arduino-luggage-prototype and... lamps are turning on/off like a charm, without any noticeable problem.

The question is: am I doing something nasty toward my MEGAs? Is the approach depicted above, a commonly-safe (as for the Arduino's health) approach?

---

P.S.: should you wonder about how the prototype looks like, here is a photo (actually, taken right after the first power-up ;-)

# Answer
> 0 votes
Connecting one side of a switch to ground and the other side to an input pin (with its pinmode set to INPUT\_PULLUP) is a standard way of connecting control switches to an Arduino installation, and is not a problem.

Note, claims that built-in pull-ups are 20KΩ oversimplifies the situation. See, for example, Table 28.2, DC Characteristics, in the ATmega48PA/88PA/168PA/328P specs, which shows a min value of 20KΩ for I/O Pin Pull-up Resistors and a max value of 50KΩ. I've measured resistances of about 40KΩ, IIRC, whenever I've measured the pull-up values.

Note, built-in pull-ups typically are of too much resistance to work as pull-ups for TWI/SPI/I2C communications.

Note, when you say in the question that you connected the relay-modules to input pins and they worked ok, I suppose that could be the case, but in general it is better to put i/o pins into output mode when you want to drive an output. When you send LOW to an input pin, its built-in pull-up is turned off, the input impedance becomes high, and then the pin can float to any value between ground and Vcc. It might fail to turn off an attached device if that device also has high impedance.

# Answer
> 0 votes
I am making the assumption the push buttons are wired directly to the mega. This may work but for me it is not acceptable. Why? All of those wires act as an antenna array tuned to a lot of different frequencies. My favorite trick is to use a 74C14 Schmidt trigger chip. The reason is several fold. First it isolates the antennas from the processor. The family I use will tolerate about 25volts input, giving a lot of head room. Second it makes the software a bit easier, all switches come in positive true. Third I use a low pass network in front so if one of the mains hits it it will probably survive. What I do is Pull up with a resistor that will cause about 1.5 ma to flow through the switch. This value is dependent on your voltage, I typically use 12 or 24 VDC. This input then goes through a 100K resistor to the input of the gate where I also put a .01 uF cap.

I am also working on a similar project, I made the same decision on a hardwired network about 15 years ago. All the switching is on several output boards (5V) located in a PC AT. I also chose the mega for several reasons, first I needed full duplex with my network, the MAX485 will do that you just have to leave the receive enabled and cycle the transmit when you want to send something. I also added a low pass on the (A line I Think) to another pin so I could determine if the network was busy, I currently have about 150 outputs with very few inputs. Code is all in ASM86.

I hope this helps, I will see if I can add to your reference question.

Thanks, Gil

---
Tags: arduino-mega, relay, pull-up
---


# Question
Title: Read sensor and convert reading to const char*
I'm working on a home automation project using Arduino and MQTT.

I've found a problem and my limited programming knowledge find a way to solve it.

I can send text trough MQTT normally, using

```
client.Publish("some/topic","Some text here");

```

But when I try to send a variable (int, char, etc), the compiler says "invalid conversion from 'char' to 'const char\*' \[-fpermissive\]"

How can I store DHT11 sensor reading in const char\* to send it?

BTW, I've found this code where

```
char *tempC;
tempC = dtostrf(((((analogRead(tempPinIn) * 5.0) / 1024) - 0.5) * 100), 5, 2, message_buffer);
client.publish("arduino/temperature",tempC);

```

is used. But the extra sensor calibration makes it even harder for me to understand whats going on.

# Answer
The function `dtostrf()` is prototyped as:

```
char *dtostrf (double          val,
               signed char     width,
               unsigned char   prec,
               char           *sout);

Where:
   val      Your float variable;
   width    Length of the string that will be created INCLUDING decimal point;
   prec     Number of digits after the deimal point to print;
   sout     Destination of output buffer;

```

An example of usage is as follows:

```
/* OPTION ONE */

    char msgBuffer[20];           // make sure this is big enough to hold your string
    char *pointer_to_created_string;

    float testFloat = 123.45;

    pointer_to_created_string = dtostrf(testFloat, 6, 2, msgBuffer);
    client.Publish("...topic...", pointer_to_created_string);

/* OPTION TWO */

    char msgBuffer[20];           // make sure this is big enough to hold your string

    float testFloat = 123.45;

    client.Publish("...topic...", dtostrf(testFloat, 6, 2, msgBuffer));

```

Don't be put off by the code in the link you included in your question. The first argument sent to `dtostrf` (everything before the first comma) is nothing more than a some calculations bundled into one single line.
> 1 votes

---
Tags: arduino-uno, string
---