title: Parsing using the ArduinoJson library

text:
# Question
Title: Parsing using the ArduinoJson library
I am trying to parse JSON using the ArduinoJson library. The problem is that I can’t parse www.read() because it’s declared as a char. I think www.read() needs to be a string? How can I convert www.read() into a format that jsonBufffer.parseObject() can understand? Please excuse any lack of terminology. I am new to using JSON.

When I run the code I get to the point where it prints "-------------------------------------” then it does nothing.

```
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include <ArduinoJson.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "WLAN_SSID_HERE" // cannot be longer than 32    characters!
#define WLAN_PASS       "WLAN_PASS_HERE"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  300000      // Amount of time to wait (in milliseconds) with no data
// received before closing the connection.  If you know the server
// you're accessing is quick to respond, you can reduce this value.

// What page to grab!
#define WEBSITE      "wefeel.csiro.au"
#define WEBPAGE      "/api/emotions/primary/totals"

StaticJsonBuffer<200> jsonBuffer;

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  Serial.print(F("\nAttempting to connect to "));
  Serial.println(WLAN_SSID);
   if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

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

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
//  while (! displayConnectionDetails()) {
 //    delay(1000);
//  }

  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE);
  Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
   }

  cc3000.printIPdotsRev(ip);

}

void loop(void)
{
  char c;
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
  delay(300);
  if (www.connected()) {
    www.fastrprint(F("GET "));
    www.fastrprint(WEBPAGE);
    www.fastrprint(F(" HTTP/1.1\r\n"));
    www.fastrprint(F("Host: "));
    www.fastrprint(WEBSITE);
    www.fastrprint(F("\r\n"));
    www.fastrprint(F("\r\n"));
    www.println();
  }
  else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    //Serial.print(www.available());
    while (www.available()) {

      //Serial.print(c);
      //char json[] = www.read();
    }
  }
  c = www.read();
  Serial.print(c);
 JsonObject& root = jsonBuffer.parseObject((char*)c);
 if (!root.success()) {
    Serial.println("parseObject() failed");
    return;
    }

  long love = root["love"];
  long other = root["other"];
  long sadness = root["sadness"];
  long anger = root["anger"];
  long joy = root["joy"];
  long surprise = root["surprise"];
  long fear = root["fear"];

  Serial.println(love);
  Serial.println(other);
  Serial.println(sadness);
  Serial.println(anger);
  Serial.println(joy);
  Serial.println(surprise);
  Serial.println(fear);

  www.stop();
  delay(100);
  www.close();
  delay(200);
 }

```

# Answer
> 1 votes
There are two `read` methods. One that returns a single character (or error), and one that populates a buffer; you want the latter, with method signature `int read(char* buf, size_t len)` or some such. Read the source.

When allocating the json buffer in `StaticJsonBuffer<200> jsonBuffer;`, make sure your expected json data fit in 200 bytes.

---
Tags: arduino-uno
---


