# Question
Title: Stuck reading an XBM image from JSON (U8g2lib)
What I'm trying to achieve is very simple, I'm using ArduinoJson lib to load a JSON from SPIFFS and trying to inject the image values in an Array to feed the small Oled display of the ESP32:

```
// This is the format the library expects
static const unsigned char image[] U8X8_PROGMEM  = {
0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x17 }

```

This is the JSON File: https://github.com/martinberlin/esp/blob/master/oled-128x64-xbm/data/1.json

The goal is to be able to generate little thumbnails after uploading an image for example, and display them in this Monochrome small display.

The problem is to convert this Json array into the format the library expects. And I tried many different ways and readed about it, without finding the right way to do it. So I though to share this here as a challenge and see if someone is also interested to get dynamic image thumbnails working in this display.

This is my sketch: (Needs /data upload since json example is there)

https://github.com/martinberlin/esp/tree/master/oled-128x64-xbm

```
#include "FS.h"
#include "SPIFFS.h"
#include <U8g2lib.h>
#include <ArduinoJson.h>
#include <Wire.h>

/*
  U8glib Example Overview:
    Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption
    Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards.
    U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only.

*/
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 15, /* data=*/ 4, /* reset=*/ 16);

static const unsigned char image[] U8X8_PROGMEM  = {
  0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x17,
  0xFC, 0xFF, 0xFF, 0xFF, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00,
  0xFF, 0xFF, 0xFF, 0x14, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xF0, 0xFF, 0xFF,
  0xFF, 0x7F, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x14, 0xFD, 0xFF, 0xFF, 0xFF,
  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9E, 0xFC, 0xFF, 0x03, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1C, 0x00, 0x0C, 0x00, 0x0C, 0x4E, 0xFE,
  0xFF, 0x33, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3C, 0x00, 0x06,
  0x00, 0x0C, 0x77, 0xFF, 0xFF, 0x33, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0x7F, 0x7F, 0x00, 0x23, 0x00, 0xCE, 0xFF, 0xFF, 0xFF, 0x16, 0xF8, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x85, 0x01, 0x00, 0x1E, 0xFE, 0xFF,
  0x7F, 0x10, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC7, 0x01,
  0x80, 0x0F, 0xFF, 0xFF, 0x3F, 0x10, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0x67, 0x00, 0xD8, 0x1F, 0xFF, 0xFF, 0x7F, 0x10, 0xFE, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF};

const char* xtemp[1024]; // Temporary array to store JSON incoming Hex as string
const unsigned char* xbm[1024] U8X8_PROGMEM;

void setup(void) {
  Serial.begin(115200);
  // Read xbm from  json
  SPIFFS.begin();

   if (SPIFFS.exists("/1.json")) {
    Serial.println("1.json found in SPIFFS");
    File configFile = SPIFFS.open("/1.json", FILE_READ);
      if (configFile) {
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        //json.printTo(Serial);

        if (json.success()) {
          Serial.println("json.success");
          JsonArray& arr = json["xbm"];

          // using C++11 syntax (preferred):
          int c=0;

          for (auto value : arr) {
            // Assign the json array to xtemp
            xtemp[c] = value.as<char*>();

            //Serial.println(String(c)+":"+value.as<char*>()); // Right value
            c++;
          }

        } else {
          Serial.println("ERR load config");
        }

        configFile.close();
      }
   }
  u8g2.begin();
  u8g2.setDrawColor(0);
  u8g2.clearBuffer();

  Serial.println("cross_block_bits size:");
  Serial.print(sizeof(image));
  Serial.println(image[1]);

  //xbm = xtemp;

  Serial.println("xbm:");
  Serial.println(xtemp[1]);

 // Should be xbm (coming from json)   xbm
 // u8g2.drawXBM( 0, 0, 128, 64, xtemp); // Does not work since requires  'const uint8_t* {aka const unsigned char*}
  u8g2.drawXBM( 0, 0, 128, 64, image);

  u8g2.sendBuffer();
}

void loop(void) {

}

```

# Answer
> 1 votes
Thanks and credits to Majenko. Sorted it out, still I don't know why addressing an existing image works but targeting a new array doesn't. Anyways as proof-of-concept that an XBM Icon can be loaded from JSON it works. For anyone wanting to achieve this, here is the code, make sure to upload some JSON to Spiffs first:

```
/*
  GraphicsTest.ino
  Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/)
*/
#include "FS.h"
#include "SPIFFS.h"
#include <U8g2lib.h>
#include <ArduinoJson.h>
#include <Wire.h>

/*
  U8glib Example Overview:
    Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption
    Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards.
    U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only.

*/
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 15, /* data=*/ 4, /* reset=*/ 16);

static unsigned char image[] U8X8_PROGMEM  = {
  0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x17,
  0xFC, 0xFF, 0xFF, 0xFF, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00,
  0xFF, 0xFF, 0xFF, 0x14, 0xFF, 0xFF, 0xFF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, 0x04, 0x3C, 0xF8, 0xFF, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0x79, 0x40, 0x18, 0x00, 0x1C, 0x9E, 0xFC, 0xFF, 0x03, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1C, 0x00, 0x0C, 0x00, 0x0C, 0x4E, 0xFE,
  0xFF, 0x33, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3C, 0x00, 0x06,
  0x00, 0x0C, 0x77, 0xFF, 0xFF, 0x33, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0x7F, 0x7F, 0x00, 0x23, 0x00, 0xCE, 0xFF, 0xFF, 0xFF, 0x16, 0xF8, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x85, 0x01, 0x00, 0x1E, 0xFE, 0xFF,
  0x7F, 0x10, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC7, 0x01,
  0x80, 0x0F, 0xFF, 0xFF, 0x3F, 0x10, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0x67, 0x00, 0xD8, 0x1F, 0xFF, 0xFF, 0x7F, 0x10, 0xFE, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF};

// Using this new array I could not get it work. Rewriting image works
long unsigned int xbm[1024];

void setup(void) {
  Serial.begin(115200);
  // Read xbm from  json
  SPIFFS.begin();

   if (SPIFFS.exists("/1.json")) {
    Serial.println("1.json found in SPIFFS");
    File configFile = SPIFFS.open("/2.json", FILE_READ);
      if (configFile) {
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        //json.printTo(Serial);

        if (json.success()) {
          Serial.println("json.success Size of xbm array");

          JsonArray& arr = json["xbm"];

        Serial.print(sizeof(arr));
          // using C++11 syntax (preferred):
          int c=0;
          const char* tempx;
          for (auto value : arr) {
            // Assign the json array to xtemp
            tempx = value.as<char*>();

            image[c] = strtol(tempx, NULL, 16);

              //Serial.print(strtol(tempx, NULL, 16)); //Thx. Majenko
              if (c<10) {
              Serial.print("i:");Serial.print(image[c]);Serial.print(" ");
              }
            c++;
          }
          Serial.print("Final c count:"+String(c));

        } else {
          Serial.println("ERR loading JSON");
        }

        configFile.close();
      }
   }
  u8g2.begin();
  u8g2.setDrawColor(0);
  u8g2.clearBuffer();

  Serial.print("image size:");
  Serial.print(sizeof(image));Serial.println();  // Here is 4096 also 4 times bigger, if I use a new array (WHY?)
  // Send the JSON array to oled display
  u8g2.drawXBM( 0, 0, 128, 64, (const uint8_t *)image);
  u8g2.sendBuffer();
}

void loop(void) {

}

```

---
Tags: esp32
---


# Question
Title: I have the code printing the data I need but don't know how to connect the data on ESP8266 IP web server
```
   #include "DHT.h"
   #include "NewPing.h"
   #include <SoftwareSerial.h>

   #define DEBUG true
   SoftwareSerial esp8266(11,10);
   #define DHTPIN 2        // DHT-11 Output Pin connection
   #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
   #define TRIGGER_PIN 4
   #define ECHO_PIN 3
   #define MAX_DISTANCE 400

    NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);
float hum;
float temp;
    DHT dht(DHTPIN, DHTTYPE);

void setup() {

   Serial.begin (9600);
   dht.begin();

   pinMode(TRIGGER_PIN, OUTPUT);
   pinMode(ECHO_PIN, INPUT);

   sendData("AT+RST\r\n",2000,DEBUG);
   sendData("AT+CWMODE=2\r\n",1000,DEBUG);
   sendData("AT+CIFSR\r\n",1000,DEBUG);
   sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
   sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

 }

 void loop()

 {

 delay(2000);  // Delay so DHT-11 sensor can stabalize

   hum = dht.readHumidity();  // Get Humidity value
   temp= dht.readTemperature();  // Get Temperature value

 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

   long duration,distance;
   duration= pulseIn(ECHO_PIN,HIGH);
   distance = duration/58.2;

   Serial.print("Humid: ");
   Serial.print(hum);
   Serial.print(" %, Temp: ");
   Serial.print(temp);
   Serial.print(" C, ");
   Serial.print("Distance: ");
   Serial.print(distance);
   Serial.println(" cm");

   delay(50);

  if(esp8266.available())

   is sending a message
 {
   if(esp8266.find("+IPD,"))
 {
 delay(1000);

 int connectionId = esp8266.read()-48;

  /* We are subtracting 48 from the
  output because the read() function returns
  the ASCII decimal value and the
  first decimal number which is 0 starts at 48*/

  String webpage = "<h1>IOT Garbage Monitoring System</h1>";
  webpage += "<p><h2>";

  if (distance<5)
 {
  webpage+= " Trash can is Full";
 }
   else{
   webpage+= " Trash can is Empty";
    }
   webpage += "</h2></p></body>";
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=webpage.length();
   cipSend +="\r\n";

   sendData(cipSend,1000,DEBUG);
   sendData(webpage,1000,DEBUG);

   String closeCommand = "AT+CIPCLOSE=";
   closeCommand+=connectionId;
   closeCommand+="\r\n";
   sendData(closeCommand,3000,DEBUG);

   }
   }
   }

   String sendData(String command, const int timeout, boolean debug)

   {

   String response = "";
   esp8266.print(command);
   long int time = millis();

   while( (time+timeout) > millis())
   {
   while(esp8266.available())
   {
   char c = esp8266.read();
   response+=c;
   }
   }
   if(debug)
      {
     Serial.print(response);
      }
     return response;
      }

```

