title: PROGMEM for IR command storage

text:
# Question
Title: PROGMEM for IR command storage
I'm working on a code that is able to send raw data as IR signal to IR transmitter, the memory of arduino Nano is not enough to store the array in SRAM storage,so i'm about to use PROGMEM to store arrays in flash memory.

these are arrays for IR signal raw command:

```
unsigned int irSignaloff[]={6060, 7420, 532, 1652, 544, 1668, 508, 1688, 508, 1688, 508, 1692, 532, 1664, 532, 1664, 532, 1664, 536, 604, 528, 588, 548, 580, 552, 580, 528, 636, 500, 600, 532, 588, 548, 580, 552, 1644, 552, 1644, 528, 1664, 532, 1668, 532, 1664, 532, 1668, 528, 1668, 528, 1668, 508, 624, 536, 600, 532, 600, 536, 576, 528, 600, 532, 604, 532, 604, 532, 580, 552, 1648, 548, 1648, 552, 1644, 552, 1648, 552, 1644, 552, 1640, 556, 1644, 528, 1668, 528, 600, 508, 624, 512, 620, 536, 600, 536, 604, 528, 576, 508, 624, 532, 604, 532, 1660, 536, 1660, 540, 596, 536, 1644, 552, 1648, 552, 1644, 552, 580, 524, 1672, 524, 604, 508, 624, 536, 1660, 536, 632, 504, 580, 552, 608, 500, 1668, 528, 600, 508, 1688, 512, 1684, 560, 1668, 504, 660, 500, 1660, 536, 604, 532, 1656, 540, 1660, 540, 584, 548, 580, 528, 596, 512, 1688, 508, 660, 500, 1660, 536, 596, 540, 584, 548, 604, 500, 1672, 528, 600, 512, 1684, 512, 620, 540, 1656, 540, 600, 536, 580, 552, 1644, 552, 576, 528, 1668, 532, 600, 508, 1688, 536, 596, 536, 1660, 540, 1660, 536, 7420, 536};

unsigned int irSignalon[]={6156, 7336, 592, 1588, 612, 1584, 612, 1588, 608, 1588, 608, 1588, 604, 1592, 604, 1592, 604, 1592, 604, 528, 504, 628, 588, 548, 588, 552, 580, 524, 608, 524, 572, 560, 592, 540, 588, 1608, 592, 1604, 592, 1604, 592, 1608, 592, 1604, 592, 1604, 592, 1604, 596, 1600, 596, 524, 608, 520, 584, 544, 596, 540, 596, 536, 596, 524, 608, 520, 604, 524, 588, 1608, 588, 1608, 588, 1608, 588, 1608, 588, 1612, 536, 1660, 572, 1624, 572, 1628, 564, 600, 504, 628, 504, 580, 528, 600, 636, 528, 540, 564, 532, 588, 548, 604, 504, 1664, 532, 604, 504, 624, 536, 1660, 532, 1664, 532, 1664, 532, 604, 532, 1660, 536, 584, 548, 1652, 548, 1644, 552, 580, 556, 572, 532, 604, 532, 1664, 532, 600, 532, 1668, 532, 1660, 536, 1688, 532, 600, 536, 1664, 532, 584, 620, 1576, 552, 1644, 552, 576, 532, 604, 608, 524, 532, 1664, 608, 512, 620, 1576, 548, 580, 556, 572, 600, 536, 604, 1588, 608, 528, 536, 1660, 536, 584, 620, 1580, 620, 508, 596, 532, 508, 1688, 512, 620, 536, 1660, 604, 532, 608, 1588, 604, 516, 620, 1576, 620, 1576, 624, 7308, 552};

```

and this is sending command uses IRemote.h library:

```
 irSend.sendRaw(irSignalon, sizeon, FREQ_KHZ, false);

```

so how can i use PROGMEM to store and read this int array in order to send them? thanks

# Answer
If your IR library does not support sending signals stored in PROGMEM, then you will have to provide the data in RAM. However, you do not have to keep *both* signals in RAM permanently: only the one you are about to send needs to be there.

I suggest you keep all the IR signal data in PROGMEM while not sending them. Whenever you want to send a signal, you copy it to a RAM-based buffer and give the address of that buffer to the library. The same buffer will be reused for any signal you are sending. This will cost you some CPU time for the copy, and save 394 bytes of RAM. The savings will scale up if you add more signals to your sketch.

```
const size_t signal_size = 197;

static PROGMEM const uint16_t irSignaloff[signal_size] = { ... };

static PROGMEM const uint16_t irSignalon[signal_size] = { ... };

/* Send an IR signal from PROGMEM. */
void send_signal(const uint16_t *signal) {
    static uint16_t signal_buffer[signal_size];
    memcpy_P(signal_buffer, signal, signal_size * sizeof *signal);
    irSend.sendRaw(signal_buffer, signal_size, FREQ_KHZ, false);
}

//...
send_signal(irSignalon);
send_signal(irSignaloff);

```

Here I am assuming that all your signals have the same length, which is true for the example you show, but may be false if you add more signals later. You may then need to size the buffer as the longest of all your signals, and provide the signal length as an extra parameter to `send_signal()`.

Note that the RAM buffer does not need to be static. I chose to make it static here only in order for avr-size to give you a good estimate of the memory requirement of the program.
> 1 votes

---
Tags: arduino-nano, ir, progmem
---


title: Stopping the program after 1 second

text:
# Question
Title: Stopping the program after 1 second
I am a Beginner in Arduino Programming. I am working on a project where I control A DC motor with IR sensor and arduino.

Until here it is fine. But I want the Motor to stop after one second even though the IR sensor detects the Obstacle

Here's My Program

Pin 2- IR Sensor Pin 4,5,6- Motor

```
enter code here
//Included Libraries
#include <motor.h>

//MACROS are defined here
Motor Motor1(4, 5, 6);

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

    pinMode(2, INPUT);

}

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

    if(digitalRead(2)) {
        Motor1.moveMotor(2.55*0);
    }
    else {
        Motor1.moveMotor(2.55*100);
    }
}

```

Can anyone help out in this Program. I Just want the Motor to stop after one second. Thank you in advance!

# Answer
> 0 votes
You need to use read the time (`millis()`) when you start the motor and read it frequently while the motor is running to know when to stop it. You also need to keep track of the sensor, and don't start the motor again until after you've seen the sensor turn off (detect no obstacle). Here is an outline of the logic in psuedo-code; turn this into a detailed `loop()` function in C++:

```
if the motor is ON {
  if (millis() - motorStartMillis) > 1000 {
  stop the motor;
}
else if sensor is ON {
  if the sensor was OFF {
    start the motor;
    motorStartMillis = millis();
    sensorWasOn = true;
  }
}
else {      // sensor must be off
  sensorWasOn = false;
}

```

---
Tags: arduino-uno, programming, motor, loop, sketch-size
---


title: NodeMCU Power supply

text:
# Question
Title: NodeMCU Power supply
I got a question about externally powering my NodeMCU V3. It has an onboard voltage regulator (3v3) which breaks out to 3 header pins. Now I want to power 3v3 from an external board. Can I supply 3v3 to all of those pins at the same time? (Basically connected in parallel). Anyone has done this before or has this experience with NodeMCU V3?

I have supplied a link below: https://www.theengineeringprojects.com/2018/10/introduction-to-nodemcu-v3.html

Thanks a lot!

# Answer
> 1 votes
Yes, you may connect all `3V` pins together (red) and all `GND` pins together (black), like so:

In some cases, more wires will improve the circuit. E.g. when you build the Ben Eater 8-Bit CPU, you'll find that connecting power in a ring instead of a line will reduce voltage drop by about 50%.

---

When first reading your question, I got the impression that you wanted to solder the 3.3 V wires directly to the voltage regulator. Here's my original answer for that:

That's not a good idea: if you connect the same wire to all pins, your're creating a short, typically causing a malfunction if not worse. You may destroy your equipment (external board as well as the NodeMCU v3). Do NOT connect 3.3V to all pins of the voltage regulator.

A voltage regulator has 3 pins:

* voltage in (for an unregulated voltage you can't exactly control; typically higher than the output voltage)
* voltage out (for the stabilized resulting voltage you want to have)
* ground

The only pin to connect the voltage to is the "voltage in" pin (VIN). And typically, a development board has a pin for that:

However, you'll find that the input voltage must be between 4.75V and 10V, so supplying 3.3V from an external board is not sufficient.

If you have regulated (stable) 3.3V already, you can connect that to a pin labelled 3V:

Also, you need to connect the grounds (GND) of both circuits together (GND of external board to GND of NodeMCU), otherwise the current will not find its way back.

---
Tags: power, nodemcu, electronics
---


title: ESP32 proper DS18B20 wiring

text:
# Question
Title: ESP32 proper DS18B20 wiring
I want to connect a DS18B20 to my newly bought Heltec ESP32 LoRa (V2). For initial testing I have used some standard code:

```
#include "heltec.h"
#include <OneWire.h>
#include <DallasTemperature.h>

OneWire ds(14);
DallasTemperature sensors(&ds);

void getDS18B20values()
{
  Serial.print(" Requesting therms...");
  sensors.requestTemperatures();
  Serial.println("DONE");

  uint8_t count = sensors.getDeviceCount();
  for (int i = 0; i < count; i++)
  {
    Serial.print("Temperature " + String(i) + "is: " + String(sensors.getTempCByIndex(i)));
  }

  delay(1000);
}

void setup()
{

  //WIFI Kit series V1 not support Vext control
  Heltec.begin(
      true /*DisplayEnable Enable*/,
      true /*Heltec.LoRa Disable*/,
      true /*Serial Enable*/,
      true /*PABOOST Enable*/,
      868E6/*long BAND*/);

  sensors.begin(); // initialize therm-sensors
}

void loop()
{
  getDS18B20values();

  delay(1500);
}

```

Here's a quick schematic I designed with the designer provided by stackexchange. Not all parts were available so I had to improvise a litte. I hope it is accurate enough.

simulate this circuit – Schematic created using CircuitLab

Another weird thing is that if I wire it all up I can start the ESP but I can't flash any new software to it because it doesn't react. So I assume it's a wiring issue the code should be fine but I posted it anyway. I had tested it with multiple DS18B20 sensors. A while ago on an Arduino they were all still working. I am more experienced with Arduinos than with ESPs. Are there any differences in regard to the wiring I have to be careful of?

Edit: I already have some sensored wired to the ESP, a BH1750, DHT11, an analog soil moisture sensor and an analog light dependent resistor.

# Answer
I have not checked your code, but you certainly have a wiring issue.

There are two main problems.

1. Your Vcc is connected to the data output of the DS18B20. This means you will never read anything except logic "high" from the data output.
2. The 4k7 resistor should not be connected this way. See the schematic below on how it should be connected. You could also set up a data pin with an internal pullup so you don't need an external pullup.

This is roughly how it should look.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: esp32, wires, ds18b20
---


title: myserial.available() returns zero byte

text:
# Question
Title: myserial.available() returns zero byte
I wrote an Arduino program that requires two ports for serial communication. I intended to use both hardware serial and software serial, but the problem is receiving data from receiving buffer of the software serial: it always returns zero byte from `myserial.available()`.

For clarity I used the software serial example in Arduino IDE ver. 1.8.4. I tried to change the baud rate but still the problem persists. I read somewhere that they made some code changes in the SoftwareSerial library's .cpp and .h files. I tried to find the site without success. And my PC where I installed those libraries was stolen. Before that it was working properly.

The mistake I made is that I just copied the code and pasted in the library without concentrating on it. Here is the example of program with two serial ports.

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

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

```

# Answer
The SoftwareSerial example code https://www.arduino.cc/en/Reference/SoftwareSerialAvailable shows that the pins used as tx and rx for SoftwareSerial need to be defined using pinMode() as digital input and output.

> Example

```
// include the SoftwareSerial library so you can use its functions:
#include <SoftwareSerial.h>

#define rxPin 10
#define txPin 11

// set up a new serial port
SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

void setup()  {
  // define pin modes for tx, rx:
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()>0){
    mySerial.read();
  }
}

