text:
Connecting Arduino with Philips Hue
I'm trying to control Philips Hue lights through an Arduino Uno (with a WiFi shield Model R3). Both the shield and the Philips Hue Bridge 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.
#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.

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:
#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());
}

See Arduino wifi shield - “No Socket available” thread in forum.arduino.cc

@jwpat: I have already seen that solution and appended the stated lines to my code but it doesn't work for me.

The error message seems to be coming from the network library code itself rather than anywhere in your sketch, which is a rather ugly practice by the library's author - what's to say that the Serial object is being used in a way that makes it an appropriate place to display errors?  To debug this more, you may need to dig into the networking library and add your own temporary (this project only) output that is more specific about why no socket is available.

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.  :-(

Thanks for the detailed answer. I'm not getting the No Socket Available error anymore but the code isn't doing what it is supposed to i.e. change the colors of the bulb.
Previously, I have sent JSON commands from my computer browser by going to the IP of the Philips Hue Bridge and it works smoothly. Have a look here once: http://www.developers.meethue.com/documentation/getting-started

@Hyperbola, I'm glad the No Socket Available error is gone, but I'll need to see "the code".  :)  You could edit your question and add an UPDATE section with the latest version.  My examples won't do anything with the network, of course.  They just use the Serial Monitor.

I have implemented suggestions #1 and #4 as #2 and #3 were throwing some errors. However, the sketch isn't doing anything irrespective of no errors. It's not able to change the color oft he bulb. Can you think of any possibilities of the same? Basically, we are just sending the same JSON commands from the arduino as we'd do from the browser: developers.meethue.com/documentation/getting-started

@Hyperbola, new UPDATE section above.  I suspect transition-time is doing what you told it to do...  :-)

I wonder if you are running out of RAM? Those sockets use RAM, and you have quite a few string constants, like this:
  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"));

I put the F() macro and cut some unnecessary data printing (MAC ID etc.) but it's still throwing the same error. I have updated the question with the new code having the macro.

Some of those Ethernet devices only support a limited number of sockets. I thought it might be 3 or 4, but can you find out how many for your WiFi shield? Or put it another way, what is the spec of the shield? (link)

I'm using the R3 Shield, exactly same as here. (https://www.arduino.cc/en/Main/ArduinoWiFiShield)

With reference to this example, 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"));.

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/ 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.


text:
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?

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 which is essential reading for anyone doing anything with networking software.

Can you tell me why aren't they using HttpClient on top of EthernetClient over here: https://gist.githubusercontent.com/jamesabruce/8bc9faf3c06e30c3f6fc/raw/11bbfe799a4122035963f8c6ee5cf3dac670ba7f/Control%20Philips%20Hue%20from%20Arduino%20Ethernet%20Shield

@Hyperbola Because you don't have to use HttpClient. You can do it all yourself manually if you like. HttpClient just saves you the hassle is all.

Thanks @Majenko. I have a question posted too regarding Philips Hue; if you could look at it once.

@Hyperbola I have no clue what a Philips Hue is nor how you communicate with it. I would recommend starting simpler and trying to send a GET request to somewhere like Google before dabbling into unknown boxes of tricks.

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

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
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?

First off, what is the circuit you are using with the photoresistor. What is the type, you get ones which have a light blocking casing allowing only IR through, or is it clear, if its clear it will pick up any light that leads to another point you can add, where is the sensor placed. There are other things to use other than an arduino, like a comparator. Have a look at this http://arduino.stackexchange.com/a/13318/2944 it has a few points there for you to start with

Without a schematic, how can we help you?

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 Why do you need a second resistor when using a photoresistor/LDR?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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.

If you post the code of your attempt, we might be able to help you.

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.

The Arduino Uno already has Schmitt triggers on all its digital inputs. C.f. figure 14.2 on page 76 of the ATmega328P datasheet.

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.


text:
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:

Thank you

Why do you need to do this? Normally you don't need to reflash the Atmega16U2 chip.

I work at a university and I'm making a shield that plugs into the top of dead Arduinos the see if they can be fixed with a simple re-flash of the chips, which is usually the fix. I used your sketch to put the Atmega16U2 chips into DFU mode, but it still requires me to connect the Arduinos to a computer to finish off the fix. It'd just be easier to put the working hex file on the chip in the first place.

I have another sketch which uploads a hex file from a SD card. The size of the full file for the Atmega16U2 may not fit into the bootloader programmer PROGMEM. However you could easily reflash the entire chip using the hex-uploader sketch. In fact you probably don't need the bootloader on the Atmega16U2 - because that is only used for entering DFU mode.

I can't reproduce that.
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.
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).

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/

Why am I getting the same error message when I try and convert Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex, the same used in your bootloader programmer sketch?

Being a combined file it would start at address zero as well. I would have stripped out the low-order bytes from the .hex file, leaving only the bootloader part.


text:
Arduino documentation on PCIFR and PINC
I was reading this thread:
Read RC receiver channels using Interrupt instead of PulseIn
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.

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 which are inside the microcontroller and PCIFR and PINC are mnemonics.
For the ATMega328 you will find the documentation to these registers in the datasheet (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 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:

Another nice description of the input ports in this tutorial.
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.


text:
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:
#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");
}

Don't you need to send any actual data in the body of the POST request? Do you get any output on the serial console?

I get nothing on the serial console, not even error code. I don't think my request goes through at all.

@Gerben, Not sure about sending data. IFTTT recipes do not expect data. That's what they say: Make a POST or GET web request to:
https://maker.ifttt.com/trigger/{event}/with/key/my_super_secret_token
With an optional JSON body of:
{ "value1" : "", "value2" : "", "value3" : "" }
The data is completely optional, and you can also pass value1, value2, and value3 as query parameters or form variables. This content will be passed on to the Action in your Recipe.

I'm still not sure how to make this work but this one (with GET method) works nicely: http://bigjungle.net/blog/2015/6/26/connect-maker-to-anything-ifttt

When you say you get nothing in the serial monitor, does that include the Serial.print()s in setup()? Nothing at all shows when you run the sketch? Perhaps its a baud rate issue? How is the ESP connected to the Node MCU?

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.


text:
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, and arduino-builder.  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?

...and http://platformio.org/#!/frameworks

I've discovered one downside of calling arduino_debug (on windows) from the command line.  It generates graphical pop-ups for errors instead of command line messages.

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

