# Question
Title: Setting 10 RGB Strips Independently from Single Arduino
I want to control 10 different 12V RGB LED strips independently from a single Arduino.

As a clarification - I've setup a bunch of NeoPixels and understand how to wire and control them independently. So now I'm looking to do something similar but rather than set color of individual LED's, I'm looking to set color of LED strips.

I've already done all the research to understand how to use a MOSFET to control a single strip - but that requires 3 PWM outputs on the Arduino board and I don't see any boards that have 3 * 10 = 30 PWM outputs.

Are there existing controllers that can abstract the power conversion and voltage control, so I can just send a color and brightness setting from the Arduino to each strip?

# Answer
> 5 votes
You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLED library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".

Wiring:

Example code:

```
#include <FastLED.h>

#define NUM_LEDS 10
#define DATA_PIN 3
#define CLOCK_PIN 2

CRGB leds[NUM_LEDS];

void setup() {
    FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

int hue = 0;
void loop(){
    for(int i = 0; i < NUM_LEDS; i++) {
        leds[i] = CHSV(hue + i*255/NUM_LEDS , 255, 255);
    }
    FastLED.show();
    delay(20);
    hue += 2;
}

```

# Answer
> 1 votes
You'll need external circuitry to control the actual LEDs.

There is the WS2811 chip which can control 3 channels of 12V LED strips controlled though a single wire and you can daisy chain them controlling each strip individually. The protocol is the exact same as you'll find in individually addressable RGB LEDS. In fact it's the same IC that is embedded in those LEDs.

---
Tags: power, rgb-led, led-strip
---


title: Servo speed in a Toggle Code

text:
# Question
Title: Servo speed in a Toggle Code
I am new to Arduino and am trying to figure out servos. Right now I have a toggle button code for the servos. Although I want to know how to speed them up. Is there a way to do this?

Currently, this is my code:

```
#include <Servo.h>
int button = 5; //button pin, connect to ground to move servo
int press = 0;
Servo servo_7;
Servo servo_8;
Servo servo_9;
Servo servo_10;
boolean toggle = true;

void setup()
{

  pinMode(button, INPUT); //arduino monitor pin state
  servo_7.attach(7); //pin for servo control signal
  servo_8.attach(8);
  servo_9.attach(9);
  servo_10.attach(10);
  digitalWrite(5, HIGH); //enable pullups to make pin high
}

void loop()
{
  press = digitalRead(button);
  if (press == LOW)
  {
    if(toggle)
    {

      servo_7.write(180);
      servo_8.write(180);
      servo_9.write(180);
      servo_10.write(180);
      toggle = !toggle;
    }
    else
    {

      servo_7.write(0);
      servo_8.write(0);
      servo_9.write(0);
      servo_10.write(0);

      toggle = !toggle;
    }
  }
  delay(100);  //delay for debounce
}

```

# Answer
Normal servos have a speed. It's their speed, and you can't change it. You can make it appear slower by moving in small increments, but you can't actually change the speed it moves.

With constant rotation servos the "angle" dictates the rotation speed, but even with those there is nothing you can do to change the relationship between "angle" and rotational speed.

Other than buying a different servo with a different degrees-per-second rating.
> 1 votes

---
Tags: arduino-uno, servo, button, switch
---


title: clear serial buffer not working

text:
# Question
Title: clear serial buffer not working
Also asked in forum.arduino.cc

```
bool receive_command(char answer[]);
void serial_flush(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  for(byte i=0;i<3;i++){
if(receive_command("OK")) Serial.println("OK found");
 serial_flush();
  }
}

void loop() {}

void serial_flush(void) {
  while (Serial.available()) Serial.read();
}

bool receive_command(char answer[]) {
 unsigned long _time = 0;
  const int max_time = 10000;
  bool flag = 0;

Serial.print("in Serial buffer=");
  Serial.println(Serial.available());
  if(Serial.available()){
  Serial.write(Serial.read());
  Serial.println(" left in serial buffer");}

  while (Serial.available() < 2) {
if ((millis() - _time) > max_time) {
      Serial.println("waited too long nothing received");
  return flag;
    }
    }
  do {
    if (Serial.findUntil(answer, '\n')) return flag = 1;
  } while (Serial.available());

return flag;

}

```

via serial monitor with CR+LF line ending I\`m sending this string: abcdefghijklmnopqrstuvwxyzOKabcdefghijklmnopqrstuvwxyz 26chars+OK+26chars+CR+LF=56 chars

Output:

```
in Serial buffer=0
OK found
in Serial buffer=1
b left in serial buffer
in Serial buffer=0
waited too long nothing received

```

after OK is found serial\_flush() is executed but after second run there serial.available() shows there is something in serial buffer. right at that moment it was char 'b' but it also can show char 'd' and 'c' depending how long it will run.

why serial\_flush() is not clearing the buffer?

Thanks.

# Answer
> 2 votes
The processor is somewhat faster than serial input. If you really want to wait for nothing more to arrive you should probably add a short delay (although jsotola's suggestion of looking for a newline is sensible). Something like:

```
void serial_flush(void) {
 while (true)
   {
   delay (20);  // give data a chance to arrive
   if (Serial.available ())
     {
     // we received something, get all of it and discard it
     while (Serial.available ())
       Serial.read ();
     continue;  // stay in the main loop
     }
  else
    break;  // nothing arrived for 20 ms
   }
}

```

# Answer
> 1 votes
the second parameter of findUntil(target, terminator) is of type char\* not char

your `Serial.findUntil(answer, '\n')` doesn't work and you patched it with `do while`.

use `Serial.findUntil(answer, "\n")`

'a' is read by readUntil, then it returns because of wrong parameter. serial\_flush sees no new character. and next you read 'b' from buffer. the sketch runs fast compared to Serial speed. it sees always no or one new character in buffer if the previous was removed

---
Tags: arduino-uno
---


# Question
Title: AT command parsing and listening for incoming SMS Arduino Leonardo SIM800H
I am trying to make a program that receives commands contained in SMS. The commands can be $CMD1 and $CMD2. Of course I need to verify the phone number of the sender by its last 6 digits. Other than this I have to ask and receive rtc clock information from the modem. AT commands format: +CCLK: "YY/MM/DD,HH:MM:SS+TT" (works properly) +CMTI: "SM",N (where N is the index number of the sms in the phone mem) +CMGR: "REC READ","+1234567890","","04/01/01,00:00:00+00" (it reaches only the 15th char and hangs)

My code:

```
const long interval = 1000;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

char esemesemes[3];

byte pointingfinger = 0;

char enabledtime = 0;

char cclkenabl = 0;

char foundchar[6];

byte cmtienabl = 0;

byte witdqt = 0;

byte acceptsms = 0;

byte ocpos = 0;

byte occurence = 0;

byte cmgrenabl = 0;

byte esemindex[3];

char phone1[6] = {'5', '6', '7', '8', '9', '0'};

char phone2[6];