```
> 2 votes

# Answer
Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69). Not all pins on the Leonardo and Micro support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
> 1 votes

---
Tags: arduino-uno, serial, softwareserial
---


# Question
Title: what command should i use to read and write through spi.tranfer command
```
#include<spi.h>
byte val;     // variabe for storing temp data
#define PIN_SPI_SS    (9)
#define PIN_SPI_MOSI  (10)
#define PIN_SPI_MISO  (11)
#define PIN_SPI_SCK   (12)

void setup();
pinMode(SS,output);
pinMode(SCLK,output);
pinMode(MOSI,output);
spi.setBitorder(MSBFIRST);
SPI.setDataMode(SPI_MODE3);
serial.begin(9600);
spi.begin();

void loop();
  digitalWrite(SS,LOW);
  uint8_t b1 = SPI.transfer(0x00);
  uint8_t b2 = SPI.transfer(0x00);
  uint8_t b3 = SPI.transfer(0xFF);
  digitalWrite(SS,HIGH);
  int16_t val = b1 | b2 ;
  serial.print("val=");
  serial.println(val,DEC);

```

refer for DATA SHEET//https://www.ti.com/lit/ds/symlink/lm74.pdf?ts=1591436049550&ref\_url=https://www.ti.com/product/LM74 my problem is i am not able to know what command should i use in SPI.transfer function for writing & reading temperature data here i use 0x00 for reading 16 bit data of temperture register,but what about writing in configuration register ,LM74 use 0xFF command for shutdown mode,but how we came to know that 0xFF refer only to configuration register.

# Answer
In the LM74 the third byte you send (or more specifically the last 8 bits of *up to* 32 bits past the 16th bit that you send) is read and used as the configuration register setting.

Since the configuration register only has two states `0xFF` is go to sleep sleep and `0x00` is do conversions (as shown in table 1 of the datasheet).

So:

```
0x00 0x00 0xFF

```

means get one result then go to sleep.

```
0x00 0x00 0x00

```

means get one result and stay awake.

If the LM74 is currently asleep from an `0x00 0x00 0xFF` sequence the result you get returned is not a temperature but the chip's manufacturer ID.

It's not an obvious method of controlling a chip, and it's actually pretty poorly written in that datasheet, so don't feel bad about not understanding it, it took me a few moments to understand it.
> 1 votes

---
Tags: arduino-uno, spi, temperature-sensor
---


# Question
Title: When does the ADC start reading again in interupt mode?
Simple question, I have set my ADC to read in "continuous"/interrupt mode and I take the reading the following way:

```
ISR(ADC_vect) {
   int val = ADCL;
   val += ADCH << 8;
   ... //Code to do stuff with reading here.
   }

```

My question is does the ADC start the new reading as soon as I have read the ADCH register or does it wait for the code inside the interrupt to finish? Basically I need to know if having more instructions in the interrupt will slow down my reading rate.

I don't have an oscilloscope or any good way to measure my reading rate accurately enough to know if a few extra lines of codes is affecting the rate or not.

# Answer
Your answer is correct. The ADC does indeed keep going independently of what the ISR does. There is, however, a point I would like to make clearer. You asked:

> My question is does the ADC start the new reading as soon as I have read the ADCH register or does it wait for the code inside the interrupt to finish?

The ADC starts a new reading as soon as it is done taking the previous one, *irrespective of* whether you read ADCH or not. When your ISR starts, the ADC is already busy making the following conversion. This guarantees a steady conversion rate, at one A/D conversion every 13 ADC clock cycles exactly.

As a side note, you can read the result with

```
int val = ADC;

```

No need to read the bytes separately unless you are using a very ancient version of gcc that does not know how to read a 16-bit register.
> 2 votes

# Answer
Ok, I'm pretty sure I know the answer to this one now after some more testing. I played around with the number of instructions performed inside the ADC interrupt call and simply timed it using micros(). Though it did not give me super precise accuracy there was a clear and quick drop in read frequency when the number of CPU cycles needed inside the interrupt call exceeded the number of CPU cycles needed by the ADC while the frequency was hardly affected when the CPU cycles needed for the instructions were less than the cycles needed for the ADC. The only way I can make sense of this is if the ADC keeps going independently of the code that's inside the interrupt.

If someone wants to correct me/add some details here I would be very happy. But for my purposes this answer is enough :)
> 0 votes

---
Tags: adc
---


# Question
Title: ESP32 using PubSub, creating an error when implemted inside a library
I wish to combine into a single library Wifi + MQTT, for a multi devices project.

right after boot, getting Wifi - I get an error the moment MQTT server is trying to connect: `mqttClient.connect(DEVICE_TOPIC, MQTT_USER, MQTT_PASS, MQTTavltopic, 0, true, "offline");`

yields :

```
WiFi connected
IP address: 192.168.3.186
Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x400d26bd  PS      : 0x00060630  A0      : 0x800d28e8  A1      : 0x3ffb1eb0
A2      : 0x3ffc116c  A3      : 0x3f4010ef  A4      : 0x3f40108c  A5      : 0x3f4010b7
A6      : 0x3ffc106c  A7      : 0x00000000  A8      : 0x800d26b6  A9      : 0x3ffb1e90
A10     : 0x00000000  A11     : 0x3ffc116c  A12     : 0x0000000e  A13     : 0x00000010
A14     : 0x0000000e  A15     : 0x3ffb1d94  SAR     : 0x0000000c  EXCCAUSE: 0x0000001c
EXCVADDR: 0x00000000  LBEG    : 0x400014fd  LEND    : 0x4000150d  LCOUNT  : 0xfffffffc

Backtrace: 0x400d26bd:0x3ffb1eb0 0x400d28e5:0x3ffb1ef0 0x400d0fa6:0x3ffb1f20 0x400d103b:0x3ffb1f50 0x400d0e59:0x3ffb1f90 0x400d3651:0x3ffb1fb0 0x40088b7d:0x3ffb1fd0

Rebooting...

```

I'm sharing both `.h` and `.cpp` files. Library is at its begining - so don't pay attention for irrelevant/ immature parts.

TNX

this is `.h` file:

```
#ifndef myIOT32_h
#define myIOT32_h
#include "Arduino.h"

// #include <ESPmDNS.h>
// #include <WiFiUdp.h>
// #include <ArduinoOTA.h>
#include "time.h"
#include "WiFi.h"
#include "secrets.h"
#include <PubSubClient.h>

class myIOT32
{

#define DEVICE_TOPIC "ESP32_SLEEP"
#define MQTT_PREFIX "myHome"
#define MQTT_GROUP ""
private:
    char MQTTmsgtopic[50];
    char MQTTlogtopic[50];
    char MQTTavltopic[50];
    char MQTTdevtopic[50];
    char MQTTlastctopic[50];
    struct tm _timeinfo;
    time_t _epoch_time;
    bool _wifi_status = false;
    char *wifi_ssid; // = "WIFI_NETWORK_BY_USER";
    char *wifi_pass; // = "WIFI_PASSWORD_BY_USER";
    char *mqtt_server;
    char *user = "";
    char *passw = "";

    WiFiClient espClient;
    PubSubClient mqttClient;

public:
    myIOT32(char *devTopic = "no-name", char *ssid = SSID_ID, char *wifi_p = PASS_WIFI, char *mqtt_broker = MQTT_SERVER1, char *mqttU = MQTT_USER, char *mqttP = MQTT_PASS, int port = 1883);
    void looper();
    void start();
    void mqtt_pubmsg(char *msg);
     bool use_wifi = true;
     void startMQTT();

private:

    void MQTTloop();
    void startNTP(const int gmtOffset_sec, const int daylightOffset_sec, const char *ntpServer);
    bool startWifi();
    void getTime();
    void MQTTcallback(char *topic, byte *payload, unsigned int length);
    void createTopics();
    void connectMQTT();
    void subscribeMQTT();
};

```

# endif

and my `.cpp` file

```
#include "myIOTesp32.h"

myIOT32::myIOT32(char *devTopic, char *ssid, char *wifi_p, char *mqtt_broker, char *mqttU, char *mqttP, int port)
{
  mqtt_server = mqtt_broker;
  user = mqttU;
  passw = mqttP;
  wifi_ssid = ssid;
  wifi_pass = wifi_p;
}
void myIOT32::start()
{
  if(startWifi()){
      getTime();
      startMQTT();
  }
}
void myIOT32::looper()
{
  MQTTloop();
}