I've written a new option for Arduino CI/unit testing and put together a decent size writeup about it as an answer to this related question.
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 shown above, used to test arduino_ci itself
A practical example, testing a Queue implementation
A complex example, simulating a library that controls an interactive device over a SoftwareSerial connection as part of the Adafruit FONA library


text:
Arduino controlled light dimmer software
I found this software:
/*

AC Voltage dimmer with Zero cross detection
Author: Charith Fernanado   http://www.inmojo.com

Adapted by DIY_bloke
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table
(the Pin numbers are digital pins, NOT physical pins:
digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)
check:   http://www.inmojo.com

Pin    |  Interrrupt # | Arduino Platform
---------------------------------------
2      |  0            |  All -But it is INT1 on the Leonardo
3      |  1            |  All -But it is INT0 on the Leonardo
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only
0      |  0            |  Leonardo
1      |  3            |  Leonardo
7      |  4            |  Leonardo
The Arduino Due has no standard interrupt pins as an iterrupt can be attached to almosty any pin.

In the program pin 2 is chosen
*/
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay
                 // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  for (int i=5; i <= 128; i++){
    dimming=i;
    delay(10);
   }
}

But don't uderstand this part:

(10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

I know 10000us is 10ms, and we need to wait less then 10ms to dim light.
But don't understand why here we has -10us and /128.
Anyone know why is that?

-10uS because of the 10uS delay at the end of the loop, and /128 because he has decided there will be 128 possible dimming levels.

Why he put dalay 10uS on the end of loop? And how he know number for dimming levels?

It states why there is a 10uS delay - it's the triac on propagation delay. And how did he "know" to use 128 dimming leves? He didn't. He decided to use 128 dimming levels. He could have chosen another value, but 128 is enough dimming levels for most people and leaves a big enough delay granularity for easy timing.

Aha i understand now for levels. but still unclear with 10uS delay... Why triac need that 10uS?  It is very small value why is it importante?

Crudely put, it's the time it takes the triac to switch on.


text:
How to wire and use a B10K linear LED potentiometer?
I've bought some nice looking LED potentiometers from Ebay. They look like this.
I'm very new to low level electronics/hardware and I don't know how to wire it. It has 4+2 pins.
Also, how to use it in the Arduino?

Can't tell.  You need to use a DMM to discover which pins are which. Then https://www.arduino.cc/en/Tutorial/AnalogInput

The Taiwan Alpha spec sheet page 2 for this type of pot shows a little information about the pinout.  Refer to the second “P.C.B. MOUNTING HOLE DETAIL” diagram, which apparently shows the top side PCB layout.  The LED's anode is at lower right, marked B; its cathode is lower left, marked E.  It doesn't say what L (the pin next to E) is.  The three numbered pins most probably are: 1 and 3, ends of the resistive element.  2, wiper.
If that is correct, you could attach pin 1 to 5V, pin 3 to ground, and pin 2 to an analog input.  Before hooking it up like that, however, take ohmmeter readings from pin 1 to pin 2 as you move the slider from one end to the other and see if readings change proportionately to position.
Note, the phrase “Center Dent” on the ebay page probably should instead be “Center Detent” or  “Center Click”.


text:
How to stop uno from running program when powered on?
Does anyone know how to prevent the Uno from running the last program when it's powered on?
Many times I have changed hardware and wiring without clearing the program first.  Then when I power it on to upload the new program it will run the old program until it's uploaded.  This has many potential unwanted effects when the old program is running with the new hardware installed.

The simplest thing is to upload the new program before connecting the hardware.
If this isn't practical, connect a jumper wire from the Reset pin to ground (Gnd) before powering it on. This will hold in a reset state, and the program won't run.
Then, compile and upload your program. As it starts to upload remove the reset wire. That should upload it without running any existing program.

Thanks,  Sometimes for big projects with lots of connections this feature would be useful.  Should the reset button have the same effect?  Is there documentation on the feature?  Thanks.

I'm not sure about documentation - well there is now, in the answer here. :) The Reset button would have the same effect but it can be tricky holding it down with one hand and uploading the new code with the other.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Return value of 0 if value is less than zero
Background: I am using an analog pressure sensor with a range from 0-100PSI returning voltage values .44v to 4.44v. It's open air (or 0 PSI) voltage on the signal pin is .47 volts. I have a function that subtracts that .47v (to make zero) and then multiplies it by 25 (25 PSI per volt). Due to signal noise or other factors, sometimes my function returns a negative number, which wreaks havoc on my math. I would like to return a value of 0 when my offset math returns a negative number, but I'm having a problem with it.
The code that I wrote that doesn't work:
double EngineOilPressure() {
    //insert oil pressure code here
    int reading = analogRead(sensorPin3);
    float voltage = reading * 5.0;
    voltage /=1024.0;

    Serial.print(voltage); Serial.println(" volts");

    if (voltage-.47 < 0)
    {
        float voltadj = 0;
    }
    else
    {
        float voltadj = (voltage-.47);
    }

    float pressureP = voltadj * 25;
    return PSIToPascal(pressureP);
}

The error that I get is
dynamic_engine.pde: In function 'double EngineOilPressure()':
dynamic_engine.pde:41:23: error: 'voltadj' was not declared in this scope
Error compiling.

The code that works but sometimes returns a very wrong value:
double EngineOilPressure() {
    int reading = analogRead(sensorPin3);
    float voltage = reading * 5.0;
    voltage /=1024.0;

    Serial.print(voltage); Serial.println(" volts");

    float pressureP = (voltage - .47) * 25;
    return PSIToPascal(pressureP);
}

The scope of each of the two different and unrelated voltadj variables that your code (as below) declares is limited to within its enclosing set of braces.
if (voltage-.47 < 0)
{
    float voltadj = 0;
}
else
{
    float voltadj = (voltage-.47);
}

Instead perhaps say
float voltadj = voltage-.47;
if (voltadj < 0) voltadj = 0;

or perhaps
float voltadj = voltage < .47? 0 : voltage-.47;

or
float voltadj = constrain(voltage-0.47, 0.0, 5.0);

or
float voltadj = max(0.0, voltage-0.47);

Also see max() and constrain() reference pages at arduino.cc.

Another method, though one that is quite cryptic to understand, would be:
float pressureP = voltage > 0.47 ? (voltage - 0.47) * 25 : 0;

That is known (by me at least) as an inline conditional.  The ? acts as an if operator, and the : as an else.  Basically it's saying:
Voltage is greater than 0.47
Is that true?
    then subtract 0.47 and multiply by 25 and assign it
otherwise:
    assign 0

The format is simply:
value = {condition} ? {true value or expression} : {false value or expression};

If can be quite useful when you want to conditionally calculate or assign something.  @jwpat7 makes mention of a max() function above.  That max() function can itself be written with this inline conditional format:
maxval = a > b ? a : b;

Or: If a is greater than b then assign a otherwise assign b.

This is the one I ended up using, thank you! I love the simplicity.

The Arduino way is to use constrain
float pressureP = constrain ((voltage - 0.47) * 25 , 0 [The Maximum your code can handle]);

This will return the value ((voltage - 0.47) * 25) but never less than 0 and never more than The maximum you provide.


text:
Configure HC-05
I am trying to send/receive data from Android to my Arduino (via a HC-05) and later from Arduino to Android. I have configured my HC-05 as slave, and the UART=9600,0,0.... To send data from Android to Arduino I don´t have problem but to send data Arduino to Android I can not...
This is my sketch:
char data;
int a=1;
int v=1;
#include SoftwareSerial connection(10,11);//RX|TX
void setup()
{
 pinMode(7,OUTPUT);
 connection.begin(9600);
 digitalWrite(7,LOW);
}

void loop()
{
 if(connection.available()>0)
 {
  data=connection.read();
   if(data=='1')
   {
    digitalWrite(7,HIGH);
    connection.write(data);
    delay(200);
   }
   //connection.write(data);
  }
 }

MY HANDLER IN THE MAIN:
       mhandler=new Handler()        {
        public void handleMessage(android.os.Message msg)            {
            switch (msg.what)
            {
                case MENSSAGESEND:
                    msg = new DriveData((BluetoothSocket)msg.obj);    //DriveData msg = new DriveData((BluetoothSocket)msg.obj);
                    break;
                case MESSAGEREADING:
                    byte[] bufferget = (byte[])msg.obj;
                    String men = new String(bufferget,0,msg.arg1);
                    sb.append(men);
                    int endline=sb.indexOf("\n");
                    if(endline>0)
                    {
                        String print=sb.substring(0,endline);
                        sb.delete(0, sb.length());
                        Toast.makeText(getApplicationContext(),"menssage"+" "+print,Toast.LENGTH_LONG).show();
                        txtData.setText(print);
                    }
                    break;

            }
        };
    };

MY METHOD FOR RECEIVER AND SEND DATA
  public void run()
    {
        byte[] wait=new byte[1024];
        int bytesReceived;
        while (true) {
            try {
                 bytesReceived=entrydata.read(wait);//entrydata is my inputstream
                mhandler.obtainMessage(MESSAGEREADING,bytesReceived,-1,wait).sendToTarget();
            }catch (IOException e){
                break;
            }
        }
    }

sorry but.. what is the line #include SoftwareSerial conexion(10,11);//RX|TX?

what is HC-05 ?

@alcor Bluetooth module. I'd add more details to the question but the Android app is annoying to use.

HC-05 is model from bluetooth for my connection                                                #include SoftwareSerial is the library for use pin´s as RX and TX on arduino UNO, "conexion" is the name from my connection is as variable

Are you sure it's not a simple hardware problem - like the TX pin being disconnected?  You are handling the HC-05 at 3.3 volts right?

No, i have Volt to 5v from arduino, my bluetooth can be using with 3.3v or 5v

@FidelPinedaSantos Just a friendly tip. Code in English, that way it's times easier to read for others.

@avamander I have already changed my codec to english, sorry

@FidelPinedaSantos Have you tried using some of the examples available on the web for communication with this combination of hardware?

I can receive data from android, but i can not yet send data from arduino to android

You are missing the line termination
you must send '\n' after your data in order to receive the data
or use
conexion.println(entrada)
rather then
conexion.write(entrada)

I already did these, but not work, only i can send data from android to arduino


text:
Works with gcc, not with Arduino. error: taking address of temporary array
I need to hard code 8 byte addresses into char arrays of length 8. This must be done many places in my code (in function scope), so I have tried to come up with a one-liner. The following works perfectly in C when compiling with gcc.
char a[8];

void cpaddr(char target[], char *source) {
    int i;
    for (i=0; i<8; i++)
        target[i] = source[i];
}

int main() {
    char b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
    cpaddr(a, b);

    // line below does not compile with Arduino IDE
    cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
}

When compiling on Arduino the last line, which is the one-liner I was aiming for, does not compile. It gives:
/home/bob/Desktop/ate/Ate.ino: In function 'int main()':
Ate:101: error: taking address of temporary array
cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
^
exit status 1
taking address of temporary array

What is the problem here, that apparently is not a problem with gcc?
How do I fix it?

Have you tried
void cpaddr(char target[], const char *source)

I tried your exact code with g++ (and gcc) version 4.8.4 and got the exact same error message you got.

I'm using 4.9.3. Screenshot of result: http://i.imgur.com/2RJbGwg.png

( type[] ){val, ues} is not a valid way to create a temporary in C++: http://stackoverflow.com/questions/15458883/using-array-init-list-as-temporary-in-c11#comment26614881_18163000 The solution is to typedef it.

It is quite right, using that kind of syntax is not allowed. It's a bit of a pain, but it's ok since there is an alternative method - kind of a "trick" if you will.
That trick is to use a string, not an array. After all, a string is just an array, it's just handled slightly differently by the compiler.
Instead of using {...} use "..." and use the hexadecimal character escape sequence \xNN, such as:
cpaddr(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D");

You could even lose your custom function and use a standard library function - memcpy():
memcpy(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D", 8);

On the 8-bit AVRs you can save RAM by using the progmem variant and the F() macro:
memcpy_P(a, F("\x00\x10\xFF\xCA\x00\x00\xA2\x7D"), 8);

I think that it should be PSTR() instead of F(). F() is a very special Arduino String hack.

F() just imposes a type to PSTR() for overloading. You can use either.

Because of the type you cannot use F() directly without a cast. The compiler will say "cannot convert 'const __FlashStringHelper*' to 'const char*'".

Mine didn't. It compiled perfectly fine. I always test before posting code. It's not a cast, it's a reinterpret_cast.

But apparently not on memcpy_P as it takes whatever, i.e. const void*.

In any case F() is part of the "black-listed" String class. That should be enough to use PSTR() instead :)

This is true ;)

No it isn't. The define #define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal))) is in WString.h, however there is no connection between F() and the String class except that the String class uses it in certain cases (as does the Print class). In fact as you can see from the #define saying to use PSTR() instead doesn't make any sense. F() already uses PSTR(). It's purpose is just to create a new type that can be used to detect if a string is in PROGMEM or RAM. That's all.

@NickGammon Isn't that mainly for overloading, like I mentioned above? ;)

Er, yes it turns # define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];}))  (which is still type const char []) into another type, which then assists with overloading. So I agree that (after casting) they would be the same thing. However neither PSTR nor F() are "part of the black-listed String class". I see no objection to using F() here. In fact your suggestion would save RAM compared to what I did in my reply, although mine is probably "cleaner" in that you aren't throwing in a memcpy_P (and making sure you get the length right).

See Using array init list as temporary in C++11?
You can solve it by using const. This compiles:
char a[8];

void cpaddr(char target[], const byte *source) {
    int i;
    for (i=0; i<8; i++)
        target[i] = source[i];
}

int main() {
    byte b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
    cpaddr(a, b);
    cpaddr(a, (const byte[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
}

Note I had to change your array from char to byte because I was getting (valid) warnings that things like 0xCA don't fit into a char.

As Majenko said, memcpy would be better than doing a byte-by-byte copy.

I hate it when people use non-standard arduino specific types like byte, when there is a perfectly good and standard uint8_t available...

As explained in the very thread you linked, ( type[] ){val, ues} is not a valid way to create a temporary in C++: http://stackoverflow.com/questions/15458883/using-array-init-list-as-temporary-in-c11#comment26614881_18163000 The solution is to typedef it.

Recent versions of the IDE use C++11, so whether or not it is valid in C++ doesn't really matter.

How do I fix it?

"Char []" shouldn't compile under c. It is just invalid.
You can use string, cast to char * . or just another pointer as you did already.


text:
Sim800L HTTP post request stop working after a while
I am desperate to get my SIM800L module (http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-Board-Quadband-QUAD-BAND-Antenna-for-MCU-Arduino-/321992759287) sending POST requests for a long period of time... Sometimes it stops after 100 requests in a row, sometimes 300 so it's really weird.
Everytime I run it, it sends the request for a while (between 1 and 3 hours) and suddenly stops on these AT commands:
---> AT+HTTPINIT
<---

OK

When it works the OK is on the same line and it goes on to the next AT command.
        ---> AT+HTTPTERM
    <--- ERROR
         ---> AT+HTTPINIT
    <--- OK
    ---> AT+HTTPPARA="CID"
    <--- OK
    ---> AT+HTTPPARA="UA"
    <--- OK
    ---> AT+HTTPPARA="URL"
    <--- OK
    ---> AT+HTTPPARA="CONTENT"
    <--- OK
    ---> AT+HTTPDATA=1221,10000
    <--- DOWNLOAD
    <--- OK
    ---> AT+HTTPACTION=1
    <--- OK
Status: 201
Len: 0
    ---> AT+HTTPREAD
    <--- OK
    ---> AT+HTTPTERM
    <--- OK

I thought it was a powering problem so I connected the module to the VIN pin of my arduino mega via a buck converter but the problem is still here!
Does anybody have any idea what could be wrong? I can send you the code if needed.
Many thanks in advance
Pauline

Cross-posting? At least include your code instead of this indecipherable nonsense.

Could you try enabling "verbose error codes" (or atleast numeric error codes) using AT+CMEE=2 or AT+CMEE=1 and then post the (error) response on AT+HTTPINIT. There are no errors in the log you have attached.

Maybe it just lost signal. You might want to make your code check for errors. And if it finds a response with: "Error" it will attempt to re-send. (Maybe add a timeout or re-try limit also).


text:
Fritzing PCB design review/questions
I've designed an PCB and due tot the delivery times, I kinda want to order it right now.
I don't yet have the components, so I haven't actually tried it on a breadboard.
Now I'm unsure if the PCB would work, as this also is my first try in PCB design.
It's a single-sided PCB.
All parts (should be) through hole.
I would be using SoftwareSerial since the ATTiny does not have serial (Rx/Tx).
[TL:DR] Would this PCB work?
Some points of which I'm unsure, or might be a problem:

Is the spacing of the board/lines to other components/side big enough?
Should I use a copper/ground fill? Which and why?
Are the rounded-off traces actually better as sharp edges?
It says: 36mm by 15mm isn't this too small to fit all those components?
Can I actually use the RESET pin as other functions (without changing fuse bits)?
Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Breadboard

Schematic

Layout

File
If someone needs the file:
It's opensource, no restrictions. Would be nice to give me some credits/donation, but you can freely use it for even commercial projects.
Download below:
https://www.dropbox.com/s/lggjg5fxd6s3kqc/ATTINY485.fzz?dl=0
Some credits to Nick Gammon, I've used his schematics as a reference (especially on the TX enable pin, which was quite smart, using only 1 pin).
Version2!

Changes:
 - replaced the "V" shape.
 - pull-up on the reset pin.
 - decoupling capacitors
EDIT: It's better not to use a pull-up resistor on the reset line. The ATtiny85 has this internally.

You could use the reset pin to make the chip reset. You can distinguish between resets and power-ups. So as long as your program doesn't require any variables to need to remain, you could add a button to the reset pin and make it do something. Or if it does you could use it to change some settings. E.g. changing baudrate.

@Gerben interesting idea, but I was looking to use the pin for UART. I think I'm going to use the MISO pin, since I don't have to receive data from the slave device. I might get one of those HVSP, since that way I can actually get full UART and full SPI. Which would be awesome for a RS485 to SPI converter.

Version 2 is flipped. Are the orange traces on the top or bottom layer. Having a mirrored board would be a problem. Though with through hole this can be fixed by soldering to components on the same side as the copper. But his a lot harder. Especially with header, where you have to temporary remove the plastic for soldering. Always double check this. I've made this mistake a few times.

@Gerben ah, yea, I switched to bottom view, I'll check it when I can. Thanks for the heads up :)

Would this PCB work?

Possibly, sometimes, under some conditions. See below.

Is the spacing of the board/lines to other components/side big enough?

Plenty.

Should I use a copper/ground fill? Which and why?

For your circuit there is no real electrical reason to use a ground plane. However, many fab houses like you to use at least a copper fill in the empty areas since it means less copper has to be etched off the board, and so their etchant lasts longer before it needs to be replaced.

Are the rounded-off traces actually better as sharp edges?

Yes. Always try to avoid right-angles. Sharp corners radiate EMI noise, mitred corners radiate a lot less.

It says: 36mm by 15mm isn't this too small to fit all those components?

Not in the slightest.

Can I actually use the RESET pin as other functions (without changing fuse bits)?

You can only disable the RESET functionality of the RESET pin using the fuse bits - and then it becomes somewhat difficult to program: you need a HVSP (High Voltage Serial Programmer) to get it back into programming mode again.  This blog post details how it is done.

Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Your circuit isn't complete.  There are a couple of things missing that you need to add, and some that you might want to add.
The things that are missing:

Decoupling capacitors (100nF) on the power pins of both chips
You should have one larger (10µF typical) reservoir capacitor at the power entry to the board
(Assuming RESET is enabled) Pullup resistor on the RESET pin

The things you might want to add:

RS-485 bus termination resistors

The latter are optional depending on where in the bus your module is. You need termination resistors at both ends, so it is common to have them on the boards but with jumpers to enable/disable them.

Setting fuses can't be done with an USB-ISP?
And good catch on the termination resistors & decoupling capacitors.
In this case, one big capacitor on the power-in line wouldn't be enough? I'm not planning on using a switching circuit and the IC's don't have a big transient load? Is it more of a cherry on the top as a requirement?

Sharp edges can also be problematic in etching. Mostly a problem with home etching. But with the thickness of the traces and the spacing between them, it doesn't really matter if there is a bit more copper etched away in the corners.

@Paul Yes, you can set fuses with a low voltage ISP, but once you have disabled RESET you can no longer use the low voltage ISP since it relies on using the RESET functionality to enter program mode. So once you have done it you can't undo it without a HVSP to enter program mode through the secondary High Voltage method.

@Gerben Yes, right-angles can trap copper in their inner angle, but sometimes right-angles are the best you can hope for - for instance, always use T junctions; never join a trace to another at an acute angle or you get a nice place to trap cruft.

@Paul The large capacitor is to deal with larger power droops caused by low speed switching, such as the communication drivers. The small capacitors are there to deal with the high speed transients caused by the internal circuitry of the chips. They cover different frequency ranges, so they are both needed. The ATTiny especially. It is a switching circuit whether you like it or not - it has a clock and things inside switch on and off very fast.

@Majenko, ah that makes sense, I'm indeed planning on SPI which is some kind of switching. And it's better to learn it right :)

I've added V2 (v1.01) to the post (I just noticed I still miss the 10uF) but the termination resistor can be added in the pin header (along with the A/B RS485 pins), so this would be a better/working design? ;D

For a reservoir capacitor, does it matter if it's a tantalum or electrolytic capacitor?

Electrolytic is the norm.

Is the spacing of the board/lines to other components/side big enough?

Looks ok.  You might be able to squeeze it a few mm smaller each way, although since the board already is small, that probably would make little difference in cost.

Should I use a copper/ground fill? Which and why?

Copper/ground fill on a single-sided board won't make much difference for this circuit.  It would be reasonable, however, to make the ground traces two or three times as wide as they are.

Are the rounded-off traces actually better as sharp edges?

If you mean, make square corners rather than the 45° turns as shown, either way will make little difference for this circuit.  The 45° turns are ok.
Note, sharp V-notches, like the one inside the traces at pin 2 of the Tiny85, are undesirable; I think they etch less accurately than more-open junctions do.

It says: 36mm by 15mm isn't this too small to fit all those components?

Looks like there's room to spare and the board could be made slightly smaller.
For homemade boards that are drilled using a hand-cranked XY table, keeping drilled holes on the intersections of a .1"x.1" grid is a good idea.  For commercially-made boards, it's less important but can help with assembly.
Edit: Regarding “Making ground traces bigger makes sense, but does that also mean 5V traces should be bigger?”, yes, both ground and power traces typically should be large, if board layout allows.  It's desirable that those traces have low inductance and it's ok to have high capacitance between ground and power traces.
Regarding how long it takes to get your PCB back from a manufacturer: The PCBshopper.com website makes it easy to compare time vs cost across a range of manufacturers.  For small circuits like yours, OSHpark is an inexpensive choice (you would get three double-sided boards for under $5, in about 15 days).  If you need up to about 10 medium-size boards, Maker Studio is quite economical but standard delivery may be slow (2-3 weeks).  If you are in a hurry and need a larger number of boards, consider (eg) PCBway.  By paying $25 for DHL shipping, you can have a batch of boards in 9 or 10 days – about three days for manufacture and a week for delivery.  The pictures below show an example of PCBway's order tracking, the left side at about two days after the order was placed, the right side 11 hours later.  This order for 50 each 36 mm x 56 mm two-layer boards with silk both sides cost $27 for manufacture and $25 for delivery.

Good catch on the V shape. The size question was quite silly, I can't yet imagine it to be 3,6cm long (which isn't a lot). Making ground traces bigger makes sense, but does that also mean 5V traces should be bigger? (They're 24 mil, can't make them bigger in fritzing?)

@Paul, see edit

I went with OshPark since they've got a Gerber viewer built in (so I could re-check each layer). Pricing was around 5x better as Fritzing and will get some nice purple-colored boards, without shipping cost.
I now actually realize I don't have any programming headers or reverse current protection. But I guess I'll make it on a breadboard beforehand anyway, and take a good look when wiring.


text:
How do I calibrate an ESC after connecting it to an Arduino?
I'm trying to connect an Arduino to an Electronic Speed Control and failing horribly. I'll explain what I've done so far, and then I'll explain the problem.
Before we get there, here's the list of parts I'm using:

Arduino Uno (genuine)
6V to 8.4V rated 18300 RPM 350 g-cm brushed motor.
Traxxas XL-5 brushed motor ESC. 1600 Hz is the highest PWM signal it accepts, if I'm not wrong.
Venom 4200mAh NiMH 8.4V battery pack (will replace soon with a 7.2V).

So I first connected the ESC to the motor. The connection is this bullet lead connection (the connection seems intact), and then the ESC to the Arduino. I connected the white wire to pin 9 and the black wire to ground. If I'm not wrong, this is the standard servo motor setup. I then plugged the Arduino into my computer, which has an intact USB port. Lastly, I connected the battery pack to the ESC.
Now I've tried to upload some basic code to try and calibrate my ESC, but it just plain our refuses to work. Under no circumstances will the motor run.
The code I'm using just sends the signal sent by the signal monitor.
I'm a complete noob to Arduino, so I don't know what could be wrong. The program I have in mind needs to be able to run while not connected to the computer, activate when a push-button switch is activated, run the motor for a certain distance (which involves an encoder, right?), and then stop.
Any pointers or things I could be doing wrong?
int value = 0;
Servo myservo;
void setup() {
    firstESC.attach(9);    // attached to pin 9
    Serial.begin(9600);
}
void loop() {
    myservo.writeMicroseconds(value);
    if(Serial.available())
        value = Serial.parseInt();    // Parse an Integer from Serial
}

and the one here:
#include <Servo.h>
#define MAX_SIGNAL 2000
#define MIN_SIGNAL 700
#define MOTOR_PIN 9
Servo motor;
void setup() {
    Serial.begin(9600);
    Serial.println("Program begin...");
    Serial.println("This program will calibrate the ESC.");

    motor.attach(MOTOR_PIN);

    Serial.println("Now writing maximum output.");
    Serial.println("Turn on power source, then wait 2 seconds and press any key.");

    motor.writeMicroseconds(MAX_SIGNAL);

    // Wait for input
    while (!Serial.available());
    Serial.read();

    // Send min output
    Serial.println("Sending minimum output");
    motor.writeMicroseconds(MIN_SIGNAL);
}
void loop() {
}

^shamelessly copied from the internet

What is the code?

just added the code c:

@a_human_mistake Please use the Code button in the editor to format code as code. Your current method did not look nice. :)

oh man, I tried and it wouldn't allow me to put newlines in the code. turned out really weird when I used the mini-Markdown formatting. Thanks for editing to make it look decent!

@a_human_mistake could you describe what the led is doing on your ESC?

http://chat.stackexchange.com/rooms/36489/discussion-between-a-human-mistake-and-rsm

The is a standard with RC connectors, that is Black always goes to ground white/orange goes to the signal and red/brown goes to 5V.
I don't know if you have made a typo, but you need to connect the white to D9 and the black to GND. Here is a instructables post, it describes using a brushed ESC step two reiterates the colour code standard.
You would also need a rotary encoder or shaft encoder to tell the distance moved, there are lots of ways to achieve this from simple(coded disk and IR arrangement) to custom made PCB add-ons.

Oops, I did make a typo. Thanks for pointing it out. I don't technically need to measure the distance I move, only make it move a certain distance. I considered using a quadrature encoder, but I have enough problems with everything else that the plan was basically benched.

@a_human_mistake do you have a RC receiver and transmitter you could use to test the ESC. Also I will move this to a comment rather or delete it.

I can check and see -- is it possible that it's a problem with the ESC?

@a_human_mistake there may be the annoying possibility that the ESC might have had too much current pulled through.

So if I were to buy a new ESC, what would I look for in order to avoid that happening? Can I avoid that problem in any way?

@a_human_mistake you can avoid an ESC burnout by making sure , as a rule of thumb, that the current rating for continues use is at least 10A higher than the motor's rated current, and then the burst/surge current would also be high to handle start up draw. Do you have the specs of your current motor's current draw?

"peak current draw 50+ amps" is all it says on the website. I feel like that's a lot... https://traxxas.com/products/parts/escs/3018Rxl5waterprooflvd <- ESC, http://www.amazon.com/RS540-Sport-Tuned-Motor-All/dp/B00061HB0K <- motor

Calibration can be done by sending the low throttle and high throttle values through the Serial monitor.Here's an instructable i have made using NODEMCU.Check this out.May be it helps.


text:
error while loading libtinfo.so.5 - SOLVED
I just installed the 1.6.7 version and want to upload it a sketch to Arduino UNO hardware. I get error message:

/home/pali/Irataim/TarBalls/Arduino/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory

I'm on Gentoo linux operating system.
How can I solve this problem?
By following this link:
https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6
I just add tinfo USE flag to ncurses package, re-emerged it and can run Arduino IDE that I emerged from Gentoo repository.

(Install dependencies with emerge -avq sun-jre-bin crossdev) Run equery belongs libtinfo.so , if the library exists then try symlinking the libraries: ln -s /lib64/libncurses.so.5 /usr/lib/libtinfo.so.5 and
ln -s /usr/lib/libtinfo.so.5 /usr/lib/libtinfo.so.

I did so, but there is no libtinfo.so library.

equery belongs libtinfo.so there is none?

Exactly! There is none libtinfo.so out there.

@PalCsanyi in the stack exchange system, questions are marked resolved not by editing the title, but by accepting an answer.  If none of the provided answers matches your solution, provide your own and accept that, however it does look like at least one of them matches what you said you did.

@sa_leinad please do not edit questions in a way that pushes the most important part of the error message off the screen.  Adding a requirement to manipulate a scroll bar to view the actual issue is the opposite of making a question clear.

@ChrisStratton thanks. good point. I'll know that for next time!

Install libtinfo5, the terminfo library.
If that doesn't help, you can try to debug the problem yourself. First,
check which libtinfo avrdude is looking for:
ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo

On my Ubuntu, I get this:
libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fa74a888000)