byte enableclock = 1;

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    if (enableclock == 1) {
      Serial1.print("AT+CCLK?\r");
    }
    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    if (enableclock == 1) {
      Serial.println("YEAR: ");
      Serial.print(rtcy1[0]);
      Serial.println(rtcy1[1]);
      Serial.println("MONTH: ");
      Serial.print(rtcm1[0]);
      Serial.println(rtcm1[1]);
      Serial.println("DAY: ");
      Serial.print(rtcd1[0]);
      Serial.println(rtcd1[1]);
      Serial.println("HOUR: ");
      Serial.print(rtch1[0]);
      Serial.println(rtch1[1]);
      Serial.println("MINUTE: ");
      Serial.print(rtcmm1[0]);
      Serial.println(rtcmm1[1]);
      Serial.println("SECOND: ");
      Serial.print(rtcs1[0]);
      Serial.println(rtcs1[1]);
    }
    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
    if (Serial1.available () > 0) {
      foundchar[0] = foundchar[1];
      foundchar[1] = foundchar[2];
      foundchar[2] = foundchar[3];
      foundchar[3] = foundchar[4];
      foundchar[4] = foundchar[5];
      foundchar[5] = Serial1.read();

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K' && foundchar[5] == ':' && enableclock == 1) {
        cclkenabl = 1;
        pointingfinger = 0;
      }

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'T' && foundchar[4] == 'I' && foundchar[5] == ':') {
        cmtienabl = 1;
        pointingfinger = 0;
        enableclock = 0;
      }

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'G' && foundchar[4] == 'R' && foundchar[5] == ':') {
        cmgrenabl = 1;
        pointingfinger = 0;
      }

      if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '1') {
        if (acceptsms == 1) {
          while (true) {
            Serial.println("CMD1");
          }
        }
      }

      if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '2') {
        if (acceptsms == 1) {
          Serial.println("CMD2");
        }
      }

      if (cclkenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        cmgrenabl = 0;
        cclkenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
      }

      if (cmtienabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        cmtienabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        enableclock = 0;
        esemesemes[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        esemesemes[1] = serialdata[searchcharpos + 9];
        esemesemes[2] = '\0';
        esemindex[0] = serialdata[searchcharpos + 12];
        esemindex[1] = '\0';
        Serial.println("CMTI");
        Serial.println(esemesemes[0]);
        Serial.println(esemesemes[1]);
        Serial.println(esemindex[1]);
        if (esemesemes[0] == 'S' && esemesemes[1] == 'M') {
          Serial1.println("AT+CMGF=1");
          Serial.println("AT+CMGF=1");
          delay(100);
          Serial1.println("AT+CMGR=1");
          Serial.println("AT+CMGR=1");
        }
        if (esemesemes[0] != 'S' || esemesemes[1] != 'M') {
          Serial1.println("AT+CMGD=4,1");
          Serial.println("Deleted");
        }
      }

      if (cmgrenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read(); //                       I THINK HERE WE HAVE SOME PROBLEM
            Serial.println("Searching");
            Serial.println(serialdata[pointingfinger]);
            Serial.println(pointingfinger);
            Serial.print(serialdata[searchcharpos]);
            Serial.print(serialdata[searchcharpos + 1]);
            Serial.print(serialdata[searchcharpos + 2]);
            Serial.print(serialdata[searchcharpos + 3]);
            Serial.print(serialdata[searchcharpos + 4]);
            Serial.print(serialdata[searchcharpos + 5]);
            Serial.print(serialdata[searchcharpos + 6]);
            Serial.print(serialdata[searchcharpos + 7]);
            Serial.print(serialdata[searchcharpos + 8]);
            Serial.print(serialdata[searchcharpos + 9]);
            Serial.print(serialdata[searchcharpos + 10]);
            Serial.print(serialdata[searchcharpos + 11]);
            Serial.print(serialdata[searchcharpos + 12]);
            Serial.print(serialdata[searchcharpos + 13]);
            Serial.print(serialdata[searchcharpos + 14]);
            Serial.print(serialdata[searchcharpos + 15]);
            Serial.print(serialdata[searchcharpos + 16]);
            Serial.print(serialdata[searchcharpos + 17]);
            Serial.print(serialdata[searchcharpos + 18]);
            Serial.print(serialdata[searchcharpos + 19]);
            Serial.print(serialdata[searchcharpos + 20]);
            Serial.print(serialdata[searchcharpos + 21]);
            Serial.print(serialdata[searchcharpos + 22]);
            Serial.print(serialdata[searchcharpos + 23]);
            Serial.print(serialdata[searchcharpos + 24]);
            Serial.print(serialdata[searchcharpos + 25]);
            Serial.print(serialdata[searchcharpos + 26]);
            Serial.print(serialdata[searchcharpos + 27]);
            Serial.print(serialdata[searchcharpos + 28]);
            Serial.print(serialdata[searchcharpos + 29]);
            Serial.print(serialdata[searchcharpos + 30]);
          }
        }
        //pointingfinger = 0;
        enabledtime = 1;
        occurence = 0;
        ocpos = 0;
        Serial.println("mode1");
        while (occurence < 7) {
          Serial.println("mode2");
          if (serialdata[ocpos] == '\"') {
            Serial.println("mode3");
            occurence++;
            Serial.println(occurence);
          }
          Serial.println("mode4");
          ocpos++;
          Serial.println(ocpos);
        }
        witdqt = ocpos;
        Serial.println("PHONE1: ");
        Serial.print(serialdata[witdqt - 1]);
        Serial.print(serialdata[witdqt - 2]);
        Serial.print(serialdata[witdqt - 3]);
        Serial.print(serialdata[witdqt - 4]);
        Serial.print(serialdata[witdqt - 5]);
        Serial.print(serialdata[witdqt - 6]);
        Serial.println("");
      }
      acceptsms = 0;

      if (serialdata[witdqt - 1] == phone1[5] && serialdata[witdqt - 2] == phone1[4] && serialdata[witdqt - 3] == phone1[3] && serialdata[witdqt - 4] == phone1[2] && serialdata[witdqt - 5] == phone1[1] && serialdata[witdqt - 6] == phone1[0])
      {
        acceptsms = 1;
        Serial.println("Accepted");
      }

      if (serialdata[witdqt - 1] == phone2[5] && serialdata[witdqt - 2] == phone2[4] && serialdata[witdqt - 3] == phone2[3] && serialdata[witdqt - 4] == phone2[2] && serialdata[witdqt - 5] == phone2[1] && serialdata[witdqt - 6] == phone2[0])
      {
        acceptsms = 1;
        Serial.println("Accepted");
      }

      /*Serial.println("");
        Serial.print(foundchar[0]);
        Serial.print(foundchar[1]);
        Serial.print(foundchar[2]);
        Serial.print(foundchar[3]);
        Serial.print(foundchar[4]);
        Serial.print(foundchar[5]);
        Serial.println("");*/

    }
  }
}

```

This is the Serial Monitor:

# Answer
> 2 votes
You should throw away all your own code and read the serial data in a line at a time. Only once a complete line has been received should you then examine it to see what you have.

For example, here's something I just threw together based around a snippet I posted here:

```
int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
            buffer[pos++] = readch;
            buffer[pos] = 0;
        }
        break;
    }
  }
  return 0;
}

// ... later, in your loop:

if (Serial1.available()) {
    // Read one character and send it to the readline function.
    if (readline(Serial1.read(), serialdata, 512)) { // do you really need 512 bytes of buffer?!?!

        // readline() told us we got a valid string. Let's
        // parse it.

        // If the string starts with '+CCLK: "'
        if (strncmp(serialdata, "+CCLK: \"", 8) == 0) {
            // Slice it up by the different delimiters
            // starting at the 9th character:
            char *cyear = strtok(serialdata + 8, "/");
            char *cmonth = strtok(NULL, "/");
            char *cday = strtok(NULL, ",");
            char *chour = strtok(NULL, ":");
            char *cmin = strtok(NULL, ":");
            char *csec = strtok(NULL, "+");

            // Check the last slicing worked
            if (sec != NULL) { // It parsed OK
                // And convert each slice to a number.
                year = atoi(cyear);
                month = atoi(cmonth);
                day = atoi(cday);
                hour = atoi(chour);
                minute = atoi(cmin);
                sec = atoi(csec);

                // Show the time.
                Serial.print(F("The time is "));
                Serial.print(minute);
                Serial.print(F(" minutes past "));
                Serial.println(hour);
            }
        }
    }

    // Do similar operations for the different possible messages
    // you may get.

}

```

---
Tags: serial
---


title: Arduino Uno with Adafruit CC3000

text:
# Question
Title: Arduino Uno with Adafruit CC3000
I am using Arduino Uno with Adafruit CC3000 wifi shield to connect to the internet and get data for Arduino. Everything works fine but I can't figure out how to use **HttpClient** library. The code is:

```
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
#include <HttpClient.h>

#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "ssid"
#define WLAN_PASS       "pwd"
#define WLAN_SECURITY   WLAN_SEC_WPA2

void setConnection(){

     Serial.println("Initializing...");
     if (!cc3000.begin())
     {
       Serial.println("Couldn't begin()! Check your wiring?");
       while(1);
     }
     Serial.print("Attempting to connect to ");
     Serial.println(WLAN_SSID);
     if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
       Serial.println("Failed!");
       while(1);
     }
     Serial.println("Connected!");
     Serial.println(F("Request DHCP"));
     while (!cc3000.checkDHCP())
      {
          delay(100);
       }
     Serial.println(F("DHCP success!!"));
 }

void dweet(){

  int ctr=0;
  char buff[100];
  int x=0;
  const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

  Serial.println(F("Initializing dweet client ..."));
  HttpClient client;
  client.get(host);
  Serial.println(F("Client Connected !"));

  while (client.available()) {
    char c = client.read();
    Serial.write(c);
    delay(100);
  }

void setup(){

     Serial.begin(115200);
     while(!Serial);
     Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
     setConnection();

}

void loop(){
dweet();
}

```

If all worked fine then I should have got a json string which is:

```
{"this":"succeeded","by":"getting","the":"dweets","with":[{"thing":"dunebot","created":"2018-05-12T13:27:56.106Z","content":{"0001":""}}]}

```

When I run the code, Arduino connects to the wifi network but afterwards when I observe the Serial monitor all I get are garbage values.

I need a way to read the key **0001** from the json string. Any help would be appreciated.Thanks.

# Answer
> 1 votes
The `HttpClient` object must be instantiated with a `Client` object which will handle the underlying connection. Source:

> Requires a networking hardware and a library that provides transport specific Client instance, such as:

Refer to the following code:

In the above example, it is done like

```
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);

```

Which means that for your code, you might want to pull out `client` as global object and instantiate it as:

```
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
/* Create new Adafruit_CC3000_Client object */
Adafruit_CC3000_Client cc3000_client;
/* Feed this into the client */
HttpClient client (cc3000_client, "dweet.io", 80);

```

You should also use the example code to see how to print the response after executing `client.get()`:

```
  // read the status code and body of the response
  statusCode = client.responseStatusCode();
  response = client.responseBody();
  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

```

The example code is pretty much example what you want, you just have to give it a `Adafruit_CC3000_Client` as the `Client`.

Full code:

```
#include <Arduino.h>
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
#include <HttpClient.h>

#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
/* Create new Adafruit_CC3000_Client object */
Adafruit_CC3000_Client cc3000_client;
/* Feed this into the client */
HttpClient client (cc3000_client, "dweet.io", 80);

#define WLAN_SSID       "ssid"
#define WLAN_PASS       "pwd"
#define WLAN_SECURITY   WLAN_SEC_WPA2

int statusCode = 0;
String response;

void setConnection(){

    Serial.println("Initializing...");
    if (!cc3000.begin())
    {
        Serial.println("Couldn't begin()! Check your wiring?");
        while(1);
    }
    Serial.print("Attempting to connect to ");
    Serial.println(WLAN_SSID);
    if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println("Failed!");
        while(1);
    }
    Serial.println("Connected!");
    Serial.println(F("Request DHCP"));
    while (!cc3000.checkDHCP())
    {
        delay(100);
    }
    Serial.println(F("DHCP success!!"));
}

void dweet(){

    int ctr=0;
    char buff[100];
    int x=0;
    const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

    Serial.println(F("Initializing dweet client ..."));

    client.get(host);
    Serial.println(F("Client Connected !"));

    // read the status code and body of the response
    statusCode = client.responseStatusCode();
    response = client.responseBody();
    Serial.print("Status code: ");
    Serial.println(statusCode);
    Serial.print("Response: ");
    Serial.println(response);

    /*
    Typical response is:
    {"this":"succeeded",
    "by":"getting",
    "the":"dweets",
    "with":[{"thing":"my-thing-name",
      "created":"2016-02-16T05:10:36.589Z",
      "content":{"sensorValue":456}}]}
    You want "content": numberValue
    */
    // now parse the response looking for "content":
    int labelStart = response.indexOf("content\":");
    // find the first { after "content":
    int contentStart = response.indexOf("{", labelStart);
    // find the following } and get what's between the braces:
    int contentEnd = response.indexOf("}", labelStart);
    String content = response.substring(contentStart + 1, contentEnd);
    Serial.println(content);

    //There was a missing brace here. Was the code cut off?!
}