void myIOT32::MQTTcallback(char *topic, byte *payload, unsigned int length)
{
  char incoming_msg[150];
  char msg[100];

  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");

  for (int i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]);
    incoming_msg[i] = (char)payload[i];
  }
  incoming_msg[length] = 0;
  Serial.println();
}
void myIOT32::createTopics()
{
  sprintf(MQTTmsgtopic, "%s/%s", MQTT_PREFIX, "Messages");
  sprintf(MQTTlogtopic, "%s/%s", MQTT_PREFIX, "log");
  sprintf(MQTTdevtopic, "%s/%s", MQTT_PREFIX, DEVICE_TOPIC);
  sprintf(MQTTavltopic, "%s/%s", MQTTdevtopic, "Avail");
  sprintf(MQTTlastctopic, "%s/%s", MQTTdevtopic, "nexton_command");
}
void myIOT32::connectMQTT()
{
  if (!mqttClient.connected())
  {
    mqttClient.connect(DEVICE_TOPIC, MQTT_USER, MQTT_PASS, MQTTavltopic, 0, true, "offline");
  }
}
void myIOT32::subscribeMQTT()
{
  mqttClient.subscribe(MQTTdevtopic);
  mqttClient.subscribe(MQTTlastctopic);
}
void myIOT32::mqtt_pubmsg(char *msg)
{
  mqttClient.publish(MQTTmsgtopic, msg);
  Serial.print(MQTTmsgtopic);
  Serial.print("/");
  Serial.println(msg);
}
void myIOT32::startMQTT()
{
  mqttClient.setServer(mqtt_server, 1883);
  mqttClient.setCallback(std::bind(&myIOT32::MQTTcallback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
  createTopics();
  connectMQTT();
  subscribeMQTT();
}
void myIOT32::MQTTloop()
{
  static long lastReconnectAttempt = 0;

  if (mqttClient.connected())
  {
    mqttClient.loop();
  }
  else
  {
    long now = millis();
    Serial.println("MQTT Server- NOT connected");
    if (now - lastReconnectAttempt > 5000)
    {
      lastReconnectAttempt = now;
      connectMQTT();
      subscribeMQTT();
    }
  }
}

void myIOT32::startNTP(const int gmtOffset_sec = 2 * 3600, const int daylightOffset_sec = 0, const char *ntpServer = "pool.ntp.org")
{
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
}
bool myIOT32::startWifi()
{
  long beginwifi = millis();
  WiFi.begin(wifi_ssid, wifi_pass);

  while (WiFi.status() != WL_CONNECTED && millis() - beginwifi < 30000)
  {
    delay(200);
    Serial.print(".");
  }

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    startNTP();
    return 1;
  }
  else
  {
    Serial.println("NO-WiFi");
    return 0;
  }
}
void myIOT32::getTime()
{
  int a = 0;
  while (a < 3)
  {
    if (getLocalTime(&_timeinfo))
    {
      delay(100);
      time(&_epoch_time);
    }
    a++;
  }
}

```

# Answer
> 0 votes
```
myIOT32::myIOT32(char *devTopic, char *ssid, char *wifi_p, char *mqtt_broker, char *mqttU, char *mqttP, int port)
    : mqttClient(espClient)  // <--- this part was missing *****
{

```

---
Tags: library, esp32, mqtt
---


# Question
Title: How do I know if I need to use a resistor in a circuit?
I have been trying to find answers on Google to this question but cannot seem to find any answers that actually pertain to what I am wanting to know. I would consider myself a beginner in the area of electronics having some experience but not understanding how everything comes together outside of the some of the basics. What I am wondering is this; How can I tell if I need to use a resistor in a circuit? More specifically, When I am hooking sensors up to an Arduino, how can I determine if I need resistors in the circuit? Anywhere I look I typically see the default LED/Resistor example but that is not helpful. It doesn't explain how Arduino/Raspberry PI modules and sensors fit into the equation. I know the data sheets for the various modules/sensors explain how much current is needed/used by the device but how do I take that and apply it to an Arduino circuit? Thanks in advance.

# Answer
> 4 votes
From the specifications of the sensor, you know the maximum current the sensor should be allowed to draw. Suppose you need to put 5v across the sensor.

Then write down Ohm's law: E = IR (the voltage across a component is given by the product of its resistance and the current through it. You need to know the value of a resistor to put in series with the sensor to limit the current to that maximum value or less. So solve Ohms law for resistance (R) of voltage (E):

R = E/I or 5v / maximum current.

That gives you the values of a series resistor to limit the current to the maximum, assuming the sensor has no (or very little) internal resistance of its own.

Or let's look at an LED, where the spec sheet gives you both the maximum current and the internal voltage drop (called "forward voltage"). If you don't need the LED to run at full power (and you probably don't), it will last longer if you limit it to less than that, so let's take 75% as a working figure and calculate the serial resistor to give 75% of maximum current. Red LEDs typically have 2v forward voltage and 15 milliamps max current (but don't build for "typical" parts - build for the part you have). We'll assume a 5v power supply:

R = E/I = (5v - 2v) / (.015 X 0.75) = 3 / .01125 = 266 Ohms. So we'd pick an available resistor value close to 266 Ohms (no need to be exact here - we've already left a safety factor by reducing the current 25%).

If you calculate the voltage (again, using Ohm's law) across the 266 (or whatever you used) Ohm resistor, you'll find a voltage drop of about 3v, and adding the LED's forward voltage of 2V, you'll get the power-supply voltage of 5v.

simulate this circuit – Schematic created using CircuitLab

Update:

> Why do we need a resistor on an LED which draws 15mA of current which the Arduino can supply nicely, but we don't on a sensor like the HC-SR04 which draws 15mA of current?

It's about the behavior of the component or module itself, and that needs a datasheet for the component and spec-sheet for the module. An LED has a forward voltage drop but otherwise looks like a nearly short circuit, so it requires a resistor to protect it from over-current. A module often provides some circuitry around the component to help the user integrate into their project. Of course, how much help it provide is up to the designer. One module may offer nothing more then breadboard-compatible pins where another one - for the same device - may have power-conditioning or power supply components, 3.3v \<-\> 5v logic-level shifters, and protective circuitry to help protect an expensive component from misuse.

Why does this component need a resistor and another one doesn't? It's up to the electrical behavior of those components. Here's a trivial, but I hope illustrative example:

The device on the left might be considered an LED module, compared to the one on the right which is just an LED. Obviously, all I've done is to solder a current limiting resistor in place on one leg to make a ready-to-go breadboard LED. It is designed for 5v circuits; putting it in a 12v circuit would fry the LED. Here is where I (as the "module designer") used the LED's datasheet to know what circuitry it needed to protect it, and as the "consumer", would need to consult the spec sheet for the module to know how to apply it. If I were selling these things, they'd come with a Spec Sheet: "Only use this LED module in 5v or less applications."\] Hmph - pretty trivial example, but you get the idea.

# Answer
> 0 votes
> How can I tell if I need to use a resistor in a circuit?

You can tell because the circuit includes a resistor.

If a circuit needs a resistor the circuit diagram will include a resistor. If it doesn't, then it won't.

The circuit for connecting an LED to an Arduino consists of an Arduino, an LED and a resistor. Because of that you know it needs a resistor. Because it says it needs a resistor.

A resistor drops a certain voltage across it when a specific current flows through it (Read up on Ohm's Law...). If you need to drop a specific voltage with a specific known current, or if you need to cause a specific current to flow with a fixed voltage, then you use a resistor for that job.

You don't just throw resistors willy-nilly into every circuit you make simply because you see one being used with an LED.

If a device says it runs off 5V and uses 300mA current then you know that you need to hook it up to a power source that is 5V. You also know that the module will use up to 300mA of current from that source, so your source has to be capable of providing at least that much current.

---
Tags: arduino-uno, electronics, resistor
---


# Question
Title: Error in defining Ticker in ESP32 library
I'm using the exact piece of code in my ESP8266 library (which works OK ), but when used in a ESP32 library- I got an error:

This is the relevant code snip:

```
void myIOT32::_feedTheDog()
{
  _wdtResetCounter++;
  if (_wdtResetCounter >= _wdtMaxRetries)
  {
    sendReset("Dog goes woof");
  }
}
void myIOT32::_startWDT()
{
  wdt.attach(1, std::bind(&myIOT32::_feedTheDog, this)); // Start WatchDog
}

void myIOT32::sendReset(char *header)
{
  char temp[150];

  sprintf(temp, "[%s] - Reset sent", header);

  if (useSerial)
  {
    Serial.println(temp);
  }
  if (strcmp(header, "null") != 0)
  {
    pub_msg(temp);
  }
  delay(1000);
  ESP.restart();
}

```

and this is the error:

```
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp: In member function 'void myIOT32::_startWDT()':
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp:333:55: error: no matching function for call to 'Ticker::attach(int, std::_Bind_helper<false, void (myIOT32::*)(), myIOT32*>::type)'
   wdt.attach(1, std::bind(&myIOT32::_feedTheDog, this)); // Start WatchDog
                                                       ^

```

# Answer
> 4 votes
ESP32 ticker attach functions take pure function pointers with at max one argument type -- not a `std::function`/ `std::_Bind_helper` that `std::bind` produces.

See code and types at https://github.com/espressif/arduino-esp32/blob/master/libraries/Ticker/src/Ticker.h#L38.

For the ESP8266 however, they do use a `std::function`:

https://github.com/esp8266/Arduino/blob/master/libraries/Ticker/src/Ticker.h#L36

And that's why it works on ESP8266 and not on ESP32 -- either adapt the `Ticker` library or rework your own code to not use member functions of classes.

Edit: You can easily rewrite your code to use a static helper function with one argument (the watchdog object itself) which then just calls the member function of that object. For this to work, the **called function must be public**. So a rewrite like

```
static void watchdog_timer_triggered_helper(myIOT32* watchdog) {
   //needs to be public!
   watchdog->_feedTheDog();
}

void myIOT32::_feedTheDog()
{
  _wdtResetCounter++;
  if (_wdtResetCounter >= _wdtMaxRetries)
  {
    sendReset("Dog goes woof");
  }
}
void myIOT32::_startWDT()
{
  wdt.attach(1, &watchdog_timer_triggered_helper, this); // Start WatchDog
}

void myIOT32::sendReset(char *header)
{
  char temp[150];

  sprintf(temp, "[%s] - Reset sent", header);

  if (useSerial)
  {
    Serial.println(temp);
  }
  if (strcmp(header, "null") != 0)
  {
    pub_msg(temp);
  }
  delay(1000);
  ESP.restart();
}

```

Since both the ESP32 and ESP8266 versions implement the

```
    template<typename TArg>
    void attach(float seconds, void (*callback)(TArg), TArg arg)

```

templated function this should work on both platforms now.

---
Tags: library, esp32
---


# Question
Title: Problem With interfacing of 16 Servo MG996R with Arduino Uno
I am using 16 MG996R servo motor with PCA9685 servo driver with Arduino Uno, but the motors are not working properly. What is the best power supply/battery for my project as it worked well earlier but is not working right now.

# Answer
> 0 votes
I use a 2s battery setup. Specifically Tenergy 18650 Lion 2600mah 7.4v. These are PCB protected lithium battery packs.

I use 3 of them in parallel 7.4v 7800mah.

BTW. I also use a UBEC rated at 7 amps to bring the voltage down to 6v.

---
Tags: arduino-uno, servo, battery
---


# Question
Title: How to read data from ThingSpeak for esp8266
I am trying to read data from thingspeak for esp8266 but I couldn't do that. There is a link: GET https://api.thingspeak.com/channels/123456/fields/1.json?api\_key=\***********&results=2 But how can I use it?

# Answer
> 1 votes
I directly code the esp8266 with thingSpeak library. Anyone who is interested look here:How to read data from thingspeak. And it worked. Thanks for your replies.

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


# Question
Title: Compile-time 'Undefined reference' error for functions defined in a .cpp source file that are called in my main project file
I'm currently working with the NodeMCU ESP12E and MPU6050 IMU using the Arduino IDE and wanted to create a project that has a .h file that declares the variables and functions. In the .cpp file, I have various function definitions. The main.ino file just calls some of these functions. Please find some excerpts of code from each file and the errors I encountered. The errors say the three functions called in the .ino file are undefined even though they are defined in the .cpp file

Algo.h file:

```
extern int activity_state; // activity_state=1 for RUN and activity_state=0 for WALK
extern float * speedarray; // Dynamic array for storing speed
extern int speedindex;
extern float * timearray; // Dynamic array for storing time
extern int timeindex;

extern unsigned int localPort;

```

Algo.cpp:

```

static void pedometerInit() // Initialising all pedometer algorithm variables
{
      int i = 0;
  //pedometerAlgo varibles
  pedi_window_high = 2000;
  pedi_window_low = 200;

  pedi_sampling_counter = 0;
  pedi_refresh_frequency = 50;
  validZone = 1;
  jatin_index_1 = 0;
  jatin_mag = 0;
  pedi_max = 0;
.
.

```

All the functions work on the variables declared in the header file.

Ped\_algo.ino:

```
void setup() {

  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(STASSID, STAPSK); // Setting up WiFi station
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(500);
  }

  Udp.begin(localPort); // Setting up UDP connection

  MPU6050_Init(); // Initial configuration of the MPU6050
  pedometerInit();
}

void loop() {

  pedometerAlgo();
}

```

Error messages:

Ped\_Algo.ino.cpp.o:(.text.loop+0x0): undefined reference to `pedometerAlgo()'
in function`loop': undefined reference to `pedometerInit()'
 undefined reference to`MPU6050\_Init()' undefined reference to \`pedometerInit()'

Error compiling for board NodeMCU 1.0 (ESP-12E Module).

# Answer
> 1 votes
Firstly, `static` keeps a function from ever being exported globally:

```
static void pedometerInit() // Initialising all pedometer algorithm variables

```

should not be `static`.

Secondly, `extern` does not define a variable, it merely tells the compiler that "this variable exists somewhere. Find it at link time." - however you're not actually defining those variables anywhere. In addition to the `extern` hints in the `.h` file you need to have the variables in the `.cpp` file for the compiler to be able to find them.

```
int activity_state; // activity_state=1 for RUN and activity_state=0 for WALK
float * speedarray; // Dynamic array for storing speed
int speedindex;
float * timearray; // Dynamic array for storing time
int timeindex;

unsigned int localPort;

void pedometerInit() // Initialising all pedometer algorithm variables
{
 ... your code ...
}

```

---
Tags: esp8266, arduino-ide, c++
---


# Question
Title: Understanding the variation of Arduino's current consumption with respect to the voltage supply
Even though this is already a well-debated topic, I couldn't find an extensive discussion about what really is drawing so much power in Arduino's board.

Here is the preamble: I have an Arduino Mega 2560, I measured its power consumption in a steady state with just a red LED turned on with a 560Ohm series resistor. The power supply (Vcc) was given to Arduino from the Vin pin and the measurement were as follows (below the schematic set-up):

* 30mA @Vcc = 5.2V;
* 65mA @Vcc = 8.3V.

What I would like to understand is:

1. From a hardware perspective, I don't see **what** is drawing all of this current in Arduino's board;
2. Why the current drawn from the power supply **changes so much** with the power supply's value (i.e. what part of the board changes its consumption with the power supply value);
3. It also seems that turning on an LED through a digital output of Arduino draws a higher current with a higher power supply (Vcc). Why is that?

Note that, by looking at the datasheet of the ATmega2560, the uC mounted on my Arduino, I saw that the current Icc drawn from the power supply is max 14mA (I suppose when no output is sourcing current, I couldn't find the test conditions, unfortunately). I thought the microcontroller was the major cause of power consumption, but it doesn't seem to be so!

Another thing I considered is the onboard LDO, but the input voltage should change the power dissipated by the LDO, not the current drawn from its output.

It's even more strange if you think that regardless of the Vin, all the electronics after the LDO is working at the same voltage.

**EDIT1**

After Majenko pointed out a big flaw in my set-up with his answer, I re-measured with Vcc = 12.1V and I measured approximately the same Icc observed at Vcc = 8.1V. I completely agree with Majenko's answer and I would just like to go a bit more in details about what happens while the board is working under voltage.

**Here is my analysis:**

The minimum operating condition when supplied from Vin is 7V, and that's the "knee" point in Majenko's answer.

However, the maximum quiescent current of the LDO is 10mA, and the Icc of the ATmega2560 is 15mA, so even if we suppose they don't draw any current at Vcc=5.2V, and then draw 25mA together at the minimum operating voltage at 7V, this doesn't add up to the actual increase of 40 or 50 mA that Majenko calculated I observed from 5.2 to 8.3 (which should be the same as from 5.2 to 7V).

And we're not even taking into account that at 5.2V the micro is perfectly able to turn on and keep on the LED, so it's somewhat working and already drawing some current.

Other things that we can take into account, but don't change the facts, are:

* a second LDO (LP2985) to generate the 3V3, whose quiescent current should be around 100uA since the circuit is not drawing any current from the 3V3.
* ~~a second microcontroller related to the USB programming, whose Icc may be up to 20mA but this one is OFF when supplying from Vin.~~  --\> Edgar Bonet correctly pointed out that this is not true!
* Some voltage dividers and comparators.

**So what is the cause of this increase in current consumption from 5 to 7V?**

# Answer
> 5 votes
There is a basic error in your methodology which leads to incorrect conclusions.

You cannot determine what is going on from just two data points. Instead you need far more.

Here is a voltage sweep from 5V to 12V with a 0.05V resolution (overkill, but the default setting for the script I use) connected to a Mega:

As you can see the current steadily climes in a pretty linear fashion up to a certain point, then it flattens out.

Everything up to the point where it flattens is below the minimum input voltage for the board. During this time the voltage regulator isn't getting enough voltage, so can't regulate its output voltage to 5V. So the board is running under voltage at this point. Once it reaches that "knee" point the voltage regulator can regulate the voltage properly - so most of the components on the board start seeing a steady 5V and their current consumption flattens out.

There are a handful of components on the high-voltage side of the regulator - most notably the voltage divider for detecting the input voltage and feeding it to the comparator that drives the P-channel FET to turn the USB power on and off - which will consume slightly more current when the voltage increases, but that is only very small amounts.

So, in short, by comparing a voltage that is below the minimum input voltage for the board with one that is above the minimum input voltage, you are comparing an invalid result with a valid result and inferring that everything in between is valid.

---
Tags: power, current
---


# Question
Title: Multiple Buttons to control the same led for different on off times
I am just learning the Arduino, it is a learning curve that's for sure.

Using the onboard Led I want to use two buttons to make the Led blink for different times.

I am not sure what is missing from the code, as pressing BUTTON2 gives the same time as BUTTON.

Any help would be greatly appreciated.

```
 const byte BUTTON = 2;
const byte BUTTON2 = 3;
const byte LED = 13;

unsigned long buttonPushedMillis;
unsigned long ledTurnedOnAt;
unsigned long turnOnDelay = 500;
unsigned long turnOffDelay = 500;
unsigned long turnOnDelay2 = 1000;
unsigned long turnOffDelay2 = 1000;
bool ledReady = false;
bool ledState = false;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(BUTTON2, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  unsigned long currentMillis = millis();
  if (digitalRead(BUTTON) == LOW) {
    delay(50);
    buttonPushedMillis = currentMillis;
    ledReady = true;
  }
  if (ledReady) {
    if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
      digitalWrite(LED, HIGH);
      ledState = true;
      ledTurnedOnAt = currentMillis;
      ledReady = false;
    }
  }
  if (ledState) {
    if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) {
      ledState = false;
      digitalWrite(LED, LOW);
    }
  }
  {
    unsigned long currentMillis = millis();
    if (digitalRead(BUTTON2) == LOW) {
      delay(50);
      buttonPushedMillis = currentMillis;
      ledReady = true;
    }
    if (ledReady) {
      if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay2) {
        digitalWrite(LED, HIGH);
        ledState = true;
        ledTurnedOnAt = currentMillis;
        ledReady = false;
      }
    }
    if (ledState) {
      if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay2) {
        ledState = false;
        digitalWrite(LED, LOW);
      }
    }
  }
}