Next, see where your libtinfo is installed:
find /lib /usr/lib -name 'libtinfo*'

On my system I get:
/lib/x86_64-linux-gnu/libtinfo.so.5
/lib/x86_64-linux-gnu/libtinfo.so.5.9

Do you have any discrepancy between the two?

I just installed terminfo package, the Haskell bindings to the terminfo library and try to upload again a sketch. I get the same error message:  arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory. However, I'm using now the just downloaded arduino-1.7.8-linux64 package.

@PalCsanyi: Then I do not have the solution, but I added some hints to help you debug the problem.

I tried followings on my Gentoo linux:
ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude
not a dynamic executable
find /lib /usr/lib -name 'libtinfo*'
There is no output.

@PalCsanyi this topic refers to  have similar problem and got it solved using a symbolic link to libncurses. Take look: https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6

@PalCsanyi: OK, I downloaded arduino.org's tarball (I was testing with Ubuntu's arduino package). Their avrdude is a shell script: the real avrdude is avrdude_bin. I updated the answer with the output I get from their avrdude_bin on a 64-bit system. You said you installed the terminfo package, did you install version 5? What files does it provide that have the ".so" extension? No libtinfo.so.5 in sight?

My installed terminfo package name is:
dev-haskell/terminfo and the installed version is:  0.4.0.0(19.15.39 2016-03-02).
Description of this package is: Haskell bindings to the terminfo library.
When I run
ldd Irataim/TarBalls/Arduino/arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo
I get:
libtinfo.so.5 => not found