# Answer
The esp-01 is in AP mode. To access the web page on the IP address 192.168.4.1 show in Serial Monitor you must connect to the WiFi network created by the esp-01.

If you click the WiFi icon in the bottom right corner of Windows, you will see a list of WiFi networks.
> 0 votes

---
Tags: arduino-uno, esp8266, sensors, web-server
---


title: Using timer classes within classes

text:
# Question
Title: Using timer classes within classes
I am trying to develop a class for a pump that works on a stepper motor, it should be simple but its not working the way I thought it would. Once I move the timer object into the class the code wont compile I have tried a lot of things but nothing seems to work correctly. The goal of this whole thing is getting the stepper motor to step on its own based off of the calls from the timer object.

pump.h

```
#include "TimerObject.h"`
#ifndef Pump_h
#define Pump_h

class Pump
{
  public:
     Pump(char pin_, char dir_);
    void pumpstep(void);
  private:
    char pin;
    char dir;
    TimerObject *pumptimer;
};

#endif

```

pump.cpp

```
Pump::Pump(char pin_, char dir_)
{
    pin = pin_;
    dir = dir_;
    pumptimer = new TimerObject(100, &this->pumpStep); //PROBLEM IS HERE

  pinMode(pin, OUTPUT);
  pinMode(dir, OUTPUT);
}

void Pump::pumpstep(void) {
     Serial.println("Stepping");
}

```

my .ino simply creates the class passing in the needed parameters but everything binds up when I try to compile because of the callback in the constructor for the timer, for some reason It wont let me use the address of a non-static method here but I cant make the method static each pumpstep() method must be separate depending on which pump is running. I have tried using &Pump::pumpstep, &(Pump::pumpstep) and many more pointers but cant seem to get the one I need.

outside this class the timer was working great I used this line below:

```
pumptimer = new TimerObject(100, &pumpStep);

```

The library for the timer can be found here: https://playground.arduino.cc/Code/ArduinoTimerObject

Any help would be greatly appreciated.

# Answer
The function prototype of a member function is completely different to that of a global function. The two are not interchangeable.

There are ways of working around it, such as "bouncing" your callback through a global function, but they're messy.

However, in this situation you are better off just ditching TimerObjects.h and doing it manually - it's not exactly difficult:

```
#ifndef Pump_h
#define Pump_h

class Pump
{
  public:
     Pump(char pin_, char dir_);
     void pumpstep(void);
     uint32_t ts;
     void run()
  private:
    char pin;
    char dir;
};

#endif

```

---

```
Pump::Pump(char pin_, char dir_)
{
    pin = pin_;
    dir = dir_;
    ts = 0;
    pinMode(pin, OUTPUT);
    pinMode(dir, OUTPUT);
}

void Pump::pumpstep(void) {
     Serial.println("Stepping");
}

void Pump::run() {
    if (millis() - ts >= 100) {
        ts += 100;
        pumpStep();
    }
}

```

Then in loop call:

```
myPump.run();

```

You can, of course, just combine `run()` and `pumpstep()` into one single function.
> 0 votes

---
Tags: motor, library, timers, stepper, callbacks
---


# Question
Title: Sending POST request to HTTPS aws server using SIM900A
I have hooked up an SIM900A module to my Arduino UNO and I wanted to send a GET request to my aws server for which I have created a RESTful API, the problem is that when I send a request using AT commands I get 601 error code. But I am easily able to connect to https:// www.goolge.com and get the HTML page. I have seen some other links which are very much technical for me like https://stackoverflow.com/questions/39177095/unable-to-invoke-aws-api-gateway-get-url-with-gprs-connection and https://electronics.stackexchange.com/questions/266974/testing-a-connection-to-a-tcp-socket-through-sim5320a-cellular-module.

I want to know if SIM900A even support connections to HTTPS and if yes, how can I connect to my aws server. I kind of a noob in networking, so sorry if I cannot elaborate on details. I have read somewhere online that SIM900A only supports half https, I don't know what that means, any help/advice would be helpful.

AT commands I used

`AT
AT+CGATT = 1
AT+SAPBR=3,1,"CONTYPE","GPRS"
AT+SAPBR=3,1,"APN","www"
AT+SAPBR=1,1
AT+SAPBR=2,1
AT+HTTPSSL=1
AT+HTTPINIT
AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","https://www.google.gom"
AT+HTTPACTION=0
AT+HTTPREAD`

# Answer
> 1 votes
When you use https, you must not use:

```
AT+HTTPPARA="URL","https://www.google.gom"

```

You must use:

```
AT+HTTPPARA="URL","www.google.gom"

```

---
Tags: arduino-uno, gsm
---


# Question
Title: Using 2 piezo buzzers to emit the same tone with phase difference
For a physics project, I want to record the effect of 2 speakers emitting 100hz at different phase differences. Trouble is, the Arduino can only send one tone() signal at a time. How do I create a phase difference effect using one Arduino?

# Answer
Since the frequency is so low, you can generate the signals in software. That would not be as clean as timer-generated signals, but it will be much easier. And probably clean enough for the intended purpose.

In order to generate a tone, you have to repeatedly switch the pin connected to the piezo. This is very similar to blinking an LED, only somewhat faster. Blinking an LED is the very first thing you learn to do with an Arduino, but you may notice that blinking **two** LEDs is a little bit trickier. The problem – and the solution – is discussed in the Arduino tutorial Blink Without Delay. Building on that tutorial, here is an example program that generates two 100 Hz signals in quadrature:

```
const uint8_t PIN_A = 8;
const uint8_t PIN_B = 9;
const uint32_t HALF_PERIOD = 5000;  // 5000 us
const float PHASE_SHIFT = 0.25;     // 1/4 period

uint8_t state_A = LOW;
uint8_t state_B = LOW;

uint32_t last_A_toggle = 0;
uint32_t last_B_toggle = - 2 * HALF_PERIOD * PHASE_SHIFT;

void setup() {
    pinMode(PIN_A, OUTPUT);
    pinMode(PIN_B, OUTPUT);
}

void loop() {
    uint32_t now = micros();
    if (now - last_A_toggle >= HALF_PERIOD) {
        last_A_toggle += HALF_PERIOD;
        state_A = !state_A;
        digitalWrite(PIN_A, state_A);
    }
    if (now - last_B_toggle >= HALF_PERIOD) {
        last_B_toggle += HALF_PERIOD;
        state_B = !state_B;
        digitalWrite(PIN_B, state_B);
    }
}

```

If you compare this with the above mentioned tutorial, there are a couple of differences worth noticing:

* The timings are measured using microseconds rather than milliseconds, for getting a better accuracy
* The variables holding the times of last toggle are updated like `last_A_toggle += HALF_PERIOD` rather than `last_A_toggle = now` (the equivalent of `previousMillis = currentMillis`). This is needed to keep an accurate average frequency. Otherwise the time taken to execute the code would make the frequency slightly off.

There is a little trickery in the initialization of `last_B_toggle`, which is an unsigned number initialized to a negative value. The initialization is valid and works modulo 232. Using a small positive value would have the ill effect of `now - last_B_toggle` overflowing to a very large positive number on the first run of `loop()`, putting `last_B_toggle` effectively in the distant past.
> 1 votes

# Answer
For a very simple example you can do something like this:

```
#define SPEAKER1_PIN    5
#define SPEAKER2_PIN    6

void setup() {
  pinMode(SPEAKER1_PIN, OUTPUT);
  pinMode(SPEAKER2_PIN, OUTPUT);
}

void loop() {
  int phase_delay = 1000;   // Phase delay (in us)
  int freq_delay = 5000;    // Half of square wave at 100Hz (5000us)

  // Generate 2 square waves (out of phase)
  while(1) {
    digitalWrite(SPEAKER1_PIN, HIGH);
    delayMicroseconds(phase_delay);
    digitalWrite(SPEAKER2_PIN, HIGH);
    delayMicroseconds(freq_delay - phase_delay);
    digitalWrite(SPEAKER1_PIN, LOW);
    delayMicroseconds(phase_delay);
    digitalWrite(SPEAKER2_PIN, LOW);
    delayMicroseconds(freq_delay - phase_delay);
    }
}

```

By the way, 100Hz may be to low of a frequency to get much sound out of a Piezo speaker. You'll likely have better success by using higher frequencies.
> 1 votes

---
Tags: piezo
---


title: GMS send SMS text messages many times

text:
# Question
Title: GMS send SMS text messages many times
The GSM sends many SMS text messages and does not stop. How to send only one SMS? This is my code:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);
char msg;
int vibr_pin = 7;

void setup() {
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);   // Setting the baud rate of Serial Monitor (Arduino)
  pinMode(vibr_pin, INPUT);
  delay(100);
}

void loop() {
  int a;
  a = digitalRead(vibr_pin);
  if (a == 0) {
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
    delay(1000);  // Delay of 1000 milli seconds or 1 second
    mySerial.println("AT+CMGS=\"+60125456758\"\r"); // Replace x with mobile number
    delay(1000);
    mySerial.println("test 1,2,3"); // The SMS text you want to send
    delay(100);
    mySerial.println((char) 26); // ASCII code of CTRL+Z
    delay(1000);
  }
}

```

**EDIT:**
After I change `if (a==0)` to `if(a!=0)`, it only sends message when the vibration sensor is moving. How to send sms when sensor is not moving?

# Answer
> 0 votes
```
int a;
a = digitalRead(vibr_pin);
if (a == 0) {

```

This sends an SMS text message every time a is 0. I'm not sure what vibr\_pin does, but maybe you want to check only for a trigger (from `a != 0` to `a == 0`).

In that case, use a boolean to check if the SMS text message has been sent, and reset the boolean when a goes from `!=0` to `0`.

---
Tags: softwareserial, gsm
---


# Question
Title: Connecting an Arduino to a servo with an external power supply
I have purchased an MG995 servo (4.8-7.2V operating voltage, 170MA no load operating current draw) and will power this using a 5V, 2A mains plug pack. Do I need a breadboard to connect this with my Arduino (which will itself be powered through its usb port)? Or is it possible to connect the servo with the Arduino directly?