```

\\

# Answer
> 1 votes
You're making your program too complex for its own good.

Instead of changing your blink code depending on which button is pressed, just make the button change the blink code's parameters, and stick to just one blink code.

That means having just one set of blink variables which your blink code uses, and your button code then just changes what values those variables contain.

---
Tags: arduino-uno
---


# Question
Title: NodeMCU (Arduino IDE) 'DynamicJsonBuffer' was not declared in this scope
```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;
String url = "http://192.168.31.170/api/mode/qwertyui";

void setup() {
  USE_SERIAL.begin(9600);

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for (uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("Robotics Incubator", "XXXXXXX");
}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {
    HTTPClient http;
    http.begin(url); //HTTP
    int httpCode = http.GET();

    if (httpCode == 200) {
      // Parsing
      const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
      DynamicJsonBuffer jsonBuffer(bufferSize);  //This was not declared error.
      JsonObject& root = jsonBuffer.parseObject(http.getString());
      // Parameters
      int Mode = root["mode"]; // 1
      Serial.print("Name:");
      Serial.println(Mode);
    }
    http.end();
  }

  if (Serial.available()) {
    url = Serial.readString();
  }
  delay(100);
}

```

How can I solve this problem? I followed this tutorial - ESP8266: Parsing JSON

# Answer
This error is caused by using a 6.x.x version of the ArduinoJson library with code that was written for a pre-6.x.x version of the library.

You have two options to solve the problem:

### A. Downgrade the library to a version that is compatible with your code

For now, this is probably the best option because the 6.x.x version of the ArduinoJson is still in beta so it makes sense to wait until the new API is stabilized before porting your code. This is even recommended by the ArduinoJson developers:

https://arduinojson.org/v5/faq/error-jsonbuffer-was-not-declared-in-this-scope/

1. Sketch \> Include Library \> Manage Libraries...
2. Wait for the download to finish.
3. In the "Filter your search..." box, type: "arduinojson".
4. Click on "ArduinoJson by Benoit Blanchon".
5. From the "Select version" dropdown menu, select "Version 5.13.2".
6. Click "Update". Wait for the update to finish.
7. Click "Close".

Now your code will compile. If you have **File \> Preferences \> Check for updates on startup** enabled, you will continue to get updatable library notification for the ArduinoJson library but you need to refrain from updating back to a 6.x.x version or the error will come back.

### B. Update your code to be compatible with the 6.x.x version of the ArduinoJson library

In this case you need to modify your deserialization code to use the new `DynamicJsonDocument` instead of the old `DynamicJsonBuffer`:

```
if (httpCode == 200) {
  // Parsing
  const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
  DynamicJsonDocument jsonDocument(bufferSize);
  DeserializationError error = deserializeJson(jsonDocument, http.getString());
  if (error) {
    Serial.println("There was an error while deserializing");
  }
  else {
    JsonObject root = jsonDocument.as<JsonObject>();
    // Parameters
    int Mode = root["mode"]; // 1
    Serial.print("Name:");
    Serial.println(Mode);
  }
}

