# Question
Title: Why is SoftwareSerial causing arduino to reboot?
I'm trying to design an RC controller using an Arduino and an XBee Series 2 Pro. I have the hardware serial running for debug information and I want the XBee to be connected to a soft serial on pins 8 and 9.

My arduino keeps restarting, or at least the setup function keeps looping, every time I try to send data through the XBee. If I modify the code so the XBee runs on the hard serial, the program works, but I would rather not have that setup because then to load new code onto the arduino I have to open the controller and disconnect the XBee.

I tried changing the pins that the soft serial runs on and that makes no difference, nor does unplugging the power to the XBee but leaving the serial connections in. I also tried to write another pin high to make sure there's enough current, and that didn't cause a restart.

My arduino is connected to the XBee, 4 potentiometers, and 1 switch.

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

#define NOTE_A3  220
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330

#define THR_JOYSTICK A0
#define YAW_JOYSTICK A1
#define RL_JOYSTICK A2
#define FB_JOYSTICK A3
#define POT A4
#define TOGGLE 4
#define SPEAKER_PIN 3
//#define WAKE_PIN 10

#define YAW_MIN 0
#define YAW_OFFSET 386
#define YAW_MAX 815

#define RL_MIN 0
#define RL_OFFSET 359
#define RL_MAX 800

#define FB_MIN 0
#define FB_OFFSET 355
#define FB_MAX 795

#define THR_MIN 0
#define THR_OFFSET 0
#define THR_MAX 754

const int ESC_MIN = 764;
const int ESC_OFFSET = 1500;
const int ESC_MAX = 2000;

XBee xbee = XBee();
SoftwareSerial nss(13,12);
uint8_t payload[10];
// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40c67584);
ZBTxRequest packet = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

