body: SoftwareSerial is reliable only up to 9600 baud or so. You can either swap ports and use Software serial as your debug output (but requires disconnecting/reconnecting the ESP8266 chip each time you upload to the UNO); or write a short sketch to set the device's baud rate to 9600 baud (and convince yourself that at least that much ran OK!) and set your SoftwareSerial to that rate.


sender: user

message:
Esp8266-01 AT commands returns random chars and/or "ERROR"

I'm trying to make my esp8266 work with my arduino.

But when I send AT commands I get some weird symbols and some functions return "ERROR"

Here's the code I'm using.

    #include "SoftwareSerial.h"

    SoftwareSerial esp8266(6, 7); // RX, TX

    void setup()
    {
      Serial.begin(9600); // serial port used for debugging
      esp8266.begin(115200);  // your ESP's baud rate might be different
    }

    void loop()
    {
      if(esp8266.available())  // check if the ESP is sending a message
      {
        while(esp8266.available())
        {
          char c = esp8266.read();  // read the next character.

          Serial.write(c);  // writes data to the serial monitor
        }
      }

      if(Serial.available())
      {
        delay(10);  // wait to let all the input command in the serial buffer

        // read the input command in a string
        String cmd = "";
        while(Serial.available())
        {
          cmd += (char)Serial.read();
        }
        // send to the esp8266
        esp8266.println(cmd);
      }
    }

Here's the Serial Monitor:

    AT

    OK
    AT+RST

    OK

     ets Jan  8 2013,rst catse:2, boot lode:(3,7)

    loab 0x40100000& len 1396, qoom 16
    tail 4C�,kk�������e
    load 0x3fge8000, len 776, room 4 tak0  t0�v�
    �!jH+��
    ����(j5�!
    ,�2%1�

    j
    �sl��o�
    Ai,Thinker Technology Co. Ltd.

    invalid
    AT+CWMODE?

    +CWMODE:1

    OK

    AT+GMR

    AT version;0.25.0.0(Juo  5 2015 17:27:16)
    SDK version:1.0
    ryJ 0

    AT+CWLAP

    +CWLAP:(4,"�P��R�*bj��b���*��2��*����Ҋ�b�Jj
    ��*A�B�br������Յź�aj��b����2j
    ":6�*AՉ����J
    "�́������

The commands where, `AT`, `AT+RST`, `AT+CWMODE?`, `AT+GMR`, `AT+CWLAP`

Why am I getting this weird symbols and etc? I haven't upgraded the firmware, should I?  There other commands I tried return "ERROR" or even "ERROQ"

I don't have a USB to TTL or any other board. I connected my board in the arduino with this schematic:

[![esp8266 connection to arduino using voltage regulator][1]][1]

  [1]: https://i.stack.imgur.com/nVxnL.png

Cap = 10uF
VolReg = LM1117 3.3v

sender: assistant

body:
 - The Arduino pin 7 (TX) signal must be level-shifted from 5V to 3.3V using a voltage divider, because the ESP cant handle 5V signals.
 - The Serial baud is a lot lower than that of SoftwareSerial plus you are spending a lot of time waiting for the whole command to come in. SoftwareSerial is also unreliable at 115200 baud. Use 57600 baud for both serial ports.

Use this code:

    SoftwareSerial esp8266(6, 7); // RX, TX

    void setup()
    {
      Serial.begin(57600);
      esp8266.begin(57600);
    }

    void loop()
    {
      while (Serial.available())
        esp8266.write(Serial.read());
      while (esp8266.available())
        Serial.write(esp8266.read());
    }

It will do the exact same thing you want to do. Good luck.


body:
I had the same issue before and it is a little bug in your code - while reading all the data from the serial port, you also read the CR & NL and then you send that as a line (with probably another NL). I solved it as such:

      if(Serial.available())
      {
        String command="";
        uint8_t c=0;
        while(c!=10) // read the command character by character
        {
          if (Serial.available()) {
            c=Serial.read();
            command+=(char)c;
          }
        }
        //Serial.print("Sending: ");
        //Serial.println(command);
        esp8266.print(command); // send the read character to the esp8266
      }

As you can tell, I was suspicious of the code and echoed back to make sure the reading from the `Serial` function. Also I went back to straight USB->Uno->ESP mode to confirm all was working, even the firmware with the 9600 Baud uploaded and then it clicked.


body:
These values mostly come when you are unable to communicate with any UART device on proper baud rate. Best is to change the baud rate of ESP8266 from dafault 115200 to 9600 using

    AT+UART_DEF=9600,8,1,0,3

And then use the regular program. And you will get what you want.

    #include <SoftwareSerial.h>
    #include<stdio.h>
    SoftwareSerial mySerial(2,3);
    void get_wifi_list();
    uint8_t flag = 0;

    void setup() {

        Serial.begin(9600);
        Serial.println("Starting the code, initial set-up");
        mySerial.begin(9600);
        delay(1000);
        Serial.println("Inside the main loop, going to start communicating with ESP8266");
        delay(1000);

    }

    void loop(){

      char data[1024];
      uint8_t ch = -1;
      uint8_t index = 0;
      memset(&data,0,sizeof(data));
      char data1[200];
      uint8_t index1 = 0;
      memset(&data1,0,sizeof(data1));

      if(mySerial.available())  // check if the ESP is sending a message
        {
        while(mySerial.available())
            {
                char c = mySerial.read();  // read the next character.
                data[index] = c;
                index++;
                if(index >= 2000){
                    Serial.print("Data received exceed allowed length \n");
                    return;
                    }
                    if (c == '+' ){
                        Serial.print("got start char");
                        //data1[index1] = c;
                        //index1++;
                        //if ( c== '\n');{
                        //    Serial.print("First data1 is :  ");
                        //    Serial.println(data1);
                        //    return;
                        //    }

          if( strstr(data,"OK")!=NULL || strstr(data,"CWLAP") !=NULL){
          Serial.print ("Get reply as OK \n");
          Serial.print (data);

            }
          }
        }
      }
      if (flag == 0){
          get_wifi_list();
          Serial.println("Getting the wifi list");
          flag = 1;
          return;
      }

      if(Serial.available()){
        delay(10);
        String cmd = "";
        while(Serial.available()){
            cmd += (char)Serial.read();
            }
        mySerial.println(cmd);
          }

    }

    void get_wifi_list(){
      String cmd = "AT+CWLAP";
      mySerial.println(cmd);
    }


message:
Is my Arduino board defect? No matter what program I upload the pin 13 turns on and off 3 times and that's it

Just trying to find out if my Arduino UNO R1 board is broken or not.

First of all, everything seems normal, Arduino board shows "on" (green) when I plug it on my computer, I also can verify and upload programs to my Arduino board. But, no matter what program I upload the pin 13 turns on and off 3 times and that's it. I'm checkin it by using a LED.
Eg. if I want to use another pin (ex. 7, 8, 12) it doesn't work, or even to write a program for turning on/off 9 times pin 13 doesn't work...

Note: I noticed that pin 8 turns the LED for less than a 1/2 a second.

I already tried to restart board by bridging the reset pin and also by pushing reset directly on the board, I also reinstalled Arduino Genuino Application. I thought to update Atmega8U2 firmware but accordingly to Arduino [site][1] I don't need to update since I have firmware rev. 0.01.

It would be also great not to have to buy a new Arduino UNO. Thanks for your help

Edit:
Here is how I'm trying to make pin 12 work

    int ledPin = 12;

    void setup()
    {
     pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
     digitalWrite(ledPin, HIGH);
     delay(2000);
     digitalWrite(ledPin, LOW);
     delay(2000);
    }

  [1]: https://www.arduino.cc/en/Hacking/DFUProgramming8U2

body:
The best way to check if Arduino is working or not is to install Firmata. Here's the necessary steps:

1) Download Firmata application from the [official website][1].

  [1]: http://www.firmata.org/wiki/Main_Page#Firmata_Test_Program

2) Connect Arduino to the computer

3) Open the Arduino IDE and burn the example Standard Firmata [File - Examples - Firmata - Standard Firmata]

4) Open the application, leaving the Arduino connected.

5) Chose the right serial port and debug every pin =D


message:
Water heater coding problem

I need help with my coding. I'm still learning on how to use interval `millis()`.

Currently I'm working on a water heater with a safety feature. This means that you can only pour water out when you activate the child-lock feature. The child-lock feature will turn on for 5 seconds and within that 5 seconds if you pour the water out, the timer will pause until you finish pouring your water and the 5 second timer will start again and the system goes off after that.

If the child lock feature on for 5 second without any action, it will turn off the system again. My lecturer does not allow me to use the `delay()` function so I already did my coding using `millis()`.

This is my code so far:

    const int redLed = 2;
    const int greenLed = 3;
    const int yellowLed = 4;
    const int greenbigLed = 7;

    const int buttonPin1 = 5;
    const int buttonPin2 = 6;

    int buttonState1 = 0;
    int buttonState2 = 0;
    float tempC ;
    int analogPin = A0;
    int yellowLedState = 0;

    const long interval1 =0;
    const long interval2 = 5000;
    unsigned long previousMillis = 0;

    void setup() {
      // put your setup code here, to run once:
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,INPUT);
    pinMode(6,INPUT);
    Serial.begin(9600);
    digitalWrite(yellowLed,yellowLedState);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    int analogValue = analogRead(analogPin);
    int buttonState1 = digitalRead(buttonPin1);
    int buttonState2 = digitalRead(buttonPin2);
    int yellowLedState = digitalRead(yellowLed);
    tempC = analogValue / 10 ;
    Serial.println(tempC);
    unsigned long currentMillis = millis();
    unsigned long currentMillis2 = millis();

    if (tempC <= 89.9 && tempC >= 0){
      digitalWrite(redLed,HIGH);
      digitalWrite(greenLed,LOW);
    }else if(tempC == 102){
      digitalWrite(redLed,LOW);
      digitalWrite(greenLed,HIGH);
    }

    if(currentMillis - previousMillis >= interval2){
      previousMillis = currentMillis;
      if(buttonState1 == HIGH){
       // if(currentMillis2 - previousMillis2 >=interval2){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
      } else{
      digitalWrite(yellowLed,LOW);
        }
    }

    if (buttonState2 == HIGH && yellowLedState == HIGH){
      digitalWrite(greenbigLed, HIGH);
    }else{
      digitalWrite(greenbigLed,LOW);
    }

    }