```

You can get more details about this here:

https://arduinojson.org/v6/doc/upgrade/
> 5 votes

# Answer
This answer needs to be updated for anyone who visits here. The 6.x.x is no longer in beta. Simply update to the latest version. At the time of writing this answer the version id is 6.15.2. Updating to this will resolve the error.
> 0 votes

---
Tags: esp8266, arduino-ide, nodemcu, json
---


# Question
Title: trying to switch input on my speakers via infrared using web browser but i have issue getting it working
ived tested the IR code with https://github.com/wemos/D1\_mini\_Examples/blob/master/examples/04.Shields/IR\_Controller\_Shield/IRsend/IRsend.ino

and it works that way, but when i try to code it together with the web server, i get nothing, can someone explain to me what's wrong in my code? the webserver works fine, its the IR part i dont fully understand why its not working

```
#include <i18n.h>
#include "ESP8266WiFi.h"
#include "ESP8266WebServer.h"
#include <IRremoteESP8266.h>
#include <IRsend.h>
ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
  WiFi.begin("net", "pass");  //Connect to the WiFi network

  while (WiFi.status() != WL_CONNECTED) {  //Wait for connection

    delay(500);
    Serial.println("Waiting to connect…");

  }

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //Print the local IP

  server.on("/on", []() {   //Define the handling function for the path

    server.send(200, "text / plain", "Switching to USB input");
    #define IR_LED D3
    IRsend irsend(IR_LED);  // Set the GPIO to be used to sending the message.
    uint16_t rawData[71] = {8992, 4494,  574, 558,  572, 558,  574, 558,  574, 558,  574, 558,  572, 558,  572, 556,  572, 1660,  572, 1658,  574, 1658,  574, 1658,  574, 1660,  574, 1660,  574, 1660,  574, 1658,  602, 528,  574, 558,  574, 1658,  576, 556,  574, 556,  574, 1660,  574, 556,  574, 554,  574, 554,  574, 1658,  574, 556,  574, 1656,  576, 1658,  576, 556,  574, 1658,  576, 1656,  576, 1658,  576, 39978,  8994, 2256,  578};
    irsend.begin();

  });

  server.on("/", handleRootPath);    //Associate the handler function to the path
  server.begin();                    //Start the server
  Serial.println("Server listening");

}

void loop() {

  server.handleClient();         //Handling of incoming requests

}

void handleRootPath() {            //Handler for the rooth path

  server.send(200, "text/plain", "NinjaLights");

}

```

# Answer
Look at your code. You set up the sender, define the data and then never use it:

```
server.on("/on", []() {   //Define the handling function for the path
    server.send(200, "text / plain", "Switching to USB input");
    #define IR_LED D3
    IRsend irsend(IR_LED);  // Set the GPIO to be used to sending the message.
    uint16_t rawData[71] = {8992, 4494,  574, 558,  572, 558,  574, 558,  574, 558,  574, 558,  572, 558,  572, 556,  572, 1660,  572, 1658,  574, 1658,  574, 1658,  574, 1660,  574, 1660,  574, 1660,  574, 1658,  602, 528,  574, 558,  574, 1658,  576, 556,  574, 556,  574, 1660,  574, 556,  574, 554,  574, 554,  574, 1658,  574, 556,  574, 1656,  576, 1658,  576, 556,  574, 1658,  576, 1656,  576, 1658,  576, 39978,  8994, 2256,  578};
    irsend.begin();

  });

```

You need to add a call to `irsend.SendRaw()` to actually send the data - otherwise you didn't actually do anything.

So your code would look like:

```
server.on("/on", []() {   //Define the handling function for the path
    server.send(200, "text / plain", "Switching to USB input");
    #define IR_LED D3
    IRsend irsend(IR_LED);  // Set the GPIO to be used to sending the message.
    uint16_t rawData[71] = {8992, 4494,  574, 558,  572, 558,  574, 558,  574, 558,  574, 558,  572, 558,  572, 556,  572, 1660,  572, 1658,  574, 1658,  574, 1658,  574, 1660,  574, 1660,  574, 1660,  574, 1658,  602, 528,  574, 558,  574, 1658,  576, 556,  574, 556,  574, 1660,  574, 556,  574, 554,  574, 554,  574, 1658,  574, 556,  574, 1656,  576, 1658,  576, 556,  574, 1658,  576, 1656,  576, 1658,  576, 39978,  8994, 2256,  578};
    irsend.begin();

    irsend.sendRaw(rawData, 71, KHZ);
  });

```

You'll need to replace `KHZ` with the frequency the remote you're trying to replicate uses, otherwise it still won't work.
> 3 votes

---
Tags: esp8266, infrared
---


# Question
Title: Error taking address of temporary array when passing compound literal array
I have an Arduino sketch that passes an array into a method as a compound literal, but for some reason I keep getting the following error:

```
void setup() { }
void printConcatLine(char chunks[][20]) { }

void loop() {
  printConcatLine((char[][20]){ "{", "255", "}" });
}

```

I've also tried passing the number of the pointers/length of the array, and explicitly terminating it:

```
void setup() { }
void printConcatLine(char *chunks[]) { }

void loop() {
  printConcatLine((char*[]){ "{", "255", "}", NULL });
}

```

...and

```
void setup() { }
void printConcatLine(char chunks[][20]) { }

void loop() {
  printConcatLine((char[][20]){ "{", "255", "}", "" });
}

```

But they both produce the same error.

What is the correct method of passing the compound literal array as a method parameter?

# Answer
> 2 votes
You can't with the Arduino. I am not quite sure why, but I think it may be because it's a Modified Harvard architecture machine.

You can better achieve what you want with *variadic arguments*, however:

```
void printConcatLine(int num, ...) {
    va_list ap;
    const char *s;

    va_start(ap, num);
    for (int i = 0; i < num; i++) {
        s = va_arg(ap, const char *);
        Serial.print(s);
    }
    va_end(ap);
    Serial.println();
}

void setup() {
    Serial.begin(115200);
    printConcatLine(3, "{", "255", "}");
}

void loop() {

}

```

The first argument is the number of arguments that follow, and all the rest are string constants.

---
Tags: array, pointer, functions
---


# Question
Title: Can I check if a message has been sent successfully using Radiohead_ASK?
I'm new to Arduino programming and I'm trying to get a simple 433 MHz transmitter and receiver module working on an Arduino Uno board. Unsurprisingly, it's not working as expected and I'm trying to debug the problem.

I'm using RadioHead and read in the documentation that the send() and waitPacketSent() methods return a boolean to indicate success. However, I disconnected the data wire and the send() method still returns true. As the module is no longer connected to the arduino I would have expected it to return false.

I understand that the messages are sent as unreliable datagrams, but I'm just trying to work out whether the transmitter has actually sent something. Is there some way I can do this?

The code I'm using is relatively short, so I've included it in full below, for what it's worth

```
#include <RH_ASK.h>
#include <RadioHead.h>

#ifdef RH_HAVE_HARDWARE_SPI
#include <SPI.h> // Not actually used but needed to compile
#endif

RH_ASK driver;

bool sent;

void setup()
{
#ifdef RH_HAVE_SERIAL
    Serial.begin(9600);    // Debugging only
#endif
    if (!driver.init())
#ifdef RH_HAVE_SERIAL
      Serial.println("init failed");
#else
  ;
#endif
  sent = false;
}

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    const char *msg = "hello";
    bool sendSuccess;
    bool waitSuccess;

    if (!sent) {
      Serial.println("sending");
      sendSuccess = driver.send((uint8_t *)msg, strlen(msg));
      if (sendSuccess) {
        Serial.println("Send completed successfully");
      } else {
        Serial.println("Send Error");
      }
      Serial.println("Waiting");

      waitSuccess = driver.waitPacketSent();
      if (waitSuccess) {
        Serial.println("Wait Sent Success");
      } else {
        Serial.println("Wait Sent Error");
      }
      Serial.println("Done Sending");
      sent = true;
      delay(1000);
    }

    if (driver.recv(buf, &buflen)) // Non-blocking
    {
      Serial.println("driver.recv");

      // Message with a good checksum received, dump it.
      driver.printBuffer("Got:", buf, buflen);
    }
}

```

The output on the serial monitor is as follows

> 22:22:30.647 -\> sending
>
> 22:22:30.647 -\> Send completed successfully
>
> 22:22:30.684 -\> Waiting
>
> 22:22:30.753 -\> Wait Sent Success
>
> 22:22:30.753 -\> Done Sending

Thanks in advance!

# Answer
There is no concept of "did the packet arrive", only "did it get sent" - and by "sent" I mean the data squirted out of the data pin for the attached module to send.

These 433MHz modules are dumb. Very dumb. You toggle the transmitter's pin high and low and the receiver sees that toggling, if it is in range, and toggles its output pin to mirror the signal.

The only way you can know if the packet arrived is if the receiver also has a transmitter and the transmitter also has a receiver. When a message arrives at the receiving node it sends a message back to the transmitting node to say "I got it". That takes a lot of work to get right, though. Especially since the original message may have arrived fine, but the acknowledgement didn't, and all sorts of horrible things can happen if you don't handle packet sequencing right.

Better is to pick a better module that does all these things for you, such as the nRF24L01+ with Auto-ACK turned on.
> 1 votes

---
Tags: programming, rf
---


title: ESP32 runtime error in 2d array

text:
# Question
Title: ESP32 runtime error in 2d array
I am trying to serial print the value of `b[0][0]`.

Has to be zero but it dose not work!

**Here is the code**

```
void setup() {
  Serial.begin(115200);
  byte b[321][241];
  Serial.println(b[0][0]);
}

void loop() {

}

```

If the array is small like `b[2][2]` it dose work

In theory esp32 has ram of 520 KiB SRAM so can this be a problem?

**Here is the error code**

```
rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

```

The code complies fine but the error gets when esp32 is running

esp32 version for arduino is 1.0.4

# Answer
> 2 votes
The ESP32 uses FreeRTOS to run everything, and that includes the Arduino API. Your code is running in a thread of its own ("loopTask"), and that task by default has 8192 bytes of stack allocated to it.

```
xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);

```

You cannot create local variables and other stack data that totals more than 8192 bytes.

Instead you will either have to have the variable as a global variable (or static local) so it gets allocated in the global data segment, or use `new` or `malloc` to create it on the heap (and don't forget the corresponding `delete` or `free` call when you're done with it).

# Answer
> -1 votes
This may be due to serial buffer size. ESP32 may wrire new data before finshing previous transfer. Add a delay after print line and see.

---
Tags: serial, esp32, array
---


# Question
Title: Formatting variables from a variadic function
I have a function that concatenates a print line, however I am having trouble getting some of the strings to format correctly.

Using Serial.print formats the output from **keypad.getKey()** correctly, however when I try to output the same format using **printConcatLine()** it does not give me the same output. I've tried casting it as both a char and an int...

```
void printConcatLine(const char* mask, ...) {
    va_list params;
    va_start(params, mask);

    while(*mask != '\0') {
      if (*mask == 'i') {
          Serial.print(va_arg(params, int));
      } else if(*mask == 'c') {
          Serial.print(va_arg(params, const char *));
      } else if (*mask == 'f' || *mask == 'd') {
          Serial.print(va_arg(params, double));
      }
      ++mask;
    }

    va_end(params);
    Serial.println();
}