# Question
Title: Communication between IC and microcontroller (Teensy 3.2)
I am trying to use a rotary encoder with an integrated circuit to measure the position of a rotating shaft. I am then taking this data and writing to an SD card. The IC seems to be working correctly and outputting binary data to the specified pins, but the data does not seem to be reaching the micro-controller. My output data is fragmented, and seems to only be receiving binary data from some of the IC pins. The IC I am using is HCTL-2021-A00 (http://www.mouser.com/ProductDetail/Avago-Technologies/HCTL-2021-A00/?qs=RuhU64sK2%252bsgeK17XZB%2fNA%3d%3d). I tried using a larger gauge wire to connect the two, but then the micro-controller didn't seem to pick up any of the data. Here is the code I used.

I am trying to use a rotary encoder with the HCTL-2021-A00 from avago. I am getting data output from the IC, but only one of the two bytes which it should be providing. When I move the encoder forward, it will only give me the LOW byte and all of the high bits will be zero. However, when I move the encoder backward, all of the high data bits are 1, and the low data bits still operate normally, counting the position. What could cause the high data bits to all be 1 when moving backward, and all 0 when moving forward? Code used is below.

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

File datafile;
const int chipSelect = 10; // connected to the CS pin on the sd card, Make sure the card is formatted
int encoderpos=0;
int i=0;
int pulses, A_SIG=0, B_SIG=1;
int b[15];  //the individual bits of data read from the IC
int pos; //position output of IC ranging from 0 to 5000 for 1 revolution
int selpin=1, OEpin=2;
int clock=4;
int d[7]; //the pins on the IC attached to which digital teensy pins
double deg; //degree position of the servo as found from the encoder and IC

void setup()
{
  //set pwm signal for timer input
  pinMode(4, OUTPUT);
  analogWriteFrequency(4, 6000000); // Teensy 3.0 pin 3 also changes to 375 kHz
analogWrite(4, 128);
   //First setup and attach the pins used to communicate with the IC and encoder
  d[0]=22;//pin numbers for attaching the IC to the teensy
  d[1]=21;
  d[2]=20;
  d[3]=19;
  d[4]=18;
  d[5]=17;
  d[6]=16;
  d[7]=15;
//first set pins as inputs and outputs
pinMode(selpin, OUTPUT);
pinMode(OEpin, OUTPUT);
pinMode(d[0], INPUT);
pinMode(d[1], INPUT);
pinMode(d[2], INPUT);
pinMode(d[3], INPUT);
pinMode(d[4], INPUT);
pinMode(d[5], INPUT);
pinMode(d[6], INPUT);
pinMode(d[7], INPUT);

digitalWrite(selpin, HIGH);
digitalWrite(OEpin, HIGH);

pinMode(5, OUTPUT);

digitalWrite(5, HIGH);
delay(5);
digitalWrite(5, LOW);
delay(5);
digitalWrite(5, HIGH);
delay(5);

pinMode(chipSelect, OUTPUT);
SD.begin();
datafile=SD.open("c.txt", FILE_WRITE);
pinMode(7, INPUT);
pinMode(8, OUTPUT);

}

void loop()
{
datafile.println(pose());
if (millis()>4000)
{
  datafile.close();
}

delay(5);
}

int pose()     //Gives the position in degrees from the readings from encoder and IC for 0 to 5000 representing one revolution
{
    digitalWrite(selpin, LOW);     // The sel pin on the IC
  digitalWrite(OEpin, LOW);     // The OE pin on the IC
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
analogWrite(4, 128);

  b[0]=digitalRead(d[0]);
  b[1]=digitalRead(d[1]);
  b[2]=digitalRead(d[2]);
  b[4]=digitalRead(d[4]);
  b[5]=digitalRead(d[5]);
  b[6]=digitalRead(d[6]);
  b[7]=digitalRead(d[7]);
if(digitalRead(7)==1)
{
  digitalWrite(8, HIGH);
}
else if(digitalRead(7)==0)
{
  digitalWrite(8, LOW);
}
  digitalWrite(selpin, HIGH);
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
analogWrite(4, 128);

  b[8]=digitalRead(d[0]);
  b[9]=digitalRead(d[1]);
  b[10]=digitalRead(d[2]);
  b[11]=digitalRead(d[3]);
  b[12]=digitalRead(d[4]);
  b[13]=digitalRead(d[5]);
  b[14]=digitalRead(d[6]);
  b[15]=digitalRead(d[7]);

  digitalWrite(OEpin, HIGH);

  pos=0;
  i=8;
  for(i; i>0; i--)
  {
pos=2*pos+b[i-1];
  }

  i=16;
  for (i; i>8; i--)
  {
    pos=2*pos+b[i-1];
  }

  return pos;

}

```

# Answer
I found the problem. I had assumed that the rst pin was supposed to be held low unless you wanted to reset the count on the encoder, and was ignoring it the whole time. Once I held the reset pin high, the count started to show up.

As of now there are still problems, I cannot read the high byte from the IC.
> 1 votes

# Answer
Wanted to just put this in a comment but apparently still don't have the rep to do that, so taking a stab at answering.

Sounds to me like you are having physical layer corruption issues. I highly doubt that your wires were too fine a gauge since these are just signal wires for SPI, however, it was instructive that you did that since larger wires seemed to make the problem worse, I would guess that you have too large capacitance on the wire for the datarate you have chosen.

When I am debugging any serial communications for the first time, the first thing I do until communication is reliable is to slow the data rate down. Something like 10kHz should work in most cases. See if this fixes the corrupted data. If it does, go back to a finer gauge wire and then bump the speed back up til you see corruption issues. If you have a logic analyzer or a scope you can get on the line, it will be very educational to see what is going on with your edge rates.
> 0 votes

# Answer
You seem to be overlooking (or at least mishandling) the fact that these parts are built with a bus interface where the /OE and SEL signals as well as the internal position data latch are *sampled* synchronously with a clock input which you do not seem to be driving.

* You need to generate a low-to-high transition of the CLK signal to latch the count into the readout
* You need to generate a high-to-low transition of the CLK signal to latch in chosen values of the /OE and SEL signals.

On second examination of your code, perhaps you are trying to use a free-running clock asynchronous to your reading. That, however, is extremely unwise. First, you don't know that a suitable clock edge will happen between when you set the /OE or SEL and when you try to read the data. Next, you do not know that an *undesired* clock edge will *not* happen in the midst of reading data, causing you to end up with a corrupted value that contains some "old" bits from before the clock edge and some "new" bits from after. This would be particularly bad if it happened across a transition such as 0b01111111 to 0b10000000 or similar...

You may have other problems as well - your question is not complete without a schematic diagram of how you have wired up this chip.
> 0 votes

---
Tags: pwm, communication, rotary-encoder
---


# Question
Title: How to use printf with Arduino's serial ports without an intermediary buffer?
How to use `printf` with Arduino's streams without an intermediary buffer? The following seems unnecessary:

```
char buf[256];
sprintf(buf, ...);
Serial.print(buf);

```

Is there a way to connect `HardwareSerial` or `SoftwareSerial` to a libc stream or is there a custom implementation of `printf` that does this?

# Answer
Sure - here's a Hello, World program that uses printf(). Everything that mentions "uart" is what connects printf() to your output stream. `uart_putchar()` does the actual outputting to ... someplace. That's what you'd modify to direct the C standard output to a different device - SofwareSerial, for instance:

```
// Hello, World program using printf()

#include <Arduino.h>

static FILE uartout = { 0 };   // FILE struct
static int uart_putchar(char c, FILE *stream);

void setup() {
   // For printf: fills in the UART file descriptor with pointer to putchar func.
   fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
   stdout = &uartout;

   Serial.begin(9600);
   printf("Hello, World!\n");
}

void loop( void ){
   printf("Elapsed time: %ld\n", millis());
}

// uart_putchar - char output function for printf
static int uart_putchar (char c, FILE *stream)
{
   if( c == '\n' )
      Serial.write('\r');
   Serial.write(c) ;
   return 0 ;
}

```
> 6 votes

---
Tags: avr, printf
---


title: Arduino Mega pin conflict

text:
# Question
Title: Arduino Mega pin conflict
I am building a rather complicated model railroad crossing signal and have moved to using the Mega since I need more pins than the Uno. Upon reading the specs of the Mega on the Arduino.cc website I noticed a potential pin conflict, or not, maybe they serve a dual purpose?

> External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2).
>
> I2C: 20 (SDA) and 21 (SCL).

SDA and Interrupt 3 both function on pin 20? Likewise with Interrupt 2 and SCL?

I assume this is true, how/why do they share the same pin?

# Answer
> 1 votes
Lots of things share pins. It's normal. The "how" is that those pins are connected, internally, to multiple bits of the circuitry.

The "why" is simply because if you had a discrete pin for each possible function you would end up with a chip the size of your desk.

Pretty much every single pin on the chip has multiple functions on it.

---
Tags: arduino-mega, interrupt
---


# Question
Title: Can Arduino be used as an FDTI Programmer?
I would like to program my ESP 8266 WiFi module. But I don't have an FDTI right now is there any way to use Arduino Uno as FDTI Programmer then use ESP without it.

# Answer
> 2 votes
Yes. Tie the reset pin on the ISP connector low to keep the ATmega328P in reset, then you can connect pins 0 and 1 to the ESP module to communicate using the Uno's USB-UART bridge. Since the pins are labelled from the perspective of the '328P, connect TX to TX and RX to RX.

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


# Question
Title: How to Capture Data from a Webpage in Arduino and Display it over Serial Monitor of ESP8266?
My Code is as follows-\>

```
#include <SoftwareSerial.h>

SoftwareSerial ESP8266(8,9);

String inData;
void setup() {
ESP8266.println("AT");
delay(1000);
ESP8266.println("AT+RST");

}

void loop() {
 String cmd = "AT+CIPSTART=\"TCP\",\"";
 cmd += "api.thingspeak.com";  // 184.106.153.149 thingspeak IP address
 cmd += "\",80";
 ESP8266.println(cmd);

 if(ESP8266.find("Error"))
 {
   Serial.println("AT+CIPSTART error");
   return;
}
String hostt = "GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA";
hostt += "\r\n";
hostt += "Host:api.thingspeak.com";
hostt += "\r\n\r\n\r\n\r\n\r\n\r\n";
ESP8266.println(hostt);

cmd = "AT+CIPSEND=";
cmd += String(hostt.length());
ESP8266.println(cmd);

if(ESP8266.find(">")){
ESP8266.print(hostt);
}
else{
ESP8266.println("AT+CIPCLOSE");
// alert user
Serial.println("AT+CIPCLOSE");
}
delay(5000);
}

```

Is this the write code? Where am I going wrong? I am not able to see the required fetched data. Help me with this.

# Answer
There are two basic things you are doing wrong:

Firstly your HTTP request is wrongly formatted. You have:

```
GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA
Host:api.thingspeak.com

```

What it should look like is:

```
GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA HTTP/1.0
Host: api.thingspeak.com:80

```

Also you only need *one* blank line after your request, not 5 as you seem to have.

Secondly you are not actually doing anything with the data the site is sending you. You make the request with `+CIPSEND=` but then the response, which is in the form `+IPD,<len>:<data>` is completely ignored. You need to use the SoftwareSerial's `.read()` and associated functions to receive that data into the Arduino so you can actually do something with it - like send it down through Serial.

Tips:

* Look for `+IPD,` first
* Read up to the : and interpret it as a number
* You now now how many bytes to read from the data section
* Read that data
* Do something with it
> 0 votes

---
Tags: arduino-uno, wifi, esp8266, softwareserial
---


# Question
Title: What would the total current requirements be for these items?
I'm using 5 of those 8mm NeoPixels \+ a 5V Trinket.

I'm trying to get a rough estimate of the current requirements that would have, assuming all 5 NeoPixels were running at full brightness "white" (255 RGB).

I'm voltage-regulated to about 150 mA from the Trinket and my current hunch is that those NeoPixels need more than that, but trying to confirm it.

# Answer
> 0 votes
According to the data sheet each LED takes a maximum of 3\*20mA, so you are pulling 300mA. You are going to need a bigger power supply :(

---
Tags: led, adafruit, current, rgb-led
---


# Question
Title: Error on Arduino Code (unknown type name 'LiquidCrystal')
I am using `Arduino IDE 1.6.8` and I am trying to compile the following code Wheatstone Bridge. I have currently a really weird error:

```
unknown type name 'LiquidCrystal'

```

This error seems to come from the header file:

```
// Include the Wheatstone library
#include <WheatstoneBridge.h>

// Include the LCD library
#include <LiquidCrystal.h>

// Declare external global lcd
extern LiquidCrystal lcd; <<<Error

```

I have already installed the `LiquidCrystal` library but I don't know if this trouble is due to the compiler (and the IDE) or something is wrong. The compiler seems to find the right libraries...

# Answer
Using "extern" when instantiating a class is unusual. We can not tell what your intentions are because this is only part of your code. However it would be my guess that this code:

```
// Declare external global lcd
extern LiquidCrystal lcd;

```

Should actually be written like this:

```
// Declare external global lcd
LiquidCrystal lcd((12, 11, 5, 4, 3, 2);

```

This is making a BIG assumption that you are using an LCD similar to the one used in the HelloWorld example and you have connected it using the same pins! Comments from the HelloWorld example to help you out:

```
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

```

Background:

Arduino sketches are written mostly in C while the libraries take advantage of C++. As such the libraries can use a C++ feature called "overloading". This is where you can have several different functions with different parameters all with the same name. The advantage is that you can call upon slightly different functions (or in this case different classes) simply by altering what is passed. The LiquidCrystal class has defined all these possibilities:

```
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

```

But in none are there no parameters. That is why the compiler could not find the class in your code. You needed to match one of the above class types.
> 1 votes

# Answer
Download the Liquidcrystal.zip file from this link, Crystal link

Now add that file into documents/Arduino/libraries folder. Now check if the library is added in the library. It should probably work.
> 0 votes

---
Tags: lcd, compile
---


title: ESP8266 as WiFi for Arduino

text:
# Question
Title: ESP8266 as WiFi for Arduino
I have a pretty simple project, where some data has to be read from a mySQL server. My idea is to do this with an ESP8266, and then provide that data to the Arduino Mega.

Is this possible or am I going to have to use the ESP8266 itself? I highly doubt that I would have enough pins then.

I read something about AT-commands. But I have no idea how to send those commands to the ESP.

Thanks in advance,

Michidez

# Answer
> 1 votes
Yes its possible, you can use the ESP8266 as a dumb Wifi to Serial convertor. Set you Arduino IDE up so you can program the ESP8266 like an Arduino, and then write a simple program to connect to the WIFI network and read the data from the server, then just print it to the default serial console with a special sequence of characters at the beginning of each line, like 'DATA'.

Connect the serial port on the ESP8266 to the Mega, don't forget top cross the RX and TX wires and then write a program on the mega that reads from the serial port you have allocated and only process lines beginning with the special sequence of characters.

Yes you could use the AT commands, but that involves a fair amount of learning. pain and different software, when you already probably have the knowledge that you need.

Some of the later version of the ESP8226 can run at 160MHz and have 1MByte or memory so you might want to hand off some of the data crunching to the ESP. (But that's a decision for later, once its working).

Hope that helps.

# Answer
> 2 votes
Check out ESP-LINK You can find it here ESP-LINK is a esp8266 wifi-serial bridge, outbound TCP, and arduino/AVR/LPC/NXP programmer. It has several configuration, one of them allowes uploading new firware ower wifi, or to act as a serial link just like if usb cable is pluged in and serialport viewer is active. The website has great documentation and has one of the slickest configuration interfaces seen on ESP.

---
Tags: esp8266
---


title: Send Photo with Arduino Uno

text:
# Question
Title: Send Photo with Arduino Uno
I'm new at Arduino projects. I googled but I couldn't quite get an answer.

I've got:

* Arduino Uno R3 clone
* 4 pin push button
* 3 color RGB LED Module
* HC06 Bluetooth-Serial Module Card
* Arduino PIC Camera Module OV7670

In my project, when the button is pushed, the Arduino takes a photo from the camera module and sends it with an HC06 Bluetooth Module to an Android device. And it receives the answer to turn on the Led green or red.

The main problem is how can I capture the photo and send it with bluetooth? I can handle the Android side.

**EDIT 1**

I reviewed that code: OV7670 FIFO on GitHub.

In the "Take Picture" method, I understand that the OV7670 continuously grabs frames and stores them in itself. I send it a signal to load a frame on Data Out pins. (*D0-7*) It loads first 8 bytes on the pins and in Arduinoo, in the for loops for height, width and byte for each pixels, I read in it from *D0-7* and send a signal for next byte array.

But I can't understand how to connect the OV7670 to the Arduino. In code, there are conts called `WRST`, `RRST`, `WEN`, `VSYNC` and `RCLK`. On the OV7670 I've got `SIOC`, `SIOD`, `VSYNC`, `HREF`, `PCLK`, `XCLK`, `D0-7`, `RESET` and `PWDN` pins. How can I connect these pins like in the github link?

By the way here is my OV7670, I read there are different versions of OV7670:

# Answer
> 1 votes
I have looked into something very similar and I think the reason you are finding it difficult to find information is you are viewing the full system. Break it down into smaller chunks and you will get more chance of finding a match. So lets look at the camera and then the rest of it.

I think that the reason you can't get an answer for this is that you can't do what you want with what you have. My research seems to say that the OVO7670 camera needs a separate micro processor and 'special' RAM to work (can't remember what is special about the RAM at the moment). There is a board that does this called a 'PIXY', but its not cheap.

On the plus side, connecting an Arduino to Android via blue tooth should be quite simple there should be lots of examples on how to set up the Arduino side. You then need to define to convey your messages between your server an client and I know you aren't asking how to turn a LED on and off from an Arduino. (If you are please see the Example Blink).

Hope that helps

**EDIT**

I think you should have 18 pins on you OV7670.

1. 3v3 - 3.3v
2. Gnd - Ground
3. SIOC - Input - I2C Clock
4. SIOD - I/O - I2C Data
5. VSYNC - Output - Vertical Synch
6. HREF - Output - Horizontal Synch
7. PCLK - Output - Pixel Clock
8. XCLK - Input - System Clock
9. D7 - Output - Data bit 7 (MSB)
10. D6 - Output - Data bit 6
11. D5 - Output - Data bit 5
12. D4 - Output - Data bit 4
13. D3 - Output - Data bit 3
14. D2 - Output - Data bit 2
15. D1 - Output - Data bit 1
16. D0 - Output - Data bit 0 (LSB)
17. RESET - Input - RESET - Low to reset
18. PWDN - Input - Power Down - High to activate

---
Tags: bluetooth
---


title: AVR has no vprintf_P?

text:
# Question
Title: AVR has no vprintf_P?
Well this was unexpected. AVR libc has many the variants of `printf`, including `vprintf`, but is missing `vprintf_P`. Is this really just not present or implemented elsewhere?

# Answer
> -1 votes
It has `vfprintf_P` and `stdout` is a `FILE`. Why would you want to waste time and space with implementing `vprintf_P` as well?

If you *really* want it, you can make your own:

```
#define vprintf_P(...) vfprintf_P(stdout, __VA_ARGS__)

```

Incidentally, the source code to `vprintf` looks like this:

```
int
vprintf(const char *fmt, va_list ap)
{
    return vfprintf(stdout, fmt, ap);
}

```

That does exactly the same job as a preprocessor macro - just forwards your request on to the FILE-based function.

It is actually more efficient to use a preprocessor macro than needlessly nesting functions like that - less stack usage, less calls, etc (unless the compiler happens to choose to *inline* that function, which since it is in a library it likely won't).

The non-FILE based functions can be considered simple *wrapper* functions to the FILE-based ones. They are mostly provided for convenience, but are actually completely redundant and can all be replaced with direct calls to the FILE-based variant. They mostly still exist purely for historical compatibility. And since `_P` is specific to AVR libc there is nothing historical for it to be compatible with.

---
Tags: avr, printf
---


# Question
Title: Unable to upload sketch after bootloader has been flashed on Arduino Micro
I have created my own custom Arduino Micro, but I am experiencing problems when I attempt to upload an sketch via USB in Arduino IDE.

Here is how I program the Arduino Micro:

```
avrdude  -c atmelice_isp  -p m32u4 -P usb -u -v -e -U flash:w:Caterina-Micro.hex

```

And the result:

```
$ avrdude  -c atmelice_isp  -p m32u4 -P usb -v -e -U flash:w:Caterina-Micro.hex
avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
         User configuration file is "/Users/aUser/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : atmelice_isp
avrdude: usbdev_open(): Found Atmel-ICE CMSIS-DAP, serno: J41800023270
avrdude: Found CMSIS-DAP compliant device, using EDBG protocol
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : JTAG3_ISP
         Description     : Atmel-ICE (ARM/AVR) in ISP mode
         Vtarget         : 4.9 V
         SCK period      : 125.00 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as CB
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 38.80s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 133.93s

avrdude: verifying ...
avrdude: 32730 bytes of flash verified

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as CB
avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)

avrdude done.  Thank you.

```

The error in Arduino IDE when flashing sketch via USB:

```
Sketch uses 23.994 bytes (83%) of program storage space. Maximum is 28.672 bytes.
Global variables use 1.145 bytes (44%) of dynamic memory, leaving 1.415 bytes for local variables. Maximum is 2.560 bytes.
Forcing reset using 1200bps open/close on port /dev/tty.usbmodem1411
PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
Uploading using selected port: /dev/tty.usbmodem1411
/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/tty.usbmodem1411 -b57600 -D -Uflash:w:/var/folders/64/6n0yv9515hz1n6z3bdzcwv6h0000gn/T/build2162381950044145986.tmp/IMUNode.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr  3 2014 at 22:00:33
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/aUser/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/tty.usbmodem1411
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

# Answer
> 1 votes
Your problem is that your board doesn't have the bootloader loaded into the chip.

You have success with the ATMEL-ICE ISP because it is an in-system programmer (ISP) and you are downloading the code directly into the chip.

When you use the USB, I see from your output that the programmer is "butterfly" and the description indicates AVR109. These both indicate that the program is trying to be loaded through a bootloader.

A bootloader is a bit of code that resides in the codespace section of flash. It allows you to send the program through the UART. The bootloader then saves it to the codespace section of flash such that both the bootloader and your program co-exist.

To fix this, use the Arduino IDE along with your ATMEL-ICE ISP to load the bootloader into the microcontroller. This can be done by going into `Tools` and then `Burn Bootloader` (of course with the correct programmer selected).

This will then allow you to download your code through the Arduino IDE.

PS. You can program your sketch straight to your Arduino using your ATMEL-ICE ISP without downloading the bootloader. Do this by selecting the `Upload Using Programmer` option in the menus.

---
Tags: arduino-ide, usb, isp, flash, arduino-micro
---


# Question
Title: My serial Monitor of the Arduino ide does not show up when running Gui?
I have created an gui in python using pyserial to communicate with Arduino but my serial monitor does not show up it says (Serial port busy) whenever I run the gui.

The gui works fine but when I want to see the printed data for that, I am using an external LCD but I was wondering if there was a way to see the data in serial monitor. If not could you explain why? I have no idea whatsoever why is this happening.

# Answer
> 1 votes
The problem is simple, you are dealing PySerial using the serial communication port arduino, so you can not communicate with Arduino IDE and python at the same time.

**Solution:**

In the program you should print python q values you need, with the Print command, so you'll see in the CMD same as you see in the Arduino serial monitor.

# Answer
> 0 votes
If an application is already using the serial port then you won't be able to reopen it. In this case you Python GUI is communicating with the Arduino over the serial port, so the IDE can't. Think back to when you are just using the IDE, the serial monitor is closed whenever you upload a new version of the code to the board.

So, how do you solve it. The simplest answer is to use another serial port for the Python app to talk to the Arduino and leave the default port free for the Arduino IDE/Serial monitor. Software serial should work, you might need to print to both serial ports from the Arduino, but you can do that by adding another function.

An alternative might be to modify your python app to rebroadcast the debug data to another serial port and then connect to this via hyper terminal.

Hope that helps.

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


title: Horse racing game

text:
# Question
Title: Horse racing game
Basically i would like to create a horse racing game, (5 horses starting all to a point A and finishing in a random position to a point B).

I did an animated GIF for you to understand it more clearly :

https://i.stack.imgur.com/oOZvB.jpg

This exactly what i want to do, but in real.

I was thinking of using 5 motors (one for each horse) with a string they pull where the horse is attached on it (like this : https://www.youtube.com/watch?v=NjuoCS9-pCY), and to create randomness at each race, do a random speed for each motors every 1 or two seconds and then stop when each horse hit the finishing line (by pushing a sensor ?). Finally when all horses hit the finishing line, the motors goes backward and get the horses back to the start line.

The horses will be tiny like 1 inch (2.5cm) and the distance from start to finish line will be like 20inch (50cm) and i need the race to last at least 5-10 sec so motors don't need to turn too fast.

I don't know if it is the best way or if it is even possible (and how ? with what components?)

I have been searching for solutions to my project but didn't found anything suitable yet so here i am..

Thank you a lot for you help

# Answer
> 1 votes
If it is going to be tiny, I would use continuous rotation servos and rubber belts. They are nice because you dont need motor drivers, unlike stepper motors. Also they consume a lot less power than stepper motors, so you may not need to attach them to external power (not just the arduino 5v). However, because you can not control how far they move, you will need buttons at the end of the race. I think you can get them from Adafruit.

---
Tags: arduino-uno
---


# Question
Title: How to wire up 4-digit 7-segment display?
I have an **Arduino Mega** and the **CL5642BH**, a **4-digit 7-segment display.** I found very helpful code here, but I don't understand how to wire it up on the breadboard.

The display has 12 pins: 6 on the top and 6 on the bottom. First I guess I need to find out which one is GND.

Then (see the link) there is this code:

```
int digit1 = 11; //PWM Display pin 1
int digit2 = 10; //PWM Display pin 2
int digit3 = 9; //PWM Display pin 6
int digit4 = 6; //PWM Display pin 8

int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

```

It's 11 pins, that's the correct amount so far. But **how do I wire it up?** The pins on the display are in no way labeled.

*Note: I'm a software developer, but as far as electronics go, I'm still a beginner.*

# Answer
The first thing you do is ask Google for a datasheet. It tells you: http://www.robotshop.com/media/files/pdf/datasheet-com-09483.pdf

Then you can read the datasheet and find the pin diagram:

That tells you that it is a *Common Anode* LED display - which means that for each digit all the *Anodes* (positive pins) of the LEDs are wired together.

Further, all the *cathode* (negative) pins of the LEDs for the same segments across the digits are connected (that is the cathode for segment A on digit 1 is connected to the cathode for segment A on digit 2, digit 3 and digit 4, etc).

From that you can then infer that you need to provide current for each digit in turn through its common anode pin, and sink current from the segments you want to have lit for the digit that is currently having its current sourced.

The diagram also shows you which pin on the display is for what function - the common anodes are pins 9, 10, 12 and 13, with pin 11 the common anode for the extra dots.

The datasheet also tells you which pin is pin 1 - in this case the one in the bottom left when you have the display facing you and the numbers the right way up. The pins count anti-clockwise from there, so 2 is to its right and 13 is above it.

By the sounds of it though you may not have the same display as in that datasheet. If your display lacks the extra dots then it may not have the LEDs on pin 11, and pin 12-13 may be moved down one, so you have 4 commons on 9, 10, 11 and 12 with no pin 13.

So the four digit select pins in your program are wired to pins 9, 10, 12 and 13, and the segment select pins connect to pins 1, 2, 3, 4, 5, 6, and 7. Don't forget the resistors on all the segment pins to limit the LED current or you will damage the Arduino.

You can do some manual testing of the display by using two wires and a resistor (say 1KΩ). Connect the resistor to +5V, and one wire to the other end of the resistor. The other wire you connect to ground.

You then take the loose ends of the wires and try probing pins. Start with the 5V wire touching pin 9 and connect the other one in turn to pins 1-8 to see if the first digit's segments light up. Repeat with the 5V wire on pins 10-12.

Edit:

If this (http://mklec.com/displays/7-segment-4-digit-12-pin-common-anode-display) is indeed the same display as yours you can ignore the numbers I mention above and work from the pin numbers on that page. The same principle applies though, just the pin numberings are different.
> 5 votes

# Answer
As page 2 of the datasheet shows, there are 5 anode pins (4 digit and 1 aux) and 8 cathode pins (7 segments and 1 DP). Connect the digit lines to the digit anodes and the segment lines to resistors connected to the segment cathodes. The location of pin 1 is shown on the top right of page 2, and as always they go counter clockwise from there. Segments are lit by putting the anode high and the cathode low.
> 1 votes

# Answer
From the datasheet found by Ignacio Vazquez-Abrams:

Now one segment will light up if there is a positive (eg. 5 V) on the anode, and a negative (eg. ground) on the cathode. You need a resistor (eg. 330 ohm) to protect the LED and the output pin.

---

Hopefully it is clear from the original question which Arduino pins go to which LED pins.

---

Then the code which I presume you found will have to multiplex the display. That is, it will ground (send LOW) to the appropriate cathode pins for the number of segments it needs to light up (all of them, for example, for the number 8, except the decimal point). And then it will raise to 5 V (send HIGH) to DIG 1. That will make some segments on digit 1 light up. Then it repeats that for digits 2 to 4, fast enough that they will all appear to be on at once.
> 1 votes

# Answer
Apply the pin 1, 2, 3 with 5v from Audrino passing through the resistors. Apply low voltage to pin-a to light up the led, so on so forth. You can use the multi-meter to confirm the common pins and led pin. For example touch the pin1 with (+) and pin-a with (-) of the multimeter. If the pins are correct, led pin-a will light up.

Picture Reference:http://www.circuitstoday.com/voltmeter-using-arduino
> 0 votes

---
Tags: arduino-mega, pins, display
---


title: float precision in arduino

text:
# Question
Title: float precision in arduino
I am reading a string which i have to convert into a float with a maximum of precision.I didn't want to use toFloat() function since it make a truncation so i made my own code. My problem is that the final result is also approximated. I need a precision of 4 digits after the float.I read the documentation about float in the arduino website.They say it should be maximum 7 digits of precision but i don't get it.When i test my code on the value of '23,459' ,all i get is 23,46. Any suggestions?

```
void setup() {

 Serial.begin(9600);

}
int longu=0;
char data='2';
  String data2="23,459";
  float val=0;
  int posVir=0;
  int t=0;
  float postVir=0;
  float preVir=0;
  int lonPostVir=0;
  int lonPreVir=0;
  float posvir2=0;
  void loop()
{

   lonPostVir=(data2.substring(posVir+1)).length();
   lonPreVir=(data2.substring(0,posVir)).length();

   longu=data2.length();
   posVir=data2.indexOf(",");
   preVir=(data2.substring(0,posVir)).toFloat();
   postVir=(data2.substring(posVir+1)).toFloat();
   posvir2=postVir*pow(10,-lonPostVir);
   val=preVir+postVir*pow(10,-lonPostVir);

  Serial.println(val);

    }

```

# Answer
> 6 votes
The simplest way to get more decimal places to print is this:

```
Serial.println(val,NUMBER_OF_DECMIAL_PLACES);

```

This will print out any number of digits after the decimal place. Regular print without the number of digits specified will default to 2 decimal places. for example, here is some code and the result that gets printed:

```
float val = 23.459;
Serial.println(val);
Serial.println(val, 4);
Serial.println(val, 10);

```

> 23.46
>
> 23.4590
>
> 23.4589996337

You may notice that with 10 decimal places printed you can start to see how much the actual value of 23.459 needs to be approximated to fit within a floating point number. This is similar to how 1/3 can not be represented 100% accurately in a finite number of decimal digits; 459/1000 cannot be represented 100% accurately in a finite number of binary bits, so it is approximated.

Also, note that for non-floating point numbers the optional second argument to `print` and `println` is the base it should be printed in (dec, hex, oct, ...) and has nothing to do with precision.

# Answer
> 3 votes
Just write the amount of numbers you want to get float here Serial.println(val); after the val. example: Serial.println(val, 5); It will give 5 digits after the decimal point

---
Tags: string, float
---


title: Arduino MP3 Player

text:
# Question
Title: Arduino MP3 Player
I want to make a MP3 player with arduino. My problem is what board should I use? There is the SparkFun MP3 Player Shield, SparkFun Audio-Sound Breakout - WTV020SD. Then I want to attach a 2.8 TFT touch screen to control volume,change track etc. Can I attach it to for example on top of MP3 player shield?I'm thinking in this one https://www.adafruit.com/products/1651. And finally what speakers can I use with which board? I want some good small speakers, two to be exact.

I don't really need help with electronics and programming. Just need to know wich are the best components that can work with each other without spending a lot of money. Thank you.

Best Regards

# Answer
I would recommend you do not use speakers but instead send the output to a 3.5mm stereo plug, so you can use headphones or speakers.

Is a 2.8" inch display really necessary? You could probably get away with a 1" display and at a guess that would use less power.

Another idea may be to look at a Bluetooth interface for sending the sound to the headphones or speakers.

You could also look at a WIFI interface to provide additional control interface and to allow downloads straight to the device. (ESP8266 would probably be the easiest interface).

Something you didn't mention was the power source. Are you going to have internal batteries with a USB charging and power socket, so you can hook it to a PC or Batter Pack.
> 1 votes

# Answer
I would recommend you the VS1003 chip ($2.30 on ebay) or module ($7 on ebay). It can play MP3, WMA, MIDI, WAV and can record and encode ADPCM. It's even programmable (own filters etc). See this project.
> 0 votes

---
Tags: arduino-uno, electronics, audio, sound
---


# Question
Title: Three phase sine wave inverter using Arduino
I want to design three phase sine wave inverter using Arduino I found this link with circuit diagram and simulation results but he did not provide code. can anyone help me with code http://microcontrollerslab.com/three-phase-sine-wave-inverter/

# Answer
At the end of the page you are linking to, there is this notice: "Code for three phase inverter is not free of cost. If you want to purchase code, you can contact me at bilalmalikuet@gmail.com"

If you are Bilal Malik, you should already have the code since you are offering to sell it - unless you want someone here to write it for free so you can sell it afterward.

If you are NOT Bilal Malik, you should not impersonate someone else here.

I am not a huge fan of the concept of intellectual property, but it seems you are trying to do something shady here.
> 1 votes

---
Tags: arduino-uno
---


title: Using a button to cycle an array

text:
# Question
Title: Using a button to cycle an array
So. I would like to cycle through an array using a button. My current code goes through if statements when the button is pushed. In each if statement I have a loop to print out a list of strings. I am curious if there is anyway to directly cycle through an array using buttons instead of this indirect route I have taken.

Last question - Is there a way to set the indents in the Arduino IDE to make formatting easier here?

```
//------------------------------------------------------------------------------------------------
// Displays information when a push button is pressed. Also turns on and off a corresponding led.
// 5/3/2016
//------------------------------------------------------------------------------------------------

// declare variables

char* titles[] = {
  "RELATION",
  "FIRST NAME",
  "LAST NAME",
  "LOCATION",
  "PHONE NUMBER"
};
char* user_info[] = {
  "SELF",
  "JOHN",
  "SMITH",
  "FLORIDA",
  "999-888-6666"
};
char* econ_one[] = {
  "BROTHER",
  "MICHAEL",
  "SMITH",
  "FLORIDA",
  "999-888-5555"
};
char* econ_two[] = {
  "WIFE",
  "EMILY",
  "SMITH",
  "FLORIDA",
  "999-888-4444"
};
char* econ_three[] = {
  "SISTER",
  "SOPHIA",
  "ADAMS",
  "NEW YORK",
  "888-777-3333"
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
// setup - set pins

void setup() {
  Serial.begin(9600);
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("Emergency Contact");
}

// main
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      int x;
      for (x = 0; x <= 4; x++) {
        Serial.println(" ");
        Serial.print(titles[x]);
        Serial.print(" ");
        Serial.print(user_info[x]);
      }
      Serial.println(" ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      int y;
      for (y = 0; y <= 4; y++) {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econ_one[y]);
      }
      Serial.println(" ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;
    } else if (state == 2) {
      int z;
      for (z = 0; z <= 4; z++) {
        Serial.println(" ");
        Serial.print(titles[z]);
        Serial.print(" ");
        Serial.print(econ_two[z]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      int q;
      for (q = 0; q <= 4; q++) {
        Serial.println(" ");
        Serial.print(titles[q]);
        Serial.print(" ");
        Serial.print(econ_three[q]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

// function to turn LEDs on/off

void setLights(int one, int two, int three, int four) {
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

```

output image

https://www.dropbox.com/sc/fwll0qe7cyye1mt/AAD5vI9buU\_X0bl04KXFAQyja

# Answer
I would recommend using multidemnsional arrays for both your contacts and your light states.

```
//------------------------------------------------ declare variables

char* titles[] = {"RELATION", "FIRST NAME", "LAST NAME", "LOCATION", "PHONE NUMBER"};

char* econs[][5] = {
  {"SELF", "JOHN", "SMITH", "FLORIDA", "999-888-6666"},
  {"BROTHER", "MICHAEL", "SMITH", "FLORIDA", "999-888-5555"},
  {"WIFE", "EMILY", "SMITH", "FLORIDA", "999-888-4444"},
  {"SISTER", "SOPHIA", "ADAMS", "NEW YORK", "888-777-3333"}
};

uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
  {LOW, HIGH, LOW, LOW},
  {LOW, LOW, HIGH, LOW},
  {LOW, LOW, LOW, HIGH},
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;

//------------------------------------------------ setup - set pins
void setup() {
  Serial.begin(9600);

  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);

  Serial.println("Emergency Contact");
}

//------------------------------------------------ main
void loop() {

  if (digitalRead(buttonPin))
  {
    if (state > 3)
      state = 0;

    {
      for (int y = 0; y <= 4; y++)
      {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econs[state][y]);
      }

      Serial.println(" ");
      setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
    }

    delay(1000);
    state++;

  }

}

//------------------------------------------------ function to turn LEDs on/off

void setLights(int one, int two, int three, int four)
{
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

```

I haven't tested the above, but it should provide the same result.

As for the second part of your question, there is an autoformat tool in the Tools menu that will auto-indent your code. Ctrl-T will do the same.
> 1 votes

# Answer
As for your question, your way is (kind of) the best way.

I just saw a problem: when you keep the button pressed you will go on showing. Moreover I really don't like the delay at the end, and if its purpose is just to avoid bounces, well, use the Bounce2 class.

As for the repeated `if`s, I prefer a `switch-case` statement.

I highly suggest you to use the Bounce2 class, though. Here is an example of its usage:

```
Bounce debouncer = Bounce();

void setup()
{
    ...
    pinMode(buttonPin, INPUT);
    debouncer.attach(buttonPin);
    debouncer.interval(5); // interval in ms
}

void loop()
{
    debouncer.update();
    if (debouncer.rose())
    {
        switch (state)
        {
        case 0:
            {
                int x;
                for (x=0; x <= 4; x++)
                {
                    Serial.println(" ");
                    Serial.print(titles[x]);
                    Serial.print(" ");
                    Serial.print(user_info[x]);
                }
                Serial.println(" ");
                setLights(HIGH, LOW, LOW, LOW);
                state = 1;
            }
            break;
        case 1:
        ...
        }
    }
}

```

As you can see the class has a `rose` member, which tells you if the button was just pressed (only on the rising edge).

Now, your particular problem can be solved in another way. Since you are repeating the same code for all the cases, you can cycle through two arrays; one stating which is the second array you need to use, the other the lights.

This is an example. Please note that I haven't tested it, so there might be some errors

```
char ** second_array[] = { user_info, econ_one, econ_two, econ_three }
uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
                        {LOW, HIGH, LOW, LOW},
                        {LOW, LOW, HIGH, LOW},
                        {LOW, LOW, LOW, HIGH},
                    }

void loop()
{
    debouncer.update();
    if (debouncer.rose())
    {
        int x;
        for (x=0; x <= 4; x++)
        {
            Serial.println(" ");
            Serial.print(titles[x]);
            Serial.print(" ");
            Serial.print(second_array[state][x]);
        }
        Serial.println(" ");
        setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
        state++;
        if (state >= 4)
            state = 0;
    }
}

```

Try to use it and then report back if there is some issue ;)
> 0 votes

---
Tags: array
---


# Question
Title: ESP8266 Arduino 2.2inch ILI9341 TFT library
I recently got one TFT LCD from aliexpress which supports SPI and uses ILI9341.

This is the one.TFT LCD

I have the ESP8266 EspressoLite 1 board, and I am using ESP8266 Arduino. (https://github.com/esp8266/Arduino)

I made the following connection : SCK #14, MOSI #13, MISO #12 and CS #4, DC #5,RESET #0

and used the example graphicTest (which is available in the Adafruit\_ILI9341-master folder) . I was able to make the display work for a few seconds. In the graphic test, once the line test starts my ESP8266 gets restarted. This was getting repeated .

In my existing project, I used the following code to just show some messages :

```
Adafruit_ILI9341 tft = Adafruit_ILI9341(4, 5, 13, 14, 0, 12);
  tft.begin()
  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);
  tft.println(message);

```

The message is shown once a response is sent back from ESP. This works for a couple of times and then it again gets stuck and reboots.

I am not sure whether I am using the optimised library for ESP8266 for this LCD or whether there is any as such.

I read in forums and could see that there were some adafruit libraries in the ESP8266 Arduino but now that it is not available and only some TFT\_Touch\_Shield\_V2 are present.

Has anyone faced the same issue or can tell me a better way to make this display work with ESP8266 Arduino.

Thanks in advance. !!!

# Answer
> 1 votes
You did not include any output from the esp8266, but I'm pretty sure what is happening is that the watchdog timer is expiring and resetting your board. This is because the SPI transactions to transfer data to the display are taking too long.

Put the following line in both `setup()` and `loop()` before any display operations happen:

`wdt_disable();`

Needless to say, if you actually *do* need the WDT in your application, you can reenable it after the display operations complete (of course, if you are doing something that depends on the wdt, you already know this!)

Look at the source for the Adafruit library, make sure there are `#ifdef ESP8266` statements there; older versions did not support the 8266. You may also want to increase the default speed at which the library drives the SPI bus from 8000000. I've gotten it to work at up to 40MHz, with the board flashed at 160MHz of course, and it's a lot faster (unsurprisingly), but if you have long wires or a marginal-quality display, that may fail.

Post pictures :)

---
Tags: lcd, esp8266, adafruit, tft
---


# Question
Title: What is the best way to get more RAM for a sound buffer?
**The problem:**

How to extend the memory for a sound buffer (intensively used) if:

1. SD card library supports only one file open at a time (and I have one open already)
2. EEPROM chips are able to stand about 100,000 write cycles only (see the datasheets!)
3. I can't find anything else to buy! (a standard and durable RAM chip that loses its content when switched off would be the best).

About the 2nd point. Let's assume that the chip is 64KB and I want to use half of it for a circular sound buffer (it's small, I know). Let's also assume that a standard MP3 song is 160kbps and it's 3.5 min long. Given that, the EEPROM chip (with 100k write cycles limit) in this condirions will reach its limit after 3.2GB of played sound, which is about 762 songs, 44 hours. That can be reached in a single week! Replacing a chip every week is not an option. I'm not a fan of planned obsolescence...

Do you know any chip that will be right for the job? (and can be bought on eBay and it's affordable?)

**Background:**

I have built a WWW-controlled MP3 and online radio player (using ESP8266 and VS1003) and it's working really great, we're using it whole days, but ESP is not fast enough to handle WWW requests and play MP3 at the same time (especially from SD card), so the sound is paused for about 0.5 - 1 sec every time a www page is served (a really small page! Just basic HTML with a title and a list of file links!). SD card content cannot be cached for generating the pages on the fly (not enough heap memory) and two files cannot be opened at the same time by the SD library (one is open for the currently playing file - if not playing an online stream - and I'm currently closing it during reading and sending of requested html page). So I've got two memory problems: 1. serving the www pages and 2. buffering the online stream (usually not needed, most streams can play on my 4KB buffer without a glitch whole day but some of them are jamming very often - depends on the server). I'm thinking about both caching the pages (so I don't have to read them from SD and my music won't be interrupted) and creating a circular buffer (for live streams) in external memory chip. It does not need to keep the data after cutting the power. I've got about 24KB of heap left in my sketch (max) and it can fall even to about 6KB when a single folder's content is loaded to memory. It's not far away from heap overflow... I need to load at least the current folder (with long filenames).

# Answer
A simple SPI SRAM chip. Available up to 128KB, such as the 23LC1024: http://www.microchip.com/wwwproducts/en/23LC1024
> 5 votes

# Answer
An FRAM chip?

* Non-volatile (though you don't need that)
* SPI or I^2C available on a breakout board from Adafruit
* Or roll you own from a bare chip, if you're handy with Surface Mount Devices.
> 3 votes

---
Tags: esp8266, sd-card, audio, memory-usage, eeprom
---


# Question
Title: Time Stamping data on an Arduino and reading it on a Java IDE
Does anyone have an idea on the best way to time stamp an arduino sketch that contains a data packet which is to be read out using a java IDE (IntelliJ) for graphic visualization of the packet. I tried declaring the time variable on the arduino section but having problem unpacking the unsigned long variable in java. Below is a snippet of the arduino code.

```
             unsigned long codeTime = 0; //The time the sketch takes to execute
         static unsigned long char dataArray [1]; // a variable to hold both sensor data

         void setup(){
              Serial.begin(9600);
              Serial1.begin(9600);
          }
         void state1(){
             if (Serial1.available()){
                    while (Serial1.available() > 0){
                 codeTime = millis(); //using the millis() instead of micros()
                 //memcpy should copy the whole data into position 0 ????
                 memcpy(&dataArray[0], &codeTime,sizeof(codeTime));
                 uint16_t newByte1 = Serial1.read(); // read in the first byte
                 uint16_t newByte2 = Serial1.read(); //read in the second byte
                 uint16_t dataByte = newByte2 >> 8;
                 dataByte = (dataByte | newByte1);
                 dataArray[1] = dataByte;
                 Serial1.write((uint16_t*)dataArray, sizeOf(dataArray));
                 }
               }
              }

            void loop(){
                   state1();
                   Serial1.flush();  //clear the serial port
                   delay(100);
                }

```

The question now is how do i unpack the data in java to ensure that the time variable (unsigned long time variable is well unpacked in the correct order)????. The second variable i could easily unpack in java as

```
              int variable1 = variable2 >> 8; //as it is a 16 bit integer I shifted
                                              // the msb/lsb accordingly
              variable1 = (variable1 | variable2);  // and finally casting it.

```

# Answer
There's a number of fundamentally wrong things in your sketch.

```
static char buffer[1]; // a variable to hold both sensor data

```

No - that has room for 1 entry - hence the 1. 1 means 1, not 2.

```
buffer[1] = newByte;

```

No. There is no buffer\[1\]. You count slices from 0. buffer\[0\] exists (the first one) but buffer\[1\] doesn't.

```
buffer[0] = millis;

```

You aren't calling the function, you are assigning the address of the function. And worse than that, `buffer` is an array of 8-bit values - neither the address of the function, nor the return value from the function (if you were to fix that) would fit in that space - since the return value is an `unsigned long` which is 4 bytes in size.

You need to have at least 5 bytes in your array - four for the time stamp and one for the value you read from serial. Then you place them in to the array in the order you see fit, and read them back in the same order in Java.
> 1 votes

---
Tags: arduino-due, java
---


# Question
Title: Serial Communication Between Two arduinos (Asking and Receiving)
Can anyone help? I'm trying to develop two sketches, where data can only be sent when a request is made for it between two arduinos. A simple hello world message can suffice. I tried out the Serial Ascii Call and Response on the arduino IDE but it didn't work for me???. Do find below the code sketches

```
//Arduino Sketch 1
uint16_t alpha;
uint16_t lambo;
Banana nanas;    //to hold the Banana object
uint16_t dataArray[2];
void Setup(){
    Serial.begin(9600);
    establishContact();
}

void loop(){
    alpha=nanas.getRad;
    lambo = nanas.getBars;
    dataArray[0] = alpha;
    dataArray[1] = lambo;
    Serial.write((uint8_t*)dataArray, sizeof(dataArray));
    Serial.flush();   //clear the serial port
}

void establishContact()
{
    if (Serial.available())
    {
        while (Serial.available()  > 0)
        {
            int newByte = Serial.read();
            if (newByte == 'Q')
            {
                Serial.write(newByte);
                Serial.flush();
            }
        }
    }
}

```

The sketch for the other arduino is shown below

```
//Arduino sketch 2
static char buffer[2];
void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
    establishContact();
}
void loop(){
    if(Serial1.available())
    {
        while(Serial1.available() > 0){
            uint16_t gondola1 = Serial1.read();
            uint16_t gondola2 = Serial1.read();
            uint16_t crixus = gondola2 >> 8;
            crixus = (crixus | gondola1);

            gondola1 = Serial1.read();
            gondola2 = Serial1.read();
            uint16_t mario = gondola2 >> 8;
            mario = (mario | gondola1);
            buffer[0] = crixus;
            buffer[1] = mario;
            Serial.write(buffer, sizeof(buffer);
            Serial1.flush();
        }
    }
}
void establishContact(){
    if (Serial.available()){
        uint16_t newByte = Serial.read();
        if(newByte == 'Q')
        {
            Serial.flush();
            Serial.write(newByte);
        }
    }
}

```

# Answer
it is not really easy to follow your code but here is a "hello world" procedure to do an on demand data send between two arduinos:

* upload this code to arduino uno before you make any connection on pins 0 and 1 of the board:

```
/**
 * Code for server side (arduino uno)
 */

uint8_t data2send = 'A'; //data to send on a received request
uint8_t incomingByte;

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

void loop() {
        // send data only when you receive data:
        if (Serial.available() > 0) {

                // read the incoming byte:
                incomingByte = Serial.read();

                if(incomingByte=='Q'){  //if incoming data is the expected request (request code = 'Q' in this example)
                        Serial.write(data2send);
                }
        }
}

```
* connect:

```
UNO  | MEGA
------------
pin0 | pin18
pin1 | pin19
GND  | GND

```
* upload to arduino mega this code:

```
 /**
 *  code for arduino mega.
 *
 *  proxy between Serial0 and Serial1
 *
 *  send data to Serial0 to forward it to Serial1.
 *  when data is received from Serial1 it will be forwarded to Serial0.
 */

void setup() {
        // initialize both serial ports:
        Serial.begin(9600);
        Serial1.begin(9600);
}

void loop() {
        // read from port 1, send to port 0:
        if (Serial1.available()) {
                int inByte = Serial1.read();
                Serial.write(inByte);
        }

        // read from port 0, send to port 1:
        if (Serial.available()) {
                int inByte = Serial.read();
                Serial1.write(inByte);
        }
}

```
* open the mega's serial monitor and send some characters. Check that you receive back data only when you send a 'Q' character.
> 3 votes

---
Tags: arduino-uno, serial, arduino-mega
---


title: Using two ultrasonic sensors together

text:
# Question
Title: Using two ultrasonic sensors together
Using two ultrasonic sensors together, how can I enable one before the other?

# Answer
> 1 votes
You need to tell the sensor to send their pulse using the trigger line. So triggering isn't a problem. The problem is that you might get an echo returned on both sensors, but you know which sensor sent the pulse so you can ignore the return that was received by the 'wrong' sensor in your code. So

```
While(1)
{
  SendPulse(SensorTx1);
  GetEcho(SensorRx1);
  SendPulse(SensorTx2);
  GetEcho(SensorRx2);
}

```

Is that what you mean? If not please can you expand you question?

---
Tags: arduino-uno, sketch
---


# Question
Title: How to turn two LED's on and off with one button?
I was wondering how to write a code that would do this, WITHOUT using IF and ELSE: when the button is pressed, one LED is on and the other one is off, but when the button is not pressed, the LED that was on turns off and the other one turns on.

# Answer
Just use the return value of `digitalRead` (which is 1 or 0) as the input to `digitalWrite`:

```
int btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, 1 - btnVal);  // Off when button is HIGH

```

Or using boolean instead:

```
bool btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, !btnVal);     // Off when button is HIGH

```
> 7 votes

# Answer
You could do it with only a `switch`/`case` statement. You do not even need to de-bounce the switch.
> 0 votes

---
Tags: led, button
---


title: error loading an array of strings

text:
# Question
Title: error loading an array of strings
I'm trying to have a user enter a series of strings. This is my code.

this is my error message - cannot convert 'String' to 'char\*' in assignment

```
char* titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup() {
 Serial.begin(9600);
 Serial.println("Storing numbers in an array");
}

void loop()

{

for (int x =0; x < 5; x++)
{
  if (Serial.available() > 0)

  {
   Serial.println("Enter a word... ");
   titles[x] = Serial.readString();

    Serial.println(" ");
    Serial.println(chartitles[x]);

   }
  }
 }

```

# Answer
So, you are confusing the object String of Arduino with a string of C (char array), to solve your problem, I've changed your code in two parts:

```
String titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup(){
  Serial.begin(9600);
  Serial.println("Storing numbers in an array");
}

void loop(){
  for (int x = 0; x < 5; x++){
    if (Serial.available() > 0){
      Serial.println("Enter a word... ");
      titles[x] = Serial.readString();
      Serial.println(" ");
      Serial.println(titles[x]);
    }
  }
}

```

So, in order to use Seria.readString(), you have to use String objects to receive the data from Serial port:

```
String titles[]

```

Instead of:

```
char* titles[]

```

The second change is related to Serial.println(chartitles\[x\]), I didn't understand what you mean with this code, so I changed in order to print the String that was read.
> 1 votes

---
Tags: string
---


# Question
Title: I’m having a tough time trying to program 2 fsr sensors
Can anyone help me please? I’m having a tough time trying to program 2 fsr sensors. The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed? I have got only one to work by using this code:

```
/* FSR simple testing sketch.

Connect one end of FSR to power, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground

For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading

  // We'll have a few threshholds, qualitatively determined
  if (fsrReading < 10) {
    Serial.println(" - No pressure");
  } else if (fsrReading < 200) {
    Serial.println(" - Light touch");
  } else if (fsrReading < 500) {
    Serial.println(" - Light squeeze");
  } else if (fsrReading < 800) {
    Serial.println(" - Medium squeeze");
  } else {
    Serial.println(" - Big squeeze");
  }
  delay(1000);
}

```

So what would be the correct code in order to get two sensors to work at the same time?

# Answer
Call your second FSR "fsr2" connect it to analog pin A1 and add to your existing code. Sort of like this:

```
int fsrPin = 0, fsr2Pin = 1;     // the FSR and 10K pulldown are   connected to a0
int fsrReading, fsr2Reading;     // the analog reading from the FSR resistor divider

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);
  delay(5);
  fsr2Reading = analogRead(fsr2Pin);

  Serial.print("Analog reading = ");
  Serial.print(fsrReading);     // the raw analog reading
  Serial.print("\t");
  Serial.print(fsr2Reading);

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Value of joystick reduces when I send it over serial
I've got two arduino cards and two bluetooth bluesmirfs. I am currently trying to read value from a joystick and send it over to the other arduino card and use that value to control my servo motor.

Here's my code.

```
       //Master Code
void loop()
{
    yVal = analogRead(yAxis);   (value between 0 and 1023)
  if(bluetooth.available())
  {

    bluetooth.print(yVal);
  }
  else if(Serial.available())
  {

    Serial.print(yVal);
  }
  delay(100);
}

//Slave code
void loop(){
  while(Serial.available())
  {

    int c = Serial.read();
    Serial.print("Joystick value: ");
    Serial.println(c);
    int val = map(c, 0, 1023, 0, 255);
    Serial.print("Map value: ");
    Serial.println(val);

      myServo.write(val);
    }
  }

```

Am I doing something wrong? Instead of getting something between 0 and 1023 I get something below 50.

# Answer
A fundamental lack of understanding of how serial communications works is what you have.

Serial sends bytes. You are attempting to read an int. The two don't match. Not only that, but you are sending the value as text, not a number, so you're interpreting it as gibberish.

My suggestion: do the `map` on the master not the slave, and send a raw byte between 0 and 255 not a string of text between "0" and "1023".

```
bluetooth.write(map(yVal, 0, 1023, 0, 255));

```
> 0 votes

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


# Question
Title: Working on a reaction test for the Arduino Uno using an led and an lcd shield
The situation involves some Asm inline practice and a basic circuit. The program turns an LED on after a somewhat random period of time then waits until the button is pressed to report back how many milliseconds it took. This is then printed by the LCD shield. My confusion occurs because after each reset it prints a 1 before the button is pressed, which overlaps returned millisecond value on the screen giving me some false data. I tried to cut the code down so if there is anything else that might be helpful let me know. I think the issue may be in the test reaction time function but am not sure.

```
/* --------------------------------------------------------------------------------------
  Includes
--------------------------------------------------------------------------------------*/
#include <LiquidCrystal.h>   // include LCD library

/*--------------------------------------------------------------------------------------
  Init the LCD library with the LCD pins to be used
--------------------------------------------------------------------------------------*/
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
/*--------------------------------------------------------------------------------------
  setup()
  Called by the Arduino framework once, before the main loop begins
--------------------------------------------------------------------------------------*/

void setup()
{
   //button adc input
   pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
   digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
   //lcd backlight control
   digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is high (on)
   pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
   pinMode(3,OUTPUT);                         //d4 is are LED
   //set up the LCD number of columns and rows:
   lcd.begin( 16, 2 );
   //Print some initial text to the LCD.
   lcd.setCursor( 0, 0 );   //top left
   //          1234567890123456
   lcd.print( "LinkSprite  16x2" );
   //
   lcd.setCursor( 0, 1 );   //bottom left
   //          1234567890123456
  // lcd.print( "Btn:" );

    Serial.begin(9600);

 pinMode(2, INPUT);

 }
/*--------------------------------------------------------------------------------------
  loop()
  Arduino main loop
--------------------------------------------------------------------------------------*/
void loop()
{

      //read the button
     byte result;//  = digitalRead(2);
      asm volatile(
          "ldi %0, 0 \n\t"
          "sbic 0x09, 2 \n\t"
          "ldi %0,1 \n\t"
          "nop \n\t"
          :"=r" (result)
          :
          :
      );
      int t =(random(0, 10000)+1000);
      unsigned long currentM = millis();
      //int t =(random(0, 10000)+1000 +millis());
      while( t < currentM){
      int x = testReactionTime();
       lcd.setCursor( 0, 1 );
     //if (result){
         lcd.print( "on " );
         lcd.setCursor(7,1);
         lcd.print(" ");
         //int x = testReactionTime();
         lcd.print(x,DEC);
         //delay(1000);
         //lcd.print("     ");
      //}else{
        //testReactionTime();
        // delay(random(0, 1000)+1000);
        //lcd.print( x,DEC );
        //digitalWrite(3, LOW);
      }
//}
}

/*
 *  after a random delay call this function to measure their reaction
 *  time in milliseconds
 *  It will immediately turn on a LED (pin 3)
 *  And then start timing the milliseconds until they hit the button (pin 2)
 *
 */
int testReactionTime()
{
  int answer;
  //delay(rand());
  asm volatile(
    "ldi %A0, 0 \n\t"  // initializw anwer to 0
    "ldi %B0, 0 \n\t"  // answer should be the number of ms until they hit the button
    "sbi 0x0b,3 \n\t"  //turn on the led pin 3
    "ldi r16, 1 \n\t"
    "ldi r17,0 \n\t"
    "movw r26, %0 \n\t"
    "rcall killms%= \n\t"
   "cbi 0x0b,3 \n\t"  //turn on the led pin 3

      "rjmp end%= \n\t" //skip over the routine
      //start of kill millesecond subrouting, need to waste ~16000 clock cycles
      "killms%=:ldi r24, 0x90 \n\t"  //lo8(3984)
      "ldi 25, 0x0f  \n\t"      //hi8(3984)
      "kloop%=: sbiw r24, 1 \n\t"   //2 clocks
       "brne kloop%=   \n\t"       //2 clocks since most times true!!
       "add r26, r16 \n\t"
       "adc r26, r17 \n\t"
       "movw %0, r26 \n\t"
       "sbis 0x09, 2 \n\t"
       "ret       \n\t"
       "rcall killms%= \n\t"
      //end of the kill millesecond loop
      "end%=: nop \n\t"
    :"=r" (answer)
    :
    :"r24", "r25"
    );

  return answer;
}

```

# Answer
> 2 votes
Expanding on my comment... I see a few issues in your asm code, not all as serious as the first one:

1. `killms` is calling itself recursively indefinitely, which should overflow your stack. The last `rcall killms%=` should probably be an `rjmp`.
2. There is no need to move the answer around between register pairs. Just use the compiler-allocated registers instead of `r17:r16`.
3. By `adc r26, r17`, you probably mean `adc r27, r17`.
4. Instead of `add` and `adc`, you could just `adiw`, which saves a register pair.

Below is my version of `testReactionTime()`. I tested it on an Uno (with `Serial` instead of an LCD) and it works fine. The assumptions on the hardware are:

* The LED is on pin 13 (PB5): it's the built-in LED.
* The button is on pin 2 (PD2), which goes HIGH when the button is pressed.

```
/*
 * After a random delay, call this function to measure the reaction time
 * in milliseconds. It will immediately turn the built-in LED and then
 * start timing the milliseconds until the user hits the button (pin 2
 * going HIGH).
 */
int testReactionTime()
{
    int result, counter;
    asm volatile(
        "    clr %A[result]                      \n" // clear result
        "    clr %B[result]                      \n" // ditto
        "    sbi %[led_port], %[led_bit]         \n" // LED on

        // delay to make the loop 0 last exactly one millisecond
        "0:  ldi %A[counter], lo8(%[iterations]) \n"
        "    ldi %B[counter], hi8(%[iterations]) \n"
        "1:  sbiw %[counter], 1                  \n"
        "    brne 1b                             \n"
        "    nop                                 \n"

        "    sbic %[button_pin], %[button_bit]   \n" // unless button up:
        "    rjmp 2f                             \n" //     we are done
        "    adiw %[result], 1                   \n" // increment result
        "    rjmp 0b                             \n" // loop back
        "2:  cbi %[led_port], %[led_bit]         \n" // done: LED off

        : [result]     "=w" (result)
        , [counter]    "=w" (counter)
        : [led_port]   "I"  (_SFR_IO_ADDR(PORTB))  // LED on PB5
        , [led_bit]    "I"  (5)
        , [button_pin] "I"  (_SFR_IO_ADDR(PIND))   // button on PD2
        , [button_bit] "I"  (2)
        , [iterations] "i"  ((16000 - 8) / 4)
    );
    return result;
}

```

---
Tags: arduino-uno, lcd, pins, assembly
---


# Question
Title: Is it safe to place a capacitor across vin and gnd?
I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

The ATX is gated by a relay on its DC side and seems to cause enough of a current drain that it causes the Arduino to reset.

I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

Standard?

EDIT: Here's a very basic sketch..

12V Transformer powers arduino on VIN/GND pins, other pins are 5V, GND and control for relay

# Answer
> 2 votes
> I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

I don't entirely follow that wording. Please draw a picture.

> I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

470µF is fine. In this situation the bigger the better. If 470µF fixes it then 470µF is fine. Don't be afraid of going higher though. I have 3,300µF capacitors here that are commonly used for similar purposes.

What you have implemented is called a *reservoir* capacitor and is a common use for large value capacitors like that.

---
Tags: power, electronics
---


title: Atmega328P - SCK pin

text:
# Question
Title: Atmega328P - SCK pin
I am using Atmega328p with arduino bootloader in a project. There happens to be an LED connected on SCK pin. During Start (or restarts), the LED appears to flicker a couple of times (3 times to be exact). I don't want this to happen. I can change the connections but I would prefer a software solution because hardware change means a PCB modification.

I probed the SCK pin and I got some expected waveforms. There were two different cases:

1) When I powered the arduino using USB to serial programmer i.e. Tx Rx connected to a PC:

2) When I powered the arduino with an external power source (the case with my project):

This is what I think:

1) As mentioned in this thread, the bootloader has a piece of code which makes it act that way. The bootloader code has a pin definition file which declares SCK pin as a LED and blinks it a couple of times to indicate that it has entered the bootloader. I found the code here:

```
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__)
/* Onboard LED is connected to pin PB5 in Arduino NG, Diecimila, and Duemilanove */
#define LED_DDR     DDRB
#define LED_PORT    PORTB
#define LED_PIN     PINB
#define LED         PINB5

```

Other relevant piece of code is here.

In this case, changing the LED definition to PINB4 and burning the bootloader and program again should take care of the issue. However this didn't work out for me. This is what I did exactly:

a) Opened the file D:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot\pin\_defs.h

b) Modified the PINB5 to PINB4 on line 6.

c) Saved the file, burnt the bootloader and then program.

d) Powered up the chip and tested whether I am getting those 3 pulses. I got those 3 pulses.

(Even though it didn't work, I am still going to try it a few more times just in case I might have made an error.) :(

2) This brings me to second thought that since atmega328 accepts code through SPI by default, it checks for incoming data by clocking the SCK pins 3 times during startup. In this case, a software fix won't do anything.

What do you guys suggest? Should I go for the PCB modification or is there still some hope left?

Ignacio pointed out that I can disable bootloader to get rid of the issue. I want to program the chip using arduino IDE (preferably via UART) but I can consider SPI as well in case everything else fails.

Note: I am not sure whether this post is more suited for EE or Arduino. In case you guys(mods) think I'd get better suggestions there, feel free to move my post to Arduino.

# Answer
> 1 votes
I compiled Optiboot a while back using the shell script below. This is for Linux, you may need to adapt slightly for other operating systems.

```
BIN_LOCATION='/home/nick/Development/arduino-1.6.5-r5/hardware/tools/avr/bin'

$BIN_LOCATION/avr-gcc -mmcu=atmega328p \
    -D__AVR_ATmega328P__ \
    -DF_CPU=16000000L \
    -DBOOTLOADER_ADDRESS=7E00\
    -DBAUD_RATE=115200 \
    -DLED_START_FLASHES=0 \
    -DOPTIBOOT_FIX=1 \
    -Os \
    -gdwarf-2 \
    -fno-inline-small-functions \
    -fno-split-wide-types \
    -fno-tree-scev-cprop  \
    -fno-exceptions -ffunction-sections -fdata-sections \
    -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -fno-jump-tables  \
    -fno-keep-inline-functions -fno-common \
    -std=gnu99 \
    -Wl,--section-start=.text=7E00 \
    -Wl,--relax -nostartfiles \
    -Wl,--gc-sections \
    -ooptiboot.elf optiboot.c

rm -f optiboot.hex

$BIN_LOCATION/avr-objcopy -O ihex --set-section-flags=.eeprom=alloc,load \
    --no-change-warnings \
    --change-section-lma \
    .eeprom=0 \
    -R .eeprom optiboot.elf optiboot.hex

$BIN_LOCATION/avr-objdump -j .sec1 -d -m avr5 optiboot.hex > optiboot.lst

```

You will need to find where your copy of avr-gcc and insert that into the first line above.

Notice I have changed the define for `LED_START_FLASHES` to be zero above. That should fix the issue.

To save you the trouble of doing that, I have made a "no blink" version for the Atmega328 and put it here:

http://gammon.com.au/Arduino/optiboot\_no\_blink\_atmega328.hex

**Warning** \- the script above compiled the "no blink" version OK, but using the latest version of the Optiboot.c code, and the latest compiler, makes a .hex file that is four bytes too long, for reasons I can't work out. However it compiles fine if you omit the blinks, because there is less code there.

---

Note re the LED on D13. Because the LED is driven by an op-amp (on the Uno), it will flash even with the above code. However that is because the op-amp has a high-impedance input. If you use a pull-down resistor on D13 it won't flash.

---

Now that I look at the download, it is so short I may as well include it here:

```
:107E0000112482E08093C00088E18093C10086E065
:107E10008093C20080E18093C40084B714BE81FFC8
:107E2000C8D088E1809360008DE080936000259A3F
:107E300018E108E033E0F32EEE24EA94DD24D39435
:107E400045E0C42E51E1B52EA7D0813429F481E05C
:107E5000BED083E09AD096C0823419F484E1B7D0C2
:107E600091C0853419F485E0B2D08CC0853599F481
:107E700093D0C82FD0E0D0930102C09300028CD0E1
:107E80009E01382BC901880F991F9093010280939E
:107E9000000297D077C0863529F484E098D080E03E
:107EA00074D070C0843609F042C07ED0E0910002E8
:107EB000F0910102F0925700E895C0E0D1E002C0D5
:107EC0006BD089938C2F90910202C917C8F38C1B39
:107ED00001C0E9929C2F980F9034D8F372D007B666
:107EE00000FCFDCF40910002509101029A01A0E0F8
:107EF000B1E08C911296FD013197608190E0962B54
:107F0000F9010C01D0925700E89511242E5F3F4FE4
:107F1000A038F1E0BF0769F7FA01C0925700E89571
:107F200007B600FCFDCFB0925700E8952BC0843710
:107F3000B1F43AD046D0E0910002F0910102CF01B5
:107F40000196909301028093000284911ED080914B
:107F500002028150809302028111EDCF13C0853758
:107F600041F42FD08EE111D085E90FD08FE00DD0F4
:107F700009C0813531F4109360000093600021D076
:107F800001C01FD080E101D05FCF9091C00095FF6C
:107F9000FCCF8093C6000895A8958091C00087FF0C
:107FA000FCCF8091C6000895F7DFF6DF80930202D0
:107FB000F3CFE0E6F0E088E180831082EE27FF2730
:107FC0000994EADF803209F0F4DF84E1DECFCF9359
:0C7FD000C82FE2DFC150E9F7CF91F3CFDA
:0400000300007E007B
:00000001FF

```

Just save that as optiboot.hex.

# Answer
> 1 votes
There is nothing in the default megaAVR initialization that causes SCK to behave in this manner; it is all caused by the bootloader.

Fortunately all you have to do to solve this is disable the bootloader. Unprogramming the `BOOTRST` fuse (ext:0) will cause execution to start at address 0 instead of the beginning of the bootloader on reset.

---
Tags: spi
---


# Question
Title: Using an Arduino to drive a digital RGB LED strip
I recently purchased a 5M strip of digital RGB LEDs, that is compatible with the "Adafruit\_NeoPixel.h" library.

Is maintaining the original order of the LEDs important? Could I cut the strip in say four sections, and then reconnect those sections out of their original order?

Just to be clear these are digital 3-pin(+5V,DI,GRN) strips, not analog 4-pin(+12V, R, G, B) strips.

I'm just not finding good info regarding if the individual LEDs are pre-assigned an ID by the manufacturer, or if they somehow use a serial-timing way to assign IDs at startup.

Before digging through the Adafruit\_NeoPixel.h, I wanted to see if I could get a quicker answer here.

THANKS!

# Answer
I can not find detailed information regarding the 5M LED strips you bought.

I have used Adafruit addressable LED strips. What Adafruit publishes on their web site helped a great deal when I cut my strips into smaller sizes.

Here is an Adafruit image which may help you:

I would think the order does not matter. But you do need to connect the data such that "outs" go to "ins". And you need to connect them in a row. That is you need to connect them in one loop.

Added later...

Assuming we are using the WS2812:

We know from the specifications that the RGB data is encoded as 3 8 bit NZR (Non Zero Return) pulses. 8 bits for each color: red, green & blue. That there is 1 such "word" of 24 bits for each pixel. That the beginning of a set of "words" is marked by a 50us or grater interval where DI is zero. And that each pixel strips off the first 24 bit "word" before passing the balance of the data on.

In other words, it doesn't matter what order WS2812 are assembled in. Also that WS2812 have no idea where they are in the sequence. All that matters is that each succeeding WS2812 gets its data from the previous WS2812.

One last note. The necessary timing is really fast and really tight. Can't be more than 150 billionths of a second off. No way can a multitasking platform like a PC, Mac or RaspberryPi pull this off. When sending off a set of "words" to a string of pixels, the embedded processor will likely not be doing anything else!
> 0 votes

---
Tags: rgb-led
---


# Question
Title: Do I need 3 voltage dividers to control ESP8266
I am buying an ESP8266 and the plan is to control it serially from an Arduino. I am going to use a voltage divider(Using a voltage divider is temporary and I know the cons of using voltage dividers).

I calculated out the values of the voltage divider and I am going to use 220 ohm and 440 ohm value resistors to get 3.3 volts and 250 ma from the Arduino 5v pin so I can power vcc and ch\_pd on the ESP8266.

**The question** is do I need to use a separate voltage divider to connect Arduino TX to ESP8266 RX and Arduino RX to ESP8266 TX. Or will it be safe to connect RX and TX directly to Arduino RX and TX.

Honestly I am extremely new to this and I don't even know if I am going at this right. If I am tell me.

# Answer
For **ESP 3.3V power supply**, I'd recommend a distinct 3.3V regulated supply.

Of course, the Arduino UNO already has a 3.3V output but it may not supply enough current to the ESP (current consumption can go up to almost 200mA): UNO 3.3V pin is limited to 50mA. So do not use it or you may roast your UNO.

Using resistors to output 3.3V from Arduino 5V might be possible (the UNO 5V pin can provide ~400mA) but it would be a big waste of energy because you'd have to use low resistor values to be able to supply 200mA for instance.

You might possibly use a 7833 regulator with additional caps to provide 3.3V from Arduino 5V pin (or `Vin` directly if your UNO is powered through the DC power jack, not USB)

For **ESP RX** a voltage divider is foreseeable but it may trigger issues due its switching response time, which may be too slow when transmitting data at high baud rates. I recommend using a MOSFET based level shifter:

The advantages of this circuit are:

* it has the fastest switching response time
* it can work in both directions (3.3V -\> 5V and 5V -\> 3.3V)

You can also buy some cheap ready-made breakouts using this circuit and offering several level shifters.

For **ESP TX**, I'd also recommend the same level shifter circuit as for RX (if you can make one, you can make two).
> 3 votes

# Answer
The RX pin is 5V tolerant (at least it is on all of my boards!) and almost certainly your arduino will recognize 3V as logic high for the TX pin. So you don't really need any level conversions there (no other pin is 5V tolerant).

Are you sure your ESP8266 board doesn't already have a 5V to 3V3 regulator? I've never seen one!
> 1 votes

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


# Question
Title: How to import data from SDcard on Arduino to the computer using Arduino serial/COM port?
I have Arduino UNO with Adaruit wifi shield. I store some data on the sd card successfully and now I need to import that data on to the computer.

I am sending some token, say "1", to the UART port of Arduino (COM port), there is a code written on the Arduino which responds to that token and sends data (byte by byte) in the bulk amount on the serial of the Arduino. I have to accept bytes and store in a file on the local machine (computer) and upload to the server ultimately at the same time.

(It will be good if the process has the browser support i.e I will send request from web browser to API and that API will connect to serial port/ COMP port of my Computer and somehow the file will be created on the local machine and the data from the Arduino will be saved in that file; the file created will be uploaded to the server ultimately.)

What is the proper way to this, is there any API or software for it?

Please help me out.

Thanks in advance!

# Answer
There is an example for the ESP8266 (using the Arduino IDE) called SDWebServer which might give you some ideas, I would suggest you try it but I doubt the libraries would work on an Arduino.

If you are going to support a web API, I would suggest you implement a REST API on the Arduino, that is a commonly used API for these type of things.

1. The client (PC) sends a HTTP GET request to the server (Arduino) with the token you want.
2. The server responds with the data the token corresponds to.

You are using standard HTTP (you can do it through a browser), so it should go through firewalls without a problem. Its a very common format, there are plenty of tools to debug it and tutorials for all sorts of platforms that you should be able learn from.

The problem is REST API isn't the best solution for Serial comms, I'm not saying its impossible you could send the network messages via serial, but it wouldn't be pretty. I think you would be better keeping your custom interface for the serial and moving as much of the code into common functions so you can share it between the two interfaces.

Hope that helps
> 1 votes

---
Tags: arduino-uno, serial, sd-card, web-server, uart
---