Now, I'm able to pour out water when child lock feature activated, but the problem is the timer (interval) still ticking.

Is there any solution on how can I pause the interval whenever I'm pouring water (button2) and the interval starts back 5 sec when I release button2 (pouring water)?

I would glad if someone can help me. Ask me anything about my code.

body:
Thanks @Arjan for reminding me. I would love to contribute to the community. So this is my final coding and its worked for me :

    const int redLed = 2;
    const int greenLed = 3;
    const int yellowLed = 4;
    const int greenbigLed = 7;

    const int buttonPin1 = 5;
    const int buttonPin2 = 6;

    int buttonState1 = 0;
    int buttonState2 = 0;
    float tempC ;
    int analogPin = A0;
    int yellowLedState = 0;

    const long interval = 5000;
    unsigned long previousMillis = 0;

    void setup() {
      // put your setup code here, to run once:
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,INPUT);
    pinMode(6,INPUT);
    Serial.begin(9600);
    digitalWrite(yellowLed,yellowLedState);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    int analogValue = analogRead(analogPin);
    int buttonState1 = digitalRead(buttonPin1);
    int buttonState2 = digitalRead(buttonPin2);
    int yellowLedState = digitalRead(yellowLed);
    tempC = analogValue / 10 ;
    Serial.println(tempC);
    unsigned long currentMillis = millis();

    if (tempC <= 89.9 && tempC >= 0){
      digitalWrite(redLed,HIGH);
      digitalWrite(greenLed,LOW);
    }else if(tempC == 102){
      digitalWrite(redLed,LOW);
      digitalWrite(greenLed,HIGH);
    }

    if(currentMillis - previousMillis >= interval){
      previousMillis = currentMillis;
          if(buttonState1 == HIGH){
             if (yellowLedState == LOW) {
                  yellowLedState = HIGH;
        }
        digitalWrite(yellowLed, yellowLedState);
      } else{
          digitalWrite(yellowLed,LOW);
        }
    }

    if (buttonState2 == HIGH && yellowLedState == HIGH){
      digitalWrite(greenbigLed, HIGH);
      digitalWrite(yellowLed,HIGH);
    }else{
      digitalWrite(greenbigLed,LOW);
      if(currentMillis - previousMillis >= interval){
      previousMillis = currentMillis;
          if(buttonState1 == HIGH){
             if (yellowLedState == LOW) {
                  yellowLedState = HIGH;
        }
        digitalWrite(yellowLed, yellowLedState);
      } else{
          digitalWrite(yellowLed,LOW);
        }
    }
    }
    }


message:
Debugging with ISP

I would like to connect the Atmega328p chip to my desktop, through the USB, so I can run teraterm or hyperterminal for debugging purposes.
I have already ordered a USB to TTL serial cable but it won't be arriving for about a week.
I recently bought a usbASP ISP to program the chip on my Arduino.
My question is: can I use the usbASP in place of the TTL cable? or is there some conditioning circuit in the usbASP that won't allow this?

It seems for the usb to ttl, all that is required to interface with the chip is VCC, GRD, RX and TX. So, which pins are the RX and TX?

Hope my question makes sense, they usually don't! thanks in advance!

body:
There *is* provision in the USBasp specification for a UART connection, **however**, not all manufacturers copy the original schematic exactly, and no firmware actually contains the appropriate code for CDC/ACM required in order to enable it. And even if they did, technically low-speed CDC/ACM is a violation of the USB protocol and not all operating systems will acknowledge it.

As for your title of "Debugging with ISP", if you have an Atmel programmer and are using Atmel Studio then you *can* perform debugging over ISP (actually debugWIRE, but they use the same connections).


message:
Is this a USBasp I can use with Arduino?

I bought the following USBasp off of Aliexpress.

[![enter image description here][1]][1]
[![enter image description here][2]][2]

The Arduino UDE doesn't recognize it. When I try to run avrdude with it, it says:

    avrdude -cusbasp -Pusb -patmega328p
    avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

Looking at the USB enumeration, it says:

USBHID:

      Product ID: 0xc8b4
      Vendor ID: 0x03eb  (Atmel Corporation)
      Version: 1.00
      Speed: Up to 1.5 Mb/sec
      Manufacturer: zhifengsoft
      Location ID: 0x14200000 / 8
      Current Available (mA): 1000
      Current Required (mA): 100
      Extra Operating Current (mA): 0