char btnPressed = keypad.getKey();
  if (btnPressed) {
    Serial.print("BtnPressed: ");
    Serial.println(btnPressed);
    // Output: "BtnPressed: 1"

    printConcatLine("ci", "BtnPressed: ", btnPressed);
    // Output: "BtnPressed: 49"

    printConcatLine("cc", "BtnPressed: ", btnPressed);
    // Output: "BtnPressed: "
  }

```

I also tried changing:

> va\_arg(params, const char \*)

to

> va\_arg(params, char)

which also did nothing.

How can I modify the call to **va\_arg()** to properly output the same output as **Serial.print()**?

# Answer
> 2 votes
Edgar beat me to it by a few seconds, but my answer is pretty much the same as his, so read that first.

I will however add a few extra notes and pointers:

* It's better to assign the va\_args to an actual variable. That makes it both easier to read and understand what's going on, and more certain for the overloading of the print function to know what is supposed to happen (at least from the reader's perspective) that mere casting.
* Bytes and chars are promoted to integer when being passed to a variadic function, so you have to treat them as such
* `float` and `double` happen to be the same on the AVR based Arduinos, so your code will be OK there, but the same can't be said for other chips. If you want your code to be portable then you should split `float` and `double` into separate handlers since they use different sizes.
* It can be good to "pass through" unknown characters in the format string so that you can add extra formatting in there. See my example below.

Here's my variant of the same code. Note the colon and space in the format that is used to add more formatting to the output (this could be enhanced by adding a `%` before any format characters as `printf` does). I also like to use a separate pointer to iterate over the format string instead so that the original start pointer is still available if I should ever want it.

Also note the difference between `c` and `i`: use `c` to print a letter from a char, and `i` to print the number in a char instead.

```
void printConcatLine(const char *mask, ...) {
    va_list params;
    va_start(params, mask);

    char *ptr = (char *)mask;
    while (*ptr != '\0') {
        if (*ptr == 'c') {
            int c = va_arg(params, int);
            Serial.write(c);
        } else if (*ptr == 'i') {
            int i = va_arg(params, int);
            Serial.print(i);
        } else if (*ptr == 's') {
            const char *s = va_arg(params, const char *);
            Serial.print(s);
        } else if (*ptr == 'f' || *ptr == 'd') {
            // Be careful with this. It's not portable. On AVR float
            // and double are the same, but that's not the case on other
            // microcontrollers. It would be better to split them.
            double d = va_arg(params, double);
            Serial.print(d);
        } else {
            Serial.write(*ptr);
        }
        ptr++;
    }

    va_end(params);
    Serial.println();
}

void setup() {
    Serial.begin(115200);
    char btnPressed = 1;
    float flt = 3.141592653;

    if (btnPressed) {
        printConcatLine("c: sisd", 'Q', "BtnPressed: ", btnPressed, " done ", flt);
    }
}

void loop() {
}

```

# Answer
> 2 votes
With the format `"ci"`, the argument is interpreted as an integer, and the output is correct: 49 is the ASCII code of `'1'`.

With the format `"cc"`, the argument is interpreted as a string (pointer to an array of chars), which is incorrect.

One (bad) solution is to use the `"cc"` format and pass `&btnPressed` as an argument. The problem with this approach is that the byte in memory right after `btnPressed` may not be a zero, and the format expects a NUL-terminated string.

A better approach would be to have one format for a `char` and a different one for a string. I suggest `"c"` and `"s"` respectively. But then you should be aware that there are special promotion rules associated with variadic functions. When playing with your code, the compiler reminded me of this one:

> warning: **‘char’** is promoted to **‘int’** when passed through **‘...’**

So the function should expect an `int`, and cast it to `char` in order to call the correct overload of `Serial.print()`:

```
void printConcatLine(const char* mask, ...) {
    va_list params;
    va_start(params, mask);

    while(*mask != '\0') {
      if (*mask == 'i') {
          Serial.print(va_arg(params, int));
      } else if(*mask == 's') {
          Serial.print(va_arg(params, const char *));
      } else if(*mask == 'c') {
          Serial.print((char) va_arg(params, int));
      } else if (*mask == 'f' || *mask == 'd') {
          Serial.print(va_arg(params, double));
      }
      ++mask;
    }

    va_end(params);
    Serial.println();
}

```

Used like this:

```
printConcatLine("sc", "BtnPressed: ", btnPressed);
// Output: "BtnPressed: 1"

```

# Answer
> 2 votes
I recommend to use printf if you don't need float support in printf. This code produces a little smaller compiled code then the one in Majenko's answer and has the full power of the printf except of float.

```
#include <StreamLib.h>

void setup() {
    Serial.begin(115200);
    char btnPressed = 1;
    float flt = 3.141592653;

    byte b;
    BufferedPrint bp(Serial, &b, 1);

    if (btnPressed) {
        bp.printf("%c: %s %i %s", 'Q', "BtnPressed: ", btnPressed, " done ");
        bp.println(flt, 4);
    }
}

void loop() {
}

```

With StreamLib you can of course print float with normal single print function for floats, the same as for Serial or network Client, with second parameter for the number of decimal places.

If you want to create a formatted C-string you can use the CStringBuilder of the StreamLib. It too builds the string with `print` functions and has 'printf' too.

---
Tags: serial, string, functions, keypad
---


# Question
Title: Assigning an element of a multidimensional array to a second array
I have two arrays. The first array is a multidimensional array holding color values.

The 2nd array stores an **active** color from the 1st array. How can I assign an element from the multidimensional **colors** array to the 2nd **EXCLUSIVE\_COLOR** array?

```
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 }
};
int EXCLUSIVE_COLOR[3] = {0};

```

I tried the following but neither seemed to work:

```
    EXCLUSIVE_COLOR = {
      colors[0][0],
      colors[0][1],
      colors[0][2]
    };
    // error: assigning to an array from an initializer list

    EXCLUSIVE_COLOR = colors[0];
    // error: invalid array assignment

```

# Answer
You can copy the array:

```
EXCLUSIVE_COLOR[0] = colors[0][0];
EXCLUSIVE_COLOR[1] = colors[0][1];
EXCLUSIVE_COLOR[2] = colors[0][2];

```

but this doesn't work in an initialization.

Alternatively, you can declare `EXCLUSIVE_COLOR` as a pointer to an array of 3 integers:

```
int (*EXCLUSIVE_COLOR)[3]; // pointer to array 3 of int

```

Then you can have this point to a row of the 2D array, either by assigning the pointer or in the initialization:

```
int (*EXCLUSIVE_COLOR)[3] = &colors[0];  // initialization

// Later in the program:
EXCLUSIVE_COLOR = &colors[1];

```

Note that when using this pointer, you will have to explicitly dereference it:

```
for (int i = 0; i < 3; i++)
    Serial.println((*EXCLUSIVE_COLOR)[i]);

```

**Edit**: As pointed out by Juraj in a comment, you can instead make `EXCLUSIVE_COLOR` a pointer to int. In this case you will make it point to the first element in the row you want:

```
int* EXCLUSIVE_COLOR = &colors[0][0];

```

One nice thing of this approach is that you can use the “decay to pointer” feature of the language to simplify the syntax:

```
int* EXCLUSIVE_COLOR = colors[0];

// Later
Serial.println(EXCLUSIVE_COLOR[i]);

```
> 1 votes

# Answer
Use arrays only where appropriate:

```
struct Color {byte r, g, b;};
const Color colors[] = {
  {0,255,0},
  {255,0,0}
};
const Color red = colors[1];

```

This works without `const` as well. But you should consider using `const` wherever possible.
> 0 votes

---
Tags: array
---


# Question
Title: Can you activate the whole pixel on LCD?
I'm working on a project where I'm trying to display the level of a filled tank through ultrasonic, then displaying it on a 16x2 LCD. I'm trying to do it through the whole LCD Pixels, such that when the tank level is full, the first 5 pixels are activated (as what happens when you connect the LCD initially without having any code for it, the whole pixels are turned on, giving 16x2 white rectangles, as shown in the picture below). Is there a way to activate an entire pixel on the LCD?

# Answer
The LCD is made up from 32 characters each is 5x7 pixels in size, with a 1 pixel gap between each character.

You can never put anything in the gap between the characters, as there is just nothing there.

But what you can do is define your own characters to fit within the 5x7 pixel rectangles.

Some variants of the HD44780 have character 255 as a solid block, but not all (it depends on what language the ROM is). If you have one that has that character you can just print it with `lcd.print("\xff")` or `lcd.write(255)`. If it doesn't it will print `ÿ` instead. In that case you will have to define your own character.

One benefit of defining your own characters is that you could then do partial blocks to give you a higher resolution. Here's an example:

You can find that example and the code that goes with it here.
> 3 votes

# Answer
The LCDs like the one you picture display **characters**. That is all they do. You can't address the pixels in the display.

And as a point of clarification, you are talking about the 5 pixel by 7 pixel character blocks on the display as if a character is a pixel. It's not. A character block consists of 5 x 7 pixels.

Some versions may have a pre-defined solid block character, as Majenko said in their answer. You could print as many of those solid blocks as you want.

You could also define a single custom character that displays a solid block and print as many of those as you want.

As a third option (again from Majenko's excellent answer) you could define 5 different custom characters, each with a different number of columns of pixels filled in. You could then write code that displayed solid blocks for all but the last character, and then one of the 5 partly filled custom characters, and get a finer resolution of simulated bar graph.

All that said, remember, the LCD display can only display 5x7 blocks with blank space between. The LCD is built without any pixels between the characters, so there will always be blank spaces.

There are other pixel displays you could use. (I've seen OLED displays where you can control every character individually.)
> 0 votes

---
Tags: lcd
---


# Question
Title: How can I list only files that begin with "/LOG?"
Trying to list root directory of LittleFS; but only files beginging with "/LOG."

```
String str;

                     if (!LittleFS.begin())
                     {
                          Serial.println("LittleFS failed to mount !");
                     }
                     Dir dir = LittleFS.openDir("/");
                     while (dir.next())
                     {

                        if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)
                        {

                            str += "<a href=\"";
                            str += dir.fileName();
                            str += "\">";
                            str += dir.fileName();
                            str += "</a>";
                            str += "    ";
                            str += dir.fileSize();
                            str += "<br>\r\n";
                        }
                     }

                     client.print(str);

```

If I comment out "if(strncmp(dir.fileName().c\_str(), "/LOG", 4) == 0)" and associated braces; all files list. Code with "if(strncmp(dir.fileName().c\_str(), "/LOG", 4) == 0)" no files are listed.

How can I list only files that begin with "/LOG?"

William

# Answer
Give a filename String to text...

```
String text = "/LOGsdfsdf";
if(text.startsWith("/LOG")){
//wee file begins with /LOG
}else{
// wops wrong file.
}

```

Look in here

https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/

Method url `startsWith("");`

https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/startswith
> 2 votes

---
Tags: esp8266, programming
---


# Question
Title: Stopping a motor after a given time period
I have a code to turn on a LED when IR Proximity sensor having a object less than 6cm in front of it, and the LED goes down after it is removed.

Now, I want the LED to run for 3 seconds only, even if the object is not removed, how should I modify my code? Many thanks in advance!

```
int LED = 13; // pin for the LED
int Sensor = 2;// pin for the IR Sensor