void setup(){
    Serial.begin(115200);
    while(!Serial);
    Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
    setConnection();
}

void loop() {
    dweet();
}

```

---
Tags: arduino-uno, adafruit, http, json
---


# Question
Title: Using a 3V latching relay to power up ESP8266
I'm trying to use a 2-Coil Latching Relay like TXS2SA-L2-3V for powering up a ESP8266. My idea is to activate the relay by setting the first coil to high and deactivate the coil by setting the second coil to high. In my circuit i will set the second coil to high at the end of the code by the esp8266. I need the latching (holding the power) function of it. Because when somebody activtes the Deep Sleep function to early, I have no electricity to power the esp8266.

My question is:

What kind of circuit I must use? I have no idea where I can start.

I have a regulator that can be enabled via de EN signal.

Thanks in advance!

# Answer
> 1 votes
You use a latching relay of this form in the exact same way as a normal relay - it's just there's two of them.

One coil you want to control with a button (power on) and the other with a transistor (and possibly an "off" button as well).

simulate this circuit – Schematic created using CircuitLab

Press ON to latch the relay into the ON position (NO -\> COM). Activate M1 or press OFF to latch the relay into the OFF position (NC -\> COM).

---
Tags: esp8266, power
---


# Question
Title: Can tx and rx pins on the uno be used like regular digital pins?
The uno has digital pins marked 0-13.

0 is marked as rx and 1 is marked as tx. Can these two pins be used as regular digital pins if i am short of digital pins?

# Answer
> 11 votes
Yes you can perfectly use these 2 pins as long as your program does not use `Serial`.

EDIT: Serial data over USB goes through copper traces connected to the rx and tx pins, connecting them to the USB to serial converter chip.

# Answer
> 3 votes
Also you will probably want to ensure these wires are not connected when programming the Arduino. Otherwise you may have problems.

# Answer
> -1 votes
You can, but it will disable the serial port.

---
Tags: arduino-uno
---


# Question
Title: PWM should be applied to ENA or IN1/IN2 for L298N board for speed control
I am new to the Arduino stuff and I am using L298N to drive two DC motors. When I searched online for sample code, I noticed that there are two types of design.

One type uses analogWrite(pin, pwmOutput) to control PWM on IN1/IN2 pin to adjust speed, and the other uses digitalWrite(pin, HIGH/LOW) to control IN1/IN2 but use analogWrite(enA, pwmOutput) to control speed.

I guess probably both can work, but I just feel it is not right to apply PWM on the enable pin. Any suggestion from the experts?

One more thing, many people say L298N is obsolete. Would anyone please recommend a replacement motor drive module?

# Answer
I'd use `PWM` on `EN` input. Motor will be driven in `HIGH` and left floating in `LOW`. The other method means it'll be shorted (= full on brake).

`L298N` is based on bipolar transistors. That means relatively big voltage drop between drivers Emitter and Collector (about `2V` on each transistor), so there are big power losses (= heat).

Maybe something like `LMD18200` could be used as unipolar replacement.
> 0 votes

---
Tags: pwm, l298n
---


# Question
Title: How to digital read and send the data through serial to PC with speed around 2 MHz?
I would like to read analog data with frequency sampling around 2 MHz and send it to PC to be processed with python for digital oscilloscope. I use Arduino Nano. I have found ADC (AD9057, PDF) that can handle up to 40 MSPS into 8 bits parallel, but I still face some problems

1. How could I read digital pin data quickly around 2-4 MHz? I read that it is possible using direct port manipulation.
2. How could I send the data to PC with that sampling rate? I know that the maximum baud rate of arduino is around 2.000.000 or let say 2 MegaBytes/s, so for 2 MHz sampling, i could only send one character per micro second, could it be more faster?

Thank you

# Answer
In short? You can't.

To have a 2MHz transmission you need 2\*Nbit MHz of serial clock to send it to the PC, where Nbit is the number of bits per sample. Since the minimum is 8, englecting the synchronization or additional bits the serial clock has to be at least 16MHz. Which is the system clock of the nano. So no way.

Now, with the alternatives. First question: what is your ADC's interface? I found the LTC2204. It is a parallel ADC, so you need something to convert it to anything readable by the PC.

I'm not sure about the feasibility of this, but a nano is not enough. I'd use an STM32 (because I have their Nucleo boards, but you can search for other 32-bit boards) and a high speed serial interface. Since even SPI can be slow, maybe ethernet needs to be used. I was not able to search for boards with native ethernet interface; anyway the STM32F4 microcontrollers should (see this article) have an ethernet interface and you will "only" need the PHY. I think that this is the only applicable way to follow..
> 1 votes

---
Tags: serial, programming, digital
---


# Question
Title: how to send data to 15 meters with KY-005
I am using the LED KY-005 as emitter and the KY-022 as a receiver, according to their specifications they reach 18 meters. I have performed the tests and it supports more than ten meters, however after the 6 meters the data is not received correctly. For example, I send 0xa90 but any other value except the desired one arrives at the receiver. Here I leave the connection diagram:

This is the code that I use to send data:

```
#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     delay(40);
   }
}

```

# Answer
> 2 votes
In the emitter breakout board there is only a LED, nothing more. Comments in the linked page of the supplier states, that the 5V pin of it is not connected to anything. This means you are driving the LED directly from the Arduinos pin, which cannot provide more than 40mA. The supplier states a forward current from 30 to 60mA. You can use a small MOSFET in combination with a resistor, that limits the current to maybe 55mA, to drive the LED indirectly.

With this you won't fry the pins hardware and can provide more current, which means the LED can shine brighter. If you can find out, what LED is actually used for this board, you can refer directly to its datasheet. I couldn't find a part number at the site.

---
Tags: arduino-uno, infrared
---


# Question
Title: How to change the value within a variable using math?
I'm up to Lesson 11 in the TopTechBoy tutorial: https://www.youtube.com/watch?v=afurKLOqqSg

Lesson 11 : http://www.toptechboy.com/arduino/lesson-11-arduino-circuit-to-dim-led-with-potentiometer/

I can use the analogRead() to fill a variable with a value and Serial.printld it out, but I want to be able to increase that integer by **×** 4.887585533

```
int pinV; // This empty variable will be filled with an integer value between 0 and 1023.
int receiverPin=0; // This is the RX pin, a ‘receiver’ that connects to the USB to Serial interface.
int ResultsPerSec=500; // The Arduino reads and prints out a result every half second.
float printingValue; // Another empty variable that is given the pinV value to multiply and print.
void setup() {
  Serial.begin(9600);
  pinMode(receiverPin,INPUT);
}

void loop() {
  pinV=analogRead(receiverPin);
  // Each Volt has a value of 204.6 (4.88 mV per integer of the 1023 available)
  printingValue = (pinV *4.887585533);
  // 5,000 mV divided by 1023 possible values = is 4.887585533 mV per integer
  // The Arduino can count from 0 to 5 Volts in 4.887585533 mV increments.
  // 1,000 mV divided by 4.887585533 mV = 204.599999989 integers out of the 1023 available equal 1V
  // Each integer of the 1023 possible values that analogRead() outputs can be increased by 4.887585533
  // This shows the real Voltage in millivolts (mV).
  Serial.println(printingValue);
  delay(ResultsPerSec);
}

```

This is actually acceptable as far as the IDE is concerned, but it doesn't work as intended. I'm getting outputs in the thousands, when it should be printing 0 in the Serial monitor. How do I do this properly?

# Answer
> -1 votes
I just got a reply from someone from one of the threads on https://8ch.net/tech/catalog.html

It turns out that the Digital pins (0,1,2,3,4,5,6,7,8,9,10,11,12,13) are not capable of reading Analog voltages. Pins A0 to A5 need to be used instead. Also, if not voltage is supplied, the Arduino will print random numbers in the Serial Monitor.

---
Tags: arduino-uno, voltage-level, sketch, float, mathematics
---


# Question
Title: My code isn't adjusting the speed of one of the motors and i'm not sure why
I'm trying to change the speed of motors depending on the amount of light hitting the LDRs. Here i'm trying to make it so that if the LDR has a high value than another, then the motor associated with that LDR slows down so it turns towards the light.

```
const int motorDirectionA = 9;
const int motorEnableA = 10;
const int motorDirectionB = 5;
const int motorEnableB = 6;

const int leftLDR = A0;
const int rightLDR = A1;

int motorSpeedA = 250;
int motorSpeedB = 250;

void setup()
{
  Serial.begin(9600);
  pinMode(motorDirectionA,OUTPUT);
  pinMode(motorEnableA, OUTPUT);
  pinMode(motorDirectionB,OUTPUT);
  pinMode(motorEnableB, OUTPUT);

  pinMode(leftLDR, INPUT);
  pinMode(rightLDR, INPUT);

}

void loop()
{
  int ldrReadL = analogRead(leftLDR);
  int ldrReadR = analogRead(rightLDR);
  int leftLDRread = ldrReadL;
  int rightLDRread = ldrReadR;

  digitalWrite(motorDirectionA, LOW);
  analogWrite(motorEnableA, motorSpeedA);
  digitalWrite(motorDirectionB, HIGH);
  analogWrite(motorEnableB, motorSpeedB);

  Serial.print("Left LDR reading: ");
  Serial.println(ldrReadL);
  Serial.print("Right LDR reading: ");
  Serial.println(ldrReadR);

  if (leftLDRread > rightLDRread)
  {
    motorSpeedA = 80;
    motorSpeedB = 210;
  }
     else
     {
        motorSpeedA = 210;
        motorSpeedB = 210;
     }

  if (leftLDRread < rightLDRread)
  {
    motorSpeedB = 80;
    motorSpeedA = 210;
  }
      else
     {
       motorSpeedA = 210;
       motorSpeedB = 210;
     }
}