No grep libtinfo:
linux-vdso.so.1 (0x00007ffee67f4000)
libusb-1.0.so.0 => /lib64/libusb-1.0.so.0 (0x00007f6fe415e000)
libusb-0.1.so.4 => not found
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f6fe3f42000)
libm.so.6 => /lib64/libm.so.6 (0x00007f6fe3c46000)
libreadline.so.6 => /lib64/libreadline.so.6 (0x00007f6fe39fb000)
libncurses.so.5 => /lib64/libncurses.so.5 (0x00007f6fe37a4000)
libtinfo.so.5 => not found
libc.so.6 => /lib64/libc.so.6 (0x00007f6fe3409000)
libudev.so.1 => /lib64/libudev.so.1 (0x00007f6fe31e3000)
/lib64/ld-linux-x86-64.so.2 (0x00007f6fe4376000)

@Personagem
Indeed, there is a solution for me. Thanks!!
https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6

Thanks, sudo apt install libtinfo5 worked for me.

You have to rebuild sys-libs/ncurses with tinfo USE flag turned on. (You can also make a symlink: libtinfo.so -> libncurses.so, but it's not elegant solution).
Firstly, check if you have a record for ncurses in any file in /etc/portage/package.use. If not, create a file /etc/portage/package.use/ncurses with such content:
sys-libs/ncurses tinfo

then, rebuild ncurses:
emerge -av sys-libs/ncurses


text:
Neopixel Ring - How to breathe in a circle motion?
I'm trying to get an effect like (https://vine.co/v/Mwwbi5a1BFK) using a neopixel ring. I can get the neopixels to turn on and off in a circle motion and I can get the neopixels to fade all at once. What I can't get working is combining the two together. Any help would be much appreciated!
EDIT Tried making fade with the circle motion
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  ledTrail(50, 100, 100,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
}

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
const byte extra = 4;  // how many ahead, and behind, to light up

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, int steps, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  int tmpR, tmpG, tmpB;         // Temp values
  // Fade up
  for (int s=1; s<=steps; s++) {
    tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (Gf * s) / steps;
    tmpB = (Bf * s) / steps;

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

    // now go "extra" pixels ahead and behind
    for (int s = 1; s < extra + 1; s++)
      {
      tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
      tmpG = (Gf * (extra - s)) / extra;
      tmpB = (Bf * (extra - s)) / extra;
      myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
      myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
      }

        // Fade down
  for (int s=steps; s>0; s--) {
    tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (Gf * s) / steps;
    tmpB = (Bf * s) / steps;
  }

    myNeoPixels.show();
    delay(pause);
  }
   }
}