Looking online, I see one blog post (http://www.sciencetronics.com/greenphotons/?p=938) about a device with the same VID/PID, and it says it can be reprogrammed but is not clear how to do it.

In particular, I know there is a jumper that I need to set to put it in self-programming mode but I can't figure out where to put this jumper. Once the jumper is in, I understand I just match the SPI pins and program it using the firmware.

Can someone help?

  [1]: https://i.stack.imgur.com/x4B7c.jpg
  [2]: https://i.stack.imgur.com/Cmd07.jpg

body:
That's not a USBasp, that's some other programmer that has co-opted Atmel's vendor ID invalidly. If you want to use it then you will need to find and use some program called "ProgISP" that is only available for Windows.

That particular device does not show the jumper required for reprogramming, so I wouldn't attempt it (and in fact I would find the nearest bin to toss it in and get a couple from Baite and/or LC Tech instead).


message:
Do external battery packs need to connect to ground on the arduino?

I am going to be controlling 2 servo motors with an arduino. I will use an external battery pack for power. Do I need to connect the negative of the battery to ground on the arduino? If I just use the battery pack to power an LED, it works without connecting it to ground. Can someone please explain the logic behind this in simple wording? Thank you

body:
Ground is merely a label. It is a logical point in the circuit relative to which you measure all other voltages against.

For instance the 5V pin on the Arduino is actually 5V *relative to the ground pin*.

A 12V battery's `+` terminal is 12V *relative to the `-` terminal*. In this situation the `-` pin can be labelled Ground.

Electricity only ever flows when there is a circuit.  That is, current can only flow when it has some way of flowing back to where it came from.

A battery with an LED and resistor attached has a circuit: *Battery -> LED -> Resistor -> Battery*.  An Arduino itself is a circuit: *Power -> Arduino -> Internal Gubbins -> Power*

By the rule above, electricity can only ever flow out of an I/O pin if it has some way of getting back to where it came from. That route back is the Ground pin of the Arduino.  Interfacing some external device with the Arduino, whether it has its own power supply or not, requires that connection back to the Arduino's ground in order for the signal you send from the Arduino to have a complete circuit.


body:
I like the Majenko's answer, but I'm going to explain it with a different approach. You know that there are some quantities that are measurable in an absolute way (mass, lenght, weight) and other that need a starting point to refer. Think about the **distance**: you cannot say "New York" is distant 10km.. the question that obviously would come in mind is: 10km from what? So you have to decide a point in the world, from which you can measure the distance of every city.

The voltage measure the potential, that is the energy that a single charge would have. Now the question is: is the potential energy an absolute value? Of course not, i have to define a point where it is zero, and measure everything from it. In a circuit this point is called Ground, evry potential measured in the circuit is calculated to the ground.

The last step is to know that charges goes from the points at higher pot to the lowest one (the ground), usually preferring the path with lower resistsnce (but that's another story). **A wire has the same potential all along it** and in order to compare the voltage of arduino and the battery pack they must refer to the same ground.


body:
> so because the arduino is sending a signal to one of the pins on the servo, the servo needs to be connected to Arduino's ground.

Here is typically how you might wire a servo:

[![Servo wiring][1]][1]

Note the shared ground. The Arduino provides the control signal (data) via the orange wire. The battery provides the motor power via the red wire. The grounds must be shared or the voltages on each wire are meaningless.

  [1]: https://i.stack.imgur.com/N7p69.jpg


message:
How to send data from Arduino Uno with SIM900 GPRS to Firebase

I'm creating a real-time vehicle tracking Android application using the Arduino Uno and SIM900 GPS. I want to use Firebase as the database for the coordinates which will hold just the longitude and latitude. My question is about sending the data through the GPRS to Firebase. Right now I've only been able to use a terminal program to send AT commands to create a connection but I've been getting errors when connecting to firebase using AT+CIPSEND. I know that it only excepts https traffic so I've been trying commands from [here][1]. Here is some code that I've tried:

    AT
    OK
    AT+CREG?
    +CREG: 0,1

    OK
    AT+CGATT?
    +CGATT: 1

    OK
    AT+CIPSTATUS
    OK

    STATE: IP INITIAL
    AT+CIPMUX=0
    OK
    AT+CSTT="att.mvno","",""
    OK
    AT+CIICR
    OK
    AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","80"
    OK
    CONNECT OK
and

    AT+CIPSHUT
    OK
    AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","443"
    OK
    CONNECT OK
If I use CIPSEND, how should my message be formatted to send lat or long in a way Firebase can interpret?
Or am I going about this in a convoluted manner? Is there an easier way? I appreciate any help/comment. Thank you.

  [1]: http://www.jarzebski.pl/datasheets/SIM900_https-121018-1.00.pdf

body:
Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. [This site][1] explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.

  [1]: http://www.devacron.com/arduino-firebase/


message:
Controlling an RC car using Arduino

I'm trying to replicate this: https://zhengludwig.wordpress.com/projects/self-driving-rc-car/ using pretty much the exact same controller and car.

I've soldered 4 wires to the controller, 1 for each direction. If I let the wires touch the ground on the controller everything works perfect. However, when I connect the wires to the Arduino nothing works. Sometimes left/right works for about 0.5 seconds then it goes back to doing nothing. Any idea on what the problem might be? Do I need to connect the controllers ground to the Arduino ground?

I've tried removing the batteries from the controller and connecting 3.3V and ground from the Arduino, which sorta works but I feel like it shouldn't be needed.

If I use the buttons on the controller while it's connected to the Arduino it goes either forward, right or forward+right.

The code I'm using to test everything looks like this:

    void setup() {
      //Initialize the pins and serial
      pinMode(reversePin, OUTPUT);
      pinMode(forwardPin, OUTPUT);
      pinMode(leftPin, OUTPUT);
      pinMode(rightPin, OUTPUT);
    }

    void reset() {
      digitalWrite(forwardPin, HIGH);
      digitalWrite(reversePin, HIGH);
      digitalWrite(leftPin, HIGH);
      digitalWrite(rightPin, HIGH);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      reset();

      digitalWrite(forwardPin, LOW);
      delay(4000);
      reset();
      digitalWrite(reversePin, LOW);
      delay(4000);
      reset();
      digitalWrite(leftPin, LOW);
      delay(4000);
      reset();
      digitalWrite(rightPin, LOW);
      delay(4000);
    }

Images: https://i.stack.imgur.com/mCpcI.jpg

body:
Can you measure how much current goes through the wire when grounded (A: 2 mA from measurements in comments) ? And the open circuit voltage between the controller's ground and the control wire?  (A: 3.1V, from 2xAA)

If the current isn't more than the 40mA per pin/100mA per port, 200mA total, and the open circuit voltage of the controller pins is less than 5V, then you should be able to connect the Arduino's output pins and ground to your controller's wires and ground.

If the voltages and currents are higher, then you would need protection to prevent damaging your Arduino.

The controller and the Arduino should share a common ground, but without a circuit and without the controller's voltages and currents, it is hard to tell exactly what is wrong.

Edit: Since the controller's open circuit voltage and short-circuit currents (3.1 V, 2mA max) fit within the Arduino's capabilities, you can wire them directly to the pin outputs, and make sure the controller and the arduino share a common ground.

You need a fifth wire between the controller ground to the Arduino ground to make the logic levels actually communicate between the two devices.

You likely also need some 5V->3V level shifting to isolate the Arduino's output levels from the controller's inputs.   Top of the line would be MOSFETS, but you could possibly use a voltage dividing resistor pair.  See the hints in https://arduino.stackexchange.com/a/419/6628


message:
How to set Delay on GSM shield?

I bought a [Gsm module][1] recently(not official arduino shield) and i connect it to Arduino uno. The problem (I guess) is , i can't set delay properly, the terminal send it too fast that i missed it or too slow even i set its baud rate to 4800 (I have tried it with many baud from 4800-to-115200).

I uploaded the code to Git ,with [this address][2].

More details: For example when i enter `d` in terminal it act like this message came up : `+CMTI: "SM",3` and it want to save it but it miss plus at first of it and it save `CMTI: "SM",3`,

After that it perform this : `AT+CMGR=3` the terminal show the message in half size : `+CMGR: "REC UNREAD","+9*********2","H/E.3D/1","16/02/28,00:27:02+14"` which totally missed body part.

The weird thing is when i put some println on the program it miss more characters , and second weird thing is it missed more character in second run or i push d again.

I have tried to change the delays but no success.How can i fix it ? any help would be appreciated.

**Edit**:

If i make it simpler, when i use these code i get half message :

    #include <SoftwareSerial.h>
    SoftwareSerial serialGPRS(7, 8);
    void setup()
    {
      Serial.begin(19200);
      serialGPRS.begin(19200);
    }
    void loop()
    {
      serialGPRS.println("AT+CMGR=1");
      delay(1000);
      while(serialGPRS.available()!=0)
        Serial.write(serialGPRS.read());
    }
like: `+CMGR: "REC READ","+9*******",".H/E.3D/1`

  [1]: http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0
  [2]: https://github.com/zigi1/Test/blob/master/gsm.c

body:
The `SoftwareSerial` receive buffer is getting filled up and discarding characters. You are not reading fast enough from the buffer. Adding `Serial.println()` will slow down your `read`ing even more. The simplest solution to this is to increase the size of the `SoftwareSerial` buffer from its default size of 64 bytes to 256 bytes (or smaller, depending on what works for you).

On a Windows PC, go to `C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial`. Open `SoftwareSerial.h` and change the line:

    #define _SS_MAX_RX_BUFF 64 // RX buffer size

to

    #define _SS_MAX_RX_BUFF 256 // RX buffer size

Save the file and try your sketch again.


message:
How to connect GPS to IMU?

I'm planning to connect GPS to IMU, Is't possible ? I tried my best to find an article that can help solving my curiosity.  How can i connect GPS and MPU to arduino uno?

body:
Is not really connecting GPS to IMU, is more like you read GPS values, read IMU values and after apply what is called a sensor fusion algorithm.

One of the most common used sensor fusion algorithms is called Kalman filter (the Extended Kalman Filter more likelly). However, if you do not have some basis on control theory you may have more trouble in applying it.

[here](http://publications.lib.chalmers.se/records/fulltext/159412.pdf) is a good example of use of this kind of sensors and fusion algorithms. It is also very commonly used in drones or autonomous vehicles.

The implementation will be specific to what you are trying to do.


message:
Simple webpage serve with Arduino ethernet shield on SD card

I have been experiment with the arduino uno board from few days but can't seem to make it serve web page stored in SD card of ethernet shield.

If I print the contents of the file to serial it works properly, even embedding the HTML code works fine, but `client.write()` just produces a never ending garbage text of ` ÿÿÿÿÿÿÿÿÿÿÿÿ `

    #include <SPI.h>
    #include <Ethernet.h>
    #include <SD.h>
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 0, 115);
    EthernetServer server(80);

    File webFile;

    void setup()
    {
        pinMode(4, OUTPUT);
        digitalWrite(4, HIGH);
        Ethernet.begin(mac, ip);
        server.begin();
        Serial.begin(9600);

    // initialize SD card
    Serial.println("Initializing SD card...");
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;
    }

    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");
    }

    void loop()
    {
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    Serial.println("starting to open htm");
                    client.println();
                    // send web page
                    webFile = SD.open("index.htm");        // open web page file
                    if (webFile) {
                        while(webFile.available()) {
                            client.write(webFile.read()); // send web page to client
                        }
                        webFile.close();
                    }
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
    }

Sorry for the poor formatting, I just copied it from tutorial, please help me out.

body: "ÿ" is character code 255, the erased state of a Flash/EPROM/SD. Check if your SD card format OK, 'index.htm' file is there, and your code can read it.


body:
Me I solve the problem by using : "/index~1.htm"
I see that the file name is seen like that using the cardinfo.ino from Example


message:
First time set up- permission denied to usb port- ubuntu 14.04

I just plugged my arduino in and the light is on, but the blink test failed to upload. here is my error:

Arduino: 1.6.7 (Linux), Board: "Arduino/Genuino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

body:
From the documentation:

> Open Terminal and type:

>     ls -l /dev/ttyACM*

>you will get something like:

>     crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

>The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

>Now we just need to add our user to the group:

>     sudo usermod -a -G dialout $USER

>then:

>     sudo chmod a+rw /dev/ttyACM0
You will need to log out and log in again for this change to take effect.

Note that the preceding is old Ubuntu instructions. On modern distros that use ConsoleKit create the file `/etc/udev/rules.d/01-ttyusb.rules` containing the following and then reload the udev rules and replug the Arduino device:

    SUBSYSTEMS=="usb-serial", TAG+="uaccess"


body:
All you need to do is add yourself to the dialout group as described in the answer by Ignacio Vazquez-Abrams. This is done in the terminal by typing:

    sudo usermod -a -G dialout $USER

You do not need to use `chmod`. This gives read/write access to all users and not just members of the group. Before attempting to connect, however, you must **logout and log back in**. Once you log back in you will be recognized as a member of the dialout group and will be able to open the device.


body:
On Ubuntu 18.04, the only way I found the Arduino IDE installation to work straight out of the box, was using the documentation steps described here:

https://www.arduino.cc/en/Guide/Linux/

No changing groups nor permissions required.


body: Nothing above have helped me. When I have installed from file, from official site, it doesnt even start. Then I have installed Arduino IDE from "linux app store" and was working but have a problem like our friend from top. So I have uninstalled it and installed via terminal    `sudo apt install arduino `and now it`s working. Cheers.


message:
How to remote control Arduino using an old 2.4Ghz toy remote controller?

I have been wondering how to remote control my arduino robot using an old 2.4ghz car toy transmitter which has 4 buttons, up down left and right.
I have the nRF24L01(+) 2.4GHz transceiver to use it as a receiver.

Is there anyway to detect the signals going out from the remote controller and use them to make my arduino works,
I am a newbie so i am sorry if any mistake.

Thanks guys!

body:
You have two options:

1. Use an nRF24L01+ on the Arduino and dismantle the controller to rip out the innards, replacing them with another Arduino and another nRF24L01+.
2. Do not use the nRF24L01+, instead, rip apart the car and salvage the receiver from it, then work out how you can wire that to the Arduino.

The car's controller will not talk to the nRF24L01+. Yes, they may be in the same frequency band, but they do not talk the same language. After all, your WiFi is on the same band and that doesn't talk to the car, and your microwave, which is also 2.4GHz, doesn't sit and watch satellite TV all day. As you can see the 2.4GHz band is used by a huge number of devices (the band is actually getting quite crowded) and everything talked to everything else in the same band it would be utter chaos.


message:
Are there any constants for default SPI port pins defined?

I'm writing a library which controls a device using SPI bus. For the communication I need to manually toggle the chip select pin. On most Arduinos SS pin is on D10, but there are also other models where it's different like D53 on Mega. Is there a way to know where it is? Like a global #define? I would like to avoid any pin configuration parameters in my library. At least for default configuration...

body:
Yes there are. They are defined in pins_arduino.h Below the pins for the yun.

    // Map SPI port to 'new' pins D14..D17
    static const uint8_t SS   = 17;
    static const uint8_t MOSI = 16;
    static const uint8_t MISO = 14;
    static const uint8_t SCK  = 15;

Use SS MOSI MISO and SCK in your code


body:
This is defined in the platform variant specific file `pins_arduino.h` in the variants folder (<arduino>\hardware\arduino\avr\variants). Each platform variant (standard, mega, leonardo etc) gets their pin definitions set here. For instance the mega:

    static const uint8_t SS   = 53;
    static const uint8_t MOSI = 51;
    static const uint8_t MISO = 50;
    static const uint8_t SCK  = 52;


message:
Start timer when pins connected

I have switch is a line connected to Digital pins 1,2,3,4,5 . When pins 1 connects, I need a timer to start. as the rest connect i need it to mark the time in the console output of each one and End on the timer on connection to pin 5. ex

    START:
    0.00
    1.43
    2.12
    2.94
    3.89
    END

Also is there a way to Save the data to a log (.txt or whatever) If not its fine but I need to record results.

(This is for a school project)
THANKS!

body:
I will not give you code, only clues on how to write the code yourself.

The way to tackle this is to (at first) remove the Arduino from the equation. Replace it, instead, with you.

Imagine you are doing the timing yourself. How would *you* go about doing it?

This is how I would set about the task:

1. When the first button gets pressed I would look at the clock and jot down the current time.
2. When the second button gets pressed I would again look at the clock, and subtract the first time from the current time to find out how much time has elapsed. I would jot that down.
3. When the third button is pressed I would do the same again - look at the clock, subtract the start time, and jot down the difference.
4. And I would keep going until I had run out of buttons.

So now you need to find the right code to read what buttons are doing, get the current time, and finally send the times somewhere useful.

For all those there are many many many examples on the web.


body:
Are you familiar with interrupts? The best/most efficient way to do this is with pin interrupts on each input pin (and make sure your switches are wired correctly and debounced).

Unfortunately, within the Arduino libraries, there are only two pin interrupts (0 and 1), which correspond to pins 2 and 3.

You have two options:

Use a polling solution. Use one pin with an interrupt to start the timer (save the value of `millis()`) and then poll the other switches in a loop, capturing the `millis()` value at each switch closure.

Alternatively, the ATmega can fire an interrupt when _any_ pin in a port changes, but IIRC this isn't built into the Arduino libraries and requires direct register manipulation.


message:
How to use a Bi-color matrix led 8x8 with 24 pins?

I've just buy this 8x8 LED matrix [WLG M20088A/BEG](https://upverter.com/upn/eca2aa194e82bd81/) and I'm trying to light all the LEDs in one single color (green) but I don't understand how the 24 pins work for this specific model.

I know that every manufacturer makes different models. Does anyone have any experience with this particular model?

body:
It seems to be:

Row 1 - 8 --> common cathode pins per row.

To light up a whole row, you must connect row X pin to Gnd and all green or red columns to High (Vcc). Do not forget to add a resistance in series!


body:
Take a closer look at the device schematic diagram, which I copy below. It will tell you how each of the LEDs are wired. For example, the green LED on the upper-left corner (which I marked with a green circle) has its anode (positive terminal) wired to pin 5, while its cathode (negative terminal) is wired to pin 1. Can you see that?

[![LED matrix schematic diagram][1]][1]

To light up that LED (**green** LED on the upper-left corner), you must apply voltage (with limited current), to pins 1 (-) and 5 (+). If you wanted to light up the **red** LED at the same position instead, you should apply voltage to pins 1 (-) and 20 (+).

To light up all LEDs of a given color, you'll have to connect pins 1, 2, 3, 4, 21, 22, 23 and 24 to the negative terminal of your power supply. These are the LED common anodes. They are called common because they are shared among each pair of red and green LEDs. If you choose to use the red LEDs, you'll also have to wire pins 13 through 20 to your positive supply. On the other hand, if you pick green, you'll wire pins 5 through 12. These are the LED cathodes.

Don't forget to wire a current limiting resistor in series with each LED.

  [1]: https://i.stack.imgur.com/nVXFo.png


message:
questions about sketch

int k ;
    int q ;
    int f;//pot

    void setup() {
      pinMode(k, OUTPUT);
      pinMode(q, OUTPUT);
      pinMode(f, INPUT);
    }
    void loop() {
      zzf();
    }

    void gf()
    {
      int a = f;//test the conditions of f and store in new variable int a
      if (a == 80)//if a reads 80 then increment a by 1
      {
        ei();//run the ei() function
      }
    }

    void ei() {
      int k = 3;
      int a = Serial.read();
      {
        digitalWrite(k, a);
      }
    }

    void zzf() {
      for (f = 0; f < 80; f++) {
        analogWrite(q, f);
      }
    }

body:
Lean the proper C syntax. This is completely wrong:

    void gf()
    int a = f;//test the conditions of f and store in new variable int a
    {

And this is just as wrong for the same reasons:

    void ei()
    int k = 3
    int a = Serial.read();
    {digitalWrite(k, a);}


message:
Clock drift - is the precision of the crystal the only culprit?

I've a [wall clock](https://github.com/mamert/iot-a/blob/master/_60_led_clock/_60_led_clock.ino) (sorry, code's a mess, look for `updateClockVars`) which makes use of the [Timezone library](https://github.com/JChristensen/Timezone) (and ultimately [Time](http://playground.arduino.cc/Code/Time)). Nothing fancy, call millis() every loop; turn to Hrs, Mins, Secs; display on LEDs.

The magnitude of the drift I am seeing on my 2 Arduino Pro Mini - compatible boards - up to ~8% lag, not a typo - blows my mind. Replacing the 16MHz quartz with one bought at a local retailer didn't help much (~33% improvement). Is something else at play here?

body:
TL;DR You're doing it wrong. Use RTC.

Ok, longer explaination is required here. `millis()` is not accurate and here is why.

First, grab official Arduino source code from their [Github repo][1].
The file `Arduino-master/hardware/arduino/avr/cores/arduino/Arduino.h`
contains few interesting macros (I'm pasting `grep` output here):

    Arduino.h:#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
    Arduino.h:#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
    Arduino.h:#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

At 16MHz `clockCyclesPerMicrosecond()` will evaluate to `16`. Keep this number in memory.

Those macros are used in `Arduino-master/hardware/arduino/avr/cores/arduino/wiring.c`:

    // the prescaler is set so that timer0 ticks every 64 clock cycles, and the
    // the overflow handler is called every 256 ticks.
    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

    // the whole number of milliseconds per timer0 overflow
    #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)

`MICROSECONDS_PER_TIMER0_OVERFLOW` macro is evaluated as `(64 * 256)/16` -  a dodgy looking **1024**. Look how they round it down to calcuate `MILLIS_INC`.

Let's assume that you run your Arduino with **ideal** main clock signal.
At 16MHz main clock, the timer frequency is 1.024kHz, not 1kHz. This results in 2.4% inaccuracy. You can get away with that in most cases, but **not when you're building a clock**.

This 2.4% error is best case. Your main oscillator is not 16MHz - it has it's own inaccuracy, that is unknown and it sums up.

You should use an external, accurate time reference provided by RTC module. When assembled properly, they guarante low time drift, temperature compensation and other goodies. Be smart - use RTC. :)

If you are scared of I2C RTC modules, you may find my [tutorial][2]
and [another tutorial][3] on MCP7940N RTC module. Know-how is applicable with other RTCs as well.

  [1]: https://github.com/arduino/Arduino
  [2]: https://iobtoolkit.com/docs/tutorials/i2c_terminal_mcp7940n.html#mcp7940n-chip
  [3]: https://iobtoolkit.com/docs/tutorials/i2c_python_mcp7940n.html


body:
The problem is the interaction between the interrupt handler that updates the value for the millis() function and the neopixels show() function.

To maintain the counter for the millis() function a interrupt is triggered approximately every 1.024 ms.

When the show() function is called all interrupts are disabled to get the precise timing needed to send the data to the neopixels.  For a 60 led strip this takes about 1800 microseconds (60 leds * 24 bits * 1.25 us per bit) so at least one interrupt is skipped each time you update the display.

[This page](https://ucexperiment.wordpress.com/2012/03/16/examination-of-the-arduino-millis-function/) has details about how the millis() function works.


body:
Expanding on my previous comment...

As I said before, I suspect the NeoPixel library to be blocking
interrupts for too long when you `strip.show()`. If a timer interrupt
fires while interrupts are blocked... it's not a big deal: the interrupt
request is put on hold and serviced as soon as interrupts are enabled
again. If **two** timer interrupts fire while interrupts are blocked...
you have a problem: the interrupt service routine will be called only
once, and your clock will miss a tick.

Craig has worked out the timings in his answer: the timer interrupt
fires every 1.024 ms, and NeoPixel blocks interrupts for
1.8 ms. So it is perfectly expected that, from time to time, you
will have two timer interrupts within this 1.8 ms window.

Here is a quick hack that could solve your problem: if you
`strip.show()` _right after_ a timer interrupt is serviced, then only
one more interrupt should fire during the subsequent 1.8 ms window,
and you should be fine. So you could simply add this _right before_
`strip.show()`:

<!-- language: c++ -->

    /* Wait for a timer interrupt to be serviced. */
    uint32_t lastMillis = millis();
    while (millis() == lastMillis) /* wait */;

A possibly better solution would be to avoid blocking interrupts for so
long. NeoPixel blocks them in order to comply with the very tight timing
requirements of the WS2812 LEDs. But it turns out the WS2812s are not
nearly as picky about timings as their datasheet suggests. You can drive
them in a more relaxed way, with interrupts enabled except for 1-bit
durations, and they still work fine. For a detailed explanation and
sample code, see [NeoPixels Revealed: How to (not need to) generate
precisely timed
signals](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/).

A third solution would be to follow the general advice given here and
grab an RTC. However, although it certainly is a good and clean
solution, I have to admit I completely agree with your comment “_I still
didn't catch WHY that is better – it's a quartz either way_”.


message:
Need help figuring out the pinout of a seven segmented display

A friend of mine gave me a 2in. 4 digit seven segment display. But when I sat down and looked at it, I found it has 7 pins on one side and 5 on the other and no indicators of its pinout on it. The only information I could gleam from it was the (presumably its model number) which said "PARA LIGHT A-5V4G-12-U1 H H0615". I searched online for it but only found ambiguous information that didn't help me. I have a feeling this is a fairly easy question, if so: sorry I am a noob.

body:
Without an image of the display, I'll have to guess. With 12 pins in total, what you most likely have is: 8 pins for 7 segments and the decimal point, and 4 COMMON anodes or cathodes, a detail you will have to discover yourself. This process requires a power source that can safely light LEDs. A multimeter in diode test mode will do since theres usually about 2 V across the probes and some internal resistance, enough to light up the LEDs in the display, though they wont be very bright. I will try to list the minimum number of steps needed to determine the pinout using this method.

 - Using a multimeter set to diode test mode, place the red probe on any pin (though its good to start at the edges). Now lazily run (i.e. make contact) the black probe through the remaining pins. If the display is a *common anode* display, you should see the all the segments of a **particular** digit (not **different** digits) light up in sequence.

 - Else, keep running the black probe through the pins until any segment at all lights up. Hold the black probe on that pin that caused the segment to turn on. Now run the red probe through the other pins. If all the segments of a particular digit light up in sequence, this indicates a *common cathode* display.

 - Another possibility is that no segment lights up at all, despite steps 1 & 2. Substitute the red probe, where it is held steady, for the black probe. Run the red probe through the remaining pins. If all the segments of a particular digit light up, then the display is a *common cathode* display.

 - On the other hand, if no digit's segments light up sequentially while running the red probe through the pins, but at least one segment of any digit lights up, then hold the red probe steady on its current pin, and run the black probe instead through the other pins. If all the segments of a digit light up in sequence, then you have a *common anode* display.

Take note of the pin that was held constant, in any of the cases above.

Now that you know what kind of display you have, you now need to discover the pinout for the segments and common anodes/cathodes. Get paper and pen so you can label each pin with its function. Create a table with pin numbers in one column (pin 1 - 12) and the pin functions (which you will find out) in the second column.

[![none][1]][1]

 - This image shows the segment labels. During the testing above, one
   probe (PROBE A) was held steady on one pin while the other (PROBE B)
   was run through the other pins. This caused all the segments of a
   digit to turn on. The pin connected steadily to PROBE A is the COMMON pin for
   the digit whose segments lit up. So in your table, **Pin xx = COMMON
   for Digit yy**.
 - To get the COMMON for other digits, move PROBE A to another pin and
   run PROBE B through the other pins until another digit has all its
   segments turned on in sequence. The pin connected to PROBE A is the
   COMMON for that digit. Include this in your table. Repeat until you
   have identified the COMMON for each digit.
 - Finally to get the segment pins A - G and DP, place PROBE A on any of the COMMONs you have in your table and run PROBE B through the other pins. Each time a segment lights up, the pin connected to PROBE B should be associated with that segment's label in your table. E.g. if segment C lights up when PROBE B is on pin 10, then the table should have something like **pin 10 = C**. Keep going until you have all the segment pins identified.

  [1]: https://i.stack.imgur.com/DxMY6.png


message:
How to write a sketch when adding more devices to an I2C data line?

I am building a weather station, using a battery-operated outside unit, that transmits data from a DHT22 sensor to a unit inside my house.

The inside unit is using I2C communications from my Arduino Uno to my LCD display.

I would like to add a BMP180 sensor which also uses I2C communications.

My question is, how would you write a sketch to incorporate both the BMP180 sensor and the LCD display on to one I2C line?

body:
Like Nick Gammon said, they have different addresses, so there shouldn't be a problem. Connect their SDAs and SCLs together, with the necessary pull-ups.

The libraries you are using should handle the low-level reading and writing. Proceed as though they are any 2 devices connected to your Uno. Print to the LCD as usual, and poll the sensor with library functions.


body:
Yes you can connect multiple devices on one I2C bus. Every device on the bus needs to have its own address. Some libraries have the default address included. Some do allow to change it. Others don't. For example [the SE95 temperature sensor][1] (page 10) does allow for setting a few bits of the address allowing more than one sensor on a bus.

You can use the Wire library from Arduino to request data from [I2C][2]. When you want to pull data from a sensor, you have to send a command depending on the specs than request data from the address.

Example: for the SE95 address 0x4F (you can repeat this for any address you have a sensor on your bus) the SE95 ranges from 0x49 to 0x4F depending on the pin settings:

    //Please note that the example is not complete because Wire has to be loaded and initialized
    byte address = 0x4F;
    byte read1;
    byte read2;
    Wire.beginTransmission(address);
    Wire.write(0x00);
    Wire.requestFrom(int(address), 2);
    if(Wire.available()) {
      read1 = Wire.read();
      read2 = Wire.read();
    }

So depending on the libraries, this would be quite easy.

  [1]: http://pdf.datasheetcatalog.com/datasheet/philips/SE95_2.pdf
  [2]: http://www.arduino.cc/en/Reference/Wire


message:
How to serially transfer/read an image to Arduino

I am using Arduino Uno and the image size is 12.7 kb. I want to read a jpeg image from computer and convert into bitmap in arduino. Later on it will be implemented using SD card.Is it possible to read a .jpeg image from computer to Arduino using serial communication? If yes, then how?

body:
You can send anything you like through the serial port. It is just 8-bit raw data. The onus is on you, however, to implement a suitable high level protocol with which to transfer the data.

One important thing to bear in mind though: JPEG is a highly compressed complex image format. I am not aware that anyone has ever managed to squeeze JPEG decompression into a lowly Arduino. Instead you will need to use a decompressed image format such as BMP, or do the decompression on the computer before-hand and send the raw RGB image data over the serial instead.


body:
Of course you can, but as stated in the comments and in the other answer JPEG use a complex algorithm to compress the images, and most computers have a dedicated hardware to perform the cosens discrete transform. Anyway the answer to your question is yes, and it's not hard.

You just have to split the image into bytes, send them through the serial port and make Arduino read and save them into an array. To avoid errors create a protocol that can decode what are you doing.

For example:
0b1111000 for 3 times = Start sending
0b00011000 = new line
and so on..

The first thing that come in my mind is to use the pySerial library, that can automate the process. Python is perfect for prototyping: open the image (maybe using the numpy library instead of using lists) and with a for loop send every byte over the serial port in according to the protocol you created.

On the Arduino just code the protocol to understand every bite and save the image in an array.


message:
Connecting Arduino with Philips Hue

I'm trying to control Philips Hue lights through an Arduino Uno (with a WiFi shield [Model R3][1]). Both the shield and the Philips Hue [Bridge][2] are connected to the same network and I'm trying to send JSON commands from the Arduino to the Hue Bridge from the following code taken from [here][3].

<!-- language: c -->

    #include <SPI.h>
    #include <WiFi.h>
    #include <WiFiClient.h>

    char ssid[] = "mynetwork";     //  your network SSID (name)
    char pass[] = "mypass";  // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    //Hue constants
    const char hueHubIP[] = "192.168.0.50";  //Hue Bridge IP
    const char hueUsername[] = "myhue";  //Hue username
    const int hueHubPort = 80;

    IPAddress server(192,168,0,50);
    WiFiClient client;

    //Hue variables
    boolean hueOn;  // on/off
    int hueBri;  // brightness value
    long hueHue;  // hue value
    String hueCmd;  // Hue command

    unsigned long buffer=0;  //buffer for received data storage
    unsigned long addr;
    IPAddress ip;

    void setup()
    {
     //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue:
        while (true);
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network:
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }

      // you're connected now, so print out the data:
      Serial.print("You're connected to the network");
      printCurrentNet();
      printWifiData();

      ip = WiFi.localIP();
      Serial.println(ip);

    }

    void loop()
    {

        String command = "{\"on\": true,\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(1,command);
        command = "{\"on\": true,\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(2,command);
        command = "{\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(1,command);
        command = "{\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(2,command);

    }

    /* setHue() is our main command function, which needs to be passed a light number and a
     * properly formatted command string in JSON format (basically a Javascript style array of variables
     * and values. It then makes a simple HTTP PUT request to the Bridge at the IP specified at the start.
     */
    boolean setHue(int lightNum,String command)
    {
      if (client.connect(server, 80))
      {
        Serial.println(F("connected to server"));
        while (client.connected()&& status == WL_CONNECTED)
        {
          client.print(F("PUT /api/"));
          client.print(hueUsername);
          client.print(F("/lights/"));
          client.print(lightNum);  // hueLight zero based, add 1
          client.println(F("/state HTTP/1.1"));
          client.println(F("keep-alive"));
          client.print(F("Host: "));
          client.println(hueHubIP);
          client.print(F("Content-Length: "));
          client.println(command.length());
          client.println(F("Content-Type: text/plain;charset=UTF-8"));
          client.println();  // blank line before body
          client.println(command);  // Hue command
        }
        client.stop();
        return true;  // command executed
      }
      else
        return false;  // command failed
    }

      //client.flush();
      //client.stop();

    /* A helper function in case your logic depends on the current state of the light.
     * This sets a number of global variables which you can check to find out if a light is currently on or not
     * and the hue etc. Not needed just to send out commands
     */
    boolean getHue(int lightNum)
    {
      if (client.connect(server, 80))
      {
        client.print(F("GET /api/"));
        client.print(hueUsername);
        client.print(F("/lights/"));
        client.print(lightNum);
        client.println(F(" HTTP/1.1"));
        client.print(F("Host: "));
        client.println(hueHubIP);
        client.println(F("Content-type: application/json"));
        client.println(F("keep-alive"));
        client.println();
        while (client.connected()&& status == WL_CONNECTED)
        {
          if (client.available())
          {
            client.findUntil("\"on\":", "\0");
            hueOn = (client.readStringUntil(',') == "true");  // if light is on, set variable to true

            client.findUntil("\"bri\":", "\0");
            hueBri = client.readStringUntil(',').toInt();  // set variable to brightness value

            client.findUntil("\"hue\":", "\0");
            hueHue = client.readStringUntil(',').toInt();  // set variable to hue value

            break;  // not capturing other light attributes yet
          }
        }
        client.stop();
        return true;  // captured on,bri,hue
      }
      else
        return false;  // error reading on,bri,hue
    }

    void printWifiData() {

      //WiFi shield's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);
    }

      void printCurrentNet() {
      //SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());
      }
}

The above code gets my Arduino connected to `mynetwork` and I have also connected Hue Bridge to the same but it throws an error of `No Socket Available`.

[![Error message][4]][4]

**UPDATE (9th March 2016):**

I implemented suggestions `1` and `4` given by slash-dev and was able to get rid of `No Socket Available` error. Following is the updated code:

   <!-- language: c -->

    #include <SPI.h>
    #include <WiFi.h>
    #include <WiFiClient.h>

    char ssid[] = "mynetwork";     //  your network SSID (name)
    char pass[] = "mypass";  // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    //Hue constants
    const char hueHubIP[] = "192.168.0.50";  //Hue hub IP
    const char hueUsername[] = "myhue";  //Hue username
    const int hueHubPort = 80;

    IPAddress server(192,168,0,50);
    WiFiClient client;

    //Hue variables
    boolean hueOn;  // on/off
    int hueBri;  // brightness value
    long hueHue;  // hue value
    String hueCmd;  // Hue command

    unsigned long buffer=0;  //buffer for received data storage
    unsigned long addr;
    IPAddress ip;

    void setup()
    {
     //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println(F("WiFi shield not present"));
        // don't continue:
        while (true);
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print(F("Attempting to connect to WPA SSID: "));
        Serial.println(ssid);
        // Connect to WPA/WPA2 network:
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }

      // you're connected now, so print out the data:
      Serial.print(F("You're connected to the network"));
      printCurrentNet();
      printWifiData();
    }

    void loop()
    {

        String command = "{\"on\": true,\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(1,command);
        command = "{\"on\": true,\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(2,command);
        command = "{\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(1,command);
        command = "{\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(2,command);

    }

    /* setHue() is our main command function, which needs to be passed a light number and a
     * properly formatted command string in JSON format (basically a Javascript style array of variables
     * and values. It then makes a simple HTTP PUT request to the Bridge at the IP specified at the start.
     */
    boolean setHue(int lightNum,String command)
    {
      client.stop();
      if (client.connect(server, 80))
      {
        Serial.println(F("connected to server"));
        while (client.connected()&& status == WL_CONNECTED)
        {
          client.print(F("PUT /api/"));
          client.print(hueUsername);
          client.print(F("/lights/"));
          client.print(lightNum);  // hueLight zero based, add 1
          client.println(F("/state HTTP/1.1"));
          client.println(F("Connection: keep-alive"));
          client.print(F("Host: "));
          client.println(hueHubIP);
          client.print(F("Content-Length: "));
          client.println(command.length());
          client.println(F("Content-Type: text/plain;charset=UTF-8"));
          client.println();  // blank line before body
          client.println(command);  // Hue command
        }
        client.flush();
        client.stop();
        return true;  // command executed
      }
      else
        return false;  // command failed
    }

    /* A helper function in case your logic depends on the current state of the light.
     * This sets a number of global variables which you can check to find out if a light is currently on or not
     * and the hue etc. Not needed just to send out commands
     */
    boolean getHue(int lightNum)
    {
      client.stop();
      if (client.connect(server, 80))
      {
        client.print(F("GET /api/"));
        client.print(hueUsername);
        client.print(F("/lights/"));
        client.print(lightNum);
        client.println(F(" HTTP/1.1"));
        client.print(F("Host: "));
        client.println(hueHubIP);
        client.println(F("Content-type: application/json"));
        client.println(F("Connection: keep-alive"));
        client.println();
        while (client.connected()&& status == WL_CONNECTED)
        {
          if (client.available())
          {
            client.findUntil("\"on\":", "\0");
            hueOn = (client.readStringUntil(',') == "true");  // if light is on, set variable to true

            client.findUntil("\"bri\":", "\0");
            hueBri = client.readStringUntil(',').toInt();  // set variable to brightness value

            client.findUntil("\"hue\":", "\0");
            hueHue = client.readStringUntil(',').toInt();  // set variable to hue value

            break;  // not capturing other light attributes yet
          }
        }
        client.flush();
        client.stop();
        return true;  // captured on,bri,hue
      }
      else
        return false;  // error reading on,bri,hue
    }

    void printWifiData() {

      //WiFi shield's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print(F("IP Address: "));
      Serial.println(ip);
    }

      void printCurrentNet() {
      //SSID of the network you're attached to:
      Serial.print(F("SSID: "));
      Serial.println(WiFi.SSID());
    }

  [1]: https://www.arduino.cc/en/Main/ArduinoWiFiShield
  [2]: http://www2.meethue.com/en-us/productdetail/philips-hue-bridge
  [3]: http://www.makeuseof.com/tag/control-philips-hue-lights-arduino-and-motion-sensor#WorkingFromArduino
  [4]: https://i.stack.imgur.com/Tub4E.png

body:
I wonder if you are running out of RAM? Those sockets use RAM, and you have quite a few string constants, like this:

<!-- language-all: lang-C++ -->

      client.println("Content-Type: text/plain;charset=UTF-8");

Change that (and all similar ones) to use the `F()` macro:

      client.println(F("Content-Type: text/plain;charset=UTF-8"));


body:
With reference to [this example][1], perhaps you should call `client.stop()` right before you call `client.connect()` at the start of `setHue()` and `getHue()`. You should also call not only `client.stop()`, but also `client.flush()` at the end of both functions, just in case: Flush first, then stop.

On a different note, correct your HTTP headers from `client.println(F("keep-alive"));` to `client.println(F("Connection: keep-alive"));`.

  [1]: https://www.arduino.cc/en/Tutorial/WiFiWebClientRepeating


body:
I suspect a low RAM failure.  Here are some suggestions that will dramatically lower your RAM usage:

**1)** You still have `Serial.print` using double-quoted C string constants.  Use `F("C string")` for those, too.  For example:

      Serial.println( F("WiFi shield not present") );

Every double-quoted C string uses RAM in addition to FLASH program space.  You have already saved a bunch, but you should get rid of the above uses.

**2) Don't use `String` for `setHue`.**

TL;DR - it will use extra RAM, FLASH, CPU time, and cause inexplicable or random failures.

Instead, use C strings, aka `char` arrays for variables, or double-quoted string constants.  When the constants are wrapped with the **F()** macro, they don't use *any* RAM.

Here is an example of how to define and call a `setHue` with C strings instead of `String`:

    --> See complete code below in UPDATE 3/9/2016 section <--

This just prints the C strings to `Serial`, but I hope you can see how they could also be printed to the `client`.

**3) Don't use `String` for `getHue`.**

Here is an example of how to define and call a `getHue` that uses C strings instead of `String`:

    --> See complete code below in UPDATE 3/9/2016 section <--

Just copy and paste the displayed JSON into the Serial Monitor "Send" field.  The debug prints will display what gets parsed.

* NOTE: It's not clear if the JSON attributes always come back in the same order.  This example expects the same order in which they were sent.  Other techniques would have to be used to accommodate *any* order.

**4)** Be sure to call `client.flush()` before *every* `client.stop()`.

**Summary:**  I would guess that the combination of non-F() "C strings" wasting RAM, plus the `String` use of RAM (doubled or more), is leading to a low-RAM failure.  The above approach will lower RAM usage dramatically, and also save more than 1.6kB in program space.  After implementing these changes, almost all RAM will be available for the WiFi libraries.

##UPDATE 3/9/2016

Here's my changes, merged into your second sketch.

    #include <SPI.h>
    #include <WiFi.h>
    #include <WiFiClient.h>

    char ssid[] = "mynetwork";     //  your network SSID (name)
    char pass[] = "mypass";  // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    //Hue constants
    const char hueHubIP[] = "192.168.0.50";  //Hue hub IP
    const char hueUsername[] = "myhue";  //Hue username
    const int hueHubPort = 80;

    IPAddress server(192,168,0,50);

    // Uncomment this to *really* use the Wi-Fi sheild.
    // Comment this to read & write everything to the Serial Monitor for testing.
    //#define REAL_WIFI
    #ifdef REAL_WIFI
    WiFiClient client;
    #else
    HardwareSerial & client = Serial; // redirect 'client' to the Serial Monitor
    #endif

    //Hue variables
    boolean hueOn;  // on/off
    int hueBri;  // brightness value
    long hueHue;  // hue value
    String hueCmd;  // Hue command

    unsigned long buffer=0;  //buffer for received data storage
    unsigned long addr;
    IPAddress ip;

    void setup()
    {
     //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println(F("WiFi shield not present"));
        // don't continue:
    #ifdef REAL_WIFI
        while (true);
    #else
        status = WL_CONNECTED;
    #endif
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print(F("Attempting to connect to WPA SSID: "));
        Serial.println(ssid);
        // Connect to WPA/WPA2 network:
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }

      // you're connected now, so print out the data:
      Serial.print(F("You're connected to the network"));
      printCurrentNet();
      printWifiData();
    }

    void loop()
    {
      setHue
        ( 1,
          F("{\"on\": true,\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"),
          random(15,25),
          F("}")
        );

      delay( 10000 );

      setHue
        ( 2,
          F("{\"on\": true,\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"),
          random(15,25),
          F("}")
        );

      delay( 10000 );

      setHue
        ( 1,
          F("{\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"),
          random(15,25),
          F("}")
        );

      delay( 10000 );

      setHue
        ( 2,
          F("{\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"),
          random(15,25),
          F("}")
        );

      delay( 10000 );

    //  getHue( 1 );
    //  getHue( 2 );
    }

    /* setHue() is our main command function, which needs to be passed a light number and a
     * properly formatted command string in JSON format (basically a Javascript style array of variables
     * and values. It then makes a simple HTTP PUT request to the Bridge at the IP specified at the start.
     */
    boolean setHue
      ( int                        lightNum,
        const __FlashStringHelper *header,
        int                        parameter,
        const __FlashStringHelper *trailer )
    {
    #ifdef REAL_WIFI
      client.stop();

      if (client.connect(server, 80))
    #endif
      {

        Serial.println(F("connected to server"));
    #ifdef REAL_WIFI
        if (client.connected()&& status == WL_CONNECTED)
    #endif
        {
          client.print(F("PUT /api/"));
          client.print(hueUsername);
          client.print(F("/lights/"));
          client.print(lightNum);  // hueLight zero based, add 1
          client.println(F("/state HTTP/1.1"));
          client.println(F("Connection: keep-alive"));
          client.print(F("Host: "));
          client.println(hueHubIP);

          // Calculate total command length.
          int cmdLength =
            strlen_P( (const prog_char *)header ) +
            1 +   //   Assume one digit for parameter...
            strlen_P( (const prog_char *)trailer );

          //  ... and add room for more digits if necessary.
          if (parameter > 9)
            cmdLength++;
          if (parameter > 99)
            cmdLength++;

          client.print(F("Content-Length: "));
          client.println( cmdLength );
          client.println(F("Content-Type: text/plain;charset=UTF-8"));
          client.println();  // blank line before body
          client.print( header );  // Hue command pieces
          client.print( parameter );
          client.println( trailer );
        }
        client.flush();
    #ifdef REAL_WIFI
        client.stop();
    #endif
        return true;  // command executed
      }
    #ifdef REAL_WIFI
      else
        return false;  // command failed
    #endif
    }

    //---------------------------------------------------------------------
    // Utility function to extract one `bool` value from the client stream.
    //   No buffers are used.  Each character is handled as it is received.
    //   (you may want/need to add a timeout)

    static bool clientParseBool( char delim )
    {
      bool val = false;
      uint8_t count = 0; // number of chars we've read for the value

      while (status == WL_CONNECTED) {
        if (client.available()) {
          char c = client.read();
          if (c == delim)
            break; // done!
          if ((c == ' ') || (count++ > 0))
            continue; // skip spaces and anything after the first non-space char

          if (c == 't')
            val = true;
        }
      }

      // Debug prints
      Serial.print( F("bool ") );
      Serial.println( val );

      return val;
    }

    //-------------------------------------------
    // Utility function to extract one 'unsigned 16-bit int' value from the client stream.
    //   No buffers are used.  Each character is handled as it is received.
    //   (you may want/need to add a timeout)

    static uint16_t clientParseUint( char delim )
    {
      uint16_t val = 0;

      while (status == WL_CONNECTED) {
        if (client.available()) {
          char c = client.read();
          if (c == delim)
            break; // done!
          if (c == ' ')
            continue; // skip spaces

          if (isdigit(c))
            val = val*10 + (c - '0'); // accumulate one digit of the bri value
        }
      }

      // Debug prints
      Serial.print( F("int ") );
      Serial.println( val );

      return val;
    }

    //-------------------------------------------

    /* A helper function in case your logic depends on the current state of the light.
     * This sets a number of global variables which you can check to find out if a light is currently on or not
     * and the hue etc. Not needed just to send out commands
     */
    boolean getHue(int lightNum)
    {
      bool gotHue = false;

    #ifdef REAL_WIFI
      client.stop();
      if (client.connect(server, 80))
    #endif
      {

        client.print(F("GET /api/"));
        client.print(hueUsername);
        client.print(F("/lights/"));
        client.print(lightNum);
        client.println(F(" HTTP/1.1"));
        client.print(F("Host: "));
        client.println(hueHubIP);
        client.println(F("Content-type: application/json"));
        client.println(F("Connection: keep-alive"));
        client.println();

        if (status == WL_CONNECTED)
        {
            client.findUntil("\"on\":", "\0");
            hueOn = clientParseBool(',');

            if (status == WL_CONNECTED)
            {
                client.findUntil("\"bri\":", "\0");
                hueBri = clientParseUint(',');

                if (status == WL_CONNECTED)
                {
                    client.findUntil("\"hue\":", "\0");
                    hueHue = clientParseUint(',');

                    gotHue = true;  // captured all three: on,bri,hue
                }
            }
        }

        client.flush();
    #ifdef REAL_WIFI
        client.stop();
    #endif
      }

      return gotHue;
    }

    void printWifiData() {

      //WiFi shield's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print(F("IP Address: "));
      Serial.println(ip);
    }

    void printCurrentNet() {
      //SSID of the network you're attached to:
      Serial.print(F("SSID: "));
      Serial.println(WiFi.SSID());
    }

A few notes:

*  I did not have the extra blank line in my original `setHue`, so I put it back in to match your sketch.
*  I added a `REAL_WIFI` define that I could comment out for testing on `Serial`.  When I run it, I get this output:
> WiFi shield not present

> You're connected to the networkSSID:

> IP Address: 0.0.0.0

> connected to server

> PUT /api/myhue/lights/1/state HTTP/1.1

> Connection: keep-alive

> Host: 192.168.0.50

> Content-Length: 65

> Content-Type: text/plain;charset=UTF-8

>

> {"on": true,"hue": 50100,"sat":255,"bri":255,"transitiontime":22}

> connected to server

> PUT /api/myhue/lights/2/state HTTP/1.1

> Connection: keep-alive

> Host: 192.168.0.50

> Content-Length: 65

> Content-Type: text/plain;charset=UTF-8

>

> {"on": true,"hue": 65280,"sat":255,"bri":255,"transitiontime":24}

*  You can copy and paste the above output if you want to add and test `getHue` with just the Serial Monitor (i.e., comment out `#define REAL_WIFI`).
*  I added a 10-second delay between each `setHue`, just to pace the output, and to give the "transition-time" um... some time to work.  The transition time is in seconds, so `loop` will call `setHue` again, *before* the requested transition has completed.  You won't see much change when you keep telling it to gradually change to the new color, but it only gets to transition a little bit.  Without any delay, I don't think you'll see anything.  This could be your current problem!  With 10 seconds, at least it will get about half-way there.  :-(


body:
For anyone else that comes across this. The reason it takes about 10 seconds to run this, is because of the Original: `while (client.connected())` or in the OP's Post above the `while (client.connected()&& status == WL_CONNECTED)`. Either are located in the setHue.

I commented that while loop out *(and the opening { and closing } brackets for that while loop or you'll get an error of course)*, and the hue light changed instantaneously.

If you put a print to serial line in that loop, you'll see that it runs that loop continuously, which causes the long delay.

If you come upon this post from the original [https://www.makeuseof.com/tag/control-philips-hue-lights-arduino-and-motion-sensor/][1] note that you should change the main loop's if statements to:

    if((digitalRead(pir) == 1) && (activated == false) )

and

    if((digitalRead(pir) == 0) && (activated == true) )

That way the setHue only is called on a change of state.

  [1]: https://www.makeuseof.com/tag/control-philips-hue-lights-arduino-and-motion-sensor/


message:
Difference between WiFiClient and HttpClient

Apologies if this question appears to be too vague but I would like to know the key differences between these two clients.

While WiFiClient comes pre-loaded with Arduino IDE, HttpClient doesn't. Also, to send HTTP commands to a server (XML/JSON), which one to go for?

body:
WiFiClient provides a raw connection to the internet through a WiFi access point (such as your home router).

HttpClient provides a connection to a web server via an existing Client connection, such as a WiFiClient connection.

So the simplest answer to your question

> to send HTTP commands to a server (XML/JSON), which one to go for?

is "Use both".

You use WiFiClient to connect to the internet, then you use HttpClient on your WiFiClient connection to communicate with a website.  As it states in the readme on HttpClient's github repository:

> Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with EthernetClient, WiFiClient and GSMClient.

To understand the concept more fully you will first need to understand the [OSI 7-Layer Model](https://en.wikipedia.org/wiki/OSI_model) which is essential reading for anyone doing anything with networking software.


body:
As Majenko Said,

WiFiClient is raw in the sense you have to deal with the HTTP protocol stuff yourself, a shot snippet of raw GET request is provided below

      WiFiClient wc;
      wc.print("GET ");
      wc.print(/xml/device_description.xml);
      wc.println(" HTTP/1.1");
      wc.print("Host: ");
      wc.println(selectedDevice->getIp());
      wc.println("Connection: close");  //automatically close Connection
      wc.println("");

each line is terminated with "\r\n", the request is terminated with an empty line

Where as the HttpClient is a library which handle all the low level HTTP protocol stuff and provide simple interface to sent HTTP GET/POST request to any device that support HTTP

    HTTPClient http;
    http.begin(serverName);
    http.addHeader("Content-Type", "text/plain");
    int httpResponseCode = http.POST("Hi Sending POST request");
    Serial.println(httpResponseCode);
    http.end();

To send JSON change the header with the below line

    http.addHeader("Content-Type", "application/json");

So the answer is if you want to deal with the low level HTTP protocol use WiFiClient else use HTTPClient


message:
Photoresistor Switch

How would I use a photoresistor like a switch. My issue is it is always bleeding out a little bit of power and always on. Is there a way to connect it to a digital pin and when a resistance of xxx is ment, set another digital pin to On?

body:
To turn an analog signal into a digital signal, at some sort of threshold xxx, you need to either condition it in electronic circuitry, with something like an amplifier or a comparator, or read the analog signal directly and apply the threshold in software.

You likely need to connect the photoresistor as half of a voltage divider, as in https://arduino.stackexchange.com/q/7921/6628


message:
how to count blinking LED flashes using arduino uno boards and LDR?

i want to know code for counting the flashes of LEDs and display no. of flashes in particular time given.by using LDR.
basically i tried it with interrupts but i'm not getting it,so please help in this regard.

body:
LDRs only give an analog output, proportional to the amount of light.

To make it give a HIGH and LOW value, you have to tweak the other resistor used in the voltage divider.

Alternatively you could use `analogRead` and add a threshold value in your code.


body: An hardware solution could be achieved by putting a photodiode or a photoresistance near the flashing LED. Connect it to a pin that supports external interrupt and you're done. With a bit more circuitry you can ensure that the value on the pin doesn't oscillate: put a Schmit Trigger after the photodiode or resitance with its output on the input pin.


message:
Nick Gammon's Hex Converter Error

I'm trying to add a bootloader hex to Nick Gammon's Atmega Board Programmer sketch, and I can't seem to get a hex file to convert.

I need to convert "Arduino-usbserial-atmega16u2-Uno-Rev3.hex", but that wasn't working so I thought I'd try converting one that's already used in the sketch, "Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex", but that's not working either. I've followed the instructions from http://www.gammon.com.au/bootloader

I've tried it using Wine and Paralells. Clicking the copy button when using Wine causes the program to stop responding.

Here is a screenshot of the error:

[![Error Screenshot][1]][1]

Thank you

  [1]: https://i.stack.imgur.com/Sa7dr.png

body:
<s>I can't reproduce that.</s>

My apologies - I couldn't quite read the error message in the screen dump. What you got was:

    Don't know end address for 0
    Please add to table: end_addresses
    Run-time error
    World: smaug2
    Immediate execution
    [string "Immediate"]:96: Cannot continue
    stack traceback:
            [C]: in function 'error'
            [string "Immediate"]:96: in function 'process'
            [string "Immediate"]:134: in main chunk

The relevant error is the first line. That file has code for address 0 - which is not part of the bootloader. It tries to detect bootloader addresses, and zero is not one of them. Looking at the start of the file I see this:

    :1000000090C00000A9C00000A7C00000A5C000006B
    :10001000A3C00000A1C000009FC000009DC0000060
    :100020009BC0000099C0000097C0000048C40000B9
    :100030000CC4000091C000008FC000008DC0000003
    :100040008BC0000089C0000087C0000085C0000090
    :1000500083C0000081C000007FC0000002C100001A
    :100060007BC0000079C0000077C0000075C00000B0
    :1000700073C0000071C000006FC000006DC00000C0
    :100080006BC0000069C0000067C0000065C00000D0
    :1000900063C0000061C000001201100102000008EE
    :1000A0004123430001000102DC0109023E0002017C
    :1000B00000C0320904000001020201000524000111
    :1000C0001004240206052406000107058203080027
    :1000D000FF09040100020A000000070504024000B5
    :1000E00001070583024000010403090432034100B3
    :1000F00072006400750069006E006F002000280027
    :100100007700770077002E006100720064007500B0
    :1001100069006E006F002E0063006300290000007C
    :10012000000011241FBECFEFD2E0DEBFCDBF11E033
    :10013000A0E0B1E0ECEAFFE002C005900D92A6312C

In particular the format is:

     :10 0000 00 90C00000A9C00000A7C00000A5C00000 6B
      ^  ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^
    len  addr TT   data                          sumcheck

So this file includes code for the Atmega16U2 *as well as* the bootloader.

My sketch is not designed to program non-bootloaders (it is a bootloader programmer after all).

---

Scroll down that page for [how to reprogram the Atmega16U2 chip](http://www.gammon.com.au/forum/?id=11635&reply=2#reply2).

The bootloader programmer sketch (as published) will put the **bootloader** onto the Atmega16U2. Then follow the instructions on that page, or on this page, below, for entering DFU mode and uploading the main part of the code (not the bootloader part).

---

## Entering DFU mode

If you have just flashed the bootloader using the bootloader programmer sketch then it should enter DFU mode, visible because the pin 13 LED flashes rapidly.

If not, enter DFU mode by shorting together Reset and Ground briefly with a screwdriver or similar. They are the two left-most pins visible in the image above, nearest to the Reset button and below the hole on the board.

(Don't keep them shorted, just a brief touch should do it).

[![Enter DFU mode][1]][1]

 Once in DFU mode, you should see it appear as an Atmel USB device, if you type `lsusb` (on Linux):

    $ lsusb
    ...
    Bus 003 Device 092: ID 03eb:2fef Atmel Corp.
    ...

A Uno which is not in USB mode might look like this:

    $ lsusb
    ...
    Bus 003 Device 090: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
    ...

(or not appear at all if there is no firmware on it).

If you are using Ubuntu or similar you can obtain the DFU programmer as follows:

     sudo apt-get install dfu-programmer

You can obtain the code for the firmware from here:

<http://gammon.com.au/Arduino/Arduino-atmega16u2-Uno-firmware-Rev3.hex>

(RH-click and "save as" to put a copy on your hard disk).

Assuming you place that firmware in the current directory of your terminal window, you can now flash the code as follows:

    sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

You should see a message like:

    Validating...
    4034 bytes used (32.83%)

Now you can unplug the USB cable, plug it back in, and the USB interface should be back to factory settings.

For other operating systems, such as Windows, you should be able to get a copy of the DFU programmer from:

* <https://github.com/dfu-programmer/dfu-programmer>
* <http://dfu-programmer.github.io/>

  [1]: https://i.stack.imgur.com/FHKp3.jpg


message:
Arduino documentation on PCIFR and PINC

I was reading this thread:

https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein/21233#21233

and I have been trying to understand the code provided within.

While I was able to udnerstand most of it, I am still unable to find proper documentation on Arduino PCIFR and PINC?

Could someone please point me in the right direction?

Thanks in advance.

body:
Welcome to Arduino.SE. The documentation that you seek on `PCIFR` and `PINC` would not be documented under Arduino, this is as these are directly related to the ATMega328 (AVR Atmel micrcontroller) which is on the Arduino, they are [registers][1] which are inside the microcontroller and `PCIFR` and [`PINC`][2] are mnemonics.

For the ATMega328 you will find the documentation to these registers in the [datasheet][3] (a good read with coffee), or in tutorials written by others explaining this information in an easy to grasp way.

The `PCIFR` register is the Pin Change interrupt flag register(description on pg 73 of linked datasheet), this holds the flag bit to tell the microcontroller that there was an interrupt and runs the `ISR()` routine that one has set out. Read this [post][4] by Nick Gammon on Pin Change Interrupts, and then read all of the post to get a better idea of interrupts in general.

The register `PINC` is for the inputs to the microcontroller, when one uses `staus = digitalRead(A0);` they are in effect using a wrapped up version of bitwise math and bit manipulation when simplified to `status = PINC & (1 << PC0);` thus `PINx` (x is for the register name ABCD) represents the state of the pin, either *HIGH(1, 5V, true)* or *LOW(0, 0V, False)*. Borrowing from the below linked tutorial:
![maxembedded][5]

Another nice description of the input ports [in this tutorial][6].

From the image you see that moving a bit to a position and then bitwise `&` that with `PINx` you will have a value returned if there is a 1 in **that** position.

     PINC      0b00001001
    (1 << PC0) 0b00000001
             & __________
    status  =  0b00000001

The above shows how you only get the state of the first input and how the 4th input is ignored as it was not needed. Also worth noting PIN is the register description and is not the same as a physical pin that sticks out the IC's body.

  [1]: https://en.wikipedia.org/wiki/Atmel_AVR#Internal_registers
  [2]: https://en.wikipedia.org/wiki/Atmel_AVR#GPIO_ports
  [3]: http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf
  [4]: http://gammon.com.au/interrupts#reply6
  [5]: https://i.stack.imgur.com/cq3aC.png
  [6]: http://maxembedded.com/2011/06/port-operations-in-avr/


message:
HTTP POST request to IFTTT

I'm trying to send a POST request to IFTTT from a Node MCU. Instead of writing the code from the scratch, I've tweaked an already existing code (for GET request). It does not seem to work, what am I doing wrong? Needless to say, I replaced the WIFI ssid, the password and the IFTTT token. When testing the POST request with CURL, it works perfectly. Here's how the request should look like:

https://maker.ifttt.com/trigger/{event_name}/with/key/my_super_secret_token

...and the code:

<!-- language: c -->

    #include <ESP8266WiFi.h>

    const char* ssid     = "mywifi";
    const char* password = "mywifipassword";

    const char* host = "maker.ifttt.com";

    void setup() {
      Serial.begin(115200);
      delay(100);

      // We start by connecting to a WiFi network

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    int value = 0;

    void loop() {
      delay(5000);
      ++value;

      Serial.print("connecting to ");
      Serial.println(host);

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
      }

      // We now create a URI for the request
      String url = "trigger/{trigga}/with/key/IFTTT_token";
      Serial.print("Requesting URL: ");
      Serial.println(url);

      // This will send the request to the server
    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");

        // Read all the lines of the reply from server and print them to Serial
      while(client.available()){
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }

      Serial.println();
      Serial.println("closing connection");
    }

body:
Problem I see is that the request is incomplete - the server will be waiting for your payload.

    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

You haven't specified a `Content-Length` header so the payload should start after the headers finish - but you don't send anything.

You need to (at least):

 * add a payload *or*
 * add a `Content-Length: 0` header *or*
 * add a payload with a matching `Content-Length: ` header.

You can use `curl` to see a full set of valid `POST` headers like this:

    curl -v -d "" http://localhost

You can use Chrome and Firefox's Web Inspector's Network tab to look at the raw headers of requests too.


message:
Arduino command line vs. Arduino builder

I'm working on adding my Arduino to continuous integration and I came across two different possible ways of doing this, [Arduino command line][1], and [arduino-builder][2].  Can someone explain why the arduino-builder tool exists separately from calling Arduino from the command line?  And what are the advantages of using one over the other?

  [1]: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc
  [2]: https://github.com/arduino/arduino-builder

body:
The Arduino IDE command line predates arduino-builder and was made available when the source pre-processing and compiling was implemented by a Java class (deeply) embedded in the IDE.

The current IDE uses arduino-builder behind the scenes to process and compile the code so if you use arduino-builder you avoid having to load the whole Java IDE. Try it out it does some pretty cool stuff


body:
I've written [a new option for Arduino CI/unit testing](https://github.com/ifreecarve/arduino_ci) and put together [a decent size writeup about it as an answer to this related question](https://stackoverflow.com/a/49161903/2063546).

I ended up using the Arduino command line instead of arduino-builder, because it worked better cross-platform for me.  It assumes a graphical display though, even if you just use the CLI features.  In the case of Travis CI, I needed to spin up a fake X display to handle the initial splash screen and other graphical error messages.  (Fortunately, you can tell based on how long a command takes to complete whether it's waiting for you to acknowledge a graphical error message.)

Some examples of how to enable CI on your own project:

* The [DoSomething example library](https://github.com/ifreecarve/arduino_ci/tree/master/SampleProjects/DoSomething) shown above, used to test arduino_ci itself
* A practical example, [testing a Queue implementation](https://github.com/sdesalas/Arduino-Queue.h/pull/1/files)
* A complex example, simulating a library that controls an interactive device over a SoftwareSerial connection as part of the [Adafruit FONA library](https://github.com/adafruit/Adafruit_FONA/pull/91/files)