void setup() {
  //start serials
  Serial.begin(9600);
  nss.begin(9600);
  xbee.setSerial(nss);

  //pin modes
  pinMode(THR_JOYSTICK,INPUT);
  pinMode(YAW_JOYSTICK,INPUT);
  pinMode(RL_JOYSTICK,INPUT);
  pinMode(FB_JOYSTICK,INPUT);
  pinMode(POT,INPUT);
  pinMode(TOGGLE,INPUT);
  pinMode(SPEAKER_PIN,OUTPUT);

  //delay to allow inputs to settle
  delay(1000);

  //the speaker will need a total resistance of at least 125 Ohm
  //so if it's an 8 Ohm speaker, an additional 117 is needed etc...

   //calibrate THR
  int first = millis();
  tone(SPEAKER_PIN,NOTE_A3);
  int reading = analogRead(THR_JOYSTICK);
  while(reading > THR_OFFSET + 5 || reading < THR_OFFSET - 5) {
    delay(20);
    reading = analogRead(THR_JOYSTICK);
  }
  int dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate YAW
  first = millis();
  tone(SPEAKER_PIN,NOTE_B3);
  reading = analogRead(YAW_JOYSTICK);
  while(reading > YAW_OFFSET + 5 || reading < YAW_OFFSET - 5) {
    delay(20);
    reading = analogRead(YAW_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate FB
  first = millis();
  tone(SPEAKER_PIN,NOTE_C4);
  reading = analogRead(FB_JOYSTICK);
  while(reading > FB_OFFSET + 5 || reading < FB_OFFSET - 5) {
    delay(20);
    reading = analogRead(FB_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate RL
  first = millis();
  tone(SPEAKER_PIN,NOTE_D4);
  reading = analogRead(RL_JOYSTICK);
  while(reading > RL_OFFSET + 5 || reading < RL_OFFSET - 5) {
    delay(20);
    reading = analogRead(RL_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //done
  tone(SPEAKER_PIN,NOTE_E4);
  delay(200);
  noTone(SPEAKER_PIN);
  delay(15);
  tone(SPEAKER_PIN,NOTE_E4);
  delay(200);
  noTone(SPEAKER_PIN);
  delay(15);
  tone(SPEAKER_PIN,NOTE_E4);
  delay(350);
  noTone(SPEAKER_PIN);
}

void loop() {
  int POTReading = analogRead(POT);
  int toggle = digitalRead(TOGGLE);

  int throttleValue = mapLimit(analogRead(THR_JOYSTICK) - THR_OFFSET,THR_MIN,THR_MAX - THR_OFFSET,0,ESC_OFFSET);
  int yawValue = mapLimit(analogRead(YAW_JOYSTICK),YAW_MIN,YAW_MAX,ESC_OFFSET-ESC_MAX,ESC_MAX - ESC_OFFSET);
  int rightLeftValue = mapLimit(analogRead(RL_JOYSTICK) - RL_OFFSET,RL_MIN,RL_MAX - RL_OFFSET,0,ESC_MAX - ESC_OFFSET);
  int frontBackValue = mapLimit(analogRead(FB_JOYSTICK) - FB_OFFSET,FB_MIN,FB_MAX - FB_OFFSET,0,ESC_MAX - ESC_OFFSET);
  int potValue = analogRead(POT);
  int toggleValue = digitalRead(toggle);

  //throttle
  payload[0] = throttleValue >> 8 & 0xff;
  payload[1] = throttleValue & 0xff;
  //yaw
  payload[2] = yawValue >> 8 & 0xff;
  payload[3] = yawValue & 0xff;
  //RL
  payload[4] = rightLeftValue >> 8 & 0xff;
  payload[5] = rightLeftValue & 0xff;
  //FB
  payload[6] = frontBackValue >> 8 & 0xff;
  payload[7] = frontBackValue & 0xff;
  //Pot
  payload[8] = potValue >> 8 & 0xff;
  payload[9] = potValue & 0xff;
  //toggle
  payload[10] = (byte) toggleValue;

  //wake XBee
  //digitalWrite(WAKE_PIN,LOW);
  xbee.send(packet);
   if(xbee.readPacket(500)) {
     if(xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
       xbee.getResponse().getZBTxStatusResponse(txStatus);
       if(txStatus.getDeliveryStatus() != SUCCESS) {
         //the remote XBee didn't ACK
         tone(SPEAKER_PIN,NOTE_C4,100);
       }
     }
   } else {
     //error or something
     tone(SPEAKER_PIN,NOTE_E4);
     noTone(SPEAKER_PIN);
     tone(SPEAKER_PIN,NOTE_E4,50);
   }

    //sleep XBee
    //digitalWrite(WAKE_PIN,HIGH);
    delay(100);
}

int mapLimit(int val, int fromLow, int fromHigh, int toLow, int toHigh) {
  int result = map(val,fromLow,fromHigh,toLow,toHigh);
  if(result > toHigh) {
    result = toHigh;
  } else if(result < -toHigh) {
    result = -toHigh;
  }
  return result;
}

```

# Answer
> 2 votes
10 bytes in `payload` were being used, but `payload` was declared using `int payload[10]` when it should have been `int payload[11]`.

# Answer
> 0 votes
Just a guess, but maybe your Arduino power supply isn't juicy enough. I had the same problem running 2 modules + LCD on a Arduino powered via USB. Try to find a power supply somewhere between 9 and 12V (from an old router, modem or cellphone you don't need anymore), and use it to power your Arduino instead of relying on the the USB port alone.

http://playground.arduino.cc/Learning/WhatAdapter

---
Tags: arduino-uno, serial, xbee, softwareserial, uart
---


title: Arduino Start en Stop

text:
# Question
Title: Arduino Start en Stop
Is there a way to set a time for instance 8.00 PM to make the arduino-uno start or stop at that time?

# Answer
> 3 votes
Really stop Arduino is possible, it's called sleep mode, but the UNO is designed so badly with respect to power consumption that you may as well keep it running.

To have it done something at a specific time you could connect a real time clock (RTC) breakout board (SparkFun has a couple). Use a 1 second timer interrupt to read the clock and compare it with (a table of) times where you want things done. A table could hold the time, an output (e.g. for a relay) and the new status (on or off). If you have just a couple of those you can store them in the RTC's battery-backed up RAM.

**edit**
You can use your PC's time, all the hardware you need is the USB cable. On the PC you run a program that sends the current time to the Arduino. (There are Processing examples of how to communicate with the Arduino on the Net.)

Note that without an RTC your PC will have to be on all the time and connected to the Arduino. You could use the PC just to sync the Arduino's clock and keep time yourself, but the clock of the Arduino is not very accurate.

Getting the time from the Internet is also possible, but then you'll need a Wifi or Ethernet shield to make the connection.

---
Tags: arduino-uno, timers
---


title: Connecting hardware to the Arduino

text:
# Question
Title: Connecting hardware to the Arduino
I'm using an Arduino Due with various sensors. At the moment, I'm using the majority of the pins along the width (the double width pins). I want to make the setup more permanent, however I can't seem to find any ribbon cables with 36-conductors. What do you use for long term connections on the Due, especially if you occasionally need to unplug all the connections? Would a 40-pin ribbon cable work as they're easy to come by.

Thanks

# Answer
I have used 40 pin cables for this purpose, specifically, IDE cables (beware: on high speed, "80 conductor" cables, but still with 40 pin connectors, some pins are permanently connected, to indicate to to the controller that this is a high speed cable!). The connectors are cheap, the cables are free if you ask around (probably less so now). In my case, I connected two extra-large 7-segment displays, and it worked great. More pins than you rarely hurts. In my case, it was especially useful since I needed some pins at the top, and some pins at the bottom of the display; my ide cable had three connectors (motherboard & two drives); I used the top row on one ide connector to the top of of my displays, and the bottom row of pins on the other connector to the bottom of the displays.
> 1 votes

# Answer
You can also make your own IDC ribbon cables pretty easily. A 36-pin cable might be pretty hard to find a connector for, but you could use a 20-pin and a 16-pin side by side.

Have a look at Kobicon 164-9008-E and Kobicon 164-9001-E.

You can get creative and mix and match different pin counts, depending on your project. Buy a few meters of 40-conductor .05" pitch ribbon cable, and you can peel off the 4 outermost conductors to make it 36-conductor, as well as separating the end of the cable into your connector groups.
> 0 votes

# Answer
Take a look at these jumper wires. http://www.amazon.com/gp/aw/d/B00M5WLZDW/ref=mp\_s\_a\_1\_6?qid=1431346007&sr=8-6&pi=AC\_SX110\_SY165\_QL70 they are really great for debugging as well as more permanent solutions.

If you are looking to build more than 5 go with some of the other posted answers
> 0 votes

---
Tags: arduino-due, hardware
---


title: Passing VAL(0-179) to OLED

text:
# Question
Title: Passing VAL(0-179) to OLED
I´m using Spark Fun Micro Pro board 5V: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

and to that i´ve hooked a true color OLED from digole: http://www.digole.com/index.php?productID=859

I manage to get my VAL from my potentiometer on screen. But when I exceeds val "10", and then go back to lets say "9", the zero from "10" is still there. It looks like: "90" instead of "9". The problem is of course that the second (and third) number don't go away.. Im sure there is a simple way of doing this but I can't get my head around it.. I´ve tried using clearScreen but that function makes the OLED blink in a unpleasant way every time it clears... Hope you get my question, english isn't my native language, as u maybe can tell =) Thanks

```
void loop()
{
  val = analogRead(potpin);        // reads the value of the     potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 179);  // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val)  sets the servo position according to the scaled     value
  mydisp.clearScreen();
  mydisp.setPrintPos(9, 6);
  mydisp.print(val);

  delay(200);  // waits for the servo to get there
 // mydisp.clearScreen();

}

```

# Answer
Instead of printing "10" or "9" etc, print "10 " or "9 ". Add an extra space at the end of what you print which overwrites the character that was there before.

```
mydisp.print(val);
mydisp.print("  ");

```

I used 2 spaces there, in case you go from 3 digits straight to 1.

Another method is to "format" the number using sprintf:

```
char temp[4];
sprintf(temp, "%3d", val);
mydisp.print(temp);

```
> 0 votes

---
Tags: led
---


# Question
Title: Serial device file no longer shows up in /dev/ after working fine for months
I am using an Arduino MEGA connected to my Linux workstation via USB. I have been using this setup for several months with no issues.

A few days ago, **the usual serial device file (`/dev/ttyACM0`) stopped showing up when I plug in the device**)

* Haven't re-flashed recently.
* Unable to reflash.
* Removing the devices only shield does not do anything.
* Have not changed my physical setup recently.
* Connector cable is confirmed working with a different device.

Is this a case of bad hardware, or is there a possible fix other than buying a new device?

**`dmesg` results**: None (cleared buffer and re-ran dmesg after plugging / unplugging device) **usb-devices**:

```
T:  Bus=01 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1a.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1d.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=02 Prnt=02 Port=03 Cnt=01 Dev#=  3 Spd=480 MxCh= 0
D:  Ver= 2.00 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1bcf ProdID=2805 Rev=20.15
S:  Manufacturer=6047B0021601A0218M7NB
S:  Product=HP HD Webcam [Fixed]
C:  #Ifs= 2 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=0e(video) Sub=01 Prot=00 Driver=uvcvideo
I:  If#= 1 Alt= 0 #EPs= 0 Cls=0e(video) Sub=02 Prot=00 Driver=uvcvideo

T:  Bus=02 Lev=02 Prnt=02 Port=05 Cnt=02 Dev#=  4 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=e0(wlcon) Sub=01 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=0bda ProdID=0001 Rev=68.17
S:  Product=CSR BS8510
C:  #Ifs= 2 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
I:  If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb

T:  Bus=03 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=04 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=5000 MxCh= 2
D:  Ver= 3.00 Cls=09(hub  ) Sub=00 Prot=03 MxPS= 9 #Cfgs=  1
P:  Vendor=1d6b ProdID=0003 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

```

**ls-usb**:

```
Bus 002 Device 004: ID 0bda:0001 Realtek Semiconductor Corp.
Bus 002 Device 003: ID 1bcf:2805 Sunplus Innovation Technology Inc.
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

```

# Answer
The fact that `dmesg` gives you nothing at all is the most telling fact. The there was a communication problem, or the firmware had messed up on the USB interface chip, then you'd expect something to show up - even if it was something along the lines of "device not accepting address 8: -71"

We can ignore the main ATMega2560 chip since that has no bearing on the USB interface. Instead we're interested in the ATMega16U2 (or whatever is on your board version).

So some things you need to confirm by probing around on the board with a multimeter, or better still, an oscilloscope:

1. Check that there is power to the board through the USB.
2. Check that there is power both sides of the green (or brown-ish if you have a clone) poly-fuse near the USB socket
3. If you have an oscilloscope, switch the probe to 10x and look for oscillations on the crystal's pins.
4. Grab the datasheet for your ATMega*xx*U2 chip and get the pinout. Check that there is power on the pins there should be power on.
5. Check that the RESET pin of the ATMega*xx*U2 chip is HIGH.

If you have a hardware programmer, or another Arduino you can use as a hardware programmer, connect it to the 2x3 header (you may need to populate it first) and try get it to identify the chip ID. Try to re-flash the USB interface firmware.

Another thing to check is the USB socket itself. Those big chunky USB sockets look strong, but they're actually quite flimsy inside. The metal leaves that the plug presses against can bend with time and not make a good contact. Using a fine needle try lifting them up slightly so they make better contact with the cable. I think Arduino are the only people that still use them in an active product these days ;)
> 1 votes

---
Tags: serial, arduino-mega, shields
---


# Question
Title: Linkit One- Connect rc522 rfid with linkit one
Linkit One is a board based in Arduino by mediatek. I am trying to connect a rfid reader with it link I am trying from past 3 days to get it working, checked my code wiring but nothing seems to get it working. The reader is perfectly working because i tested it on raspberryPi and it worked flawlessly. In my linkit board i am able to detect the reader but card is not getting scanned. I am using this library GitHub and my code is fairly simple one

```
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9   //
#define SS_PIN  10  //
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
void ShowReaderDetails() {
// Get the MFRC522 software version
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
Serial.print(F("MFRC522 Software Version: 0x"));
Serial.print(v, HEX);
if (v == 0x91)
Serial.print(F(" = v1.0"));
else if (v == 0x92)
Serial.print(F(" = v2.0"));
else
Serial.print(F(" (unknown)"));
Serial.println("");
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF)) {
Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
}
}

```

This program in theory should detet reader and when card is scanned should display the UID.

I am getting msg that my card is v2, so its detecting the reader but not reading the card.

# Answer
> 0 votes
This link worked for me:

http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid\_en\_ino.txt

Found it in a forum:

> Please have a look at this ino file http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid\_en\_ino.txt this ino file works with my reader but this rc522 library does not https://github.com/miguelbalboa/rfid I want to know the difference as i was not able to spot any, one works and another does not.
>
> Please let me know if there is any editing to be done so to get https://github.com/miguelbalboa/rfid this working

# Answer
> -1 votes
my friend, i have some problems with version 2.0 trying to read some cards. i think that the problem when u cant read the card is this version . i have both version 1.0 and 2.0, version 1.0 detect all card type, and 2.0 some not. for me is a big problem because, here in argentina i only found version 2.0. maybe change on library some.

---
Tags: rfid
---


# Question
Title: Programming ATmega2560 processor with FTDI instead of ATmega32
Has anyone tried to program an ATmega2560 with an FTDI chip as is done in the Arduino Nano (this is for a custom design).

Will it work?

# Answer
> 2 votes
In fact, the basic Arduino Mega (with the ATmega 1280) **utilizes an FT232RL**, so yes, it will work if you connect it correctly.

It is only the newer Mega2560 (along with the similar-generation Uno, etc) which utilizes an ATmega16u2 or similar as the USB bridge.

Generally speaking, the bootloader doesn't care - you should be able to use either target chip with either USB bridge (or others).

# Answer
> 0 votes
The Arduino Mega already has a built-in USB-UART bridge, so there's no need for a separate chip.

The ATmega1280 on the other hand is just a bare AVR MCU and does require either a separate USB-UART bridge for serial programming (provided it is programmed with an appropriate bootloader) or an ISP programmer for ISP programming.

---
Tags: arduino-nano, ftdi, atmega2560
---


title: Using Arduino command line on windows

text:
# Question
Title: Using Arduino command line on windows
I have an nmake file;

```
  srcpath = ..\pilot
  cmdline =  "C:\Program Files (x86)\Arduino\arduino.exe"
  cmdflags = --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files
  prefs = --pref sketchbook.path=$(srcpath) --pref build.path=build
  deps = $(srcpath)\pilot.ino $(srcpath)\commands.h $(srcpath)\publish.h $(srcpath)\motor.h

  pilot.hex :$(deps)
    type $(srcpath)\pilot.ino
    $(cmdline) $(cmdflags) $(prefs) $(srcpath)\pilot.ino

```

The file types out fine, but Arduino returns an error;

"failed to open sketch ..\pilot\pilot.ino"

I am setting --pref sketchbook.path=$(srcpath), but I have tried with and without (and many variations of both) and get the same error.

This is the command that is currently being invoked, and looks correct to me;

```
"C:\Program Files (x86)\Arduino\arduino.exe" --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files --pref sketchbook.path=..\pilot --pref build.path=build ..\pilot\pilot.ino

```

Any ideas?

# Answer
> 0 votes
```
srcPath = C:\Users\mikep\Documents\MWPRobotics\Pilot\Pilot
bldPath = $(srcPath)\build
arduinoCmd = "C:\Program Files (x86)\Arduino\arduino.exe"
arduinoFlags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --preferences-file $(bldPath)\pilotPrefs.txt
prefs = --pref sketchbook.path=$(srcPath) --pref build.path=$(bldPath)

deps = $(srcPath)\Pilot.ino $(srcPath)\commands.h $(srcPath)\publish.h  $(srcPath)\motor.h

pilot.hex : $(deps)
#   type $(srcPath)\Pilot.ino
    $(arduinoCmd) $(arduinoFlags) $(prefs) $(srcPath)\Pilot.ino

```

Apparently it is really picky about absolute full paths (contrary to the comments that say it is relative)

---
Tags: arduino-ide
---


# Question
Title: connection between two ARDUINO with xbee
I have a setup where two XBEES modules are talking to each other, both using XBEE shields, one attached to an UNO ARDUINO and the other a MEGA ARDUINO. One XBEE sends the data and the other receives it and switch on or off a LED. The problem is the receiver one don't work. This is the sender code

```
int led = 13;
const int bouton = 2; String inputString;
void setup() {
pinMode(led, OUTPUT);
Serial1.begin(9600);
Serial.begin(9600);
digitalWrite(led, LOW);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}
if (inputString.length() >0) {
Serial.println(inputString);
Serial1.println(inputString);
inputString="";
}
}

```

This the receiver one

```
int led = 13;
String inputString;
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}

if (inputString.length() >0) {
Serial.println(inputString);
if (inputString == "on"){
digitalWrite(led,HIGH);
Serial.println("LED ON");
}

if (inputString == "off"){
digitalWrite(led,LOW);
   Serial.println("LED OFF");
}
inputString="";
}
}

```

I get on the serial monitor of ARDUINO UNO what i wrote in the serial monitor of ARDUINO MEGA but the LED don't switch on or off :/

# Answer
> 0 votes
Probably you are getting a new character/carrier return (\n or \n\r) in your receivers' string, that is why it won't match exactly "on" or "off", it will be "on\n", "on\r\n" or similar.

---
Tags: xbee
---


# Question
Title: How to create a serial communication connection between Cubieboard running Android and Arduino
I am connecting my Arduino to my Cubieboard that is running Android.

I tested this originally with my android tablet and USB cable. This worked successfully for the most part using the firmata kit but I don't want to use firmata.

I want a basic function library written in Java for use with Unity (eg Library Tutorial Video) to connect to the Arduino via the USB serial port connection much like a connection with my Windows computer.

**I'd like basic command functions like:**

* Connect / Open
* Write
* Read
* Flush
* Close

I was thinking maybe of using this library here but I am unsure how to go about this. I know similar discussion have already taken place on the forum claiming it may not be possible, but it is very clear that it is. It has been done many times. All I need to do is send strings with serial after finding the Arduino's COM port and reading from the serial.

# Answer
Using the library you linked should be a simple case of downloading the library's jar file from https://github.com/mik3y/usb-serial-for-android/releases and adding it as a reference/library/dependency (I forget what eclipse calls them) in your eclipse project.

Then of course providing you connect with the right baud rates and so on it should work.
> 2 votes

# Answer
Totally insane thought here but.....

Have you tried writing a chrome App to talk to your Arduino?

I did it on the Mac - had chrome monitoring things happening on the network and sending Serial Commands to the Arduino over USB.

You can find samples in the Chrome samples / docs

https://developer.chrome.com/apps/serial
> 0 votes

---
Tags: serial, android
---


# Question
Title: Can the Arduino Due be used as a serial to USB converter?
The Arduino due exclusively runs on 3.3V, so I am wondering if this can be used as a USB to serial converter just like the Arduino Uno could, or do you need to do level shifting?? Will I ruin the board if I just hook up RX and TX to a 5v device?

# Answer
> 1 votes
Yes it will work as a USB to serial device, however the serial will be at 3.3V not 5V. It'll still be serial though.

For it to send data to a 5V device, depending on the device, it might work. 3.3V is often around the "high" threshold for an input pin on a 5V device, but check the datasheet for the 5V device to be sure.

For receiving data the 5V will be above the 3.3V supply voltage of the main SAM3X chip, so should be avoided. As with most Atmel datasheets, actually finding the information you want is almost impossible, and I haven't found if there is a maximum "over voltage input current" or not, so to be on the safe side a full level shifting voltage divider should be used on the RX pin.

---
Tags: usb, serial, ftdi
---


# Question
Title: Simple compiler design help: Variable length arrays in Arduino?
I'm trying to write a simple compiler in the Arduino language that I am making up for my lab. The compiler will have to be able to turn a string like this:

```
"do command_one 3 times"

```

into a data structure that represents this:

```
<command_one>, <command_one>, <command_one>

```

it should also be able to turn something more complicated like this:

```
"do do c_one do c_two 2 times 2 times c_thr 2 times"

```

into a data structure that represents this:

```
<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

```

Another function will then read the commands out one by one.

These examples show all of the functionality that I would want from the compiler.

I'm having design issues for the compiler that I want to create. Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands. However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in Arduino need to be initialized with a length, this could be a problem.

I am not fluent in Arduino so I am hoping that an Arduino whiz can show me a quick solution. I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.

You will also notice that I posted the same question in the C++ stackexchange. I am trying to write the same code for an Arduino and in C++. I know that Arduino code is based on C++, if the answer is the same in Arduino as it is in C++ that would be very helpful.

# Answer
> 1 votes
You may have more luck investigating standard C ways of dealing with this issue, instead of the common C++ methods.

Although it is typically not advised, you can use malloc and free on the Arduino. This allows you to dynamically use memory. I would provide a more detailed code example than below but when using dynamic memory it can be hard to troubleshoot what is going on without the use of a library to simplify the process. I would strongly advise doing a little study and understanding both dynamic memory management, and the repercussions of doing so on the Arduino platform. A solid foundation in this will pay off tenfold in time saved when debugging.

Note that you should check each time that you call malloc that it is successful

These resources might help:

Simple Example:

```
// Make a pointer to your array
someType *A;

// The size of your array, may be changed programmatically.
int arraySize = 5;

// Reserve memory for your array.
A = malloc(arraySize * sizeof(someType));

// Use Array
A[0] = someData;

// Release A's memory when complete.
free(A);

```

# Answer
> 2 votes
1. The Arduino IDE features nearly full C++ *language* support (at least for C++03 features).
2. *library* support is limited, but any standard component you need, you should be able to get an open source implementation that compiles.
3. That said, you have **2K** of RAM to work with on an Arduino, so the kind of C++ code you would write for a general purpose computer just won’t get you very far.
4. I could be wrong, but I very much doubt there are full Python implementations for Arduino.

**Edit:** Thanks to Mr. Penguin for pointing out that we’re dealing with an Arduino Due, not an Uno (I had overlooked the OP’s tag). 96K of memory is actually a decent amount to play with, so grab a library implementation like this one and use the C++ techniques you wish to use.

# Answer
> 2 votes
You question isn't totally clear to me, so this is just a pile of advice:

* I think that you *might* be looking for a `run()` type of command, where you can run any function in code. However, since C++ is a *compiled* language, this is not possible. You can only do this in scripting languages.
* Besides that, you want a variable length array? I haven't been able to confirm that this works with Arduino, but I know in standard C++ it is called *dynamic memory allocation* and you can do this with a pointer.
* As for the string to store your data, where you're heading is wrong if you care about efficiency. I'd go with an array of integers (`unsigned int myData[2] = {1, 290};`) since you can store a *lot* more data in two bytes than you could typing out the function names.

For the "multiple run" function of your language, a simple for loop might work better to save space:

```
for(int x = 5; x <3; x++) {
  //Code here
}

```

---

Another thing you might want to do is store this "code" on a SD card encoded in two characters to yield a number like this:

```
byte valOne = SD.read();
byte valTwo = SD.read();
int outputVal = (valOne << 8) + valTwo;

```

This would solve the whole variable array crisis in the first place.

*End of unorganized thoughts...*

---
Tags: arduino-due, compile
---


title: Arduino AD-converter tolerance

text:
# Question
Title: Arduino AD-converter tolerance
I created a quite simple Arduino sketch:

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

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);

  float voltage = sensorValue * (5 / 1023.0);
  Serial.println(voltage);

  delay(1000);
}

```

I use the following circuit:

My multimeter measures **3.31 V**, between the pin 3V3 and GND.

I get a *sensorValue* of **730** and a calculated *voltage* of **3.57 V**. This is 8% higher that 3.3V. What is the tolerance by the AD-converter?

# Answer
The absolute accuracy of the ADC in the ATmega328P when its clock is within its optimal range is given in the datasheet as 2LSB. This means that the actual value could be anywhere between 728 and 732.

Of course this depends on the accuracy of VCC, since it is being used as the ADC reference. This is why supply voltage measurements should be performed using the internal bandgap voltage instead.
> 1 votes

---
Tags: c++, analogread, hardware, analog-sampling
---


# Question
Title: Reading/writing to Arduino GPIO pins from raw C code
I'm interested in writing a C program *without* the Arduino IDE and related libraries and am trying to figure out how I can access the GPIO pins for read and write.

My *assumption* is that the GPIO pins are - at the hardware layer - just memory addresses, and so if I know what their address is I can send/receive data to and from them.

* For writing to the digital pins, do I just send an `int` with a value of `0` or `1` to the pin's address? If so, what might that code look like? Can I then assume I could poll that address for a value, which would be either `0` or `1`?
* Can I assume the same for analog pins, but instead of binary values, I'd get an integral value between `0` and `1023`?

And if I'm way off here, and pins are *not* accessed via memory addresses, then how?

Again, the solution I'm looking for wouldn't involve Arduino software, just the Arduino hardware (an AVR or ARM MCU). Bonus points for C pseudo-code examples! Thanks in advance!

# Answer
In theses cases you are right, using register address is the way to read/write data from/to digital pins. In the case you use analog input, the process is similar but you have to follow some procedures before getting the value of the data.

**GPIO REGISTERS**

For AVR micro-controllers these registers are: DDRn – Data Direction Register PORTn – Port Output data Register PINn – Port Input Register n- Indicates the port name i.e. A, B, C & D If you have arduino board and want to use these pins, look for mapping pictures about arduino and avr pins.

The following is an example from the Arduino website.

DDRD is the direction register for Port D (Arduino digital pins 0-7). The bits in this register control whether the pins in PORTD are configured as inputs or outputs so, for example:

```
DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin 0 as input
DDRD = DDRD | B11111100; // this is safer as it sets pins 2 to 7 as outputs
                         // without changing the value of pins 0 & 1, which are RX & TX

```

See the bitwise operators reference pages and The Bitmath Tutorial in the Playground

PORTD is the register for the state of the outputs. For example;

```
PORTD = B10101000; // sets digital pins 7,5,3 HIGH

```

You will only see 5 volts on these pins however if the pins have been set as outputs either by using the `DDRD` register directly or by using the `pinMode()` function.

**For analog read**

You just need to include the headers and start using the registers. They hold the equivalent hexadecimal values for your microcontroller. And the procedure is described in the datasheet. All you have to do is to translate it to code.

```
// this code scans ADC1 for an analog signal upon request, using 8Mhz processor clock

#include <avr/io.h>
#include <stdint.h>       // needed for uint8_t

int ADCsingleREAD(uint8_t adctouse)
{
    int ADCval;

    ADMUX = adctouse;        // use #1 ADC
    ADMUX |= (1 << REFS0);   // use AVcc as the reference
    ADMUX &= ~(1 << ADLAR);  // clear for 10 bit resolution

    // 128 prescale for 8Mhz
    ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

    ADCSRA |= (1 << ADEN);    // Enable the ADC
    ADCSRA |= (1 << ADSC);    // Start the ADC conversion

    while(ADCSRA & (1 << ADSC)); // waits for the ADC to finish

    ADCval = ADCL;
    ADCval = (ADCH << 8) + ADCval; // ADCH is read so ADC can be updated again

    return ADCval;
}

int main(void)
{
    int ADCvalue;

    while (1)
    {
        ADCvalue = ADCsingleREAD(1);
        // ADCvalue now contains an 10bit ADC read
    }
}

```

For more information about analog read, see this.
> 3 votes

---
Tags: pins, c
---


# Question
Title: How to power Arduino only when light is on
I want Arduino to conserve energy and turn it on automatically only when the lights is on. Can I use some kind of light sensor and put it in between power supply and arduino somehow? Ideally light sensor will power from the same power source, if possible. I'm not an electrical engineer - just enthusiast, so please explain your idea as detailed as possible. Many thanks!

# Answer
For a chip like the basic Arduino's ATmega, you don't really "turn it off" to save power, rather you put it into a low-power sleep mode.

First, make sure you aren't consuming more power than needed normally. Make sure unused peripherals like the ADC are off. If your program spends most of its time waiting for external events, try reducing the clock speed either with a slower crystal or the 8 MHz oscillator, and with the clock prescale register.

Next, implement a sleep cycle. Turn off everything you can, and program a hardware timer to generate an interrupt at some point in the future. Enter sleep mode, so the processor stops and only the logic in the counter is still running. When the interrupt fires, the ATmega CPU will wake up and continue operating, at which point you enable the ADC, use a GPIO to drive your light sensor, and take a reading from it. If it doesn't meet your conditions, turn it all off again and go back to sleep until it's worth checking again.

In low power design you must be very careful of things outside the processor stealing power. Watch out for any resistors pulling signals, if the signals are actively drive against the resistor. LEDs are an obvious issue. Also watch out for voltage regulators which may have high quiescent current. And finally beware of peripheral chips - a stock Arduino has an entire second processor sitting there in the USB-serial adapter wasting power. So you will either need to customize the firmware of that to shut down too, or else use a simpler board that doesn't have one (don't just hold it in hardware reset, as the reset pin has an internal pullup which will then consume power).
> 1 votes