LED TRAIN CODE
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  ledTrail(100, 255,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
}

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);
    myNeoPixels.show();
    delay(pause);
  }

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rb,Gb,Bb);
    myNeoPixels.show();
    delay(pause);
  }
}

BREATHING CODE
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  breathe(20, 100, 255,255,255);       // Pause; Number of steps; Full-on R,G,B values
}

// Pause = delay between transitions
// Steps = number of steps
// R, G, B = Full-on RGB values
void breathe(int pause, int steps, byte R, byte G, byte B) {

  int tmpR, tmpG, tmpB;         // Temp values

  // Fade up
  for (int s=1; s<=steps; s++) {
    tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (G * s) / steps;
    tmpB = (B * s) / steps;

    for (int i=0; i<numPix; i++) {
      myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
    }
    myNeoPixels.show();
    delay(pause);
  }

  // Fade down
  for (int s=steps; s>0; s--) {
    tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (G * s) / steps;
    tmpB = (B * s) / steps;

    for (int i=0; i<numPix; i++) {
      myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
    }
    myNeoPixels.show();
    delay(pause);
  }

  delay(pause * 30);
}

Try to describe the effect in words, and it might shed light on how to write it in code.

I don't have any NeoPixels to try it with (yet) however this should do it. Replace the ledTrail function by this:
const byte extra = 4;  // how many ahead, and behind, to light up

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  int tmpR, tmpG, tmpB;         // Temp values

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

    // now go "extra" pixels ahead and behind
    for (int s = 1; s < extra + 1; s++)
      {
      tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
      tmpG = (Gf * (extra - s)) / extra;
      tmpB = (Bf * (extra - s)) / extra;
      myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
      myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
      }

    myNeoPixels.show();
    delay(pause);
  }
}