```

@Maximillian Gerhardt If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.

If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

# Answer
> 1 votes
> If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.
>
> If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

In code you would express this as

```
void loop()
{
    int ldrReadL = analogRead(leftLDR);
    int ldrReadR = analogRead(rightLDR);
    int leftLDRread = ldrReadL;
    int rightLDRread = ldrReadR;

    digitalWrite(motorDirectionA, LOW);
    analogWrite(motorEnableA, motorSpeedA);
    digitalWrite(motorDirectionB, HIGH);
    analogWrite(motorEnableB, motorSpeedB);

    Serial.print("Left LDR reading: ");
    Serial.println(ldrReadL);
    Serial.print("Right LDR reading: ");
    Serial.println(ldrReadR);

    //assuming motorSpeedA is the left motor
    // left > right
    if (leftLDRread > rightLDRread) {
        motorSpeedA = 80;
        motorSpeedB = 210;
    } else if( leftLDRread < rightLDRread ) {
        //left < right
        motorSpeedA = 210;
        motorSpeedB = 80;
    } else {
        // left == right
        motorSpeedA = 210;
        motorSpeedB = 210;
    }
}

```

Also note that this is a quite primitive form of a PID controller. You want to respond to environmental influences in some kind of way, for which a PID is for.

You might find these videos interesting:

Edit: The code was fixed, a wrong variable was used (the pin number vs the read value)

---
Tags: arduino-uno, motor
---


title: Connect ESP-01 to USB Uart

text:
# Question
Title: Connect ESP-01 to USB Uart
for programming my ESP-01 chip I bought an "USB Uart", but it looks different to all the ones in all tutorials. I don't know how to connect the uart to the esp. The uart i bought has following pins: 3V3, DTR, RXI, TX0, GND, +5V. The ESP01 has the known layout (http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family#esp-01).

Once connected: Do I need an external power source, or do i just connect the usb uart to my computer?

Many thanks

# Answer
Just to give an anwser for users struggling with the same problem I will sum up what helped me.

To connect the UART to the ESP the `Beginner's Guide to the ESP8266` from @tttapa was very helpful. Another helpful link was this one: https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/

So in my case I just needed the GND, 3V3, RXI and TX0 pins from my UART.

I needed no external powersupply for the flashing process and some simple examples.
> 1 votes

# Answer
You can program the ESP-01 whith described method in this page:

https://zinventor.wordpress.com/primeros-pasos-con-esp8266/

Its works fine!
> 0 votes

---
Tags: esp8266, usb, uart
---


# Question
Title: Working with multiplexers for constant voltage output
I'm working on creating a circuit where I'm trying to have the ability to switch multiple strands of LED rope on and off at a time using an Arduino and a multiplexer.

With my current configuration, I have the a circuit and a sketch that will cycle through the various LED rope strands, turning them on and off.

What I'm not sure how to do is modify my sketch / circuit so that I can turn ALL of the rope strands on and off, as well as individually.

Below is my current Arduino sketch:

```
//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);

}

void loop(){

  //Loop through and read all 16 values
  //Reports back Value at channel 6 is: 346
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

```

I'm using two multiplexers to control multiple rope strands. Here's roughly what that looks like:

I'm still a bit new to electronics prototyping (coming from software development); so I'm not sure if what I want to do is possible with a multiplexer

Happy to start offer a bounty to a helpful answer.

Thank you

# Answer
Even I am new to this and I also find it a bit challenging with the available setup and desired output. Though it seems tough, I want you to just try out this code (it is a little modification to the one posted by you) and check whether it matches the expected result.

```
    //Mux control pins
#define s0 8;
#define s1 9;
#define s2 10;
#define s3 11;

//Mux in "SIG" pin
#define SIG_pin 3;

#define testValue 255;  //maximum value for analogWrite() function

void setup()
{
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop()
{
  //Loop through and read all 16 values
  for(int i = 0; i < 16 ; i ++)
  {
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel)
{
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]=
  {
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++)
  {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  for(int i_testValue = 0; i_testValue < testValue; i_testValue++)
  {
    analogWrite(i_testValue, SIG_pin);      //incresing intensity slowly with delay of 100ms
    delay(100);
  }

  //return the value
  return 0;
}

```
> 1 votes

---
Tags: arduino-uno, led, code-review, multiplexer
---


title: Serial Monitor stops printing data

text:
# Question
Title: Serial Monitor stops printing data
I have an IMU sensor (MPU 6050) connected with arduino UNO. Pin maps are as follows:

MPU6050 --\> Arduino
Vcc --\> Vcc
Gnd --\> Gnd
SCL --\> A5
SDA --\> A4

(Not using any pull up resistors)

I am using jeff rowberg's MPU6050 library to get data from sensor. To test the sensor, I am using the raw value example sketch from the library. I am getting readings for both the accelerometer and the gyroscopes.

The problem is after some time the serial monitor just stops printing data. I have tried to figure it out but have not succeeded in solving the problem. It could be due to one of two reasons:

1. The MPU6050 stops giving sensor values
2. There is a problem with the serial monitor

As far as I have figured, the sensor is giving values because when I restart the serial monitor, the data starts to print again on the serial monitor and stops printing after same duration of time as it did before restarting the monitor.

I have tried the serial monitor of the arduino IDE and hyperterminal. In both cases the data stops printing after some time.

Any idea, what causes the serial monitor to stop printing data? Is it the sensor or the serial monitor?

Help would be greatly appreciated. Thanks in advance.

# Answer
> 2 votes
I had exactly same situation.
I initially started to inspect on FIFO overflow of MPU6050, then experimented setting different clock speed for I2C communication, tried to tweak with pullup resistors as recommended. Finally, here is the solution which worked for me. Basically, I just disconnected INT pin from MPU6050.

Now the schema is:
(MPU) -\> (Arduino)

AD0 -\> GND
SDA -\> A4 (No pullup)
SCL -\> A5 (No pullup)
GND -\> GND
VCC -\> 3.3V

I used this code as an example:
https://github.com/jarzebski/Arduino-MPU6050/blob/master/MPU6050\_gyro\_pitch\_roll\_yaw/MPU6050\_gyro\_pitch\_roll\_yaw.ino

from this library:
https://github.com/jarzebski/Arduino-MPU6050

---
Tags: serial, sensors
---


# Question
Title: Can I simulate a clock without an RTC connected?
I want to program for a timer that works as set timer such as in an oven where user can set their own time. One of the way I know is using an IC(RTC) for the timer. However, I don't have the IC yet only the coding and Arduino.

Is it possible to simulate the Arduino code without having the RTC? Or is there any electrical component that I can use to replace the IC for the time being? Thank you for your help and comment.I really appreciate that.

# Answer
TimeLib.h has a virtual clock that can be updated and corrected from multiple sources, including an RTC chip or an NTP server on the internet (assuming an internet connection).

It doesn't *need* that clock source, though, but it will drift with time. Once you have set the clock correctly it will keep close to the right time (assuming no reset or power loss of the Arduino). Not perfect (because the Arduino's main clock isn't perfect) but close enough for many simple applications.
> 2 votes

# Answer
There are programs to simulate Arduino code, but they are very limited. To really simulate the circuit the program would have to also know about the IC you are using. You didn't told us what IC this is, so we can only speculate, that it might not be something, that these programs know (though you can try it). And sometimes Arduino Simulators have problems with simulating time sensitive code. If you want to try, just google for Arduino Simulator and check out the possibilities. I cannot suggest one, since I didn't use one until now.

At this point it might be the better option to write time-keeping code using the `millis()` function, which returns the number of milliseconds since the Arduino started. Save a timestamp from when you started and compare the difference between `millis()` and your timestamp to the wanted bake time.

You can pack this code in extra functions, that can later be replaced by code managing the "timer IC". With dividing your code this way you can write the rest of the logic without bothering about the timing part (after writing the `millis()` part as a "dummy").

For an oven timer the accuracy of the Arduinos clock should be ok, since it doesn't really matter, if it is a few seconds off. And for testing and writing the first code version it is also sufficient.

---

If the IC you are referring to is a RTC (Real Time Clock) module, the code for it should be pretty simple to write. There are libraries for the most common RTCs. You might want to try the Arduino Time library.
> 0 votes

---
Tags: arduino-uno, programming, timers, electronics
---


# Question
Title: attiny85: ISR not triggering for PCINT2?
I am using an attiny85 to read the fan speed reported by a pair of 4-wire fans. I had planned to attach the TACH output from the fans to pins 1 and 2, but I ran into a problem: I was able to handle interrupts on pin 1 without a problem, but I can't get the ISR to trigger for changes on pin 2. Code demonstrating the problem looks like this:

```
#define PIN_LED 0
#define PIN_TACH2 2

void setup() {
  cli();
  pinMode(PIN_TACH2, INPUT_PULLUP);
  pinMode(PIN_LED, OUTPUT);

  GIMSK |= _BV(PCIE);
  PCMSK |= _BV(digitalPinToPCMSKbit(PIN_TACH2));
  sei();
}

void loop() {
  digitalWrite(PIN_LED, 1);
  delay(2000);
}

ISR(PCINT0_vect) {
  byte tach2;

  tach2 = (PINB & _BV(PIN_TACH2));

  if (! tach2) {
    digitalWrite(PIN_LED, 0);
  }
}

```