If it's possible to connect it directly, which pins should I be using on the Arduino? Will it look something like this:

except the red wire (and black wire?) connects to the external power supply?

Any answers (or links to relevant tutorials which have all three of these components) would be welcome. Thanks!

# Answer
Your question is not very concise, but I'll try to hit the main points.

I'm going with the assumption that your "Arduino" is the Sparkfun Redboard. The Redboard has a current limit of \<800mA (heat management on the Redboard probably lowers this number even more), as per the LM1117 voltage regulator listed in the provided RedBoard schematic, and a minimum input voltage of 7V. You won't be able to power your Arduino with the 5V2A powerbrick. If you are powering the RedBoard through the standard USB, then it will typically be limited to 500mA.

Are you sure your servo has a no-load draw of 170mA? That's really high for a servo. If it does, then I'm assuming it's a large servo that likely has a high stall current draw, so 800mA from the Redboard's on-board regulator won't cut it, nor a USB port.

To power your servo externally, wire the servo and Redboard according to the schematic below. The power supply is indicative of your 5V 2A "wall wart". It's important to note that you need to connect the ground of the the power supply to the ground of the Arduino. For controlling the servo, check out Adafruit's servo tutorial. You will also need to provide power to your Arduino via USB or a DC barrel jack with a power brick that outputs \>= 7v.
> 5 votes

# Answer
You did not indicate how you plan to connect the 5V, 2A mains plug pack to the Arduino board. If you want to use the barrel jack on the left, please note the listed input voltage. 5 volts is too low if you plan on powering the Uno board with the external power source. There is a voltage comparator circuit that will switch over to the barrel jack power if the voltage is high enough.

But since you are not really asking about powering the Uno, just the servo, then it gets interesting. The Sparkfun schematic shows a diode in line with the barrel connector and the Vin connection point on the board. This could provide a power path for the servo. The problem is that the servo voltage range 4.8 volts on the low end. With a 5 volt output of your external power supply, a voltage drop from the diode would give the servo almost enough voltage to meet the 4.8 volt minimum but not quite.

You are better off to not connect the servo power through the Uno board. If you had a somewhat higher voltage supply, at least 6 volts, then it would be ok. But if it is only 5 volts then it really is at a very marginal level.
> 1 votes

---
Tags: arduino-uno, servo, breadboard, adapter
---


title: DHT22 need pull down/up ESP8266

text:
# Question
Title: DHT22 need pull down/up ESP8266
I have the strange pb. My esp8266 was working fine with my DHT22 and then failed every time. I loaded an example sketch in a other ESP8266 and I have the same pb.... until I shut down -\> up the DHT22 when the ESP8266 is working. To check more, I added this at the setup before `dht.begin()` :

```
      digitalWrite(0, LOW); // turn the LED on (HIGH is the voltage level)
  delay(1000); // wait for a second
  digitalWrite(0, HIGH);

```

And it works. But I don't know why I need to do this "pull up". PS : I already tried with or without the 10K resistor, same pb. PS2 : I already tried with 3.3v or 5V for DHT22. Same pb.

Any idea ?

# Answer
I answer my own question in case someone has the same issue. **The ADAFRUIT\_DHT lib DOESN'T WORK WITH ESP8266.** It keep saying `Failed to read from DHT sensor!` until you unplug/plug the VCC on the DHT.

But the **DHTesp** (link) works very well at first try !

Thx @Juraj and @Jot for their support.
> 3 votes

---
Tags: esp8266, temperature-sensor
---


# Question
Title: Trying to understand how to make a program do three things with a button press
I am trying to write some code, which I barely grasp - but it's coming along! But I think I've hit a wall that I could using some help getting over...

I'm not asking for you to fix my code - I know that's not how I am going to learn, maybe explain why my code isn't doing what I want it to, and/or some resources I can using to learn about it.

I think it has something to do with me trying to use the same pins in the initialization part since the error is about a conflicting declaration..

Here's my breadboard layout if this helps too:

```
//ABOUT - This programs goal is to make a button cycle through three    different 'modes'
//Mode 1 - make a RGB LED cycle through its colors
//Mode 2 - make the same RGB LED fade-cycle through its colors
//Mode 3 - make the same RGB LED blink on-off all three colors at once
//Additional modes may follow but this is the beginning.

//currently all my initialization code is from three different programs and I think that's why parts are not working.. I think
//I can share the mode initialization code for each mode....?  But the face code uses the uint8_t vs just int so maybe not?

//Button Cycle - this is the first part of my code, designed to teacah me how to make a button cycle through to different parts of the code

int counter = 0;
int switchPin = 13;
int LEDB = 11;
int LEDG = 10;
int LEDR = 9;

//RGB LED Cycle Circuit - mode 1
const int redLED=3; //red LED connects to digital pin 8
const int blueLED=5; //blue LED connected to digital pin 7
const int greenLED=6; //green LED connected to dogotal pin 6

//RGB LED Fade Circuit - mode 2
const uint8_t redLED = 3;  // pin connected to the red LED - I don't understand why this code says const uint8_t  -
const uint8_t blueLED = 5;  // pin connected to the green LED
const uint8_t greenLED = 6; // pin connected to the yellow LED

void setup()
{
  Serial.begin(9600); //I added this to help learn what the counter was doing
  pinMode(switchPin, INPUT);
  pinMode(LEDR, OUTPUT);
  pinMode(LEDG, OUTPUT);
  pinMode(LEDB, OUTPUT);
}

void loop() {
  //Handle input
  int switchVal = digitalRead(switchPin);
  if(switchVal == LOW) //changed from HIGH which was making the modes appear to change randomly - may come in useful later but not what I want initially
  {
    delay(500);
    counter ++;
    Serial.println(counter); //prints value of counter to serial monitor so I can see why it appeared to be random
    //I learned that when the switchVal == HIGH was in place the counter would cycle continuously. Making each button
    //press appear random. Changing this to LOW made the counter wait for a LOW event before counting. Increasing the
    //delay to half a sec gives time to release the button before the counter continues.

    //Reset count if over max mode number
    if(counter > 3)
    {
      counter = 1; //in serial monitor you will see that the counter goes to 4 but this code tells the program that 4 = 1 so it runs the right mode
    }
  }
  else
    //Change mode 1
    switch (counter) {
    case 1:
      analogWrite(LEDB, 000);
      analogWrite(LEDG, 000);
      analogWrite(LEDR, 255);

      //start LED Cycle - this is simply pasted in from the LED cycle program - seems to work fine

      digitalWrite(redLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(redLED,LOW);//turns the LED off
      digitalWrite(greenLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(greenLED,LOW);//turns the LED off
      digitalWrite(blueLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(blueLED,LOW);//turns the LED off
      break;

    //mode 2 code
    case 2:
      analogWrite(LEDR, 000);
      analogWrite(LEDB, 000);
      analogWrite(LEDG, 255);

      //LED Fade Cycle
      // Fade an analog pin up and down.
      void fade(uint8_t pin);
      {
        for (int i = 1; i <= 255; i=i+5) {
          delay(10);
        }
        for (int i = 254; i >= 0; i=i-5) {
          delay(10);
        }
      }
      //void loop(); - think I can only have one void loop so I'm commenting this out for now..
      {
        //Serial.println(F("Fading GREEN."));
        fade(redLED);
        //Serial.println(F("Fading BLUE."));
        fade(blueLED);
        //Serial.println(F("Fading YELLOW."));
        fade(greenLED);
      }
      break;

    //mode 3 not coded yet - waiting to make mode 2 work
    case 3:
      analogWrite(LEDG, 000);
      analogWrite(LEDR, 000);
      analogWrite(LEDB, 255);
      break;
    }
}

```

# Answer
There are two immediate things I can see wrong:

1. You have two sets of the same pin definitions. You only want one set. Both sets are identical - once it's defined its defined - you can't define it again as the same thing.
2. You seem to have a function defined in the middle of your loop() function. That can't work - functions have to be separate things. (also you don't want a `;` in your function definition...)
> 2 votes

# Answer
You've used the blue lower rail for Ground but used the red lower rail (usually used for +5v) as a simple connection point. It's not wrong but it's unusual enough to be confusing to readers. The choice of red button-signal wire on the red rail also strongly suggest a connection to +5v even though that is not the case here.

The buttons, "tact" switches, are confusing by design (see picture below). Each pair of pins curved toward each other (I marked one with a red arrow) are the physically *same* pin and always connected to each other. The *pairs* are connected to each other only when the button is pressed. It's really easy to miss that and insert the button 90deg either way from what you intended. Fritzing's button icon doesn't show the orientation either. Yours may well be correct - it's just a pitfall to be aware of.

`void fade(uint8_t pin);` doesn't define a function - it declares that one exists somewhere else. I think you meant `void fade(uint8_t pin){ ... }` (note no semi-colon), which would define the function, if that were a proper location to do so. But in C and C++, functions may not be defined within other functions (loop(), in this case). Fix the definition of 'fade' and move it to above 'setup()'. That will properly define it and make it usable from within the loop() function.