# Answer
If it's OK for it go off (not just to sleep) when the light is off, power it from the lighting circuit. These two parts will do it without messing with the electrics:

The light socket adapter with two outlets is a hardware-store part, probably about USD$3, and the USB charger makes a compact and useful Arduino 5v power supply, USD$6 at Amazon right now. (Apple's little USB power cube might fit better but is more expensive). I use the Nokias for Arduino power supplies and their no-load voltage is just barely over 5v. If you substitute a different one, that would be a worthwhile test to make before you connect it to your Arduino.
> 0 votes

# Answer
Conserve energy?
There are many ways to conserve energy in an Arduino(e.g. Use a USB adapter that does not waste energy as heat, instead of using Battery power)
But if you want to save energy by only switching on the Arduino when light is on, it depends on the intensity of the light.
If it is supposed to switch on only during the day, use Solar Panels to power the Arduino.
Else, use an LDR.
> 0 votes

# Answer
You may keep your Arduino powered, but have it sleep when the lights are off. During sleep, it would periodically awake to check the light level: if it's low enough, it goes back to sleep, otherwise it resumes its work. Here are the detailed steps:

1. Try to find a power-efficient Arduino or clone (no ON LED, no USB bridge...) or learn how to build and program a barebones one. If you can live with a 8 MHz clock, a bare ATmega, or even ATtiny, may be a good option.
2. Get an LDR (light-dependent resistor) and an ohmmeter.
3. Measure the resistance of the LDR at the relevant light levels, and decide for a value of resistance that will serve as a threshold for switching on and off. I will call this `LDR_THRESHOLD_RES` in the code.
4. Get a plain resistor with a value close to the previous threshold (within a factor 10 should be OK), but not lower than 1 kΩ. This will be your "pullup" resistor, and its resistance will be `LDR_PULLUP_RES`.
5. Decide how often the program will check for the lights being turned on. This delay, in milliseconds, will be `LDR_CHECK_DELAY`.
6. Assign both a digital and an analog pin for measuring the LDR. These will be `LDR_DRIVE_PIN` and `LDR_SENSE_PIN` respectively.
7. Connect the LDR between `LDR_SENSE_PIN` and ground; connect the pullup resistor between `LDR_SENSE_PIN` and `LDR_DRIVE_PIN`.
8. Update the code below (the first 5 #defines) and include it in your sketch.
9. Add `pinMode(LDR_DRIVE_PIN, OUTPUT);` to your `setup()`.
10. Call `wait_for_lights()` inside `loop()`, wherever you want your program to pause if the lights are off.

```
#include <avr/sleep.h>

#define LDR_THRESHOLD_RES 25e3  // 25 kOhm
#define LDR_PULLUP_RES    10e3  // 10 kOhm
#define LDR_CHECK_DELAY    200  // 200 ms
#define LDR_DRIVE_PIN        2  // digital 2
#define LDR_SENSE_PIN        0  // analog 0

#define LDR_THRESHOLD_RATIO (1.0*LDR_PULLUP_RES/LDR_THRESHOLD_RES)
#define LDR_THRESHOLD_READING ((int)(1024 / (1 + LDR_THRESHOLD_RATIO)))

/* Sleep until the light is on. */
void wait_for_lights() {
    for (;;) {
        // Sense light level.
        digitalWrite(LDR_DRIVE_PIN, HIGH);
        int reading = analogRead(LDR_SENSE_PIN);
        digitalWrite(LDR_DRIVE_PIN, LOW);

        // Low reading means the light is on.
        if (reading < LDR_THRESHOLD_READING) return;

        // Wait for a few milliseconds.
        unsigned long start = millis();
        do sleep_mode();
        while (millis() - start < LDR_CHECK_DELAY);
    }
}

```

This should already get your power consumption pretty low. If you want to save further power, you will likely have to dig into your microcontroller's datasheet. You can try the various `power_*_disable()` functions and turn off all the peripherals you do not need. You can also try a deeper sleep mode than the default one (IDLE), but then your `millis()` clock will freeze during sleep, and you will have to set up some wake up source if you do not want to sleep forever. The watchdog timer is a good option.
> 0 votes

---
Tags: sensors, power, battery
---


# Question
Title: Custom Bootloader on Atmega328p - PU - 28 pin DIP
I am experimenting with low-power wireless arduino modules. For that, I needed 3V powered arduino so that I can do away with voltage regulators which eat up a lot of battery juice.

I am using 28 pin Atmega328p-PU dip IC with 8 MHz external crystal oscillator. Just for trying, I dumped the arduino pro mini 3.3V 8 MHz bootloader into it and it was a success. Everything is working as expected. However, I realized that SMD package which is being used in pro mini has 8 ADC pins compared to 6 in the DIP version.

Should I be worried about it?

Second feasible option is modifying the Arduino UNO board definition to use 8 MHz clock source as compared to 16 MHz and leave everything else same. Do you think this will serve my purpose?

# Answer
> 2 votes
The Atmega328p has 8 analog inputs. Some packages (such as the DIP) don't have enough pins to bring all of them out, but they are in there. The SMD package brings all of them out, but it apparently the Pro Mini does not pick up two of them. The net result is the same - 6 useable and 2 unusable analog inputs.

---
Tags: arduino-uno, bootloader, arduino-pro-mini
---


# Question
Title: Wifi REST API GET call - how to concatenate and pass URL parameters?
I'm not too familiar with the Arduino C++ language, but I would like to get this native code to work.

In curl this works:

> curl "http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&outputMode=json&apikey=my-apikey"^C

So I am trying to use a WiFi client for the same request but it seems the passing and parsing of the URL parameters is causing a problem.

```
sprintf(request,"/calls/text/TextGetTextSentiment?apikey=%s&text=%s&outputMode=%s","31adba6dfc3a879b88762f50efc9f892bd573207", "i+feel+great", "json");
Serial.println(request);

```

When I print the request, everything after the & gets truncated.

```
  char serverName[] = "access.alchemyapi.com";
  if(client.connect(serverName,port) == 1)
  {
    sprintf(outBuf,"GET %s HTTP/1.1",page);
    client.println(outBuf);
    sprintf(outBuf,"Host: %s",serverName);
    client.println(outBuf);
    client.println(F("Connection: close\r\n"));
  }

```

This works (HTTP status 200, though with missing parameters error from the API service) if I only pass in 1 parameter.

# Answer
> 0 votes
Concatenating the string data in memory before sending it shouldn't be necessary. Instead, you should just be able to use `client.print()` (or equivalent) to output each part of the request in sequence. For example:

```
client.print("GET ");
client.print(page);
client.print(" HTTP/1.1\r\n");

client.print("Host: ");
client.print(serverName);
client.print("\r\n");

// etc.

```

That should let you output any combination of HTTP headers you need.

---
Tags: wifi
---


title: Big endian or little endian?

text:
# Question
Title: Big endian or little endian?
I need to pass a 16-bit long address (for an external EEPROM) to a function (`twi_writeTo`) in a buffer. I am currently doing this

```
byte buffer[2];
buffer[0] = (byte)(eeaddress >> 8);
buffer[1] = (byte)(eeaddress & 0xFF);

```

where `eeaddress` is an `unsigned int` with the address.

I then do

```
int8_t ret = twi_writeTo(eeprom_i2c_addr, buffer, 2, 1);

```

Before I tried

```
int8_t ret = twi_writeTo(eeprom_i2c_addr, (uint8_t*)&eeaddress, 2, 1);

```

but that returns garbage. Probably the byte order is swapped. Is that the case? And if so, is there a better way than copying the two bytes to a buffer?

# Answer
If it's the byte order that causes a problem that's likely compiler specific and I don't think one can change it. Even if it were possible, changing the global endianness might break libraries that depend on it, so you likely can't escape using a function to swap the variable.

If you know you only need one value at a time you could write something like the following code, with a global buffer (untested but in principle should work (and I know global variables are evil, but should work for an Arduino project)):

```
byte buf[2];

byte* reverse(int val) {
    buf[0] = (byte)(val >> 8);
    but[1] = (byte)val;
    return buf;
}

```

So you could use it like:

```
int8_t ret = twi_writeTo(eeprom_i2c_addr, reverse(eeaddress), 2, 1);

```
> 2 votes

---
Tags: byte-order
---


# Question
Title: Comparing orientation data obtained using gyroscope and accelerometer
Recently, I have been playing around with a gyroscope and accelerometer in the hopes of building a quadcopter. I have plotted some of the data the two sensors and I am noticing that the pitch from the accelerator lags significantly behind the gyroscopic pitch.

From some research, I understand that these two are not going to equivalent values due to the mechanisms of measurement, however is it common to have such large discrepancies (i.e a difference of 20 degrees or higher) between the two sensors or is this an issue with my conversion?

I have listed the graph and source code here. Any help would be appreciated!

Sincerely, Anand

# Answer
Normally the values from gyroscope will drift overtime. It is natural and depends on the parameters of your code. It could drift a few degrees per seconds and the data will be far way from the accelerometer in a few seconds.

I have seen that you have applied the complementary filter, so you don't need to worry about the single value from the gyros since you combine them with the acceleromter and everything seems fine.

The gyros are good for short time response, in long time response the values get pretty bad as they drift a lot.

On the other hand, accelerometers are good for long time response, since short time response is noisy because of gravitational influence.

That's why you need a filter to combine them.

Wrapping up, it is normal to have this behavior in gyros. If you want to know more about the effect behind this sensor, try this reading.
> 0 votes

---
Tags: arduino-uno, accelerometer, gyroscope
---


# Question
Title: Arduino UNO code ignores variables selectively
This is the first code I wrote for my UNO R3 just to feel out the functions and I've already got some jankiness. Throughout this description I am referring to the **first two if statements** one inside the other one.

I'm trying to increment `i` every time the signal is activated and then `j` is used to create a small space of time where the button being pressed will not increment `i`. My problem is my if statement involving `j` seem to be totally ignored. I've tried multiple configurations of the if statement structure to no avail.

Here is where things get interesting. So upon setting up the serial connection back to my PC to debug this irritating problem and printing out the actual value of `j` (to see why it was triggering my if statement prematurely) it magically fixed the problem. It's like until the program literally acknowledges `j`'s value in the print statement it doesn't exist but if it does it works. Any ideas on this?

Note: the serial monitor in both picture depicts consecutive iterations with the signal activated the entire time.

This picture shows the serial monitor after running with the button pressed but the print statement commented out

This picture shows the serial monitor at a space where the button was pressed and held (same time frame as image 1) but in this one it increments `i` to 3 and then continues incrementing `j`. How is this happening?

# Answer
Its hard to see you code, but I think I can make a pretty good guess from your description what is going on.

It seems that you are using the time it takes to increment a value as a way to slow down your code. I think you are underestimating the speed of the arduino. The time it takes to count to 200 (if I'm reading your pictures right) is almost instant; However, you then start printing to with serial each time. Once the serial buffer is full, `Serial.print()` will wait until there is room in the buffer to place the new value. This time is still small, but making the code wait for it to pass 200 times will take much longer than just waiting for a number to increment to 200.

I think that having added a print statement is slowing down the code enough that your increment based delay is having a noticable effect. What you should do is use the `void delay(unsigned long milliseconds);` function to cause the code to stop for a bit after it first detects the button has been pressed, and then see if its still pressed afterward. You can also use `delayMicroseconds(unsigned int)` for shorter but more precise timing. Or better yet, use the `unsigned long millis();` function to grab and store the time when the button was activated, and continue polling the current time until the desired delay has been acheived. That way is more code, It allows the code to do something productive while it waits or keep looping.
> 1 votes

# Answer
Yes, and I do appreciate the original answer as it is effective(something just bugs me about losing sensory capability for any amount of time), I just was not really looking for a work around but rather the engineer in me was simply interested in why the code would be responding the way it was. Anyways though I got around to writing my tester and now it's working like a charm. Maybe I was being sloppy before? Obviously I just need to do a bit more testing. I'll post the code just in case anyone is interested in seeing it(also will keep in mind the preference to actual code rather than screen shot in the future) . Thanks for the support!
> 0 votes

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


# Question
Title: Arduino clock needed to print the time a button is pressed while continuing to count the time?
I'm making a clock using an arduino uno and a compatible freetronics screen. So far it can count the time in a 24 hour loop after which it repeats and counts again. The screen had a number of buttons built onto it and I want to get it so that when one of the buttons on the screen is pressed it prints the time that it was pressed on the top line of the screen while continuing to count and print the time on the second line of the screen.

How can I edit my code below to do this when a button is pressed? What sort of command do I need to add?

```
#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
* Clock Variables
*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 0, hours = 8;

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

void setup()
{
  Serial.begin(9600);
    lcd.begin( 16, 2 );

}

void loop()
{
setClock();

/**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 lcd.setCursor ( 0, 1);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);

}

void setClock()
{
currentMillis = millis();
/**
 * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

```

Any help will be greatly appreciated, thanks

# Answer
> 1 votes
Since you will have to deal with *two* different times, I suggest writing a small class for representing those times in broken-down form. This is a reduced version of the classical `strcut tm`. Times are made `Printable` so you can just `print()` them to the LCD. I included an `increment()` method to add one second to this time.

```
class BrokenDownTime : public Printable {
    uint8_t hours;
    uint8_t minutes;
    uint8_t seconds;
public:
    void increment();
    size_t printTo(Print &p) const;
};

/* Increment the time by one second. */
void BrokenDownTime::increment()
{
    if (++seconds >= 60) {
        seconds = 0;
        if (++minutes >= 60) {
            minutes = 0;
            if (++hours >= 24)
                hours = 0;
        }
    }
}

/*
 * Print to anything that inherits from the Print class (Serial,
 * LiquidCrystal, etc.). This makes times `Printable'.
 */
size_t BrokenDownTime::printTo(Print &p) const
{
    p.print(hours/10);
    p.print(hours%10);
    p.write(':');
    p.print(minutes/10);
    p.print(minutes%10);
    p.write(':');
    p.print(seconds/10);
    p.print(seconds%10);
    return 8;  // 8 bytes written
}

```

The main program checks in `loop()` for the button being pressed. When this happens, it saves the current time as `lastPress`. If the button was ever pressed (variable `button_was_pressed`), the recorded time is displayed on the first line:

```
#include <LiquidCrystal.h>

#define BUTTON_ADC_PIN A0

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

/* Detect a press on `left', change the thresholds for other buttons. */
bool buttonPressed()
{
    int reading = analogRead(BUTTON_ADC_PIN);
    return reading > 405 && reading < 605;
}

/* Update `now'. */
void updateTime()
{
    static unsigned long last;
    if (millis() - last >= 1000) {
        now.increment();
        last += 1000;
    }
}

void setup()
{
    lcd.begin(16, 2);
}

void loop()
{
    static BrokenDownTime lastPress;
    static bool button_was_pressed;

    updateTime();

    /* Record the time of the button press. */
    if (buttonPressed()) {
        lastPress = now;
        button_was_pressed = true;
    }

    /* Display the recorded time on the first line. */
    if (button_was_pressed) {
        lcd.setCursor(0, 0);
        lcd.print(lastPress);
    }

    /* Display the current time on the second line. */
    lcd.setCursor(0, 1);
    lcd.print(now);
}

```

I did not test the program, but I hope you get the idea.

# Answer
> 0 votes
use a second variable called TNow and when the button is pressed pass it the value of currentMillis. parse and use this as the value to display. or have misunderstood your question? wondering why you aren't using a time library. such as this if you look on the site here use the time library you can then use *variable name* = now();

# Answer
> 0 votes
You probably want to read the button press on LCD using "read\_LCD\_buttons" function. See an example at: Arduino LCD KeyPad Shield.

So your part of your code would probably be:

```
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5
int lcd_key     = 0;

void loop()
{
 setClock();

 /**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 printValueAtLine(0);

 lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)
 {
   case btnSELECT:
   {
     printValueAtLine(1);
     break;
   }
   case btnRIGHT:
   {
     // code in case other buttons like  btnRIGHT, etc are pressed
     break;
   }
   case btnNONE:
   {
     //do nothing
     break;
   }
 }
}

void printValueAtLine(int line)
{
 lcd.setCursor (1, line);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);
}

```

The code is untested and you may have to make minor corrections to it.

Also, rather than saving values in global variables, you might want to use local ones using libraries suggested by wobbler.

---
Tags: arduino-uno, time
---


title: Arduino Cross Correlation?

text:
# Question
Title: Arduino Cross Correlation?
How can I write lightweight cross correlation code for arduino? I couldnt find any solution. The measurement system contains an ultrasonic sensor and a servo that turns from 45 to 135 degree and measures distance from 4-300 cm. Than i collect data in an array which contains distances with respect to angle. System makes several measurement like this and program finds cross correlation between new and old arrays.

http://www.instructables.com/id/How-To-Make-an-Obstacle-Avoiding-Arduino-Robot/

# Answer
> 4 votes
Given the time scale of the measurements, performance is not an issue. And since you are not computing in real-time, as the samples are being measured, you can apply the definition of cross-correlation as is, and compute it in a double loop. The only difficulty is figuring out that cross-correlation may not be the proper tool for the job... and finding the right one! My assumption is that you want to estimate a rotation angle between the two measurements.

The mathematical definition of cross-correlation assumes infinite arrays. In practice, cross-correlation is often used to locate a short pattern inside a long signal. In this case, the computation is done only for shifts where the pattern completely overlaps the signal. Then the length of the result is

```
length(result) = length(signal) − length(pattern) + 1

```

In your case, since your pattern is a previously measured signal, this would give a single-sample result, which is useless.

You could instead compute the integral for all shifts where there is *any* overlap between the pattern and the signal. This is equivalent to zero-padding the signal. This has the drawback of biasing the result: if your signal and pattern are both featureless (positive constants), you will find a very nice peak at zero shift!

You can remove this bias by subtracting the average from both the signal and the pattern, and correlating (signal − avg(signal)) with (pattern − avg(pattern)). This still carries a bias for “big” features. Imagine for example that, after removing the averages, you have

```
pattern = [  0,   0, −20, +20,   0,   0];
signal  = [−50, +50,   0,   0, −20, +20];

```

You would expect your correlator to find a good match between the \[−20, +20\] of the pattern and the \[−20, +20\] of the signal. The correlation is, however, much better with the \[−50, +50\] of the signal. You may try to alleviate this by computing a normalized cross-correlation instead, but you will at best make both matches equally good.

My suggestion is that you completely forget about correlations and instead think in terms of “goodness of fit”. Correlations are good for finding scaled and shifted copies of a pattern inside a signal. You are looking for *shifted only* copies, with no scaling. Your question should be: if you shift the pattern by some amount, how well does it fit the signal? What amount of shift gives the better fit? The canonical answer to all “goodness of fit” questions is to minimize the RMS difference between the two: you compute the sum

```
S = Σ(signal − shifted(pattern))²

```

Then the RMS difference is

```
RMS(difference) = √(S/N)

```

where *N* is the number of samples involved in the sum. The most likely shift is the one that minimizes this error. In practice, you do not need the square root, you just minimize

```
RMS(difference)² = Σ(signal − shifted(pattern))² / N

```

You can implement this formula as-is, it's completely straightforward. Just beware that *N* depends on the shift, as it's the length of the overlap. And avoid going to very small overlaps (i.e. large shifts).

Now, if you expand the square inside the sum, you may find that, after all, this is not so far from a cross-correlation... And BTW, all this has nothing to do with Arduino.

---
Tags: analogread, signal-processing
---


title: Arduino-uno sending email with Hotmail

text:
# Question
Title: Arduino-uno sending email with Hotmail
I want to get emails read from a Hotmail account using an Arduino Uno. Is there a way to do it with SSL or is there a way to disable SSL?

```
#include <SPI.h>
#include <Ethernet.h>
// Use comments to enable or disable this define for debug messages
#define DEBUG_POP
// Use comments to enable or disable the deleting of the mail
#define ENABLE_DELETE_POP

// The mac address must be an unique number
// A mac generator is used:
//   http://www.miniwebtool.com/mac-address-generator/
byte mac[] = { 0xDE, 0x36, 0x5F, 0x0A, 0x19, 0x83 };
// change network settings to yours
IPAddress ip(192, 168, 1, 117);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// Set the server POP3 address, the port, the user and password.
// The POP3 mail server is something like this:
//     mail.yourdomain.com, pop.yourdomain.com, pop3.yourdomain.com
// Using PROGMEM for these causes a fail when trying to connect and log in.
const char pop_server[] = "pop3.live.com";
const int  pop_port = 995;
const char pop_user[] = "xxxxxx@hotmail.com";
const char pop_pass[] = "xxxxxx";

// The number of milliseconds timeout for parseInt() and find().
// The response time for the Server can still be 10 seconds.
#define POP_TIMEOUT 10
#define POP_TIMEOUT_DEFAULT 1000

EthernetClient client;

void setup()
{
    Serial.begin(9600);
    Serial.println(F("\nArduino POP3 email reader"));

    pinMode(13, OUTPUT);     // the system led is used for testing

    // When the Ethernet Shield is used, there is also a SD card connected
    // to the SPI bus. Disable the SD card with chip select at pin 4.
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    // Start Ethernet. Use only the 'mac' parameter for DHCP
    // Use 'mac' and 'ip' parameters for static IP address.
    //  Ethernet.begin( mac, ip);
    //  Ethernet.begin( mac, ip, gateway, gateway, subnet);
    if (Ethernet.begin(mac) == 0)
    {
        Serial.println("Failed to configure Ethernet using DHCP.");
        // no point in carrying on, so do nothing forevermore:
        while (1);
    }
    Ethernet.begin(mac, ip, gateway, gateway, subnet);
    // print your local IP address.
    Serial.println(F("Ethernet started."));
    Serial.print(F("Local IP = "));
    Serial.println(Ethernet.localIP());

    Serial.println(F("Press 'c' to check mail."));
}

void loop()
{
    // Create a buffer to receive the commands in (that is the Subject of the mail).
    char buffer[32];

    byte inChar = Serial.read();
    if (inChar == 'c')
    {
        // The getEmail gets the text of the mail Subject into the buffer.
        // The valid number of received characters are returned.
        // If the return value is < 0, it is an error.
        int n = getEmail(buffer, sizeof(buffer));

        if (n < 0)
        {
            Serial.print(F("Email POP3 failed, error = "));
            Serial.println(n);
        }
        else
        {
            if (n == 0)
            {
                Serial.println(F("Ready, nothing to do."));
            }
            else
            {
                // 'n' is > 0, a command received.
                Serial.print(F("Email checked, Command = \""));
                Serial.print(buffer);
                Serial.println(F("\""));

                // Check the commands.
                //
                // At this moment, a single command 'L' is used to set system led on or off.
                //    L=1   (set led on)
                //    L=0   (set led off)
                if (buffer[0] == 'L' && buffer[1] == '=')
                {
                    digitalWrite(13, buffer[2] == '0' ? LOW : HIGH);
                }
            }
        }
    }
}

// getEmail
// --------
// Find an email on a mail server, using POP3.
// The Subject should start with "ARDUINO " and the text
// after that is copied into pBuf.
//
// The data in pBuf is only valid if the return value is not an error
// (an error is return value less than zero).
//
int getEmail(char *pBuf, int nBufSize)
{
    // nBytes is the number of bytes that is returned by getEmail.
    int nBytes = 0;

    // Connect to server
    // client.connect returns '1' if okay, or negative number if error.
    //    SUCCESS 1
    //    0     (error, unknown timeout, perhaps an error in the library)
    //    TIMED_OUT -1
    //    INVALID_SERVER -2
    //    TRUNCATED -3
    //    INVALID_RESPONSE -4
    //    -5    (there is no mail server at that IP address and port)
    // The string for the server must be a normal string in sram, no PROGMEM allowed.
    int nError = client.connect(pop_server, pop_port);

    // During testing, a value of zero was sometimes returned.
    // This is not according to the documentation and it is an error.
    // Therefor the non-error value '0' is turned into a negative number to
    // indicate an error.
    if (nError == 0)
        return(-200);

    // Only a value of 1 is okay.
    if (nError != 1)
        return(nError);

#ifdef DEBUG_POP
    Serial.println(F("connected"));
    //Serial.println(nError);
#endif
    // The server should respond with "+OK" and maybe more text after that.
    // Check if "+OK" can be read.
    // The parameter 'true' is to read also everything after the "+OK".
    if (!readOk(true))
        return -102;

#ifdef DEBUG_POP
    Serial.println(F("command USER"));
#endif
    client.print(F("USER "));
    client.println(pop_user);
    if (!readOk(true))
        return -103;

#ifdef DEBUG_POP
    Serial.println(F("command PASS"));
#endif
    client.print(F("PASS "));
    client.println(pop_pass);
    if (!readOk(true))
        return -104;

#ifdef DEBUG_POP
    Serial.println(F("command STAT"));
#endif
    client.println(F("STAT"));
    if (!readOk(false))
        return -105;

    // The whole line was like this: "+OK 3 15343"
    // It means that 3 emails are waiting with a total size of 15343.
    // At this moment, the "+OK" is read, but nothing else.
    // Check if there is a space after "+OK".
    char c = client.read();
    if (c != ' ')
        return -106;

    client.setTimeout(POP_TIMEOUT);       // set timeout lower for parseInt
    // Read the number of emails that are on the server.
    int nMails = client.parseInt();
    client.setTimeout(POP_TIMEOUT_DEFAULT);  // restore timeout to 1 second

    // Read the remaining of the response to STAT.
    readRemaining();

#ifdef DEBUG_POP
    Serial.print(F("Number of emails="));
    Serial.println(nMails);
#endif

    // Test if there are emails waiting.
    if (nMails == 0)
    {
        // No emails, but no error. Set buffer to empty string.
        nBytes = 0;               // the returned value
        pBuf[0] = '\0';           // set empty string
    }
    else if (nMails > 0)
    {
        // emails are waiting.
        // Scan the emails until the first is found with the keyword "ARDUINO " at the
        // beginning of the "Subject: ".

        boolean found_and_ready = false;
        for (int nMailNumber = 1; nMailNumber <= nMails && !found_and_ready; nMailNumber++)
        {
            // The command RETR <x> gets the whole mail.
            // The command TOP <x> <size> gets the header plus 'size' of the body.

#ifdef DEBUG_POP
            Serial.print(F("command TOP "));
            Serial.print(nMailNumber);
            Serial.println(F(" 0"));
#endif
            client.print(F("TOP "));
            client.print(nMailNumber);
            client.println(F(" 0"));

            // Use readOk with parameter 'false' to stop reading after "+OK".
            if (!readOk(false))
                return -107;
            // The header of the email is waiting to be read, use the Stream.find() to look for the Subject.
            // The text "Subject: " should be at the beginning of a line, but that is not tested.
            // The first found text "Subject: " is assumed to be the real subject.
            // I have checked many years of emails, and the text is always "Subject: ", and never "SUBJECT: ".
            // At the moment, it is not possible to use the F() macro for Stream.find
            // Only the email that starts with "ARDUINO " at the start of the Subject is used.

            client.setTimeout(POP_TIMEOUT);      // set short timeout for find().
            // find() returns true if found and false if not.
            boolean foundsubject = client.find("Subject: ARDUINO ");
            client.setTimeout(POP_TIMEOUT_DEFAULT);   // restore timeout to 1 second

            if (foundsubject)
            {
#ifdef DEBUG_POP
                Serial.println(F("Found an email for me"));
#endif

                // Read the remaining subject (that is the command for the Arduino) into a buffer.
                // Every line from the mail server should end with CR + LF,
                // but to be sure, both CR and LF are checked.
                // Alternative:
                //    client.readBytesUntil('\r', pBuf, nBufSize);

                // The last position in the buffer is reserved for the zero terminator.
                // So read data until (nBufSize-1).
                int i;
                for (i = 0; i < (nBufSize - 1) && client.available(); i++)
                {
                    char c = client.read();
                    if (c == '\r' || c == '\n')
                        break;
                    pBuf[i] = c;
                }
                // Add zero terminator
                pBuf[i] = '\0';
                nBytes = i;     // the number of received bytes is returned by the getEmail() function.

                // More text of the header could be following the Subject.
                // That is read and disregarded.
                readRemaining();

#ifdef DEBUG_POP
                Serial.print(F("Subject = \"ARDUINO "));
                Serial.print(pBuf);
                Serial.println(F("\""));
#endif

#ifdef ENABLE_DELETE_POP
                // Delete the just read message.
#ifdef DEBUG_POP
                Serial.print(F("command DELE "));
                Serial.println(nMailNumber);
#endif
                client.print(F("DELE "));
                client.println(nMailNumber);
                if (!readOk(true))
                    return -108;
#endif

                // Everything is okay, the mail is read and deleted.
                // Ready for now, don't process the remaining emails.
                found_and_ready = true;
            }
            else
            {
#ifdef DEBUG_POP
                Serial.println(F("No ARDUINO keyword in subject"));
#endif
                // This email has no "Subject: ARDUINO ".
                // But the remaining text has still to be read and disregarded.
                readRemaining();
            }
        }
    }

#ifdef DEBUG_POP
    Serial.println(F("Sending QUIT"));
#endif
    client.println(F("QUIT"));

    // After "QUIT", the server still respons with "+OK",
    // but after that, the connection might get lost.
    // So don't read everything after "+OK" (use parameter 'false' for readOk).
    if (!readOk(false))
        return -109;

    client.stop();

#ifdef DEBUG_POP
    Serial.println(F("normally disconnected"));
#endif

    return(nBytes);
}

// Read the response from the mail server.
// That is "+OK" if everything is okay.
// Parameter 'readAll' is to read every character after the "+OK".
boolean readOk(boolean readAll)
{
    // Check the response "+OK" from the mail server
    // In most cases that is followed by a space and more text, but not always.
    // In case of an error the text "-ERR" is received.

    int loopCount = 0;
    char bufOk[4];
    Serial.print("Connected: ");
    Serial.println(client.connected());

    Serial.print("Client Available: ");
    Serial.println(client.available());
    // Wait for response of mail server, with a timout.
    while (!client.available())
    {
        delay(1);
        loopCount++;

        // if nothing received for 10 seconds, timeout
        if (loopCount > 10000)
        {
            client.stop();
#ifdef DEBUG_POP
            Serial.println(F("\nTimeout"));
#endif
            return false;
        }
    }

    // Read the first three bytes.
    client.readBytes(bufOk, 3);

#ifdef DEBUG_POP
    Serial.write(bufOk, 3);
    Serial.println();
#endif

    // Is it "+OK" ?
    if (strncmp(bufOk, "+OK", 3) != 0)
    {
        popFail();
        return false;
    }

    // When the text after "+OK" is not needed, everything
    // else can be read and disregarded
    // (or shown in the serial monitor during debugging).
    if (readAll)
        readRemaining();

    return true;
}

void readRemaining()
{
    // This function is called after checking the "+OK".
    // It reads everything from the server, until no more text is
    // available.

    while (client.available())
    {
        char c = client.read();
#ifdef DEBUG_POP_EXTRA
        Serial.print(c);
#endif
    }
    return;
}

void popFail()
{
    int loopCount = 0;

#ifdef DEBUG_POP
    Serial.println(F("popFail"));
#endif

    while (!client.available())
    {
        delay(1);
        loopCount++;

        // if nothing received for 10 seconds, timeout
        if (loopCount > 10000)
        {
            client.stop();
#ifdef DEBUG_POP
            Serial.println(F("\nTimeout"));
#endif
            return;
        }
    }

    client.stop();

#ifdef DEBUG_POP
    Serial.println(F("disconnected due to fail"));
#endif
}

```

Output:

```
Arduino POP3 email reader
Ethernet started.
Local IP = 192.168.1.117
Press 'c' to check mail.
connected
Connected: 1
Client Active: 0

Timeout
Email POP3 failed, error = -102

```

# Answer
Hotmail doesn't provide a non-encrypted POP3 service, which would normally run on port 110.

You have no choice but to use the SSL service. However, you can't. Or not easily. SSL is quite a heavy protocol and it is highly doubtful the little Uno is capable of even coming close to being able to work with it.

The Due might have a chance, but again, unlikely.

You would be best off using a computer (server) to check the emails for you and provide a "digest" of information to the Uno instead.
> 1 votes

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


title: Sending serial data to Processing

text:
# Question
Title: Sending serial data to Processing
I have a question about using the Arduino and Processing. I want to build a touch sensor using aluminum foil and connect it to an interface built in Processing. However i've come across a problem. I don't know how to send the serial data from the Arduino to Processing. This is the code I'm using to get the sensor value from the aluminum foil:

```
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);

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

void loop(){
  long start = millis();
  long total1 =  cs_4_2.capacitiveSensor(30);

  Serial.print(millis() - start);
  Serial.print("\t");

  Serial.print(total1);
  Serial.print("\t");
  Serial.print('\n');

  delay(100);
}

```

The foil is connected to dig pin 4 with a resistor of 1M in between and to dig pin 2 with a resistor of 1K. Pin 4 is the send pin, pin 2 is the receive pin. It all works just fine, in the serial monitor in the Arduino software I get the value of the time between refreshes and the sensor value. But how do I use this sensor value in a Processing sketch? I thought of maybe using Firmata on the Arduino, but then I wouldn't know how to use the CapacitiveSensor library and get the sensor values. Does anyone know how to get this to work? Help would be greatly appreciated!

# Answer
> 1 votes
Try to use this code:

```
// Graphing sketch

import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

void setup () {
// set the window size:
size(400, 300);

// List all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my  Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
}
void draw () {
// everything happens in the serialEvent()
}

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:
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height);

// draw the line:
stroke(127,34,255);
line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning:
if (xPos >= width) {
xPos = 0;
background(0);
}
else {
// increment the horizontal position:
xPos++;
}
}
}

```

Also look at: http://www.arduino.cc/en/Tutorial/Graph

# Answer
> 0 votes
SparkFun has a tutorial where they explain in great detail how to create a project where your Arduino communicates with Processing on your PC.

# Answer
> 0 votes
You're already half way there - you're sending the data from the Arduino. All you need to do now is read up on how to use Serial in Processing (hint: Arduino is based on Processing, so you should already know most of it) in order to read what you're sending.

---
Tags: serial, processing-lang
---


# Question
Title: What protocols and tools does Arduino Due use for flashing and debugging?
I am interested in writing a simple C program *outside* of the Arduino IDE and respective libraries, but deploying it directly to an Arduino Due (which uses a SAM3X8E ARM MCU). I am trying to figure out what comms/serial protocols are used for:

* Flashing/deploying the program to the ARM MCU; and
* Connecting the program to a debugger

And, not just the protocols used, but what *tools* are compatible with these protocols, and henceforth, can be used for both use cases. How can I tell what my viable options are?

# Answer
> 3 votes
The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).

I know of two systems for communicating with it. Atmel's SAM-BA program, and the open source BOSSA. The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.

---
Tags: serial, arduino-due, debugging, uart, flash
---


# Question
Title: How to make an RC mixer with the arduino
I want to make a RC mixer mixing two channels of a receiver.

What I have: a delta model plane, two servos, a receiver and a Arduino Nano.

So I'd like to mix the aileron (two channels) with the elevator(one channel).

EDIT: What I've done: I read the input of the receiver and wrote it to the servos. The problem: The servo stutters and the arduino displays false inputs.

```
int pin = A0;
int pin1 = A1;
unsigned long duration;
unsigned long dur;

unsigned long duration2;
unsigned long dur2;

#include <Servo.h>

Servo myservo;
Servo myservo2;

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);
}

void loop()
{
  duration = pulseIn(pin, HIGH);
  dur = duration;
  Serial.println(dur);
  myservo.writeMicroseconds(dur);
  delay(50);
//  duration2 = pulseIn(pin1, HIGH);
//  dur2 = duration2-980/4-200;
//  Serial.println(dur2);
//  myservo2.write(dur2);
}

```

# Answer
> 1 votes
You do not need to use long for values from pulseIn, using int will be sufficient.

Your code is not complete, at least there is a missing '}' at the end of setup.

The slower the baud rate (9600) actually the more it interferes with timing code, to a point. PWM is all timing code. I would suggest 57,600.

You never set the servos to any pins. And is using Servo lib needed? I have always used analogWrite with no problems.

You are not using parenthesis on your math (currently commented). It will not give you the result you expect. But you are somewhat on the right track, subtract 1500 from each pulse read, that will give you -/+ range. How you mix that depends on how your radio is setup (servo reversing, which channel is which). Keep in mind ailerons is 1 channel, so left aileron = -rightAileron. Elevator up = that + elevator. so;

aileronLeft = airleronChannel + elevatorChannel
aileronRight = -airleronChannel + elevatorChannel

You do realize this a $3 part?

update: I have always used analogWrite, but I also always use good equipment. I see cautions that cheapo servos might be damaged with analogWrite. You can read more here. It has always worked for me.

---
Tags: arduino-nano, pwm, remote-control
---


# Question
Title: This specific code just refuses to compile?
I've been working on some software to do REALLY basic composition of music. Here's my code so far:

```
#include "notes_sharps.h"

int notes[] = {NOTE_B0,NOTE_C1,NOTE_D1,NOTE_E1,NOTE_F1,NOTE_G1,NOTE_A1,NOTE_B1,NOTE_C2,NOTE_D2,NOTE_E2,NOTE_F2,NOTE_G2,NOTE_A2,NOTE_B2,NOTE_C3,NOTE_D3,NOTE_E3,NOTE_F3,NOTE_G3,NOTE_A3,NOTE_B3,NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5,NOTE_D5,NOTE_E5,NOTE_F5,NOTE_G5,NOTE_A5,NOTE_B5,NOTE_C6,NOTE_D6,NOTE_E6,NOTE_F6,NOTE_G6,NOTE_A6,NOTE_B6,NOTE_C7,NOTE_D7,NOTE_E7,NOTE_F7,NOTE_G7,NOTE_A7,NOTE_B7,NOTE_C8,NOTE_D8};

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

  for(int i = 0; i < 51; i++){
    Serial.println("%i's sharp is %i",notes[i], notes[i]+(notes[i]*0.05937));
  }
}

void loop(){}

```

This code just refuses to compile, no error messages, it simply leaves my computer dormant. Here's the log:

`C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10604 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp -o C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp.o`

# Answer
As Majenko stated in the comments, your use of the println function is not valid as there exists no overload that takes char\*, int, int as parameters.

You could get your program to work by replacing your println as following:

```
for(int i = 0; i < 51; i++){
    Serial.print(notes[i]);
    Serial.print("'s sharp is ");
    Serial.println(notes[i]+(notes[i]*0.05937));
}

```
> 1 votes

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


# Question
Title: How to increase Arduino's memory to save Dot Matrix Library?
I need to display some dynamic Chinese characters to 12864 using Arduino. What to show is transported from my web server. The character is stored as a 16x16 dot matrix, needing 16\*16/8=32 byte. And I need to show some sentences, which contains more than 100 Chinese characters.

The problem is that I can't storage all the dot matrix data in Arduino because it has too small memory.

* If I get the dot matrix data from web server, I need to have 100\*32B memory, but SPAM with EEPROM have only 3k. So that failed.
* If I save the dot matrix "library" in the Flash memory, I need 3500\*32B (There are 3500 Chinese frequent-used characters), but there is only 32K Flash. Saving the "library" means that I should storage the dot matrix data of all the 3500 chars in Flash, then the server only need to send the Unicode of characters, and I can get the matrix of the char.

Any help is appreciated!

# Answer
> 0 votes
The basic EEPROM write, each 1 byte, as is mentioned in the above answer.

http://www.hobbytronics.co.uk/arduino-external-eeprom

The PAGE WRITE which is suitable for this situation. One can easily read 32 bytes for a dot matrix.

http://www.hobbytronics.co.uk/eeprom-page-write

# Answer
> 1 votes
1. Use a different Arduino or Arduino-clone with more flash memory
2. Store the character bitmaps in external EEPROM (example)

---
Tags: arduino-uno, memory-usage
---


# Question
Title: Disturbed digital out at 4Mhz on Arduino NANO
I've written a simple program - it generates signals over `Port D` at 4 MHz:

```
#include <Arduino.h>

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;
        PORTD = 5;
        PORTD = 10;
        PORTD = 15;
        PORTD = 20;
        PORTD = 25;
        PORTD = 30;
        PORTD = 35;
        PORTD = 40;
    }
    return 0;
}

```

and this is the signal coming out on D4:

I've modified the program by inserting NOP after each assignment to `POTRD`:

```
#define NOP __asm__ __volatile__ ("nop\n\t")

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;NOP;
        PORTD = 5;NOP;
        PORTD = 10;NOP;
        PORTD = 15;NOP;
        PORTD = 20;NOP;
        PORTD = 25;NOP;
        PORTD = 30;NOP;
        PORTD = 35;NOP;
        PORTD = 40;NOP;
    }
    return 0;
}

```

and now signal looks fine, but frequency is limited to 800 KHz:

What is the reason for interference at 4 MHz? Is there a limitation to maximal frequency on digital out? I do not really need it for some particular project, just wanted to know it.

I've asked this question on stackoverflow, but then I've discovered this dedicated forum so... I've decided to try it out ;)

# Answer
This is not a limitation of the Arduino: you can toggle a pin on every clock cycle. It's a synchronization problem between the generated signal and the triggering of the scope. Your scope displays several traces superimposed, and it synchronizes them on the rising edges, but since those are unequally spaced, it gets out of sync with the full period of the signal. By adding a few nops you reached a lucky synchronization in your second version of the code.

The simplest solution is to set the scope mode to *Single* instead of *Normal*. Then it only displays a single trace and synchronization is not an issue anymore.

Another option would be to use one of the bits of `PORTD` as a trigger signal. This bit should cycle only once inside the loop. `PD5` should work in the current version of your code. Configure the scope for external trigger and feed this signal into its TRIG input.
> 1 votes

# Answer
Thank you - correct trigger solves my problem:
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How can I programming detect that a Bulb/LED is ON/OFF or a circuit is working as expected using Arduino?
I've created a circuit to turn on bulb using GSM module and Arduino. I want a mechanism(or programming) to know whether the bulb is on or off or fused. I've tried taking the input from the pins. But it only tells whether the pin is on or off but not the circuit as a whole.

# Answer
This can be done using a few methods. The simplest and least expensive option is to measure the current consumption of the device you want to verify correct operation of, and see if it's using enough, but not too much, current.

For instance, the following would work well in the arduino case of using an LED:

simulate this circuit – Schematic created using CircuitLab

Connect the `Power` to 5V or to the pin you're controlling the LED with. Connect the `Sense` to an analog input such as A0.

If the LED isn't installed, or is broken as an open circuit, the sense would register 5V. If the LED is broken as a shorted element, the sense would register 0v. If the LED is operating correctly, you would sense the voltage drop of the LED (which varies according to the LED's design), but it would be well above 0V and well below 5V.

For bulbs and other loads, use a much smaller resister for R1 (so the resistor doesn't affect the load as much) and it would be considered a current shunt. Knowing the resister value, and the voltage at the `Sense` location will give you a current value using `Current = Voltage / Resistance`. Again, the load should be drawing current within an acceptable range during proper operation. If it's not drawing enough current, or too much current, it may not be operating correctly.

This won't tell you if the LED is on, however it's a very reliable method to discover if it's working correctly, and you'll probably never run into a situation where the correct LED is installed and in the right current range, but not emitting light.
> 1 votes

---
Tags: arduino-uno, programming
---


# Question
Title: Can I change the USB device name of Arduino?
I have several Arduinos connected to my Windows PC, and they appear as follows:

> COM7 (Arduino Uno)
> COM11 (Arduino Uno)
> COM13 (Arduino Uno)

So there's no way to tell which is which, and when I want to upload a sketch to one, I have to unplug the others to make sure my code goes to the right one.

Is there a way to change the "Arduino Uno" description?

(I found a similar question but that was about Mac specifically).

# Answer
> 2 votes
You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side. It's not trivial, and probably not worth it.

However, Windows attempts to use the same serial port for the same devices in the same USB positions, so if you figure out which is which (blinking the LED at different frequencies) then you can mark the USB port itself with the com number that Windows uses when you plug an arduino into it.

If you use a hub, and you move that hub to a different port, the com numbers will change, but if you keep it in the same port, then it too will try to have them match what they have been in the past.

It's an annoyance, but it's a design decision by arduino.cc. The old FTDI chips kept their assigned com port numbers because they have individual serial numbers and windows would attempt to reassign the same com port to the same chip each time it was plugged in, regardless of its location. When Arduino.cc moved to a programmed MCU for the USB interface, they chose not to provide USB serial numbers, and thus windows has little option but to try to keep things straight by determining the location in the USB hierarchy that the device is connected, and try to keep com port assignments the same using that method.

# Answer
> 0 votes
I have never tried it, but I suspect using zadig might work; http://zadig.akeo.ie/

It lets you pick the driver and name for WinUSB and LibUSB devices. Uninstall any existing driver first. And remember to pick the driver you wish to use when it asks. Also it is not real apparent, but you can edit the name of the device as it installs the driver.

Let us know if it works

---
Tags: serial, usb
---


# Question
Title: ATMega1284 and Relative Humidity libraries
I am trying to use some Relative Humidity sensors (DHT11 and DHT22) with the ATMega1284 processor on a breadboard. I use libraries from Arduino playground (dht.h), Adafruit (DHT.h) and others. Even though both sensors and libraries work fine with Arduino Uno and Mega, they fail with ATMega1284, which produces an INVALID\_VALUE error.

Connections are double checked, and other libraries such as Wire, OneWire etc work fine.

Does anyone have any experience with the ATMega1284 processor, or any suggestions?

# Answer
Per the library instructions, you will receive `INVALID_VALUE` in the following situations:

> The `readXX()` functions return:
>
> * `DHTLIB_OK` (0) : if the sensor sample and its checksum is OK.
> * `DHTLIB_ERROR_CHECKSUM` (-1) : if the checksum test failed. This means that data was received but may be incorrect.
> * `DHTLIB_ERROR_TIMEOUT` (-2) : if a timeout occured, communication failed.
>
> In case of a `DHTLIB_ERROR_TIMEOUT`, humidity and temperature will both get the value `DHTLIB_INVALID_VALUE`. In case of `DHTLIB_ERROR_CHECKSUM` the values of humidity and temperature are left unchanged as it is impossible to determine which byte failed in the checksum. It is up to the programmer to decide what to do. One can compare with previous value, but better reread the sensor.

So read the value returned by the `read11()` or `read22()` functions to verify that it's an `DHTLIB_ERROR_TIMEOUT` condition, and if so try to figure out why the library is having trouble talking to the device.
> 0 votes

---
Tags: sensors
---


# Question
Title: How does this Motor Circuit not ruin the Microcontroller
I came across this instructable about using no external hardware but two pwm pins to control a motor in both directions. Usually you would use an H bridge. However, ever since I have had my Arduino I have heard that you are not supposed to connect a pin to another pin. So how does this circuit works. It looks like he sends a signal from one pin and in my experience it would fry the board. So basically, my question is this circuit ok with an Arduino Nano and if so how does it work? Below is a picture of the setup he gave:

# Answer
> 4 votes
This is a bad idea, but not because two pins seem to be connected directly. They're not; there is a load (the motor) between the pins, and that motor will take care of different levels between the pins. High and low will make the motor turn one way, low and high the other way, and the same level on both pins will stop the motor.

Why is this bad? An I/O pin can only supply a limited current, and even for a small motor that will peak rather high. If you run the motor for some time this way you will damage the I/O ports. An H-bridge, like you mention, is the solution.
Note that electric motors cause a lot of noise in the power supply, which may cause the microcontroller to reset all the time, so that your program doesn't work. (The motor may seem to start/stop all the time.) You need to decouple the power supply with capacitors.

# Answer
> 1 votes
You are not supposed to connect one pin directly to another pin because the current will destroy the electronics connected to the pins. The motor provides a small impedance and limits the current flowing (although the amount of current will increase if the motor stalls).

As to the other reason you missed for the MCU possibly being damaged, the answer is that it is absorbed by the input protection diodes and subsequently the supply.

# Answer
> 0 votes
Another problem here is when running a motor you want to include a 'flyback diode' to prevent damage from voltage spikes, which is a problem with loads like motors.

See this article for details.

---
Tags: arduino-nano
---