void setup(){

  pinMode (LED, OUTPUT);
  pinMode (Sensor, INPUT);
}

void loop(){

  if (digitalRead(2)){

      digitalWrite(LED , LOW);
  }

  else{

    digitalWrite ( LED, HIGH);
    // if the IR sensor detects an object, the LED turns on or else it should not turn on
}

```

# Answer
> 0 votes
```
int LED = 13;
int Sensor = 2;

void setup(){

  pinMode (LED, OUTPUT);
  pinMode (Sensor, INPUT);
}

void loop(){

 if (digitalRead(2)){

        digitalWrite(LED , LOW);
        delay(3);
  }

 else{

    digitalWrite ( LED, HIGH);``
 }

```

---
Tags: arduino-uno, programming, sensors, led
---


# Question
Title: Teensy to Teensy serial communication via USB connector
I have 2 Arduino Teensy 3.2 boards that I'm trying to implement serial communication between the 2 boards. I have successfully done this by connecting RX1 of the 1st Teensy with TX1 of 2nd Teensy and TX1 of 1st to RX1 2nd.

However I was wondering if I could send serial messages between the Teensys i.e. do the same thing, by connect the 2 Teensys via the USB port? Or is this USB port reserved to connecting the Teensy to a computer?

# Answer
Note: The Teensy you pictured is an ARM based (NXP MK20DX256) Arduino which is very different from well established legacy Arduinos. There have been (and, maybe, still are) "bugs" in some ARM Arduino code. So Teensy pins used outside their normal (expected) purpose my or may not work like similar pins on legacy Arduino platforms.

In order for 2 USBs to talk to each other, one needs to be a USB Host and the other a USB Device. There can be multiple USB Devices so the USB protocol is made more complex to handle this feature. There can be many types of USB Devices each with their own underlying protocol so the USB protocol is made more complex to handle this additional feature. A serial port USB Device uses the CDC or Communications Device Class protocol.

So, in order to have two Teensy board to talk to one another using the USB CDC protocol, one of the Teensy boards needs to be turned from a USB Device to a USB Host. Which is not trivial. Most developers will turn to the OEM of the processor. As most processor OEMs offer free software for such purposes to promote the sales of their hardware.
> 0 votes

# Answer
Teensy 3.5, 3.6, 4.0 and 4.1 have a second USB interface which is configured as USB Host. You can use this interface in CDC mode (see @st2000 answer) and connect it to the normal USB device plug of any other Teensy if you need to. But please note that a T3.2 can transmit up to about 3 MBaud over its serial UARTS. So, I don't see any reason to use USB for board to board communication.
> 0 votes

---
Tags: serial, usb, teensy
---


# Question
Title: Assigning an empty array row to reference
```
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 }
};
int (*EXCLUSIVE_COLOR)[3];

```

I have a two-dimensional array to store some color values.
I have a 2nd array, which I am using to assign an **"EXCLUSIVE\_COLOR"** from the first colors array.

What is the best method to assign a null or empty value to the **"EXCLUSIVE\_COLOR"** array to be used upon initialization and when the **"EXCLUSIVE\_COLOR"** is unset?

Initially I tried just assigning a default value to the array upon initialization:

```
int (*EXCLUSIVE_COLOR)[3] = {0,0,0};
//Produces an error: scalar object ‘EXCLUSIVE_COLOR’ requires one element in initializer

int (*EXCLUSIVE_COLOR)[3] = {0};
//assigns non-zero values to all three elements

```

I know that I can add a "dummy" record to the colors array to reference, when there isn't an **"EXCLUSIVE\_COLOR"** set.

```
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 },

  { 0, 0, 0, }   //dummy record
};
int (*EXCLUSIVE_COLOR)[3] = &colors[4];

```

However I wanted to know if there was a cleaner way to be able to assign an empty value to reference when a color is not set, and when the array is initialized.

# Answer
> 1 votes
If you're using a pointer then there's no limit to what that pointer can point to.

The way I see it you have two sensible choices:

1. Point to a default value

This doesn't have to be in your array. It can be anything that is an `int[3]`, since that is what your array consists of.

```
int[3] nothing = {0, 0, 0};

EXCLUSIVE_COLOR = nothing;

```

This means that it's actually pointing to something valid, in this case it's actually (I assume) the colour black. That can make it easy to deal with, since `EXCLUSIVE_COLOR[0]` will be a valid value.

2. Point to nothing

You can point your pointer to `NULL` and it will be pointing to "nothing". This means that `EXCLUSIVE_COLOR[0]` is no longer valid, which can make handling it somewhat harder. However it does allow you to distinguish between "nothing" and "black", unlike option 1.

For example:

```
EXCLUSIVE_COLOR = colors[2]; // {0, 0, 255}
...
EXCLUSIVE_COLOR = NULL; // Not pointing anywhere

```

To test if it's pointing somewhere you can simply use `if`:

```
if (EXCLUSIVE_COLOR) {
   // you have a valid entry
}

```

---
Tags: programming, c++, array, pointer
---


# Question
Title: How many LED displays can be hooked to one Arduino board?
I am new to Arduino development. I need to connect multiple led displays(between 20 and 100), such as this one to an Arduino board. The led displays will be pretty far out from each other.

How can this be achieved? How can i uniquely identify the LCD displays? At this point i need some 101 orientation.

# Answer
> The led displays will be pretty far out from each other.

Those are I2C connected displays. I2C is not designed (though there are technologies to allow it) to operate over long distances. It's designed primarily for communication between chips within a circuit board.

> How can i uniquely identify the LCD displays?

Since you can't change the I2C address of the displays you would either need a separate I2C bus for each one or employ some form of I2C multiplexer.

All of this is getting too complicated. The more accepted way of doing this would be to have a small microcontroller directly connected to each display (one display per microcontroller) and then make the microcontrollers communicate with each other (or with a single master) over some suitable communication medium (some wireless system, or a serial bus like RS485 or CAN, for example).

You're then just rubber-stamping the units as many times as you want, and connecting them all together.
> 2 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Motor cutting out when using HC-05 Bluetooth module
I'm using an L293D motor driver chip along with an HC-05 Bluetooth module. The two work as expected separately - I can send a string via a Bluetooth terminal app on my phone to the HC-05 and I see it in the serial monitor just fine, and I can use the serial monitor to change the speed/direction of the DC motor without an issue. However, if I try to use the Bluetooth console on my phone to change the speed, the motor only spins for about a second before I lose connection with the HC-05 and it stops.

I think this is happening because the Arduino is tripping some breaker by drawing too much current to power both the HC-05 chip and the DC motor. Is this the case? Should I use an external battery pack to power the DC motor and L293D chip, and then keep the HC-05 connected to the 5V out line on the Arduino?

Thanks.

# Answer
> Previously I was powering everything off of the 5V line on the Arduino, but I just switched to using an external battery pack of 4 AAs and that seems to work fine.

That suggests, that your power source was not strong enough. You didn't say, how you are powering the Arduino, but I guess you are doing so via USB. The USB port of a PC can only give you 500mA of current (at least without any extra configuration to get more). Also the parts on the Arduino (for example the diode between USB power and the 5V pin) can only give you a limited amount of current. Especially when the motor is starting, the needed current is rather big. That might have caused a short voltage dip, deep enough to irritate the HC-05 module.

Using an extra battery as power source for the motor eliminates that problem. Though I think you should be able to connect all parts to the same power source, as long as it is powerfull enough to power all parts (plus some overhead). In that case be sure to connect the power for the L293D and Arduino in parallel, so that the motor current does not have to flow through the Arduino (which could kill the voltage regulator or the diode).

Depending on your motor, it also might generate a huge amount of EMI (Electromagnetic Interference) either though air transmission or through the power lines, which might irritate the HC-05 enough. In that case the easiest option would be to add a second power source. Though I think the problem is with the power source as described above.
> 0 votes

---
Tags: power, bluetooth, current, hc-05, l293d
---


# Question
Title: Setting an array pointer to null on declaration
How can I set an array pointer to **null**?

I have a pointer to a 3 int array that I am trying to set to **null**.

> int (\*EXCLUSIVE\_COLOR)\[3\];

Per this link I was trying to set it to null upon initialization.
However this does not assign a null value to it. It assigns three 'random' integers to the array elements:

> {128, 447, 451}

How can I make it point to a **null** or **empty** value?

# Answer
> 5 votes
Here is a full example that shows you all thing things you have been asking over the past few days:

```
int colors[][3] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255}
};

#define NCOLOR (sizeof(colors) / sizeof(colors[0]))

int *EXCLUSIVE_COLOR = NULL;

void setup() {
    Serial.begin(115200);
    Serial.print("You have ");
    Serial.print(NCOLOR);
    Serial.println(" colors defined.");
    reportColor();
    EXCLUSIVE_COLOR = colors[2];
    reportColor();
    EXCLUSIVE_COLOR = NULL;
    reportColor();
}

void loop() {

}

void reportColor() {
    if (!EXCLUSIVE_COLOR) {
        Serial.println("Color is not set");
    } else {
        Serial.print("Color is set to ");
        Serial.print(EXCLUSIVE_COLOR[0]);
        Serial.print(",");
        Serial.print(EXCLUSIVE_COLOR[1]);
        Serial.print(",");
        Serial.println(EXCLUSIVE_COLOR[2]);
    }
}

```

You have an array of colours. You have a pointer that can point at a colour or at nothing. It starts off pointing at nothing. The code recognises that it's pointing at nothing and reports it. It gets assigned to a specific colour in your colours array. The code recognises that it's now a valid value and reports it. The pointer then gets pointed to nothing again. Again the code recognises that and tells you.

The result:

```
You have 3 colors defined.
Color is not set
Color is set to 0,0,255
Color is not set

```

---
Tags: array, pointer
---


# Question
Title: Efficient way to store array with repeating values?
So I have about 2000+ X and Y values where I will look up the Y value for a given X value. If I store the values naively they won’t fit in memory, however there are a lot of repeating values and the X values are arranged in numerical order so I don’t really need to store them explicitly.

So my plan is to use the 3 most common Y values and have an array for all the Y values with only 4 possible values (So using only 2 bits with a bitfield), where 0,1 and 2 corresponds to the most common Y values and 3 tells the program to go fetch the value somewhere else, and here I am thinking a hash table/tree.

Before implementing all this stuff I thought I would ask here if anyone has a better way of doing this, such as if it’s possible/recommended to use the flash memory on the arduino for this or if there’s some better way to store the data. The Y data consists of analog read values which hover around a specific value (say 800) and vary +- 20 or so. I think a histogram of the Y data follows a normal distribution, but I currently do not have enough data to tell.

# Answer
> 1 votes
Without a better understanding of what the data is or how you intend to use it it's impossible to give you real recommendations.

However it is simple enough to store your data in flash memory.

Since X is just a sequential value it can, as you have noted, be ignored.

For the rest, a simple array in flash which you then read with `pgm_read_<X>()` where `<X>` is the data size that you are using.

All this can be read on the Arduino PROGMEM Reference Page although the documentation is not great.

So here's a little example:

```
const int values[] PROGMEM = {
   100, 399, 2847, 1, -497, 32, 4370
};