If I replace the definitions of `PIN_TACH2` and `PIN_TACH2_INT` with pin 1, such as...

```
#define PIN_TACH2 1
#define PIN_TACH2_INT PCINT1

```

...it works just fine (interrupts also works for pins 0 and 3).

Why can't I handle pin change interrupts for pin 2?

**for @chrisl**

This is just testing code. The LED remains on until the ISR fires, at which point it will go out for up to 2 seconds. With interrupts attached to pins 1 or 3, it works as expected: a falling edge on the pin causes the LED to go off.

On pin 2, the ISR never triggers.

# Answer
So, it turns out that it was a really stupid problem and entirely my fault, but I'm going to leave this question here in the hopes that it will prevent someone else from running into the same issue.

The answer is...

**DISCONNECT THE PROGRAMMER BEFORE TESTING YOUR SKETCH**

That's it. With the programmer disconnected, it all behaves as expected.
> 2 votes

---
Tags: interrupt, attiny, isr
---


title: FastLed LED Strip Output Checksum

text:
# Question
Title: FastLed LED Strip Output Checksum
I am wondering if anyone has ever connected the output of their LED strip back to the Arduino to read and make sure the strip is functioning correctly, kinda like checksum functionality.

I am using the FastLed library and it doesn't appear that this has been done.

The reason why I want to do this is because when an LED breaks on the strip, it causes all of the following LEDs to flicker wildly. I need to be able to shut the LED strip off immediately if it starts flickering because my device is being used as a visual therapy aid in a school.

I am using an Arduino Due with WS2812B LED strip.

# Answer
> 1 votes
Look at timing on sheet 4 of the datasheet, and the times on sheet 3

A Low bit is 400 +/- 150nS wide Low followed by a 800 +/- 150nS wide High

A High bit is 850 +/- 150nS wide High follow by a 450nS wide Low.

To do what you suggest with a checksum, you'd have to send the checksum (minimum of 3 bytes to fake the data for an extra WS2812B for example) first, and see if the 24 bits were received correctly while at the same time the last 3 bytes were being sent out.

A Due might be fast enough to do that. I don't think a 16 MHz Arduino could.

Checking power level is not really feasible, as many strips get power attached to the beginning, middle, and end of a strip to ensure uniform brightness and to keep the strip's power traces from overheating from excess current flow.

# Answer
> 0 votes
I don't think LED strips support this feature, however, probably there is a voltage reduction depending on how many LEDs are on. So you could check the voltage at the end of the strip, based on the LEDs which are on (assuming you store this) and compare the values.

---
Tags: arduino-due, led-strip, ws2812
---


# Question
Title: Can I switch from Serial to SoftwareSerial at runtime with the same baud?
I'm trying to use a GPS and the Adafruit thermal printer module with an Arduino Nano in the same project (both use baud 9600) and was wondering if I could do something like in the code below? Basically, in the example I made, I'm getting the time from the GPS and when it's on the minute, it will call the `printTime()` method.

What I'm wondering is if it's okay to do what I did in my `disableGPS`, `enablePrinter` methods by ending the serial connection for GPS and starting it for my printer? I feel like this should work, but I don't fully understand serial connections.

If this doesn't work, is there an alternative I could do? I never need to read from GPS and write to the printer at the same time in code.

```
#include <Adafruit_Thermal.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define PrinterTXPin 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define PrinterRXPin 5 // Arduino receive   GREEN WIRE   labeled TX on printer

static const uint32_t baud = 9600;
//Printer
SoftwareSerial PrinterSerial(PrinterRXPin, PrinterTXPin);
Adafruit_Thermal printer(&PrinterSerial);
//we only want to print on the minute
boolean havePrinted = false;

//GPS
TinyGPSPlus gps;
TinyGPSDate lastDate;

void setup() {
  enableGPS();
}

void loop()
{
  if(gps.time.isValid() && checkDate(gps.time)){
    printTime(gps.time);
  }
}

boolean checkDate(TinyGPSTime theTime)
{
 if(theTime.second() == 0 && !havePrinted)
 {
    havePrinted = true;
    return true;
 }
 if(theTime.second() == 1){
    havePrinted = false;
 }
}

void printTime(TinyGPSTime theTime)
{
  //Disable since we can only have 1 serial connection per baud
  disableGPS();
  enablePrinter();

  printer.doubleHeightOn();
  printer.println(theTime.hour() + ":" + theTime.minute());
  printer.feed(1);

  disablePrinter();
  enableGPS();
}

void enablePrinter()
{

  PrinterSerial.begin();
  printer.begin();
  printer.wake();
}

void disablePrinter()
{
  printer.sleep();
  PrinterSerial.end();
}

void disableGPS()
{
  Serial.end();
}

void enableGPS()
{
  Serial.begin(baud);
}

```

# Answer
> 4 votes
I think you are missing what the baud rate is. It is the speed at which the data is transmitted. So the fact that your two devices are the same is not an issue. It looks like from the code that your gps is connected to the hardware serial(pins 0,1 on uno) and the printer is on a software serial( pins 5,6) If this is the case, there is no reason to turn off either of them, they can both work. In the case of using multiple SOFTWARE serial connections, only one can be 'listening' at any time, so you must switch between them. This is not the case in your code, as there is only one software serial connection.

---
Tags: serial, arduino-nano, gps
---


title: Unstable ESP8266 - flickering lights

text:
# Question
Title: Unstable ESP8266 - flickering lights
A while ago I have bought NodeMCU board along with few sensors to play with. I have coded everything, and, when powered via USB, works like a charm. Problem begins, when I try to use my contraption as a standalone system. It works for few minutes, then it starts giving me false readings from the sensors (like, luminosity of few thousands in a dark room).

I am powering the system with (pics at the bottom of the post) AC-DC step down module, 230v -\> 5v (1A of current), which then I am stepping down with DC-DC step down module, 5v -\> 3v (800mA of current). Using only these two modules, I power NodeMCU and all of my sensors - currently luminosity, temp&humid, motion, SSR (I had led matrix too. I thought that maybe it drags too much current, but no luck there - after disconnecting it I have same problems).

**My main indicator that something is not right, is SSR module**. It has a built-in diode of the same size that NodeMCU has. It lights immediately as I start the system, and it (it's diode) flickers (it's intensity changes). It does not flicker, when I connect everything through USB.

I have also tried to put 50uF capacitor into the wiring, but no luck either, system is still unstable. **What am I doing wrong? Why does the light flickers? Is 1A/800mA not enough power for my system?**

**Edit**: I know what is the cause. I just do not know how to fix it. I just kept my multimeter on for 10mins for both of the step down modules. 5V -\> 3V step down (2nd item in the pics below) is initially giving me 800mA, but then gradually losing current (right now it's at 350mA after just few minutes of work). Is there anything I can do here? Or just throw the thing away and look for some other power supply? It's a standard AMS 1117 with some capacitors on it.

Below are the pictures, of my step-down modules and SSR module:

# Answer
The VIN pin on the NodeMCU board can take the 5V directly. Had no problem with that way until now.

What is strange to me is that the current from your 5V to 3V regulator is degrading. The regulator on the board it's self is basically the same (maybe another manufacturer). What may be the cause is that the regulator is overheating and somehow that the effects the output current and/or voltage.

What you can also try is a LM2596 step down regulator. Those are pretty cheap as well and have a good output capacitance. They can deliver up to 3A at down to ~1.3V. Input voltage is somewhere between 40V and your output voltage plus 1 or 2 volts to let it properly regulate. You can use that module to transform your 5V down to 3.3V easily - i've done it so often with it, i lost count.
> 1 votes

# Answer
Take care how you power the nodemcu. the VU pin is 5v from USB and i am not sure it can be powered with this pin. I do think it is safe to power your device with the 3.3v pins.

does that solid state relay want 5v?

it may be best to put 5v (upto 20v max) into the VIN pin (which goes to the on-board voltage regulator).
> 0 votes

---
Tags: arduino-uno, esp8266, power, current
---


title: Power consumption for arduino

text:
# Question
Title: Power consumption for arduino
I am using an Arduino SMD UNO r3 board ,and connecting thermal sensor MLX 90614 , wifi modem ESP 8266 , a buzzer and an arduino based sound sensor . How much power distribution will it require ? What should be the capacity of the battery ?

# Answer
> 1 votes
You need to create a power budget. This means pouring through the datasheets of each component and finding the max and nominal current consumption info and then summing it up. From this, you should be able to come up with a battery capacity value.

There is a great article called "What is a Power Budget" written by Chris Gammell (from The Amp Hour) that goes into power budgets in more detail. Here are the key items from that page:

> So what is a power budget? Much like a budget you might have for your personal finances, a power budget shows where all the possible power will be used by a device to by breaking it down into components and categories.
>
> As you can see, not much more is required than your datasheets and a spreadsheet type program. ... The first two columns (A&B) are simply identifiers to allow you to recognize which components correspond to which set of data. The next two columns (C&D) determine the multiplicative factor. If you have 5 components that contain 4 op amps per, then that will consume 20x the power of a device that has the same supply current needs but only one op amp per and there is only one on the board. The next two columns (E&F) show how much current each individual component contributes and then the sum of all the components of that type contribute. Note that this parameter on a data sheet would be listed as “supply current” or “active current”. The “quiescient” number is when the device is in a resting state and will likely be much less than the active number (and not relevant for this example). Finally, the supply voltage is listed (in column G) to calculate power (using the formula P=I\*V) which is listed in column I per device. All of these contributors are summed, an efficiency is estimated (I assumed a poor efficiency linear type supply) and the total power required input to the device is given. Further calculations could result from much of this initial data.

---
Tags: arduino-uno, esp8266, power
---


title: ESP8266 Led is not working

text:
# Question
Title: ESP8266 Led is not working
My led is not blinking, I have no idea why it's not working. I am running it on "generic esp8266 module" plate.

```
 /*Blink

  Turns an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino
  model, check the Technical Specs of your board at:
  https://www.arduino.cc/en/Main/Products

  modified 8 May 2014
  by Scott Fitzgerald
  modified 2 Sep 2016
  by Arturo Guadalupi
  modified 8 Sep 2016
  by Colby Newman

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Blink
*/

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

My scheme

Wifi module is working fine, but led is not working at all.

Another sketch

```
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <Servo.h>
// Initialize Wifi connection to the router
char ssid[] = "---";     // your network SSID (name)
char password[] = "---"; // your network key
int tempsensorPin = 0;
int lightsensorPin = 1;
bool searchState = false;
bool starting = false;
bool lightState = false;
Servo servo_test;
// Initialize Telegram BOT
#define BOTtoken "----"  // your Bot Token (Get from Botfather)

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

int Bot_mtbs = 1000; //mean time between scan messages
long Bot_lasttime;   //last time messages' scan has been done

void setup() {
  //servo_test.attach(8);
  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  pinMode(13, OUTPUT);
}

void loop() {
 digitalWrite(13,lightState);
  if (millis() > Bot_lasttime + Bot_mtbs)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      for (int i=0; i<numNewMessages; i++) {
        String id = bot.messages[i].chat_id;
        String text = bot.messages[i].text;

       //bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
        if(searchState){
          searchState=false;
          bot.sendMessage(bot.messages[i].chat_id, "http://lmgtfy.com/?q="+text, "");
        }else{
          bot.sendMessage(bot.messages[i].chat_id, answerMe(text), "");
        }
      }
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }

    Bot_lasttime = millis();
  }
}
String answerMe(String request){
 int tempSensor = analogRead(tempsensorPin);
 int lightSensor = analogRead(lightsensorPin);
 float voltage = tempSensor * 5.0;
 voltage /= 1024.0;
 Serial.print(voltage); Serial.println(" volts");
   float temperatureC = (voltage - 0.5) * 20 ;
 Serial.print(temperatureC); Serial.println(" degrees C");
 float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
 Serial.print(temperatureF); Serial.println(" degrees F");
 if(starting){
  if (request=="/temperatureF"){
    return "Current temperature is " + String(temperatureF) + " F";
  }
  if (request=="/temperatureC"){
    return "Current temperature is " + String(temperatureC) +" C";
  }
  if(request=="/lightIntensity"){
    return "Current light intensity is " + String(lightSensor);
  }
  if(request=="/lightON"){
    lightState=true;
    return "Current light state is true!";
  }
  if(request=="/lightOFF"){
    lightState=false;
    return "Current light state is false!";
  }
  if(request=="/lightDepend"){
    analogWrite(13,lightSensor);
    return "Here we go!";
  }
  if(request=="/google"){
    searchState=true;
    return "What you want to google?";
  }
  if(request=="close"){
    starting=false;
    servo_test.write(0);
    return "Bye bye!";
  }
}else if(request=="/open"){
    starting=true;
    servo_test.write(90);
    return "What's next?";
}else
    return "Open the box first!";

}