The braces, {}, where you tried to define a second loop function are unnecessary (and, you're correct, you can't define more than one function with the same name and signature (parameter count & types, and return type). But you don't need another `loop()`; the code contained in the {} - three calls to the fade function - remain part of `case 2:`.
> 0 votes

# Answer
I think what you are missing is a pulldown resistor for the button. Simply put, a pulldown resistor is a resistor pulls down the input reading to 0 when the button is not pressed. Without the pulldown resistor, the value read in the `digitalRead` will float around giving inaccurate results.

Above is a circuit showing how the pulldown resistor should be wired with a button.

If you would like to learn more about pulldown resistors, please refer to this page describing buttons in the Arduino Website.

This is just a hardware issue I noticed; hopefully, this will help you out in addition to the other recommendations given.

As a side note, a pull-up resistor can also be used, and in this case, the value will be 1 when the button is not pressed.
> 0 votes

---
Tags: arduino-uno
---


title: Keyboard.h not found

text:
# Question
Title: Keyboard.h not found
I keep getting this error message:

```
"'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?"

```

... when I have already included `Keyboard.h`.

```
#include <Keyboard.h>

void setup() {
  pinMode(3,INPUT_PULLUP);
  pinMode(4,INPUT_PULLUP);

 Serial.begin(9600);    //begin seral comms for debugging
}

void loop() {
  Keyboard.begin();
  if (digitalRead(3) == 0) //if button 3 is pushed
   {
Keyboard.write('z');
delay(200);
}
   else if (digitalRead(4) == 0) //if button 3 is pushed
{
  Keyboard.write('x');
  delay(200);
}
  Keyboard.end();
}

```

`Keyboard.h` is already included as a default library in Arduino so I'm not sure what's wrong

# Answer
> 4 votes
If you have **Arduino/Genuino Uno** selected as your board in the **Tools ► Board ►** menu, then you get the error. If you select **Arduino Leonardo** it compiles correctly.

From Can't seem to be able use Keyboard.h library, this post states:

> Keyboard.h (and Mouse.h) only works on devices that use the ATmega32u4 processor, like the Leonardo or Micro. See: https://www.arduino.cc/en/Reference/MouseKeyboard

This solution might help though

> I had the same problem using Flora
>
> This worked for me:
>
> 1. Tools \> Boards \> Boards Manager
> 2. Install TeeOnArdu (Then select that board from Boards Manager)
> 3. Tools \> USB Type \> Serial, Keyboard, Mouse \< Joypad
> 4. Upload and run code again (might need to restart IDE)

---
Tags: keyboard
---


# Question
Title: What makes this library work exclusively with Atmega328P boards?
I've been looking into libraries that read CPPM signals that I can use on my Arduino Pro Micro, and this one looked promising (github.com/jmparatte/CPPM) until I read that it only works on Atmega328P chips. Sure enough, I tried it, and it doesn't function on the Pro Micro as it does on my Arduino Uno. Why is this the case, *i.e. what does it have that the Atmega32u4 doesn't*?

> **Implementation**
>
> This library works only on ATmega328 implementation of Arduino UNO, Duemillanove and similar, also Leonardo. It uses the 16bit Timer1. So PWM analogWrite() on pin 9 and 10 are unavailable. The library Servo is not compatible because it also uses Timer1.

I tried to do some research on my own, to no avail:

I'm new to this kind of thing and really stumped as to what could be the issue here.

# Answer
That library relies mostly on Timer 1 and, as you already noticed, the Timer 1 of the ATmega32U4 is very similar, if not identical, to the one of the 328P. At least similar enough to expect the library to work identically.

I took a look at both datasheets and the only difference I can see that can possibly affect the library is the pinout. The pins relevant to the library are:

```
       328P  32U4
ICP1 =  PB0   PD4
OC1A =  PB1   PB5

```

The pinout of the 328P is hardcoded into the library. CPPM.h contains these lines:

```
#define CPPM_ICP1 8 // Input Capture Pin of Arduino UNO is pin 8 - ICP1 (Atmega328 PB0)
#define CPPM_OC1A 9 // Output Compare Pin of Arduino UNO is pin 9 - OC1A (Atmega328 PB1)

```

CPPM.cpp has two instances (here and here) of this:

```
if ((PINB & _BV(PINB1))) // rising edge ?

```

If you change the code in these three places to match the pinout of the 32U4, I would expect the library to work for you.

You could also change that conditionally as

```
#ifdef __AVR_ATmega32U4__
    ...
#else // assume ATmega328P
    ...
#endif

```

in order to make the library compatible with both MCUs, and then submit a pull request to the original author.
> 1 votes

---
Tags: arduino-uno, arduino-pro-micro
---


# Question
Title: Does SoftwareSerial and the servo library produce interrupt conflicts?
I'm planning a project that will involve multiple serial ports and the Arduino servo library. I have heard that this may cause interrupt conflicts. Are there any simple solutions to this

# Answer
> 1 votes
> I have heard that this may cause interrupt conflicts.

Indeed. The Arduino can only run one interrupt routine at a time, and:

* Servos use rapidly firing interrupts
* SoftwareSerial both turns off interrupts while sending (for relatively long periods)
* SoftwareSerial uses an interrupt for receiving that runs for an extended period

So really you can't use both together.

Options?

1. Use hardware PWM to drive the servos (There is a library for this somewhere)
2. Use an external servo PWM driving board (Adafruit do one IIRC)
3. Don't use SoftwareSerial. IIRC AltSoftSerial is better, though no software serial implementation will ever be particularly good.

The underlying problem is that the low-end Arduinos only have on serial port. If you need to use more than one serial port then you really need to be looking at using a different Arduino - one with multiple serial ports.

---
Tags: serial, servo
---


# Question
Title: How to fix this code so instead of having to hold button to change led, you can press?
```
const int buttonPin = 1; // the pin number of the pushbutton input pin
const int ledPins[] = {2, 3, 4, 5, 10, 11, 12, 13};    // variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonPressCount = 0;
int numberOfLED = 8;

void setup() {    // initialize the LED pin as an output:
  for (int i = 0; i < numberOfLED; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT);
}

void loop() {    // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);    // check if the pushbutton is pressed.    // if it is, the buttonState is HIGH:
  if (buttonState  == HIGH) {
    for (int i = 0; i < numberOfLED; i++) {
      if (buttonPressCount % numberOfLED == i)
        digitalWrite(ledPins[i], HIGH);  // turn LED on
      else
        digitalWrite(ledPins[i], LOW);   // turn LED off
    }
  }
  buttonPressCount++;
  delay(300);
}

```

# Answer
> 2 votes
instead of changing every time the buttonState == HIGH, change it when the button state was `LOW` the previous time but `HIGH` now:

```
buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState && buttonState == HIGH) {
    //...
}
oldButtonState = buttonState;

```

However keep in mind contact bounce. Which can result in multiple transitions being detected. Most solutions for that set a minimal delay between handling transitions, dropping all others detected.

---
Tags: led, button
---


# Question
Title: How to use IRremote library with atmega8a
A few days ago I tested a circuit on a breadboard based on a ATmega8a with 1 MHz internal oscilator. It sould turn on and off a relay based on a IR code that is received and if it matches the programmed in the EEPROM it shoud enable or disable the relay. Now I developed a PCB and soldered everything together but now it isn't working. On an Arduino Nano it is working ok.

```
#include <IRremote.h>
#include <EEPROM.h>

int RECV_PIN = 11;
int RELAY_PIN = 4;
int setpin = 3;
unsigned long work_at;
unsigned long adres;
unsigned long irbuffer;
IRrecv irrecv(RECV_PIN);
decode_results results;

void dump(decode_results *results) {

    if(digitalRead(setpin) == 0){
      work_at = results->value;
      Serial.println(work_at, HEX);
    }
    irbuffer = results->value;

}

void eeprom_writer(){
  if (irrecv.decode(&results)) {
    if(digitalRead(setpin) == 0 && work_at != 0){
      EEPROM.put(0, work_at); //put walue
      Serial.println(work_at, HEX);
      adres = work_at;
      Serial.println(adres, HEX);
      delay(1000); //wait
   }
  }
}
void setup()
{
  EEPROM.get(0, adres);
  pinMode(setpin, INPUT_PULLUP);
  pinMode(RELAY_PIN, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();

void loop() {
  if (irrecv.decode(&results)) {
    // If it's been at least 1/4 second since the last
    // IR received, toggle the relay
  //  if(&results == adres){
      dump(&results);
      if (millis() - last > 250) {
        on = !on;
        if(on == true && adres == irbuffer){
          delay(5000);
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
        }else if(on != true  && adres == irbuffer){
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
          delay(5000);
        }
      }
    //}
//    Serial.println(dump(&results));
//    Serial.println(count, DEC);

    eeprom_writer();
    last = millis();
    irrecv.resume(); // Receive the next value
  }
}

```

# Answer
Changing the internal oscillator to 8MHz helped.
> 0 votes

---
Tags: arduino-nano, library, ir
---


# Question
Title: Do I need the Ground and 5 V pin connect to Led?
I am building an ambilight. So I bought a 3 pin LED Strip which I power with the USB hub from my TV. Next step is to connect it to the Arduino Nano. Is it OK when I only use the dataport from the Aduino and the power only from the television?

# Answer
> 2 votes
I think it is not a good idea to power the LED strip via USB.

Normally USB delivers a maximum of mA (see below). Assuming you have 30 LEDs (minimum for a normal LED strip), and each LED gives 40 mA (maximum), this is already more than what most USB ports can deliver. This can ruin your USB port.

For the Arduino Nano you can use the 5 V, and you should connect all GNDs together.

But you will need a decent adapter anyway for the LED strip, so than you can power your Arduino Nano from the adapter you use for the LED strip.

**Update**

According to Wikipedia USB power

> Low-power devices (such as a typical USB keyboard) may draw at most 1 unit load (1 unit load is 100 mA for USB devices up to USB 2.0, while USB 3.0 defines a unit load as 150 mA), and all devices must act as Low-power devices when starting out as unconfigured.
>
> High-power devices (such as a typical 2.5-inch USB Hard Drive) draw at least 1 unit load and at most 5 unit loads (500 mA) for devices up to USB 2.0 or 6 unit loads (900 mA) for SuperSpeed devices.

# Answer
> 1 votes
Yes, you can take +5v from the TV's USB and supply data from the Arduino, as long as you connect both the TV's USB-Ground and the Arduino-Ground together.

# Answer
> 1 votes
simulate this circuit – Schematic created using CircuitLab

Can you follow this? Connect all GNDs. TV 5V can power the Arduino, connect to the 5V/VCC pin and not the Vin pin. 5V power supply only powers the LED strip. No reason it couldn't power the Arduino as well tho, in which case there would be no need to connect to connect anything to the TV.

PC USB ports typically can only supply 500mA, only enough for 8 RGB LEDs at full white. I doubt your TV can do much more.

---
Tags: arduino-nano, power, usb, led-strip
---


title: 3V Arduino options

text:
# Question
Title: 3V Arduino options
I have an Arduino Mega board to test 3V devices. Which is the simplest way to connect those 3V devices to the Arduino Mega (it works at 5V) without burning them? I saw the Adafruit Trinket works at 3V, could be an option? Since I need many input/outputs (around 50), Arduino Mega is the most suitable in terms of input/outputs pins.

What do you suggest me to do?

# Answer
There are plenty of non-Arduno boards that both give you more power and 3.3V operation. Personally I love the chipKIT boards (the Max32 is the chipKIT equivalent to the Mega2560).

If you want to stick with Arduino then consider the Due, which is the same footprint as the Mega2560 but again with more power and 3.3V operation.

For interfacing 3.3V devices to a 5V board, though, that can be done simply with level shifters. You need to get the right type though:

* Basic GPIO, SPI and UART etc can be done with a simple MOSFET shifter (cheaply available on eBay)
* I2C requires a special I2C level shifter (I use the PCA9306) which maintains the open-drain and bidirectional operation required for I2C
> 1 votes

---
Tags: arduino-mega, voltage-level
---


title: HC-05/Arduino receiving spam data

text:
# Question
Title: HC-05/Arduino receiving spam data
I connected everything properly. On the first try I did receive data as I was supposed to. I then wrote some logic, re-uploaded and started receiving crazy spam.

My serial monitor is getting spammed with:

* question marks if the variable is `char`, or;
* `25252525252` if the variable is `int`, or;
* `-1` if variable is `String`.

I'm monitoring at 38400 baud which is the same as my `Serial.begin()`.

Any ideas ?

Code:

```
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define MIN_PULSE_WIDTH 650
#define MAX_PULSE_WIDTH 2350
#define DEFAULT_PULSE_WIDTH 1500
#define FREQUENCY 50

char data = 'a';

void setup()
{
  analogReference(DEFAULT);

  Serial.begin(38400);

  pwm.begin();
  pwm.setPWMFreq(FREQUENCY);
  Serial.println("hello world");
}

void loop()
{
  data = Serial.read();
  Serial.println(data);
  Serial.flush();
  if (data == 'a'){
    pwm.setPWM(0, 0, pulseWidth(90));
  }
  if (data == 's'){
    pwm.setPWM(0, 0, pulseWidth(30));
  }
  delay(1000);
  //printing time in seconds
}

int pulseWidth(int angle)
{
  int pulse_wide, analog_value;
  pulse_wide = map(angle, 0, 180, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  analog_value = int(float(pulse_wide) / 1000000 * FREQUENCY * 4096);

  return analog_value;
}

```

# Answer
`Serial.read()` returns -1 if no data is available. It doesn't wait for the byte. Test for -1 or use `Serial.available()` as any example does.

Replace `Serial.print(data)` with `Serial.write(data)` to get the data echoed back unchanged.
> 2 votes

---
Tags: arduino-uno, hc-05
---


# Question
Title: Weird behavior (Couldn't pull the pin LOW)
I was trying to implement my own code to control a stepper motor on arduino uno, however I noticed that the pins were always HIGH despite what was written to them. I started to erase the code to leave only the crucial part to troubleshoot it and was left with the following

```
#define IN1  8
#define IN2  9
#define IN3  10
#define IN4  11
long int *period;

void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
*period=256;
}

void loop() {
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, HIGH);
}

```

The period statements were leftovers from the previous code, and didn't think of them too much but once I deleted them the code started working. More over, the code worked if the period value was below 256. Once it reached 256 the pins weren't pulling low.

The problem is solved now, however I am interested why would a value of a variable cause such a behavior?

# Answer
> 7 votes
You are creating a pointer variable, not a normal variable.

That pointer variable is, until told otherwise, pointing at address 0x00. It covers 4 bytes.

Addresses 0x00 to 0x1F are the internal CPU registers R0 to R31. Your pointer variable points to R0 plus three more addresses above it (a long is 4 bytes in total).

So when you write to your pointer you are directly writing to CPU registers R0, R1, R2 and R3.

According to the AVR-GCC ABI:

* R0 is the scratch register
* R1 is the zero register
* R2 & R3 are general purpose (call-saved) registers.

So if you write 255 to your pointer variable you are doing:

```
R0 = 255
R1 = 0
R2 = 0
R3 = 0

```

And that's no big deal: some things may go a little awry, but nothing major.

However, writing 256 results in:

```
R0 = 0
R1 = 1
R2 = 0
R3 = 0

```

The big thing here is that the *zero register* R1 is now 1, not zero. The ABI states:

> **R1** always contains zero. During an insn the content might be destroyed, e.g. by a MUL instruction that uses R0/R1 as implicit output register. If an insn destroys R1, the insn must restore R1 to zero afterwards. This register must be saved in ISR prologues and must then be set to zero because R1 might contain values other than zero. The ISR epilogue restores the value. In inline assembler you can use `__zero_reg__` for the zero register.

So R1 must be zero except for a brief moment when you use it for something else. Since you're setting it to 1 and leaving it as one, any other operations that then rely on that register being zero will have a hard time knowing just what they are doing.

Having a "zero" register is a common thing. There are many times (especially in a RISC architecture) when you want the number zero - and having a register that is guaranteed to always be zero saves a lot of time. For instance, in MIPS the register $0 is hard-wired to be zero and can never change. AVR doesn't have that luxury, but the GCC compiler imposes the rule for R1 which you have to abide by - since there are huge amounts of library code and other auto-generated code that rely on that register being zero.

So when it's set to one, all gloves are off, and no one can ever really know just what is happening - you'd have to disassemble the code (or get an intermediate listing out of the compiler) to see just what is using R1, and work out what the effect of that being 1 instead of 0 would be.

As an example, `digitalWrite` has this:

```
        if (val == LOW) {
 370:   11 11     cpse r17, r1
 372:   05 c0     rjmp .+10          ; 0x37e <digitalWrite+0x50>

```

That's "COMPARE SKIP IF EQUAL". It's looking at the value you pass (`val`) to see if it's equal to zero - by using R1 as the zero value. But if R1 isn't zero then it will never know that what you passed as LOW is LOW - instead it would find HIGH as LOW, since HIGH is 1 and R1 is 1. So you've basically swapped HIGH and LOW over as far as `digitalWrite` is concerned.

There are also places where the number 255 is wanted. This is easy to generate with "eor r1,r1" - exclusive-or of the zero register. EOR turns bits off that are on and on that are off - so zero becomes 255. Except if zero is actually 1, you end up with 254 not 255, and more strange things happen.

# Answer
> 1 votes
You have an uninitialized pointer:

```
long int *period;

```

It will point to zero (or a register map, see comment Edgar Bonnet below), but you write 256 to it. Since a long pointer points to 4 bytes, if you write values upto 255 only one byte will be filled (and others are 0), when you write a value from 256, another byte will be filled with a non-zero value.

Anyway, uninitialized pointers can result in strange effects, so initialize it like:

```
long int period;

long int* periodPointer = .

```

And set the content by

```
*periodPointer = 256;

```

---
Tags: arduino-uno, pins, avr-gcc
---


# Question
Title: Arduino Uno with ESP8266-01. Is that any alternative way to connect Arduino Uno to Wifi
I have bought an ESP8266-01 Wifi module last month, and I am trying to connect Arduino Uno to network so that I could connect to the MQTT broker. However, I failed to upload the sketch/communicate with ESP8266 module due to the error:

```
espcomm_open failed
espcomm_upload_mem failed
espcomm_upload_mem failed

```

I think the problem is wiring problem or power supply is unstable because the ESP8266 is required 3.3V to communicate. This is how I connect ESP8266 Wifi module to Arduino Uno, and I just simply connect Arduino Uno to USB port on my laptop:

I've been searching solutions on Internet and watching tutorials but ending up with getting the same error. In addition, I am not using any resistor, capacitor when I do the connection between ESP8266 & Arduino Uno.

These are my confusions as below:

1. What is the best/easiest way to connect Arduino Uno to Wifi?
2. How can I avoid power supply issues? Maybe a Serial Adapter Wireless development board or module?
3. What do I need to connect Arduino Uno to Wifi?
4. Is it possible to connect Arduino Uno to MQTT broker without using network? I found this Ardulink but I don't know how to deal with it
5. Can external wifi shield solve my problem instead of using ESP8266-01?

Thank in advance

# Answer
The Arduino board does not have enough current available to power the ESP8266. You should have a 3.3 volt supply that is capable of at least 500mA. The average current consumption is typically 80mA but the peak currents can go to 600mA during a start up calibration.

You also need to use a proper level converter to connect the RX and TX of each board. The ESP8266 is NOT 5 volt tolerant.

The ESP8266 can be programmed under the Arduino framework. This is how most people use it. (rather than using the AT command set the board comes with. This is what I suggest, but is not a requirement. If you do go that way I suggest you get a NodeMCU or a Wemos type board to learn with. Just working with the ESP8266 alone. They are cheap, they have a USB to serial converter, and they have a proper regulator for Vcc.

The ESP modules are not simple to power. You have to use a good regulator and have it electrically close to the board. No 20cm jumper wires.

Continuing on with your electrical connections. Reset is not connected to ground. It should be pulled up to 3.3 volts with a resistor, typically 10K.

And external WiFi shield is a simpler option. I prefer the ESP8266 since it has a fast processor, 80 or 160Mhz. Lots of ram and up to 1MB of program space. It is my go-to board. It is a little light on IO but that is easy to add. It is cheap, and there is a huge user base for it.
> 0 votes

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


# Question
Title: Learn Arduino Basics : Temperature sensor with LCD Display and Potentiometer setup
I have temperature sensor, potentiometer and LCD screen attached to mini breadboard and wired to an Arduino. My temp sensor appears to be working fine however sometimes it reads inaccurate numbers which is unusual. It only does this when I have all my components on the same mini breadboard. When I detach then reattach my temperature sensor to a separate breadboard its hasn't been noticeably inaccurate. There is no issue but I was thinking that maybe the temperature sensor is hotter because its closer other to components or maybe because the close electrical wiring range is making it hotter. My solution is putting the temp gauge on another breadboard but I was save space to use one. Any ideas as why my gauge reads random hotter temperatures more often when sharing a board?

# Answer
> 2 votes
It could be measuring the heat of nearby components, or it could be a wiring issue. Breadboards are convenient but it also allows people to use poor wiring practices. Long wires, poor ground return paths, insufficient bypass capacitors.

The first thing to do is to arrange the layout so that there is little chance of the other components heating the sensor. You might also try using a fan to blow on all the components. Make it so that if there is any heat generated it does not accumulate it the parts. If that clears up the problem then look into making a better thermal layout. Maybe with the sensor physically separate from the rest of the circuit.

If the fan makes no difference then you may need to consider the way it has been wired.

---
Tags: temperature-sensor, temperature, breadboard
---


# Question
Title: Alternative Rx/Tx Pins for Arduino Uno and Pro Mini
Do they have specific pins that is best to be use as Rx/Tx pins (aside from D0 and D1)? If so, what makes them special?

edit: What pin feature i should look out for when choosing the rx/tx pin? Is there any specific pins that will make it a better rx/tx pin?

# Answer
> 2 votes
Pins `D0` and `D1` are used for *hardware serial*, see `Serial` library reference.

You can use any other pins for virtual Rx/Tx lines employing a *software serial* mode, for example by using the `SoftwareSerial` library, see Software Serial example, or by implementing your own custom code, or custom library.

# Answer
> 1 votes
The Arduino SoftwareSerial library can use any pair of pins.

AltSoftSerial uses special pins. AltSoftSerial uses a 16 bit hardware timer to generate the transmit output and measure the receive input waveforms. The timer works on pins 8 and 9 on Uno and Atmega 328p boards.

---
Tags: arduino-uno, softwareserial, rx-pin
---


# Question
Title: Arduino Pro Micro TX and RX leds flash quikly while power drawn from VCC pin
I just got a 5V Arduino Pro Micro, which I connected to an RC RX powered from the VCC and GND pins of the board.

However, whenever I do so and power on the board from a computer USB connection or a wall adapter USB connection, the board goes into an odd mode where the red RX and TX leds flash rapidly (*~0.5s on and ~0.5s off*) and USB serial ceases functionality. (*presumably, because the MCU isn't on anymore*)

If I remove the load and power the board again, everything works as normal.

This is an odd behavior, especially since I read online that the VCC pin is rated for ~150ma max and my device (FS-iA6b) isn't a very high power device, tested by me to draw 30-50ma max.

What is happening here? I haven't even connected the 5v signal pin yet!

# Answer
Aah, I figured it out! @JeffWahaus was correct, the RC RX was placing too great a strain on the Arduino Pro Micro. My latest working theory is that when the RC RX is in communication with the RC TX, it has current spikes that allow the system current draw to exceed that required to drop the voltage coming out of the 5V regulator below that required to shut off the ATmega32U4 MCU.

The solution I found, upon recommendation, was to move the RC RX voltage source from the `VCC` pin to the `RAW` pin which taps power from ahead of the 5V regulator and add a 10uf capacitor in parallel with the RC RX to smooth out any current spikes.

simulate this circuit – Schematic created using CircuitLab
> 0 votes

---
Tags: power, arduino-pro-micro
---


# Question
Title: What are the negative PINs for on the IndustrialShield M-Duino 58 Analog
I am working as an internship on an Arduino based PLC. It is the M-Duino 58 Analog from IndustrialShields. I try to figure out how it works; Reverse Engineering. But i dont know why it has negative Digital Inputs like normal Digital Input I1.0 also has a connection -I1.0. It is probably a simple question but i cant figure it out. Hope you guys can help me.

I guess i figured it out. Seems to be the GND connections. Should read the Manual better next time.

# Answer
It looks like those inputs are opto-isolated. That means that the "input" goes through a resistor and the internal LED of an opto-isolator, which then comes back out of the "-" pin:

simulate this circuit – Schematic created using CircuitLab

So "-" connects to the ground of the remote device, and the "input" connects to the signal.
> 1 votes

---
Tags: arduino-mega, atmega2560
---


# Question
Title: What is the necessity of "Prototyping Shield" for an arduino UNO R3?
I just want to learn Arduino and make some small projects. But in the beginner starter kit there's a part named Prototyping Shield. Is it necessary or will it help me?

# Answer
> 1 votes
A prototyping shield allows you to create your own circuit that can sit neatly on top of an Arduino. Its main advantage is the pins/holes to connect to the Arduino, as these aren't evenly spaced so they are difficult to replicate with strip-board. Do you need one? I doubt it very much, stick to the bread board and leave the soldering iron alone until you know what you are doing.

# Answer
> 0 votes
You can make a slightly neater project with a prototyping shield. You can use much shorter jumper wires are sufficient to connect to the Arduino pins than if the proto was on your bench beside the Uno. That makes the project much more easily portable without knocking wires out of place. And if the project is one you want to make permanent, you've already laid it out for a shield and you're pretty near ready to start soldering parts and wires to the board.

The shield is certainly not needed for prototyping. I don't own any; I keep a handful of solderless breadboards around for the purpose. But if I were planning to build a permanent Arduino shield, that's where I'd start.

---
Tags: arduino-uno, shields, prototype
---


# Question
Title: Using c_str() on String for IPAddress with NTPClient provides wrong values
## Libraries

## Board

Olimex ESP32-POE board

## Behaviour

I have written a code that connects the board to a local NTP Server (which is an embedded board). I tried assigning the IP Address of the above NTP Server using `IPAddress` and then convert it to `c_str()` to pass into the `NTPClient` constructor as follows:

```
 WiFiUDP ntpUDP; // udp socket object for NTP

 IPAddress NTPServer(192.168.3.11); // Local NTP Server IP Address

 NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000);

```

The reason for this is because the `NTPClient` class uses `const char*` for the IP Address of the NTP Server.

The values that are obtained once the code is flashed on the board are wrong because the timestamps are have the year `2106`.

On the contrary, when I use

```
 NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000);

```

and run the code on the board, this provides me perfect values of UTC time.

Why is there some discrepancy here?

# Code

```
#include <Wire.h>
#include <ETH.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <RTClib.h>

WiFiUDP ntpUDP;
/* IP CONF for NODE */
///////// >>>> MODIFY Values Here <<<< ////////
const IPAddress node_static_ip(192, 168, 3, 101);
const IPAddress default_gateway(192, 168, 3, 250);
const IPAddress subnet_mask(255, 255, 255, 0);
const IPAddress dns_add(192, 168, 3, 250);
const IPAddress NTPServer(192, 168, 3, 11);

NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000); // This works
NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000); // This won't (provides timestamps of 2106)

void setup() {
  // put your setup code here, to run once:
  Wire.begin(I2C_SDA, I2C_SCL);
  Serial.begin(115200);
  ETH.begin();
  ETH.config(node_static_ip, default_gateway, subnet_mask, dns_add);
  delay(1000);
  if (!rtc.begin()) {
    Serial.println("No RTC");
  }
  timeClient.begin();

}
void loop() {
  // put your main code here, to run repeatedly:
  timeClient.update();
  Serial.println(timeClient.getEpochTime());
  DateTime now_time(timeClient.getEpochTime());
  Serial.print(now_time.year(), DEC);
    Serial.print('/');
    Serial.print(now_time.month(), DEC);
    Serial.print('/');
    Serial.print(now_time.day(), DEC);
    Serial.print(now_time.hour(), DEC);
    Serial.print(':');
    Serial.print(now_time.minute(), DEC);
    Serial.print(':');
    Serial.print(now_time.second(), DEC);
Serial.println();

  delay(2000);

}

```

# Answer
The String object created as return from IPAddress.toString() as parameter to constructor of NtpClient is temporary. It contains the char array returned by c\_str(). NTPClient doesn't copy the string, only stores a reference to it. And the referenced string (char array) doesn't exist at the time the NTPClient wants to use it.

```
class TestClass {
public:
  TestClass(const char* _ip) : ip(_ip) { }

  void test() {
    Serial.println("--");
    Serial.println(ip);
    Serial.println("--");
  }

private:
  const char* ip;
};

//String s("abc");
//TestClass Test(s.c_str()); <- this works

TestClass Test(String("abc").c_str()); // <- this can't work

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

```
> 5 votes

---
Tags: ethernet, string, esp32, tcpip, c-string
---


title: Midi Timecode Fails to Send

text:
# Question
Title: Midi Timecode Fails to Send
I have an ATMEGA 2560 platform running HIDUINO and a sketch based on the stock MIDI library. I'm intending to use it to convert Linear Timecode (LTC) to MTC. Got a long way through the project - LTC decoding working fine, timer configuration OK, and Midi output working fine. It's just that as soon as I try and generate MTC messages, they are being dropped before they land on the computer USB interface.

Equipment to hand: Macbook Pro running El Cap/Reaper and Protools., ATMEGA2560 MEGA R3 (With 16u2 for HIDUINO) and small audio interface circuit.

Using Timer 4 for LTC Decoding and Timer 5 for MTC generation (4 messages per LTC Frame).

Midi Monitor on the OSX box.

Sees Note on/Note off packets quite happily, but no MTC messages are registering.

I do note the TX LED is active during MTC Message generation, indicating that the sketch is actually generating messages and sending them to the 16u2 chip.

Specifically, my question is how do I get the MTC messages through HIDUINO into the computer?

https://pastebin.com/pAXyq04s

# Answer
> 0 votes
The HIDUINO library supports only some MIDI message correctly; most System Common and System Real-Time message are buggy, and SysEx messages are not handled at all.

Try some other library, e.g., mocoLUFA.

# Answer
> 2 votes
If you clone my fork of the code, I have got this working. https://github.com/mwr9uk/mocolufa

I have generated a pull request to merge it with mainline.

---
Tags: midi
---


# Question
Title: Custom Classes - Redefinition of void error
I'm getting a redefinition error from my classes, but can't see what I did wrong.

**Error: Icon.cpp:3:6: error: redefinition of 'void Icon::setIcon(byte (\*)\[8\])'**

Can any help me out on this? Thanks!

**MyFile.ino**

```
#include "MyIcon.h"

MyIcon myIcon;

```

**MyIcon.h**

```
#ifndef MyIcon_h
#define MyIcon_h

#include "Arduino.h"
#include "Icon.h"

class MyIcon : public Icon {
  public:
    MyIcon();
};

#endif

```

**MyIcon.cpp**

```
#include "MyIcon.h"

MyIcon::MyIcon() {

  byte _icon[8][8] = {
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 2, 2, 2, 2, 1, 1},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {2, 1, 2, 2, 2, 2, 1, 2},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {1, 1, 1, 2, 2, 1, 1, 1},
    {1, 1, 2, 1, 1, 2, 1, 1},
    {0, 0, 0, 1, 1, 0, 0, 0},
  };
  MyIcon::setIcon(_icon);

```

**Icon.h**

```
#ifndef Icon_h
#define Icon_h

#include "Arduino.h"

typedef struct{
  byte r;
  byte g;
  byte b;
} RGB;

class Icon {
  public:
    Icon();
    inline virtual void setIcon(byte icon[8][8]){};
    inline virtual void setIconColors(RGB colors[3]){};
};

#endif

```

**Icon.cpp**

```
#include "Icon.h"

void Icon::setIcon(byte icon[8][8]) {
  __icon = icon;
}

void Icon::setIconColors(RGB colors[3]) {
  __colors = colors;
}

```

**Edited on 09/11/18**

I attempted the following changes, before I realised thanks to KIIV, that I couldn't use array like that.

My idea was to be able to getIcon() and get back the byte array, which is later used to light up specific leds on a NeoMatrix panel.

I thought I would be able to build an icon "library" by extending a base class, setting the correct byte array in the class, and using it as needed (MyIcon, MyOtherIcon, etc...)

Have I completely missed the point?

**Icon.h**

```
void setIcon(byte icon[8][8]);
void setIconColors(RGB colors[3]);

```

**Icon.cpp**

```
#include "Icon.h"

Icon::Icon(){ }

void Icon::setIcon(byte icon[8][8]){
  memcpy(__icon, icon, sizeof(icon));
}

void Icon::setIconColors(RGB colors[3]){
  memcpy(__colors, colors, sizeof(colors));
}

```

# Answer
You have bodies for `setIcon` and `setIconColors` in both the header file and the cpp file. You can only have them in one or the other - choose.

Also, as an aside, the way that you are assigning icon data will go out of scope before you use it. You create a local array variable which you then pass a pointer to to your constructor. That pointer is then saved. But then you go out of scope and the pointer is discarded, and the data will be overwritten.
> 2 votes

# Answer
As Majenko writes, you are having two bodies.

The bodies in the header file are empty and probably you do not want this. It is normal to implement the functions in the cpp file (which you do), so in the header file remove the {} in

```
inline virtual void setIcon(byte icon[8][8]){};
inline virtual void setIconColors(RGB colors[3]){};

```

so it becomes

```
inline virtual void setIcon(byte icon[8][8]);
inline virtual void setIconColors(RGB colors[3]);

```
> 0 votes

---
Tags: arduino-uno, c++
---


# Question
Title: How to do I2C on Arduino with SDA and SCL pin already used
i have a Arduino screwshield from sparkfun that I purchased: https://www.sparkfun.com/products/9729 which I used to put between my arduino uno and my 2.8" TFT LCD touch shield so that I am able to use the unused pins. I have to make an I2C connection between 2 Arduino Unos which I understand will require the A4 and A5 pins however the TFT currently uses both pins. also, my tft screen is from here: https://www.sgbotic.com/index.php?dispatch=products.view&product\_id=2756

The schematics of my tft are: http://www.sgbotic.com/products/datasheets/development/02756-schematic.jpg .

I am wondering if I can just use the A4 and A5 pins using the screw shield anyway since according to the schematics, the A4 pin is connected to the LCD\_RST or is the pin necessary for displaying images taken from the SD card? If that isn't the way, how should I go about doing it, does anyone know?

# Answer
No, you can't just use it. While I2C itself *may* work, the screen will keep resetting itself all the time and will be useless.

You may be able to get some luck with a software bit-banged I2C on other pins. However I would personally choose to modify the TFT screen's PCB and cut the LCD\_RST signal from the A4 pin and connect a 10kΩ resistor to +5V, or re-route it to another pin. That way you can then use I2C.
> 4 votes

# Answer
If the LCD is using A4/A5 for something besides I2C, than no you cannot.
> 1 votes

# Answer
As I have very little knowledge about Prototype connection.But to avoid the soldering problems,

You May use I2C adapters as well as I2C cable joiners will be much useful and are specially designed for expansion of more than 1 I2C modules at the same time.

Hope These Sheilds and Adapters will be helpful for you.
> 0 votes

---
Tags: arduino-uno, i2c
---


# Question
Title: Connecting wires and coding in GPS Module GY-NEO6MV2 with ESP8266-01
Here is the link : https://www.circuito.io/app?components=10167,11021,12083,13678,13959,975601

I'm just a beginner I don't have the idea on how GPS module wires should be connected

```
#include "DHT.h"
#include "NewPing.h"
#include <SoftwareSerial.h>
#define DEBUG true
 SoftwareSerial esp8266(11,10);
  //SoftwareSerial gps(8,9);
 #define DHTPIN 2       // DHT-11 Output Pin connection
 #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 float hum;
 float temp;

 DHT dht(DHTPIN, DHTTYPE);

 void setup() {
 Serial.begin (9600);
 Serial.println("START");
 esp8266.listen();
 esp8266.begin(9600);
 gps.begin(9600);
 dht.begin();

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sendData("AT+RST\r\n",2000,DEBUG);            // command to reset the
  module
     sendData("AT+CWMODE=2\r\n",1000,DEBUG);       // This will configure
     the mode
     as access point
   sendData("AT+CIFSR\r\n",1000,DEBUG);          // This command will get
   the ip
   address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);       // This will configure the
  esp
for multiple connections
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // This command will turn on
the
server on port 80
}

void loop()
{

 delay(2000);  // Delay so DHT-11 sensor can stabalize

 hum = dht.readHumidity();  // Get Humidity value
 temp= dht.readTemperature();  // Get Temperature value

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

long duration,distance;
duration= pulseIn(ECHO_PIN,HIGH);

distance = duration/58.2;

Serial.print("Humid: ");
Serial.print(hum);
Serial.print(" %, Temp: ");
Serial.print(temp);
Serial.print(" C, ");
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(50);

gps.listen();
while (gps.available())
Serial.write(gps.read());

esp8266.listen();
if(esp8266.available())         // This command will that check if the esp
    is sending a message
    {
    if(esp8266.find("+IPD,"))
    {
    delay(1000);

    int connectionId = esp8266.read()-48; /* We are subtracting 48 from the
    output because the read() function returns
                                        the ASCII decimal value and the
    first decimal number which is 0 starts at 48*/
     String webpage = "<head><meta http-equiv=\"refresh\" content=\"5;
     url=192.168.4.1/\"></head>";
     webpage += "<h1>Mabalacat City College Garbage Monitoring System</h1>";
    webpage += "<p><h2>";
    if (distance<=5)
    {
    webpage+= " Trash can is Red";
    }
    if (distance == 20)
    {
      webpage+= " Trash can is Orange";
      }
      if (distance == 35)
    {
      webpage+= " Trash can is Light Orange";
      }
      if (distance == 50)
    {
      webpage+= " Trash can is Yellow";
      }
      if (distance == 70)
    {
      webpage+= " Trash can is 2st Light Yellow";
      }
      if (distance == 85)
    {
      webpage+= " Trash can is 1st Light Yellow";
      }
      if (distance == 95)
    {
      webpage+= " Trash can is Green";
      }
      if (distance >= 100)
    {
      webpage+= " Trash can is Empty";
      }
      webpage+= "<br>";
      webpage+="Distance: ";
      webpage+=distance;
      webpage+=" cm";
      webpage+= "<br>";
      webpage+="Temperature: ";
      webpage+= temp;
      webpage+=" celsius";
      webpage+= "<br>";
      webpage+= "Humidity: ";
      webpage+= hum;
      webpage+= " %";

 webpage += "</h2></p></body>";
 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);
}
   }
  }

  String sendData(String command, const int timeout, boolean debug)
{
esp8266.listen();
String response = "";
esp8266.print(command);
long int time = millis();
while( (time+timeout) > millis())
{
  while(esp8266.available())
  {
    char c = esp8266.read();
    response+=c;
  }
}
if(debug)
{
  Serial.print(command);
  Serial.print("> ");
  Serial.print(response);
}
gps.listen();
return response;
}

```

# Answer
```
GPS - Arduino
---------------
GND -  GND
TX  -  pin of SoftwareSerial RX
RX  -  pin of SoftwareSerial TX
Vcc -  3.3 V

```

Only one instance of SoftwareSerial can listen. Method listen() determines which one. So you must add `esp8266.listen();` before talking to esp8266 and `gps.listen();` before talking to GPS module.

* in `setup()` add `esp8266.listen()` before first `sendData` call
* in `loop()` add gps.listen() before `while (gps.available())`
* in `loop()` add esp8266.listen() before `if (esp8266.available())`
> 0 votes

---
Tags: arduino-uno, esp8266, gps
---


title: Won't break out of for loop

text:
# Question
Title: Won't break out of for loop
I'm new to Arduino and I'm trying to use PWM to generate a tone through a buzzer. I've created a `for` loop, however, the `for` loop doesn't seem to break when the variable `ms` is \< 1000000.

```
int second = 1000000; //1 second in microseconds

void setup() {
  pinMode(3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  //Play middle C for 1 second
  for(int ms=0; ms <= second; ms+=3830)
  {
    digitalWrite(3, HIGH);
    delayMicroseconds(1915);
    digitalWrite(3, LOW);
    delayMicroseconds(1915);
    Serial.println(ms);
  }
  Serial.write("Finished C");
}

```

We can see on the serial output that the value of `ms` exceeds 1000000 but the `for` loop is still going. Can anyone see where I am going wrong?

# Answer
> 4 votes
An `int` can't hold 1000000. It is a *signed 16-bit variable*, which means it can only hold between -32768 and +32767.

To store larger numbers you need to use `long`, or `unsigned long` which are signed and unsigned *32-bit* variables.

# Answer
> 2 votes
In addition to Majenko's answer (an `int` on this platform can't hold a number greater than 32767) you have a second problem. You are evidently trying to make a middle C tone (261.6 Hz) by toggling a pin with a period of 1/261.6 seconds. However your Serial.println **takes time**. In particular at 9600 baud each byte you send will take 1/960 of a second (because there are 8 data bits, one start bit and one stop bit per byte), and assuming the number you are printing is roughly 4 digits, plus carriage return plus linefeed, you are sending 6 bytes for each time around the loop.

6 bytes of 1/960 (1042 µs) would be 6252 µs which completely dwarves your delays of 1915 µs.

Whenever you try to do things with timing loops you need to take account that **everything** in the loop takes time, not just your `delayMicroseconds` statements.

---
Tags: arduino-uno, pwm, piezo, buzzer
---


# Question
Title: Can I have two separated serial monitor for the same arduino board connected to PC?
I'd like to split serial communication into the two channels: 1) debug info, 2) application data.

There's only one Serial object to use.

However, maybe, there is an alternative way to print data separately, is there?

P.S. I use Nano and UNO.

# Answer
> 2 votes
As Majenko mentioned in his answer, you can connect a USB to UART adaptor such as a PL2303HX to your Uno (cost is $0.70 CDN). Just connect the RX, TX, GND pins to your Arduino correctly and include the SoftwareSerial Library in your sketch.

Here is a simple test sketch which is almost identical to the "SoftwareSerialExample" that comes with the SoftwareSerial Library.

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup(){
  Serial.begin(9600);
  Serial.println("Print to Serial Monitor");
  mySerial.begin(9600);
  mySerial.println("Print to SoftwareSerial");
}

void loop(){
  if(mySerial.available()){
    Serial.write(mySerial.read());
  }
  if(Serial.available()){
    mySerial.write(Serial.read());
  }
}

```

# Answer
> 5 votes
If you want to have two Serial Monitors, start the IDE twice. Use your desktop shortcut or start menu entry to start the second instance of the IDE. In the second instance you can select a different port. It will not work for Upload of course, but when you open the Serial Monitor, it will work at the selected port.

Other option is to use some terminal program to see the output of the com port.

The other answers cover the fact that you need an USB to TTL Serial adapter to connect to USB and in sketch SoftwareSerial as your second serial interface or use some board with two or more hardware serial ports like the Mega on the picture.

# Answer
> 1 votes
Not without adding more hardware, no.

You could add a usb to UART adapter and use software serial. Better would be to switch to a board that has a proper usb connection and a usb stack that supports multiple CDC/ACM instances, like a chipKIT board (Lenny, for instance).

# Answer
> 1 votes
You can add another channel with the SoftwareSerial library and an FTDI cable. The cable costs about US$17 in the US and is available here from Amazon, Sparkfun, and probably others. Internationally, I don't know. The SoftwareSerial library does have some limitations, most notably that it has to interrupts off while it's actually operating to get its baud rate right. But it does work and may be the simplest solution for you.

# Answer
> 1 votes
Depending on your software environment, the simplest thing may be to send all the data multiplexed through the single serial port, then split it into two channels at the other end. For that, you will need some sort of multiplexing protocol. If all your data is text and line oriented, this may be as simple as prefixing each line with "1" or "2" to select the appropriate channel:

```
Serial.println("1This app data goes to stdout.");
Serial.println("2This diagnostic message goes to sterr.");

```

If you want to send arbitrary byte streams, you would instead use two control characters for selecting the channels and an "escape" character for when you want the control characters to be transmitted literally.

For convenience, you could encapsulate this logic into two separate objects and implement `stdout.println()` and `stderr.println()`.

Then on the computer side, you will have to write a program that reads the serial port and splits the received bytes into two separate streams. How you implement those streams is OS-dependent. On an Unixish system I would probably use pipes, or pseudo-terminals if I needed bidirectional communication.

---
Tags: serial
---


# Question
Title: Arduino Adafruit playground: Adafruit_CPlay_LIS3DH.cpp:27:35: fatal error: Adafruit_CPlay_LIS3DH.h: No such file or directory
I've tried installing the Arduino Adafruit playground but came across the same error.

```
sketch\src\Libraries\Adafruit_Circuit_Playground\utility\Adafruit_CPlay_LIS3DH.cpp:27:35: fatal error: Adafruit_CPlay_LIS3DH.h: No such file or directory

 #include <Adafruit_CPlay_LIS3DH.h>

                                   ^

compilation terminated.

exit status 1

```

I don't really know what else I can try. I've tried reinstalling the library and different versions of the Arduino IDE but is doesn't seem to work.

IDE version: 1.8.7

Playground version: 1.8.1

# Answer
> 0 votes
Sorry completely forgot about this post. Apparently I had a folder in my project with the playground library that wasn't updated. When I removed this folder everything worked fine.

---
Tags: adafruit
---


# Question
Title: Arduino Comms disrupted, prevents program loading (catch 22)
I have written some software which, when loaded onto an Arduino Micro, blocks communications for some reason. Lets stipulate that there is something wrong with it.

Using the Ardiono IDE on Windows 10, and (ex internet) pressing the board's reset button twice within 5 seconds of power-up, then (device manager) a comms port comes into existence for 2 seconds, presumably under control of the micro-controller's bootstrap program.

In the IDE, you can only select an existing comms port. As above, a comms port comes into existence for 2 seconds.

The download button causes compilation and downloading to the comms port - typically taking 8 seconds.

Thus, one can only replace the duff program by selecting the briefly available comms port, compiling and downloading to it, which takes longer that the port availability window.

And so replacing the duff code with anything is impossible. Have I missed something here? Does anyone have some "emergency" code that waits for a port to appear and immediately loads something innocuous?

BTW the Tags restriction is preventing me from using meaningful tags.

# Answer
I would suggest:

1. Turn on verbose compilation in the IDE.
2. Set up as you have been with the right port selected and go to upload - it will fail as normal
3. Find the `avrdude` command in the verbose output and copy the full command and its parameters
4. Open a command prompt or terminal window and paste in the command you copied (but don't run it yet).
5. Press reset twice to trigger the serial port creation
6. Run the command you pasted. It should immediately start uploading and "fix" your problem.
> 1 votes

---
Tags: communication, arduino-micro, ide
---


# Question
Title: How to access a website running on my localhost(host/server) to Serial Monitor using ESP8266(Client)?
The following source code is from the official ESP8266 website(Explanation provided): https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-examples.html
This .ino code returns the html code of the server name mentioned in "const char\* server" declaration, on to the Serial Monitor.

And Yes, this code perfectly returned the html codes of wwww.google.com, www.arduino.cc etc. But when I try it with my 'led blinking.html' I am unable to find any luck. I guess it is because the website should be hosted on a live server.

**Other Details:**
1. uC Board: Wemos D1 mini (An ESP8266 Variant)
2. I am using Xampp to run Apache server and MySQL
3. Wemos board is set up as a WiFiClient

```
#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "xxxxxxxx";

```

**I have put the html,php code of the website in the directory :** C:/xampp/htdocs/LED BLINKING/led blinking.html

**IP Address of my Windows PC:** 192.168.100.9

```
const char* server = "192.168.100.9/LED BLINKING/led blinking.html";

```

I tried with just "192.168.100.9"; too. I also unblocked the windows firewall for my ApacheHTTP Server. Now I can view the webpage on my mobile with the URL: 192.168.100.9/LED BLINKING/led blinking.html.

```
void setup()
{
  Serial.begin(115200);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  WiFiClient client;

  Serial.printf("\n[Connecting ...");
  if (client.connect(server, 80))
  {
    Serial.println("connected]");

    Serial.println("[Sending a request]");
    client.print(String("GET /") + " HTTP/1.1\r\n" +
                 "server: " + server + "\r\n" +
                 "Connection: close\r\n" +
                 "\r\n"
                );

   Serial.println("[Response:]");
    while (client.connected())
    {
      if (client.available())
      {
        String line = client.readStringUntil('\n');
        Serial.println(line);
      }
    }
    client.stop();
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

```

The output on Serial Monitor is: Connecting to ssid connected \[Connecting connection failed!\]

# Answer
> 2 votes
Variable `server` is a hostname or IP address for TCP connection. The `/LED BLINKING/led blinking.html` goes after HTTP GET. Now there is `/` and it worked for main page of servers.

You need

```
client.print(String("GET /LED%20BLINKING/led%20blinking.htm") + " HTTP/1.1\r\n" +
             "server: " + server + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

```

and you must escape the space

---
Tags: esp8266, wifi
---


# Question
Title: Broken Arduino Uno, works over USB but cannot take DC in
My Arduino Uno (r3) board seems to be broken. It can still be powered over USB, and can store/run code properly, but the DC power in system appears to be crippled. I'm not entirely sure what happened, but I was most likely being careless with the power in and the vin pin. I'm not sure what component(s) are broken, but when I plug in 12v into the barrel connector, the uno doesn't power on. I can read about 0.6 volts from the 5 volt pin, and at some other locations on the board. Besides the 0.6, the only other voltage I read is the 12 volt, although it is slightly lower than the power supply, which outputs about 12.2 volts. How can I go about fixing this? Or is it even worth it?

# Answer
As you have noticed, measuring voltages is the first step. Here's some voltages for you and what they mean if they aren't there. These are all assuming precisely 12V in through the barrel jack. They are in order of "priority" - start at the top and work down, the first one that fails is your culpret (i.e., the barrel jack feeds VIN through the diode, VIN feeds 5V through the 5V regulator, and 5V feeds 3.3V through the 3.3V regulator).

* Roughly 11.4V on VIN - if it's not there the input protection diode has blown
* 5V on the 5V pin - if it's not there the 5V regulator has blown
* 3.3V on the 3.3V pin - if it's not there the 3.3V regulator has blown

Fixing it may be as simple as replacing the faulty component identified above - although they are all surface mount and some are more tricky to replace than others. That said, if it is (as it sounds) the 5V regulator that has gone, that is one of the larger components (SOT-223) so should be eaiser to replace. Also it's dirt cheap - I get them for a few cents each in bulk.
> 3 votes

---
Tags: power
---