What this is doing is having an inner loop that "looks ahead" and behind another extra pixels and makes them brighter/darker. Debugging code (since removed) shows the effect:
i = 4, R = 255, G = 255, B = 255   <-- original code
i = 5, R = 191, G = 191, B = 191   <-- one ahead  (darker)
i = 3, R = 191, G = 191, B = 191   <-- one behind (darker)
i = 6, R = 127, G = 127, B = 127   <-- two ahead  (darker still)
i = 2, R = 127, G = 127, B = 127   <-- two behind (darker still)
i = 7, R = 63, G = 63, B = 63      <-- and so on
i = 1, R = 63, G = 63, B = 63
i = 8, R = 0, G = 0, B = 0
i = 0, R = 0, G = 0, B = 0

Ahh I see! Is there a way to fade the LEDs as they move around in a circle? Right now, they still just turn on and off abruptly so you can still see the "steps" as the light rotates. I tried updating the code in OP.

It should fade as my debugging displays show. I can't see why it isn't. I'll have to wait until my NeoPixels arrive in the mail so I can try it out myself.

Ok cool. I'll try at it for now then. :)


text:
ESP8266 shows garbage in serial monitor
I have my ESP8266 connected via serial to USB like the image shows:
It worked just fine, however, when I tried flashing Blynk code
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = "YourAuthToken";

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, "ssid", "pass");
}