```

# Answer
The esp8266 will not blink the LED on pin 13 or any other pin of the Uno. It has no access to pins of Uno. And your analogRead calls return some random values.

The RX to RX, TX to TX connection reduces the Uno to an "USB to Serial" adapter for the esp8266. You upload the Blink to esp8266. If the Blink sketch would have the original LED\_BUILTIN pin number, then the LED on the esp8266 module would perhaps blink.

After you changed the connection RX to TX and TX to RX, you can't upload to esp8266 because the esp8266 is not anymore connected to PC over USB.

If you want to read and write the pins of Uno from esp8266, use ConfigurableFirmata sketch in Uno and FirmataMaster library in esp8266.

Other option is to write your own sketch for Uno and handle the communication between esp8266 and Uno over Serial.

Or you can use the esp8266 as network adapter with some firmware (AT firmware or WiFi Link) and port your sketch to Uno.
> 1 votes

# Answer
Probably you are not uploading the code to ESP8266. Instead the code is getting uploaded to the Arduino. You should Ground the GPIO1 and connect ESP8266 Reset to Arduino Reset. Then go to the Sketch and see if you have changed the Board from ARduino to ESP8266.
> -1 votes

---
Tags: arduino-uno, esp8266, led
---


# Question
Title: Arduino SocketIO library not working over HTTPS
I am currently using this Socket.io library to be able to send data from the Adafruit Feather HUZZAH (based on ESP8266) to my NodeJS server. It works like a charm on my local webserver, never failing me. However, when I try the setup with the proper webapp hosted on Heroku, the command `SocketIOClient::connect(host, port)` fails and no connection is established with the webserver's SocketIO.

Since there is no mention of limitations with HTTPS connections, I assume that I might be doing something wrong. If the impossibility of having HTTPS connection is the case, however, is there any other way to send this kind of data through web sockets to a NodeJS server hosted on Heroku?

# Answer
For anyone having the same issues with SocketIO and the ESP8266, this issue on Github explains how I solved it:

> When specifying the host, avoid including the `http://` or any other trailing slashes. So it became `String host = "something.herokuapp.com";`
> 0 votes

---
Tags: esp8266, adafruit, http
---


title: General confusion about how to start

text:
# Question
Title: General confusion about how to start
I want to test around with my ESP32 and an E-Paper display - yet i am stuck at uploading sketches via Arduino IDE. I get those kind of errors:

```
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48

```

and looking into tools,i dont even see my board there - i bought it on amazon and the article just says "ILS - LOLIN32 Lite V1.0.0 Wifi and Bluetooth Board with ESP-32 Rev1 MicroPython 4MB FLASH".

What am i missing here? I am 99% sure i got the pins correct (finally), i got the USB-Serial driver, i got the right port - yet even a simple test sketch i found on the internet didnt work.

# Answer
> 1 votes
The Arduino IDE does not have a core for the ESP32 installed by default.

The problem was solved by explicitly installing the ESP32-Arduino Core in the Arduino IDE according to their manuals

---
Tags: ide, esp32
---


# Question
Title: Arduino HTTPClient passing string to variable
For some reason I can't seem to pass a simple string from one variable to another. Below is my code:

```
  HTTPClient http; // Declare an object of class HTTPClient
  http.begin(address); // Specify request destination
  int httpCode = http.GET(); // Send the request

  Serial.println("String: " + http.getString());

  String prp = http.getString();
  Serial.println("temp string: " + prp);

```

It prints out:

> String: \< ! DOCTYPE HTML\> 26
>
> temp string:

Why doesnt my string get correctly passed on to my temporary string variable?

Tom

# Answer
> 3 votes
The getString() method calls `writeToStream` which is documented `write all message body / payload to Stream`. It writes all the data of the http response to he output and doesn't store them internally. The next call has nothing to read because the first call to getString() put everything out.

---
Tags: esp8266, string, http
---


# Question
Title: Share I2C pins with other device when lacking GPIOs
We're Using `ESP12E` as our `MCU` and we have three functionality :

* `SIM800` connected to TX(GPIO1), RX(GPIO3)
* `Matrix Keypad` connected to `GPIOs: 14,13,2,10,0,4,5,16`
* `GLCD` connected to `GPIOs: 15,12`

And we also need to communicate with an `RTC(DS3231)` module via `I2C` bus!

So i'm wonder how we could do this?

Is it possible to share `I2C` pins with any other pins ?

And BTW for some reason we can't use IO expander such as `PCF8574`

# Answer
Since you already want to use I2C it makes sense to move other things onto that same I2C bus to save IO pins. And even off-load processing.

For instance, you could move your keypad to a dedicated matrix keypad interface chip, such as the MAX7365 (probably overkill for a small keypad), or a general I2C GPIO IO expander, such as the MCP23017.
> 0 votes

# Answer
We found `74C922` at long last! without any other choices.

A cheap, available, reliable and easy setup `IC`.

The simple schematic we use:

here is a good topic to start with
> 0 votes

---
Tags: esp8266, i2c, pins, communication
---


# Question
Title: How to set sampling rate for digital pin input?
I have an ADC that have sampling rate up to 40 MSPS, but i use 8 MHz clock so it will be 8 MSPS. The board used is arduino nano. The problem is i have to sampling it just 2 MHz (because the capacity of array variable in arduino Nano, which is around 10.000 elements in array variable). I know that using direct port reading will increase the speed of the digital read, but how can i set the direct port reading to just read every 0.5 us? Micros function cannot do the job of course

Thank you

# Answer
> 5 votes
You need:

1. A timer
2. A board that is capable of running fast enough to do what you want.

The Nano fits the first criteria, but not the second.

At 16MHz you get a clock period of 63ns. That means you get a mere 8 clock ticks (actually gives you 504ns) per interruption from the timer. That's *at most* 8 assembly instructions that can be executed within that time.

Since an interrupt service routine's preamble is longer than 7 instructions you can see there would be a slight problem there. No time for actually reading a digital IO port - and if you are using a serial protocol to communicate with your ADC you can multiply the reading time by the double the number of bits you need to read. That's a *long* time compared to 500ns.

So no. Think again. Use a more suitable board. Maybe an ARM based board (like the Teensy 3.x) would be a better fit.

# Answer
> 3 votes
**Note**: this is an attempt to answer the question as asked. This answer is unlikely to be of any use to the original poster, who presumably asked the wrong question. I am writing this only as a way to explore the limits on how fast a modest AVR can sample a port. For an answer that genuinely attempts to address the OP’s problem, see Majenko’s answer.

I read the question as follows: can we sample a digital port at 2 MHz on an Arduino Nano clocked at 8 MHz? Can we do so while storing the values in a RAM-based buffer?

The answer is yes, but it is non trivial, and it requires some assembly. To see the problem, let’s start by trying to do it in C++:

