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

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

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

Answers: 2

body:
It seems to be:

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

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

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

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

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

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

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

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


body:
    int k ;
    int q ;
    int f;//pot

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

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

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

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

title: questions about sketch

Answers: 1

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

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

And this is just as wrong for the same reasons:

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


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

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

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

Answers: 3

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

body:
Expanding on my previous comment...

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

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

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

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

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

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

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


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

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

Answers: 1

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

Answers: 2

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

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

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

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

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

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

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

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


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

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

Answers: 2

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

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

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

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

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

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

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


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

<!-- language: c -->

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

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

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

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

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

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

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

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

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

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

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

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

    }

    void loop()
    {

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

    }

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

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

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

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

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

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

    void printWifiData() {

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

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

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

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

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

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

   <!-- language: c -->

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

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

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

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

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

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

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

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

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

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

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

    void loop()
    {

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

    }

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

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

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

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

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

    void printWifiData() {

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

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

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

title: Connecting Arduino with Philips Hue

Answers: 4

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

##UPDATE 3/9/2016

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      delay( 10000 );

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

      delay( 10000 );

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

      delay( 10000 );

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

      delay( 10000 );

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

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

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

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

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

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

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

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

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

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

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

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

      return val;
    }

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

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

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

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

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

      return val;
    }

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

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

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

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

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

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

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

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

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

      return gotHue;
    }

    void printWifiData() {

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

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

A few notes:

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

> You're connected to the networkSSID:

> IP Address: 0.0.0.0

> connected to server

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

> Connection: keep-alive

> Host: 192.168.0.50

> Content-Length: 65

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

>

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

> connected to server

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

> Connection: keep-alive

> Host: 192.168.0.50

> Content-Length: 65

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

>

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

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

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

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

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

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

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

and

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

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

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


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

title: Difference between WiFiClient and HttpClient

Answers: 2

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

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

So the simplest answer to your question

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

is "Use both".

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

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

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

body:
As Majenko Said,

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

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

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

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

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

To send JSON change the header with the below line

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

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


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

title: Photoresistor Switch

Answers: 1

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

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


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

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

Answers: 2

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

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

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

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


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

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

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

Here is a screenshot of the error:

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

Thank you

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

title: Nick Gammon's Hex Converter Error

Answers: 1

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

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

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

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

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

In particular the format is:

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

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

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

---

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

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

---

## Entering DFU mode

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

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

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

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

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

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

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

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

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

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

     sudo apt-get install dfu-programmer

You can obtain the code for the firmware from here:

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

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

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

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

You should see a message like:

    Validating...
    4034 bytes used (32.83%)

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

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

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

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


body:
I was reading this thread:

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

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

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

Could someone please point me in the right direction?

Thanks in advance.

title: Arduino documentation on PCIFR and PINC

Answers: 1

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

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

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

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

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

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

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

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

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


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

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

...and the code:

<!-- language: c -->

    #include <ESP8266WiFi.h>

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

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

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

      // We start by connecting to a WiFi network

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

      WiFi.begin(ssid, password);

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

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

    int value = 0;

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

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

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

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

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

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

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

title: HTTP POST request to IFTTT

Answers: 1

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

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

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

You need to (at least):

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

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

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

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


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

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

title: Arduino command line vs. Arduino builder

Answers: 2

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

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

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

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

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

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


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

title: Arduino controlled light dimmer software

Answers: 1

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


body:
I've bought some nice looking LED potentiometers from Ebay. They look like [this][1].
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?

  [1]: https://www.google.co.uk/search?q=b10k potentiometer&espv=2&biw=1270&bih=701&site=webhp&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjM7-TM26DLAhUBOJoKHT3hAAUQ_AUIBygC#tbm=isch&q=b10k potentiometer linear led&imgrc=XY_E0nFmWPaxzM:

title: How to wire and use a B10K linear LED potentiometer?

Answers: 1

body:
The Taiwan Alpha [spec sheet page 2](http://www.taiwanalpha.com.tw/english2014/p_e_086.htm) 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”.


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

title: How to stop uno from running program when powered on?

Answers: 1

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


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

title: Return value of 0 if value is less than zero

Answers: 3

body:
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()](https://www.arduino.cc/en/Reference/Max) and [constrain()](https://www.arduino.cc/en/Reference/Constrain) reference pages at arduino.cc.

body:
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`.

body:
The Arduino way is to use [constrain][1]

    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.

  [1]: https://www.arduino.cc/en/Reference/Constrain


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

<!-- language: c -->

    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;
                }
            }
        }

title: Configure HC-05

Answers: 1

body:
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)


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

title: Works with gcc, not with Arduino. error: taking address of temporary array

Answers: 3

body:
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);

body:
See [Using array init list as temporary in C++11?](https://stackoverflow.com/questions/15458883/using-array-init-list-as-temporary-in-c11)

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.

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


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

title: Sim800L HTTP post request stop working after a while

Answers: 0


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

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

**Breadboard**

[![Breadboard][1]][1]

**Schematic**

[![Schematic][2]][2]

**Layout**

[![Layout][3]][3]

**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][4], I've used his schematics as a reference (especially on the TX enable pin, which was quite smart, using only 1 pin).

**Version2!**

[![schematic][5]][5]

[![layout][6]][6]

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.

  [1]: https://i.stack.imgur.com/okCNw.png
  [2]: https://i.stack.imgur.com/1iPyH.png
  [3]: https://i.stack.imgur.com/9lvmo.png
  [4]: http://www.gammon.com.au/forum/?id=11428
  [5]: https://i.stack.imgur.com/aFiLp.png
  [6]: https://i.stack.imgur.com/saaRD.png

title: Fritzing PCB design review/questions

Answers: 2

body:
> 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.](http://projectsfromtech.blogspot.co.uk/2013/04/using-reset-pin-as-io-on-attiny8545.html)

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

body:
>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](http://pcbshopper.com/) makes it easy to compare time vs cost across a range of manufacturers.  For small circuits like yours, [OSHpark](https://oshpark.com/) 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](http://makerstudio.cc/index.php?main_page=index&cPath=8) 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](http://www.pcbway.com/).  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.

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

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


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

<!-- language: c -->

    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:

<!-- language: c -->

    #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

title: How do I calibrate an ESC after connecting it to an Arduino?

Answers: 2

body:
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][1], 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.

  [1]: http://m.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/http://m.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/?ALLSTEPS

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

  [1]: https://www.instructables.com/id/Quadcopter-With-Nodemcu-and-BlynkWithout-Flight-Co/


body:
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][1]
  [1]: 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.

title: error while loading libtinfo.so.5 - SOLVED

Answers: 2

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

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


body:
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*

<!-- language: c -->

    #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*

<!-- language: c -->

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

title: Neopixel Ring - How to breathe in a circle motion?

Answers: 1

body:
I don't have any NeoPixels to try it with (yet) however this should do it. Replace the ledTrail function by this:

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

    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:

<!-- language-all: lang-none -->

    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