void loop()
{
  Blynk.run();
}

It started outputting loads of garbage in the serial monitor, while Blynk app said ESP is not connected to network. I've tried since then flashing empty sketches or some other stuff, whatever I do, serial monitor shows loads of junk. I've tried changing modes, I've tried changing baud rates (57600 was default, and AT worked just fine).
Junk example:
  …ÕZªP‚,JHVYº—¡VÕ]J*ÉW¥¡Õ¥Õ-”ªUŠQd®”¡âJ%H
!HiZÊIIRPÖuUPÒ‚BñZT¥ *EUeZB\)*EVjU!\©Š_¥¢”ÅVªqYiUµP”¬ÕPQT°*uH)HZKB*ÕXªuH!HBHBH…µEIâHBH!H©ªqY+hZVB\BH!HÊ*Òµe�qHBHBHŠ*i±…Z¦-hUµPÔ¬ÔPQT°*uH)H-KB*ÕXªuH!HBHBH…µEB\!H!HBVªqY+iZVB\BH!HeVÒZ¢qHBHBHŠ*iQ…Z¦-hUµPÔ¬ÔPQTaYRB\    jHiBHªaYRB\BH!HBVªaYRB\BH!HBVªqY+iZVB\BH!HÊVÒZ¢qHBHBHŠ*i±Õ\V
iUµPÔ¬ÕPQT°*uH)H-JBVªaYRB\BH!H!VªaYR!\BHBH!Vªq©+hZW!\BHBHJ*iµE�âHBH!HŠ*i±…Z¦-hUµPÕ¬ÔPQTaYR!\    %Hi!HÕXªuH!HBHBH…µEIqHBHBH