```
uint8_t buffer[1024];

void fill_buffer()
{
    cli();
    for (size_t i = 0; i < sizeof buffer; i++)
        buffer[i] = PINB;
    sei();
}

```

Note that the loop runs with interrupts disabled, otherwise the timer interrupt would wreak havoc with the loop timing. This is translated by gcc into an assembly equivalent to this:

```
    cli
    ldi  r30, lo8(buffer)      ; load the buffer address into pointer Z
    ldi  r31, hi8(buffer)      ; ditto
0:  in   r24, 0x03             ; read the port
    st   Z+,  r24              ; store into buffer, increment the pointer
    ldi  r24, hi8(buffer+1024) ; save (buffer+1024)>>8 in r24
    cpi  r30, lo8(buffer+1024) ; compare the pointer with buffer+1024
    cpc  r31, r24              ; ditto
    brne 0b                    ; loop back
    sei
    ret

```

The loop takes 8 cycles per iteration. With an 8 MHz clock, that would be one reading per microsecond. Too slow by a factor two.

One could save one cycle by using a different register for the port data and for the end-of-loop condition, and by moving the third `ldi` out of the loop. Another cycle could be saved by testing only the high byte of the Z pointer, but that would require aligning the buffer to 256 byte boundaries. With those two optimizations, we still need 6 CPU cycles per iteration, i.e. 0.75 µs at 8 MHz.

In order to make this faster, the only solution is to unroll the loop. This can be done in assembly by using the `.rept` (meaning “repeat”) directive:

```
void fill_buffer()
{
    cli();
    asm volatile(
        ".rept %[count]\n"  // repeat (count) times:
        "in r0, %[pin]\n"   //   read the port input register
        "st Z+, r0\n"       //   store in RAM
        "nop\n"             //   1 cycle delay
        ".endr"
        ::      "z" (buffer),
        [count] "i" (sizeof buffer),
        [pin]   "I" (_SFR_IO_ADDR(PINB))
        : "r0"
    );
    sei();
}

```

This takes 4 cycles, or 0.5 µs per iteration. Note that a delay cycle had to be introduced, otherwise the sampling would be too fast : 3 cycles, or 0.375 µs, per iteration.

This is not the fastest one can get. It is possible to take one sample per CPU cycle with something like this:

```
    in r0, 0x03
    in r1, 0x03
    in r2, 0x03
    ...

```

However this technique is limited to burst readings of at most 32 samples.

---
Tags: adc, digital-in
---


# Question
Title: Interruption triggered twice when set to FALLING
I have a simple sketch with a button that triggers an interruption set to happen when the button pin goes from HIGH to LOW. It has debouncing so no repetitions happen when the button is pressed, but sometimes when releasing the button the interruption also fires. Why would that be? Shouldn't the debouncing take care of any micro-rising during the release of the button?

```
volatile int contador = 0;
int n = contador;

long t = 0;
void setup() {

    pinMode(2, INPUT_PULLUP);
    attachInterrupt( 0, incrementaContador, FALLING);
}

void loop() {
    if (n != contador) {
        n = contador;
    }
}

void incrementaContador() {

    if ( millis() > (t + 50) ) {
        contador++ ;
        t = millis();
    }
}

```

This same code works correctly when set to LOW instead of FALLING.

# Answer
> but sometimes when releasing the button the interruption also fires

Yes, well when you release the button it may also bounce. In other words OFF/ON/OFF so that will count as a press. A capacitor over the switch might be better.

Example:
> 2 votes

---
Tags: interrupt, debounce
---


# Question
Title: Issues uploading to atmega324pb w/ adruino as ISP
I've been having some issues programming a new atmega324pb I have on a custom board. I set up an old adruino UNO as an ISP by uploading the ArduinoISP sketch, setting the programmer to "Arduino as ISP" and then using the "Upload using programmer" option but to no avail. Here is the verbose error message that the console logs:

```
System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

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

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

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000 (retrying)

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

avrdude: Device signature = 0x000000 (retrying)

```

I think it might be an issue with Arduino possibly targeting a chip other than atmega324pb that I'm using, but I'm not sure. I don't know of any official arduino boards that utilize the 324pb. The main issue that I see is that avrdude can't find the device signature. I've see others mention it might be faulty wiring, but I made sure all connections are intact.

# Answer
> 1 votes
In case anyone was wondering, I solved the problem.
Unfortunately I wasn't able to figure out how to upload it using Arduino as ISP, but I was able to get it to work with an AVR Pocket Programmer from Sparkfun. If you decide to use this, check out this drivers guide. It will It'll save massive headache getting the usb device to be recognized.

**IMPORTANT FOR ATMEGA324PB USERS!!!**
The atmega324pb is apparently not a default microcontroller in avrdude. You need to add it to the toolchain manually. You can do this by following this blog:
https://hackaday.io/project/9313-uino-mini-super-atmega328pb/log/31003-easy-way-to-a-toolchain-for-the-atmega328pb
It is the same process to add any Microchip microcontroller to avrdude, so this guide will work for the atmega324pb (did it firsthand). From there, you can also add a custom entry to Arduino's boards.txt config file if you'd like to use the Arduino IDE for development. I didn't mind working the command line, but having it in Arduino definitely streamlines the proccess of compiling the .hex and uploading it in one go.

Here is the custom entry I added to Arduino's boards.txt file for the Atmega324pb. All the data was gathered from the datasheet:

```
####   ATmega324PB    ####
m324p.name=Atmega324pb
m324p.upload.via_ssh=true

m324p.vid.0=0x0424
m324p.pid.0=0x2740

m324p.upload.tool=avrdude
m324p.upload.protocol=usbtiny
m324p.upload.maximum_size=28672
m324p.upload.maximum_data_size=2560
m324p.upload.speed=57600
m324p.upload.disable_flushing=true
m324p.upload.use_1200bps_touch=true
m324p.upload.wait_for_upload_port=true

m324p.bootloader.tool=avrdude
m324p.bootloader.low_fuses=0x62
m324p.bootloader.high_fuses=0xD9
m324p.bootloader.extended_fuses=0x0f

m324p.build.mcu=atmega324pb
m324p.build.f_cpu=1000000L
m324p.build.vid=0x0424
m324p.build.pid=0x2740
m324p.build.usb_product="Arduino m324pb"
m324p.build.board=AVR_m324pb
m324p.build.core=arduino
m324p.build.variant=standard
m324p.build.extra_flags={build.usb_flags}

```

Note that I set the upload.tool to avrdude, and the upload.protocol to usbtiny since I was using the pocket AVR programmer.

**IMPORTANT!!!** The high fuse bit in this config also is 0xD9, instead of the default 0x99. I changed one fuse bit to disable JTAG and regain access to GPIO pins. To my knowledge Arduino wasn't setting fuse bits when uploading with the programmer, but this is an important note to take. If you need to use GPIO pins that share JTAG functionality, run the avrdude command line to set the high fuse bit appropriately. (0xD9 for me).

---
Tags: uploading, avrdude, isp
---


title: What is the output of A0 - A5?

text:
# Question
Title: What is the output of A0 - A5?
I'm new to Arduino Uno, When I run this piece of code, I get numbers 340 to 370.

This is my question, why it returns 340 to 370 which correspond to 1.66 to 1.80 actual voltage? since I don't have any input equipment plugged into these pins so it must return zero voltage if i'm right in other words why default values in these pins are in this range of numbers ?

```
void loop() {
int val = analogRead(A0) ; //A1, A2 ...
Serial.println(val) ;

}

```

# Answer
> 2 votes
You will get varying values on each read. A pin’s input is said to be floating if nothing is connected, which in simple terms can be explained as it just acting as an antenna for whatever electric noise is present in your environment. Its state is unknown, and utterly meaningless. If you hold a spinning electric motor close to the pin, you can see the values rise and fall more clearly.

Use a high value (10K or more) pull-down or pull-up resistor to partially mitigate this jitter. A pull-down would bring the read value down to around 0, and a pull-up would bring it up to around 1023.

Furthermore, it’s a good idea to always smoothen out analogRead (5-10 reads, ~25-50ms apart, average the values out) to get a good reading if precision is important. This is especially valid if you use longer wires, have an unshielded case, or use a switched mode power supply. Twisting the wires (GND and wiper IIRC, otherwise correct me) to a potentiometer helps.

Edit: You can use `pinMode( A0, INPUT_PULLUP );` \- it provides a 20-50Kohm pull-up, though I don’t trust this and always use 1/4W resistors instead. It saves space though, and is quite handy.

---
Tags: arduino-uno
---


# Question
Title: Arduino reading value from external devices on
For this device it says:

*The PC Interface Option has all the features of the standard DC1100, but also has a COM Port interface that allows you to capture the air quality data to a PC for graphing and analysis. A 9pin serial cable or USB-to-COM Port Adapter (not included) links the DC1100 to your PC or laptop which then captures the data as it samples.*

Is it possible to connect such a device directly to an Arduino so that measured data are sent through the Serial Interface and Arduino is able to read them and manipulate them?

# Answer
Yes, with a small converter board it can be connected to an Arduino. The "9 pin serial cable" is very likely an RS-232 interface.

RS-232 is like UART with a few extra connections. Here is what the cable looks like:

Basically UART with flow control and other modem lines. Most likely it hasn't any of them conencted but that standard RXD, TXD and GND. These are all the connections needed for the microcontroller.

The voltage level of RS232 is however specified in a wide range (plus/minus 3V to 25V), so you need a converter chip (e.g. this one with a MAX3232, search for "RS232 to TTL Converter Board"). You need to measure the voltage levels with a multimeter to see what converter for what voltage rage you need.

Then conencting it to an Arduino is as simple as just connecting these 3 wires to the Arduino, either to the Hardware Serial port (D0, D1, GND) or via a software serial port.

Reference project:

However, receiving the communication data is only half the battle. You still have to figure out what the sent data represents and what commands you can send the device. Without datasheets from the vendor, you are left alone. This is where reverse-engineering starts.