void setup() {
    Serial.begin(115200);
    for (int i = 0; i < 7; i++) {
        Serial.println((int)pgm_read_word(&values[i]));
    }
}

void loop() {
}

```

The casting of the return from `pgm_read_word` as an `int` is needed to interpret the sign bit properly (it returns unsigned by default).

---
Tags: memory-usage, data
---


title: Atmega 328pu as stand alone

text:
# Question
Title: Atmega 328pu as stand alone
I am used atmega 328pu as stand alone.i used 7805 as regulator. I regulated from 12 VOLT 2 amp smps.

When I connect my dc 12 VOLT pump in between 12 VOLT and ground dc motor working fine but Atmega stops working.

Please help me with this.

EDIT: Information added from the comments.

Q: Does the Arduino work with the motor disconnected?

A: Yes it's works fine

# Answer
Add 0.1uF caps from pin 7 to 8, and from pin 20 to 22. Keep them close to the chip. If you will be doing any analogRead()s, then add one from 21 to 22 as well.
> 1 votes

---
Tags: atmega328, relay
---


title: How To Activate H-Bridge?

text:
# Question
Title: How To Activate H-Bridge?
My understanding of the H-bridge is, that activating in1 or in2 will direct the 12V current to the motor, so it either spins right/left. Not that in1 or in2 is the actual current passing through to the 12V motor.

These are the schematics.

I am trying to activate the H-bridge and the 12V motor by powering In1 with digital 2 from my Arduino.

The power outlet is an universal adapter connected to my wall outlet, which then goes to a breadboard power supply.

I don't have a functioning multimeter, so I cannot measure the exact current going through, but I do know, that if I place in1 in the power outlet's Vout the 12V motor spins.

Other than that, I do not have much information, and I would like to ask you guys for help as to why, the 12V motor doesn't spin when I power in1?

# Answer
There was no common GND between the H-Bridge and the Arduino.

The question has been solved.
> 1 votes

---
Tags: hardware, h-bridge
---


title: Arduino IDE 1.8.6 not starting.

text:
# Question
Title: Arduino IDE 1.8.6 not starting.
My Arduino IDE is not getting started. It just crashes before opening up. I don't know what the problem is. It was working well enough before without any issues.

This is what I see after running the arduino\_debug.exe in the command line

Note: I added a library (DHT) to work with my humidity and temperature sensor and since after then, this issue comes up. I tried to reinstall it like more than 7 times, but the issue still persists.

Please help me with it. Thanks.

# Answer
> 7 votes
The cause of the problem is that you have a corrupted library index file. The solution is to delete the file, which will force the Arduino IDE to download a (hopefully) uncorrupted fresh version from the Internet:

1. Open the C:\Users\JK\AppData\Local\Arduino15 folder
2. Delete the file library\_index.json
3. Try starting the Arduino IDE again

---

For anyone encountering this problem who is using an operating system other than Windows, the location of library\_index.json is different:

On Linux:

`/home/{username}/.arduino15` (a.k.a. `~/.arduino15`)

On macOS:

`/Users/{username}/Library/Arduino15`

If using the Arduino IDE in portable mode:

`{Arduino IDE installation folder}/portable`

---

The issue of a corrupted library index file preventing the Arduino IDE from starting has been reported to the Arduino developers and they are already working on a fix:

https://github.com/arduino/Arduino/issues/7937

# Answer
> 2 votes
Had same issue when migrating from Arduino IDE 1.8.2 to 1.8.9

In my case, deleting just the library\_index.json was not enough but a good hint.

I did also delete the subdirectories of "packages" directory (boards which I downloaded- the ESP32 board and the ESP8266 board), and all files (not folders) in C:\Users\\%username%\AppData\Local\Arduino15\ except the preferences.txt

This solved the issue for me.

# Answer
> 1 votes
I had the same problem this morning when trying to launch the IDE (1.8.3). I'm running Linux Mint 18.

Running the IDE from the command line showed the following errors:

The output hints at a problem with 'packages' so I renamed ~/.arduino15/package\_index.json to package\_index.json.old. The IDE was then able to be launched. 'package\_index.json' can then be rebuilt by starting your boards manager through 'Tools-\>Board'.

---
Tags: arduino-ide
---


# Question
Title: Using HC-SRO4 sensor and looking for obstacle
I am working in TinkerCAD, I want to design and simulate a circuit in which there are following components: 1.)An Arduino board. 2.)A potentiometer 3.)An HC-SRO4 sensor 4.)An LED. So, the sensor should be able to tell if the range that has been set via the potentiometer has any objects in it or not. And if there are one or more objects in that range then the LED should also light up. Also, the user should be able to change the range using potentiometer during simulation. I have attached the code here, but for some reason, I don't feel satisfied. Here is a list of the possible reasons. 1.) For LED lightening up, I had to use another `if else` , since it was showing an error `else used without a previous if` if I used LED in the same `if else`2.) The theoretical range for the sensor I have used is `2cm-400cm` but in my circuit, it was not showing the upper range as `400cm`. Please tell the possible solutions. Also, can I improve my code and circuit

Here is the code which I used.

```
const int echoPin = 6;
const int pingPin = 7;

void setup()
{
 Serial.begin(9600);//Starting serial terminal
}

void loop()
{
  int sensorValue = 0;//Setting variable
  int mappedValue = 0;
  const int potentiometerRange = 0;//setting the buttons to variables to avoid confusion.
  long distance;//declaring a varible in loop because we can change the range during runtime.
  long actualDuration;//...
  long duration;
  pinMode(A0,INPUT);
  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);//
  sensorValue = analogRead(potentiometerRange);//reading the potentiometer value.
  mappedValue = map(sensorValue,0,1023,2,400);//mapping the value accordingly for ultrasonic sensor.
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);//to ensure a clean high pulse later
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);//to trigger the ping.
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);
  pinMode(echoPin,INPUT);//noe echo which tuns low in the time when waves return back.
  duration =  pulseIn(echoPin,HIGH);//time calculated by sensor
  //calculation of distance from any object
  actualDuration = duration/2;//reducing the time in half for the distance is half only.
  distance = 0.0343*actualDuration;//keeping in mid that speed of sound is 343 m/s and pulseIn returns time in microseonds.
  if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
  else
    Serial.println("NO");
  if(mappedValue>=distance)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);
   delay(500); // Delay a little bit to improve simulation performance
}

```

I'm also attaching the picture of my circuit.

# Answer
There's not much code there, so not much to optimize. I will however show you how to combine your two `if`s.

You have:

```
if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
  else
    Serial.println("NO");
  if(mappedValue>=distance)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);

```

and I guess you tried this:

```
if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
  else
    Serial.println("NO");
    digitalWrite(11,LOW);

```

That would be correct in Python where the indenting matters (oh how that brings back the PTSD of having to work with COBOL...) but not in C. In C indenting is ignored completely. It's only there for our benefit in reading the flow of code.

Instead to group statements together within an `if` or an `else` (or any other conditional or loop structure) you wrap those statements in a *block*. That is, place `{` before it and `}` after it. Thus:

```
if(mappedValue>=distance)//checking if the object is in range
{
    Serial.println("YES");
    digitalWrite(11,HIGH);
}
  else
{
    Serial.println("NO");
    digitalWrite(11,LOW);
}

```

Or with my preferred formatting:

```
if(mappedValue>=distance) { //checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
} else {
    Serial.println("NO");
    digitalWrite(11,LOW);
}

```
> 0 votes

---
Tags: sensors, potentiometer
---


title: Power MPU 6050 module through pin AD0

text:
# Question
Title: Power MPU 6050 module through pin AD0
**TL;DR**: is it safe to power a MPU 6050 module through its AD0 pin instead of VCC?

We managed to have two MPU 6050 modules on the same I2C buffer by changing the address of one of them by connecting its AD0 pin to the same current origin used for VCC.

We found out that we can get the same result if we just switch the power cable which goes to the VCC pin to the AD0 pin: the module changes its address and we are able to read its data normally.

This would be a better configuration for us because, if the AD0 cable ever got disconnected, we wouldn't get anything from the second module but we would still get uncorrupted data from the first one. In the other case (cable to both VCC and AD0), if the AD0 cable got disconnected, we would get corrupted data.

So the final configuration would be: GND, SCL, SDA pins connected normally, power to AD0, pin VCC left unconnected.

The question is: is this a safe configuration or is it better to just leave the VCC pin connected normally and get another cable to the AD0?

From empirical tests it looks like it works fine, but we couldn't find any confirmation and are not experts on the matter.

# Answer
Theoretically that should be OK.

According to the datasheet the MPU6050 consumes no more than 3.9mA with all the internal options turned on. That is below the limit of 25mA sustained current from a single IO pin for the ATMega chips. Just be aware of the total limit of the ATMega's power pins of 200mA, but it would take a lot of modules to reach that limit.

Since the MPU6050 is a 3.3V device your modules most likely have a voltage regulator on them to allow powering from 5V. That should mitigate any voltage droop caused by the higher impedance of using an IO pin as a voltage source.
> 1 votes

---
Tags: i2c, mpu6050
---


# Question
Title: ESP01 and Arduino - Serial port confusion
I'm trying to understand how to think about ESP01 devices and arduino connectivity

I purchased one of the USB programmers from Ebay to program the ESP01 - this works nicely, I can see the ESP doing things (I have it pinging a server sending data back and forth)

Obviously, the ESP01 has very few GPIO pins, so I'm interested in connecting to an arduino so I can combine the Arduino's IO with the Wifi on the ESP, and this is where I'm getting a little stuck. I'm assuming I have to connect the RX pin on the Uno to the TX on the ESP and the TX on the Uno to the ESP RX to set up the connection, but I'm confused as to which serial port to use on the Uno.

Specifically:

* are the TX/RX pins on the arduino actually the same serial port as the USB connector - i.e if my intent is to plug the arduino into a computer to talk to it over USB, should I not then re-use the TX/RX pins to talk to the ESP
* if so, should I look to software serial or something similar and use other IO pins on the arduino to connect to the ESP01

... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

# Answer
> 1 votes
The Arduino UNO only has one serial port. That is pins 0/1 (RX and TX), which is mapped to the `Serial` object.

Those pins and that object are also used for communication with the PC through the USB connection. That means you can't easily use them for both PC communication and ESP8266 communication. It's possible, but it gets messy.

That is why many people use `SoftwareSerial` because that can work on any combination of pins on the Arduino that you like.

> ... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

Again, that is possible, but very messy. You could possibly get things to pass through from `Serial` to a `SoftwareSerial` instance, but it's not reliable (`SoftwareSerial` in general is not reliable for sustained transfers of data), and using the Arduino as a dumb UART interface would entail changing the wiring to pins 0/1 when you wanted to program.

So it's far simple to just use your USB interface for programming. Either that or set up OTA programming for the ESP8266 so you don't even have to use wires.

---
Tags: arduino-uno, uart, esp
---