Try stabilizing the power source.
I parallel connected two AA batteries with the Arduino's 3.3V output and the garbage disappeared and my ESP8266-01 got much more stable.

In this case, it looks like your Serial Monitor just isn't set to the right baud rate with Both NL & CR. Even if your monitor is set to the default 115200 baud rate, you'll still see some garbage characters which leads into the next issue.
Using 115200 has too many instructions for the Arduino Uno to reliably decode characters and that's where the garbage is coming from.
The ESP8266 default baud is 115200, so you need to connect at the default rate and issue an AT command to reduce the baud rate to 9600.
Each time you reset, the ESP8266 goes back to the default baud rate.
Here's an example script that connects at the default baud rate and then reduces it to 9600. You'll connect the Serial Monitor at 9600. At the lower baud rate, I'm not getting any garbage characters.
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

void setup()
{
  Serial.begin(9600);
  ESPserial.begin(115200);
  ESPserial.println("AT+IPR=9600");
  delay(1000);
  ESPserial.end();
  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Ready");
  ESPserial.println("AT+GMR");
}

void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
}

An odd thing that happened to me is that I tried to use a baud rate of 4800 and I bricked one ESP8266 module. I don't know if that was a glitch or just a coincidence.

I had errors in printing sensor values to serial, normal output starts with "D:" and ends with "all".
D: 23 24 25 23 22 22 21 22 22 22 23 24 23 24 24 24 24 25 25 25 26 26 25 25 21 21 21 21 21 21 all
 36 36 37 45 44 43 41 41 41 40 39 39 38 38 37 38 38 38 37 40 all
&&B⸮⸮R⸮B &⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮
⸮⸮5
D: 29 45 29 28 27 26 25 27 29 26 22 23 24 22 21 21 20 20 22 22 149 26 25 24 27 26 23 21 21 22 all

I grounded, stabilized power source, change code not to use interrupts notthing had changed
How i solved:
I had spare mcu, changed it,  now serial works flawlessly.

Have you also pulled up the ESP8266's reset pin? I don't know what effect not doing so might have, but the recommended connections I have read and followed include that. The RST and CH_PD pins are adjacent; they're easy to jumper together.

I had a similar problem with a NodeMCU ESP-12E (Amica v2) board... after pressing and releasing the RST button with Serial Monitor open & set to 115200 baud, it would display the boot message (starting with " ets Jan 8 2013, rst cause:2, boot mode(3,6)", and ending with "~ld"), then display gibberish when the program itself attempted to use Serial.print() or Serial.println().
It appears to be a strange bug related to NodeMCU itself, but the following work-around got Serial.print working for me:

Before using Serial.print() or Serial.println() for the first time in the program (setup() is probably a good place), do Serial.begin(74880);
Step 1 notwithstanding, set the baud rate in Serial Monitor to 115200.

My guess is that somewhere between the Arduino library and CP2102, a register value is being miscalculated (or mangled), and calling Serial.begin(74880) results in setting a register to the value that calling Serial.begin(115200) should have set it to.
Here's the page where I read about the bug: https://github.com/esp8266/Arduino/issues/4005

it is not a bug. the esp ROM bootloader expects a 40 MHz crystal, but most esp8266 modules use 26 MHz crystal. then the resulting baud rate is 74880 instead of 115200 used by the bootloader. but it has nothing to do with the baud rate used by the application/sketch which uses the right frequency setting

This might be related to old ESP-01 firmware. I mean 2018-ish firmware in 01s I bought 3 years ago or so.
I had the same problem –- write_flash works but after the reset garbage is coming in. Try this [installs micropython; change serial device to fit your setup]:
esptool.py -p /dev/tty.usbserial-02022FD3 erase_flash
esptool.py -p /dev/tty.usbserial-02022FD3 write_flash 0xfc000 esp_init_data_default.bin
esptool.py -p /dev/tty.usbserial-02022FD3 write_flash -fs 1MB 0x00000 ../upython-esp8266-1m-20220117-v1.18.bin

Note: the location is flash size dependant – my ESP-01s have 1 MB of flash and you can check it using the esptool.py flash_id command. Use this reference:

0x7c000 for 512 KB, modules like most ESP-01, -03, -07 etc.
0xfc000 for 1 MB, modules like ESP8285, PSF-A85, some ESP-01, -03 etc.
0x1fc000 for 2 MB
0x3fc000 for 4 MB, modules like ESP-12E, NodeMCU devkit 1.0, WeMos D1 mini

The esp_init_data_default.bin file is taken from Espressif SDK, here's my SHA256 of it:
shasum -a 256 esp_init_data_default.bin
81e04e5ec0afef0aad3b52cca2a9bbccc205f4c57334c438e1d81e38ce94b932  esp_init_data_default.bin

But I guess the init file from Github should work OK as well [didn't try though].
https://github.com/espressif/ESP8266_RTOS_SDK