As a starting point, you can "eaves-drop" on the communucation that PC software does with the device by just connecting a USB-RS232 converter to your computer and connecting the RX line line to either the TX or RX line of the the target device's COM port. This allows you to see the entire communication exchange. From this you might be able to see what commands you're supposed to send. But as I said, from there it's unchartered territory.
> 4 votes

---
Tags: serial, serial-data
---


# Question
Title: How to connect a 240x320 37-pin TFT to an Arduino Nano?
I have an old TFT display (extracted from an MP5 player) and I can't figure out how to connect it with an arduino nano, pls help. here's the datasheet of the TFT: http://read.pudn.com/downloads137/sourcecode/embed/586271/Varitronix-2.8-lcd/vl-ps-cog-t280mbqi-041.pdf Thank you.

# Answer
The Nano isn't a good choice for driving that screen. You need almost all the pins of the Nano to connect to the screen alone, and there's not enough to include the touch-screen as well. And that's when you're *not* using the serial port of the Arduino (TX/RX pins) for communication with the PC.

You need to connect:

* 16 data pins
* /CS pin
* /RS pin
* /WR pin
* Optionally RD pin, or tie it to 3.3V
* /RESET pin

And all those need to be level shifted to 3.3V.

You need to provide 3.3V to VCC1/2 and VCI. The LED A connects to 5V (since it has more current capacity than the 3.3V) and each LED Kx pin through a suitable resistor (220Ω maybe) to ground.

The touchscreen needs the X- and Y- pins connecting to a digital IO pin, and the X+ and Y+ pins to analog IO pins that can also double as digital IO pins (so not A6/A7 on boards that have them).

And then you need to obtain or write the software to drive the ILI9320 through the 16-bit interface.

Driving the interface is simple enough:

Initially:

1. Set /CS HIGH
2. Set /WR HIGH
3. Set /RD HIGH (if not tied to 3.3V)
4. Set /RESET HIGH
5. Short delay
6. Set /RESET LOW
7. Short delay
8. Set /RESET HIGH

Then to transfer a group of 16-bit words:

1. Set /CS LOW
2. Set the value to write on the 16 data pins
3. Pulse /WR LOW then HIGH
4. Repeat from 2 for each word
5. Set /CS HIGH

Refer to the ILI9320 datasheet for how to control the chip, or use existing library code (does uTFT or u8glib support it?).

For the touch screen it's a case of setting Y- LOW and Y+ HIGH, and X- and X+ to INPUT, then reading the analog value from X+. Repeat with X- set LOW and X+ set HIGH, and both Y set to INPUT, and read the analog value from Y+.

You can also get better results by reading multiple inverted settings:

* Y- = LOW, Y+ = HIGH, X- = INPUT, Read X+.
* Y- = HIGH, Y- = LOW, X- = INPUT, Read X+.
* Subtract the second reading from 1023
* Add the first and (modified) second reading
* Divide by two.
* Repeat for X-/X+ reading from Y+.

You can also take multiple readings and average them out to reduce noise and stabilise the output somewhat.

And of course on top of all that you need to find a way to connect to a 0.5mm pitch connector. Normally a 0.5mm pitch FPC socket is used, which means a PCB with one on. You may be able to find 37 pin adaptor for it, but 37 pins isn't a common format. Normally 50 pin is more common to accommodate a more general purpose interface including the M0-M2 pins that allow you to select the interface type, as well as an 18-bit data bus to allow full RGB6/6/6 interfacing, and even buffer-less clocking of raw display data for very high speed display updates by MCUs that support such an interface.
> 0 votes

---
Tags: arduino-nano, tft
---


# Question
Title: Arduino Nano /Uno USB is not getting recognized
I have multiple Unos and Nano and recently due to some bad configuration the USBs are not getting recognised on my Mac Air Laptop. These were working models for almost 1-2 years. I used it to control motors and something must have happened and it stopped.

But strangely the small boot up LEDs on the Nano/Uno light up when connected so it seems that the connection from the laptop USB to the device is good - but the driver ports are not showing up on the Arduino IDE. How do I go about resolving that it is not just a software issue and is a hardware issue ?

I reinstalled the CH340G driver.img and yet the device when plugged in - does not show the USB port on the IDE ? Any thoughts or ideas on how to resolve this.

The Uno/Nano are Chinese Clones and have CH340 chipset on them. Is there some firmware that may have gone wrong and can be reset ? or new boot loader that can be burnt to bring them back to life.

I want to be able to see the Tools-\> Port -\> /dev/cu.usbserial1410 and also be able to see /dev/cu.usbserial on the command xterm prompt .

# Answer
> 1 votes
Assuming that the atmega328p still works fine, you can still use the Nano. I have solved this a few times by just using a FTDI breakout board (remember to set it to 5V, though 3V3 upload works on a Nano), and connecting RX to TX, TX to RX. Press reset before each upload.

---
Tags: arduino-uno, arduino-nano, usb, port-mapping
---


# Question
Title: Arduino, exit status 1. Can't compile for Arduino Uno
```
#include <LedControl.h>

void setup() {
// put your setup code here, to run once:
}

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

```

This is my code: with `LedControl.h` it gives me exit status 1, can't compile for Arduino Uno. Please help.

If I remove the `#include` it works normally.

Also Arduino says that the library has been installed.

What I have tried (but didn't work):

Re-installing the library. Re-downloading Arduino.

# Answer
> 1 votes
I tried compiling your code with Arduino 1.6.12. As you found, without the #include, it compiles OK. With the #include, it fails. Here is the error message I got:

```
/var/folders/bl/s5kzhm3s0lb2rcvp3md8c7040000gp/T/untitled1814027053.tmp/sketch_may17a/sketch_may17a.ino:1:24: fatal error: LedControl.h: No such file or directory
 #include <LedControl.h>
                        ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno 115.2.

```

The error - at least in my case - is that the library, LedControl.h, was not found. Try to find out why not.

> also aruino says that the library has been installed.

It's easy to check: "Installing" library `foo.h`, only means your sketchbook folder contains a library folder called `libraries` (all lower case); `libraries` contains a folder `foo`; and `foo` contains the file `foo.h` and any other files necessary for that library, such as a `foo.cpp` if needed:

```
- Sketchbook - libraries - foo
                             foo.h
                             foo.cpp
                             anything.else.you.like

```

Update:

The library documentation is on github and has links to some sample code. Sorry I can't be more help - I haven't used the library or those LED devices.

---
Tags: arduino-uno
---


title: Concatenate integers as string

text:
# Question
Title: Concatenate integers as string
How can i concatenate integers as a single string?

```
int out1, out2, out3 = 0;

    out1 = digitalRead(r1);
    out2 = digitalRead(r2);
    out3 = digitalRead(r3);

```

I tried like so, between others, with no luck.

```
Serial.write(out1 + "" + out2 + "" + out3);

```

For example the expected result when all outputs are `HIGH` should be `111`, while when only the `r3` output is `HIGH` it should be `001`

All i want, is reporting to the sender of the serial command, the pins state

# Answer
> 3 votes
If you're just outputting to serial you don't need to concatenate - just print each bit separately, such as:

```
Serial.print(out1);
Serial.print(",");
Serial.print(out2);
Serial.print(",");
Serial.println(out3);

```

You should avoid using String as it's not good on devices with small amounts of memory like Arduinos. Instead if you really need to concatenate numbers you should use a C string and maybe `snprintf` to format the numbers into it:

```
char out[30];
snprintf(out, 30, "%d,%d,%d", out1, out2, out3);

```

# Answer
> 1 votes
I second Majenko's points about just printing the bits separately if possible, and avoiding `String` objects.

However, if you do need to build such a string (not String object, just plain C string), you don't need `sprintf()`, which is quite a big function: you can build the string character by character. For example:

```
char out[4];  // 3 + 1 char for the termination character
out[0] = out1==HIGH ? '1' : '0';
out[1] = out2==HIGH ? '1' : '0';
out[2] = out3==HIGH ? '1' : '0';
out[3] = '\0';  // add NUL termination
Serial.println(out);

```

This is using the ternary operator, which here means “if `out1` is `HIGH`, then use the character `'1'`, otherwise use `'0'`”.

Now, it just happens that in Arduino `HIGH` means 1 and `LOW` means 0. And single digit numbers can be converted into character by just adding the numeric code of character “0”, which is 48 but can written as `'0'` in C++. Thus you can write:

```
out[0] = out1 + '0';  // convert number to character

```

And you can put all together as:

```
char out[4];  // 3 + 1 char for the termination character
out[0] = digitalRead(r1) + '0';
out[1] = digitalRead(r2) + '0';
out[2] = digitalRead(r3) + '0';
out[3] = '\0';  // add NUL termination
Serial.println(out);

```

# Answer
> 1 votes
Serial.write(b) prints one byte not a string. Use print() to print strings and numbers.

```
Serial.print(digitalRead(r1));
Serial.print(digitalRead(r2));
Serial.println(digitalRead(r3));

```

---
Tags: arduino-uno
---


# Question
Title: Reducing Clock Speed increases sketch size?
I just lowered the clock speed of my arduino promini 3.3v - 328p from 8Mhz to 1Mhz on the external clock disabling the brounout detection and when I compiled I my old sketch it wouldn't upload any more because suddenly the size has increased from 31KB to 35KB.

Does anyone know why this could happen. I didn't make any changes in the code and it still loads into the 8Mhz Arduino without any problems.

I used these low power config files: https://github.com/joe-speedboat/Arduino-LowPower

# Answer
Does your code have delays in it? If you changed the clock speed, then the compiled assembly for the delays may require more NOP instructions or something similar to achieve the same real-time delay. As a result, the size of the compiled sketch could increase.
> 1 votes

---
Tags: arduino-pro-mini
---