title: Using StringStream in Arduino sketch

text:
# Question
Title: Using StringStream in Arduino sketch
I learned about StringStream today at work.

```
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>

using namespace std;

char* getSql() {
    float outdoorTempInC = 15;
    int outoorHumidity = 23;
    float indorTempinC = 20;
    int humidity = 22;
    int val = 400; // soil sensor reading
    int avgVal = 38; // avaerage of 10 values of soils sensor
    char statusMsg[50] = {"Hello World"} ;
    std::stringstream sqlQuery;
    sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
        << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
        << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
        << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
        << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
        << statusMsg << "');";

    char *mychar = new char[sqlQuery.str().length() + 1];
    strcpy(mychar, sqlQuery.str().c_str());
    return mychar;
}

string getSqlStream() {
    float outdoorTempInC = 15;
    int outoorHumidity = 23;
    float indorTempinC = 20;
    int humidity = 22;
    int val = 400; // soil sensor reading
    int avgVal = 38; // avaerage of 10 values of soils sensor
    char statusMsg[50] = {"Hello World"} ;
    std::stringstream sqlQuery;
    sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
        << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
        << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
        << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
        << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
        << statusMsg << "');";
    return sqlQuery.str();
}

int main() {
    string sql = getSqlStream();
    cout << getSql() << "\n";
    cout << sql.c_str() << "\n";
    return  0;
}

```

I was very happy until I discovered I cannot use StringStream in Arduino, so I dug in the internet and came across with this.

So if I try to use the above linked gist StringSteam like I have used in my example code, I am getting this error:

```
error: no match for 'operator<<' (operand types are 'StringStream' and 'const char [60]')
     sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
               ^
webServer_Displaying_everything_v01:24: error: 'outdoorTempInC' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
            ^
webServer_Displaying_everything_v01:24: error: 'outoorHumidity' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                        ^
webServer_Displaying_everything_v01:24: error: 'indorTempinC' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                                                    ^
webServer_Displaying_everything_v01:25: error: 'humidity' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                      ^
webServer_Displaying_everything_v01:25: error: 'val' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                            ^
webServer_Displaying_everything_v01:25: error: 'avgVal' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                                             ^
webServer_Displaying_everything_v01:28: error: 'class StringStream' has no member named 'str'
     char *mychar = new char[sqlQuery.str().length() + 1];
                                      ^
webServer_Displaying_everything_v01:29: error: 'class StringStream' has no member named 'str'
     strcpy(mychar, sqlQuery.str().c_str());

```

Or I am doing it completely the wrong way? It feels I still cannot use it the way I have done in the example. Please help.

# Answer
> 3 votes
**Direct Answer**

Program in C++ and cross compile to the Arduino Yún. The Arduino Sketch language is a thin layer over C++, but the std:: namespace is not light weight to the degree it would need to be to fit the things you are appreciating from the standard C++ library into the memory footprint of a small embedded CPU board. See Arduino Yun C++ environment? Bridge + Cross-Compiler.

**Serious Programming on Arduino**

If you wish to open the door to C++ elegance on smaller embedded CPU boards like the simpler Arduinos, you will need to move beyond the Arduino sketch language. You may find it both fun and useful to learn how to cross compile and link using the GNU tool set that targets the Atmel CPU you have on your board.

This more professional approach is not for the faint at heart, but it is done all the time. We do it here in TranSeed Labs every day.

To get started, you don't need to download or install anything other than the Arduino software. The tool set that targets Atmel's AVR architecture (used by several Arduino boards) is in a sub-directory under the Arduino IDE's home directory. The tool set that targets Atmel's SAM Architecture for the Arduino Due is placed in a sub-directory of your home directory when you set up the IDE to upload sketches to the Due.

**Returning to the Question in This C++ Context**

Once you learn how to compile and link using g++ from the GNU tool chain1 and use the upload tools2 your program via the USB port, you can create a template class to get the elegance available in C++ like the operator overloading that you like.

The issue with trying to employ the C++ library with embedded targets is that the allocation system and other dependencies will probably exhaust much if not all of your program memory. The ostringstream class from the C++ library, with all its dependencies included, is not extremely lean.

An approach that consumes very little memory and does not require the CPU cycles of dynamic allocation is to create a C++ template that wraps a static array. Its buffer size can be one of the template parameters.

Then you can overload the \<\< operator of the class using these examples as a guide. You get your elegance and drastically reduce your computing resource requirements.

---

*\[1\] Both cross compiling and cross linking are done with g++ (gcc for the Aruino and Atmel C files in the library). For Arduino boards using the AVR based Atmel CPUs, use the AVR GNU Tool Chain. For the Due, which uses the SAM based Atmel CPUs, use the SAM5X GNU Tool Chain.*

*\[2\] The program bossac is used to upload to the Due. The program avrdude is used to upload to the Mega 2560.*

# Answer
> 1 votes
It has nothing to do with cross compiling or linkage using the GNU tool. IO streams do present on Arduino but attempt to include it result in too big binary. It simply does not fit on chip's memory.

There are a couple of solutions to this problem. One is to use a library called ard-streams. Another one is to use a lightweight, simplified version of `stringstream` just enough to compile your code.

```
#include <string>

namespace ard
{
    struct ostringstream
    {
        ostringstream() = default;
        ostringstream(std::string arg) : s(std::move(arg)) {}

        const std::string& str() const {
            return s;
        }

        // Arithmetic types: int, float, ...
        template <class T>
        auto operator<<(T arg) -> decltype(std::to_string(arg), *this) {
            s.append(std::to_string(arg));
            return *this;
        }

        // String types: std::string, const char*
        template <class T>
        auto operator<<(const T& arg) -> decltype(std::string().append(arg), *this) {
            s.append(arg);
            return *this;
        }

        // Single char: 'a', '\n', ...
        ostringstream& operator<<(char arg) {
            s.append(1, arg);
            return *this;
        }

    private:
        std::string s;
    };
}

```

Now just replace `std::stringstream` with `ard::ostringstream` and it will work as expected.

---
Tags: programming, c++, string
---


# Question
Title: Programming ATTiny1614; Unexpected Signature
Trying to program an ATTTYIN1614 with jtag2updi.

```
https://github.com/ElTangas/jtag2updi

```

I was able to use this tool to program an ATTINY1626-XFR and ATTINY807-MNR, but I'm getting an error with ATTINY1614-SSFR.

```
avrdude: Expected signature for ATtiny1614 is 1E 94 22
         Double check chip, or use -F to override this check.

```

# Answer
I had the wrong ATTiny1614 selected. Needed to select the non-optiboot option.
> 1 votes

---
Tags: attiny
---


# Question
Title: NodeMCU ESP32 as a replacement for my arduino project
I would just like to ask if this microcontroller can power or can manage 2 servos, 2 motors, and 2 hc-sr04 ultrasonic distance sensor combined? Also, does this board come with a bluetooth module?

# Answer
The ESP32 has more than enough free GPIOs to manage those peripherals. Also, the ESP32 does indeed come with a bluetooth module.

Your question about powering these peripherals very much depends on their power requirements. I would not count on being able to run motors or servos from the internal power supply of a NodeMCU board, so you would need an external supply.

Also, note that the ESP32 is a 3.3V device and might require logic level translation if you’re using 5V peripherals.
> 4 votes

---
Tags: arduino-uno, esp8266, esp32, nodemcu
---


# Question
Title: How do you get 2 PWM pins to inversely bitbang at 25 KHz on a Nano?
I need 2 PWM pins to oscillate at 25 KHz but they need to oscillate inverse to each other. When one is high, the other must be low and vise-versa.

I want to do this with a Nano.

# Answer
> 8 votes
There are various solutions. I suggest using two PWM channels driven by a single timer. This way you do not have to worry about synchronizing two timers. You can configure the channels identically, except that one of them would be in “non-inverting” PWM mode, while the other one would be in “inverting” mode.

Here is how I would do it: use Timer 1 to drive pins 9 (PB1, OC1A) and 10 (PB2, OC1B) in fast PWM.

```
void setup() {
    // Configure Timer 1 for complementary PWM @ 25 kHz.
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    DDRB  |= _BV(PB2);    // set pin 10 = PB2 = OC1B as output
    TCCR1A = 0;           // undo the Arduino timer initialization
    TCCR1B = 0;           // ditto
    ICR1   = 640 - 1;     // period = 640 CPU cycles = 40 us
    OCR1A  = 320 - 1;     // OC1A HIGH for 320 CPU cycles = 20 us
    OCR1B  = 320 - 1;     // OC1B LOW for 320 CPU cycles = 20 us
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock at F_CPU
}

```

---
Tags: arduino-nano, pwm
---


# Question
Title: MC33926 Brushed Motor Driver (Shield/Carrier)
How can I use a MC33926 Motor Driver like it is offered for Arduino to drive forwards, backwards with a PWM and a direction control.

**The problem is that the MC33926 has Inputs IN1 and IN2 and not PWM and DIR as usual. How can IN1 and IN2 be directly used with a Arduino. Such as it is done in the ArduMower project.**

I'm also wondering under which conditions this is controller is energy efficient? If the load has a flywheel effect (e.g. high RPM mower disk) reducing RPM would waste energy?

I know there are different shields that have logic to drive the inputs with PWM and DIR, but the ArduMower PCB 1.4 decided to hook it up directly. Here is a hardware solution by pololu (I wish i would understand these two NAND gates and the Q2, but that's another problem):

https://www.pololu.com/product/1213/pictures

# Answer
I have figured this so far:

* If the PWM frequency is too low, the load-free power consumption (100% PWM 200mA) of the motors increases(!) rapidly when driving slowly, e.g. 33% to 1A.
* From a certain PWM frequency (\>2kHz), the power consumption normalizes and driving more slowly requires less power.
* MC33936 has IN1 and IN2, which are normally connected with IN1 = LOW and IN2 = PWM or IN1 = PWM and IN2 = LOW (not good for most MCs)
* Alternatively you can use IN1 = PWM and IN2 = LOW / HIGH **BUT you must INVERT the PWM SIGNAL when running reverse**, i.e. IN1 = PWM and IN2 = LOW or reverse IN1 = ~PWM (inverted PWM) and IN2 = HIGH. Otherwise you start driving at 0 PWM with 100% motor power. This is quite tricky, too.
* MC33936 has no freewheel (except if ENABLE = LOW) and brakes the motor to 0 when IN1 = IN2
* MC33936 is a braking motor controller that actively sets the output RPM. of the motor according to PWM.
> 1 votes

---
Tags: motor, pwm, arduino-motor-shield
---


# Question
Title: Using the touchscreen.getpoint causes program to instantly crash
this code runs fine until I add in the if statement surrounding the draw screen() method. upon clicking the screen, the program instantly crashes, turning the screen white. any help would be appreciated.

```
"
// IMPORTANT: Adafruit_TFTLCD LIBRARY MUST BE SPECIFICALLY
// CONFIGURED FOR EITHER THE TFT SHIELD OR THE BREAKOUT BOARD.
// SEE RELEVANT COMMENTS IN Adafruit_TFTLCD.h FOR SETUP.

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library

#include <stdint.h>
#include "TouchScreen.h"
#define YP A2  // must be an analog pin, use "An" notation!
#define XM A3  // must be an analog pin, use "An" notation!
#define YM 8   // can be a digital pin
#define XP 9   // can be a digital pin

// The control pins for the LCD can be assigned to any digital or
// analog pins...but we'll use the analog pins as this allows us to
// double up the pins with the touch screen (see the TFT paint example).
#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0

#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin

// When using the BREAKOUT BOARD only, use these 8 data lines to the LCD:
// For the Arduino Uno, Duemilanove, Diecimila, etc.:
//   D0 connects to digital pin 8  (Notice these are
//   D1 connects to digital pin 9   NOT in order!)
//   D2 connects to digital pin 2
//   D3 connects to digital pin 3
//   D4 connects to digital pin 4
//   D5 connects to digital pin 5
//   D6 connects to digital pin 6
//   D7 connects to digital pin 7
// For the Arduino Mega, use digital pins 22 through 29
// (on the 2-row header at the end of the board).

// Assign human-readable names to some common 16-bit color values:
#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
// If using the shield, all control and data lines are fixed, and
// a simpler declaration can optionally be used:
// Adafruit_TFTLCD tft;
int six;
int hundred;
int twenty;
int ten;
int four;
int eight;
int two;
int twelve;
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
void setup()
{
  Serial.begin(9600);
  Serial.println(F("TFT LCD test"));
  tft.reset();
  uint16_t identifier = tft.readID();

  tft.begin(identifier);
  tft.fillScreen(BLACK);

  six = random(1, 6);
  eight = random(1, 8);
  twenty = random(1, 20);
  hundred = random(1, 100);
  four = random(1, 4);
  ten = random(1, 10);
  two = random(1, 2);
  twelve = random(1, 12);

  tft.setTextColor(WHITE);  tft.setTextSize(4);
  drawNumbers();

}

void loop() {

  six = random(1, 6);
  eight = random(1, 8);
  twenty = random(1, 20);
  hundred = random(1, 100);
  four = random(1, 4);
  ten = random(1, 10);
  two = random(1, 2);
  twelve = random(1, 12);
  if (ts.getPoint().z != 0) {
    drawNumbers();
  }

}

void drawNumbers() {
  tft.setCursor(0, 0);
  tft.fillScreen(BLACK);
  tft.println("D2: " + String(two));
  tft.println("D4: " + String(four));
  tft.println("D6: " + String(six));
  tft.println("D8: " + String(eight));
  tft.println("D10: " + String(ten));
  tft.println("D12: " + String(twelve));
  tft.println("D20: " + String(twenty));
  tft.println("D100: " + String(hundred));

}"

```

this library seems largely ill documented, but this seems egreigous if its not on my end.

# Answer
> 1 votes
**Updated:**

* Provided info not revelant.

I would approach the problem like this. What if anything is returned by getPoint.

```
  if (ts.getPoint().z != 0) {
    drawNumbers();
  }

```

To

```
  auto pt = ts.getPoint().z;
  Serial.print("Point: ");
  Serial.println(pt);

  if (pt != 0) {
    drawNumbers();
  }

```

This would tell me if I am getting a value back or if it is a problem elsewhere.

Hope this helps.

# Answer
> 1 votes
Figured it out

the TFT screen im using forces the sharing of pins being used for analog and digital together. By starting my draw method with pinMode() i set the pins to be treated as the touchscreen's

```
void drawNumbers() {
    pinMode (XM, OUTPUT);
  pinMode (YP, OUTPUT);
  tft.setCursor(0, 0);
  tft.fillScreen(BLACK);
  tft.println("D2: " + String(two));
  tft.println("D4: " + String(four));
  tft.println("D6: " + String(six));
  tft.println("D8: " + String(eight));
  tft.println("D10: " + String(ten));
  tft.println("D12: " + String(twelve));
  tft.println("D20: " + String(twenty));
  tft.println("D100: " + String(hundred));

}

```

---
Tags: tft
---


title: AW9523B I2C on Arduino Nano

text:
# Question
Title: AW9523B I2C on Arduino Nano
I'm testing the AW9523B IO expander with an Arduino Nano. I can't get the device to be recognized.

Using I2C scanner to find all attached I2C devices.

I've connected AW9523B to the correct pins to the SDA/SCL pints of the Arduino, with 5K pullups. INTN is connected to GND.

An EEPROM is also connected on the bus. The EEPROM is recognized on the bus. I swapped the SDA/SCL pins just to make sure, and still AW9523B was not found on bus.

I've tried changing the AD0 and AD1 pins to no avail.

I have a 22uf capacitor on the VCC.

Changing the AD0 pin does change the default state of a connected LED, so I'm fairly confident the chip is not dead.

I've also tried the two example sketches from:

> https://github.com/mrmx/AW9523B

Curious if anyone has gotten their AW9523B to work.

**Updated Working Schematic**

# Answer
> 2 votes
Transcribing and adding to the answer from the comments.

The AW9523B has a reset (RSTN) pin 23 which is internally pulled low by a 100K ohm resistor (i.e., default = reset). @Majenko suggests attaching a pull-up 10K ohm resistor to +5V (i.e., not reset) to enable the chip.

The data sheet schematics and section describing the reset function (pg14) seem to anticipate the RSTN pin being connected to an MCU GPO pin used to dynamically control the reset function.

---
Tags: arduino-nano, i2c
---


# Question
Title: Printing the array using print and serial write function in Arduino Uno
I have, one program with only using printing array and other with serial write and print function for the array, while using serial write and print function I get these extra characters between the data as shown below, can anyone help me with this

Printing the array with print function

```
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "%02X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    //Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}

```

Using with serial write and print function for array

```
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "%02X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}

```

# Answer
> 6 votes
`Serial.write(some_byte)` writes a byte on the serial output. The Arduino serial monitor tries to interpret the bytes it receives as text:

* `0x11` is a control character, displayed as “□”
* `0x22` is the ASCII code for the double quote (")
* `0x33` is the ASCII code for the digit 3.
* `0x44` is the ASCII code for the uppercase letter “D”
* etc.

# Answer
> 1 votes
To store a 2 character string you need a 3 byte array, not a 2 byte array. This is because in C a string consists of the actual string data *and* a zero ("NULL") byte at the end to indicate where the end of the string is.

So you would need:

```
char Hex_Array[3];

```

so it can store, for the number 0x69: `69\0`. Otherwise you overrun the array and corrupt other data that follows in the stack, and changing that other data corrupts your string by changing the "end of string" marker to some other random ASCII character.

---
Tags: serial, softwareserial, array, print
---


# Question
Title: unable to modify NTPClient to use static IP address
I tried the example File \> Examples \> ESP8266WiFi \> NTPClient which requests the current time and it worked fine. Then I tried to modify it so that the ESP8266 would have a static IP address on my home network. I added the following lines before **void setup()**

```
IPAddress staticIP(192, 168,   0, 159);
IPAddress  gateway(192, 168,   0,   1);
IPAddress   subnet(255, 255, 255,   0);

```

Then, in **void setup()** I added a line and commented out the original line like this

```
//  WiFi.mode(WIFI_STA);
WiFi.config(staticIP, gateway, subnet);

```

After running the sketch after I did this, it connected to my home network without any problems (as it did before). But this time, after it prints the message **sending NTP packet...** to the serial monitor, it just says **no packet yet**. This process is repeated every 10 seconds, but it never comes back with the time.

My troubleshooting efforts have been to uncomment the original line and comment out the line I added above. This restores the sketch to its working condition. I have done this several times over the past three days and the same thing always happens.

If I subscribed to conspiracy theories, I might think that some DHCP zealots are behind this. Unfortunately, I can't come up with a better explanation. So to ask just one question, "How can I get my ESP8266-01, flashed with Arduino 1.8.10, running on a Windows 8.1 laptop, to have a static IP on my home network and fetch current NTP timestamps from the internet?

(for reference, this is the sketch in question)

```
/*

  Udp NTP Client

  Get the time from a Network Time Protocol (NTP) time server
  Demonstrates use of UDP sendPacket and ReceivePacket
  For more on NTP time servers and the messages needed to communicate with them,
  see http://en.wikipedia.org/wiki/Network_Time_Protocol

  created 4 Sep 2010
  by Michael Margolis
  modified 9 Apr 2012
  by Tom Igoe
  updated for the ESP8266 12 Apr 2015
  by Ivan Grokhotkov

  This code is in the public domain.

*/

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#ifndef STASSID
#define STASSID "peopleMightFreakIfIuseMyRealInfo"
#define STAPSK  "dontHaveAsecurityPanicAttack"
#endif

const char * ssid = STASSID; // your network SSID (name)
const char * pass = STAPSK;  // your network password

IPAddress staticIP(192, 168,   0, 159);
IPAddress  gateway(192, 168,   0,   1);
IPAddress   subnet(255, 255, 255,   0);

unsigned int localPort = 2390;      // local port to listen for UDP packets

/* Don't hardwire the IP address or we won't get the benefits of the pool.
    Lookup the IP address for the host name instead */
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;

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

  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);
//  WiFi.mode(WIFI_STA);
  WiFi.config(staticIP, gateway, subnet);
  WiFi.begin(ssid, pass);

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

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

  Serial.println("Starting UDP");
  udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(udp.localPort());
}

void loop() {
  //get a random server from the pool
  WiFi.hostByName(ntpServerName, timeServerIP);

  sendNTPpacket(timeServerIP); // send an NTP packet to a time server
  // wait to see if a reply is available
  delay(1000);

  int cb = udp.parsePacket();
  if (!cb) {
    Serial.println("no packet yet");
  } else {
    Serial.print("packet received, length=");
    Serial.println(cb);
    // We've received a packet, read the data from it
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = ");
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);

    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    Serial.print(':');
    if (((epoch % 3600) / 60) < 10) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ((epoch % 60) < 10) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch % 60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(10000);
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress& address) {
  Serial.println("sending NTP packet...");
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  udp.beginPacket(address, 123); //NTP requests are to port 123
  udp.write(packetBuffer, NTP_PACKET_SIZE);
  udp.endPacket();
}

```

# Answer
> 2 votes
As well as specifying your IP address and gateway you also have to provide DNS server addresses. These are normally provided by DHCP, and the ESP8266 *doesn't* assume that it's the same as your gateway address when using a static IP address.

Normally you would use your router's IP address as your DNS server address, but you can also use the Google public DNS servers on `8.8.8.8` and `8.8.4.4`.

The full format of the `config` function is:

```
  WiFi.config(staticIP, gateway, subnet, dns);

```

where `dns` is, like the other parameters, an `IPAddress`.

# Answer
> 1 votes
If you use Arduino IDE with \<ESP8266WiFi.h\> there is a different order for the arguments in the config-statement See the comment in the source code: //ESP argument order is: ip, gateway, subnet, dns1 //Arduino arg order is: ip, dns, gateway, subnet.

So after lots of trouble i changed my config in WiFi.config(STATICIP, DNS1, GATEWAY, SUBNET) and everything works smooth now. The comment means that if you use ESP-IDE (?) the argument order is: ip, gateway, subnet, dns1. When you use Aduino IDE (for ESP8266) the argument order is: ip, dns, gateway, subnet.\_

---
Tags: esp8266, programming, time
---


# Question
Title: How to retrieve the data type of a variable?
I am using Arduino and I would like to know if there is a function that returns the data type of a variable. That is, I would like to run something as like the following:

```
// Note: 'typeof' is a sample function that should return the data type.
Serial.println(typeof(myVar));

```

# Answer
> 20 votes
In a typical C++ program, you would use the `typeid` operator, like this:

```
std::cout << typeid(myVar).name();

```

***However,*** that requires a compiler feature called Runtime Type Information (RTTI). It's disabled in the Arduino IDE, presumably because it tends to increase the runtime memory requirements of the program.

You can get more information about the resource cost here: https://stackoverflow.com/questions/579887/how-expensive-is-rtti

Any fully-featured C++ compiler will definitely support RTTI though. If you want to try using a 3rd party IDE (such as Eclipse with the Arduino plugin) then you could easily enable it. It's probably not worth the hassle just for that though.

---

**Alternative**
A higher-performing (but less flexible) solution would be to use a traits class approach. This involves some funky template meta-programming:

```
// Generic catch-all implementation.
template <typename T_ty> struct TypeInfo { static const char * name; };
template <typename T_ty> const char * TypeInfo<T_ty>::name = "unknown";

// Handy macro to make querying stuff easier.
#define TYPE_NAME(var) TypeInfo< typeof(var) >::name

// Handy macro to make defining stuff easier.
#define MAKE_TYPE_INFO(type)  template <> const char * TypeInfo<type>::name = #type;

// Type-specific implementations.
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( short )

```

You can add `MAKE_TYPE_INFO(..)` lines for any type you want, including the names of custom classes. You could then use it like this:

```
int myVar = 17;
Serial.println( TYPE_NAME(myVar) );

```

Anything you don't define using `MAKE_TYPE_INFO(..)` will show up as `"unknown"`.

That's some fairly advanced stuff in there, so I won't try to explain how it all works here. There are various tutorials on the web though about C++ template programming if you're interested.

EDIT: It's worth noting that the `typeof` operator isn't standard C++, but is supported by a few compilers, such as GCC. It's basically an older equivalent of `decltype`, which appears in the C++11 standard.

# Answer
> 19 votes
I use a simple stupid approach...

```
// serial print variable type
void types(String a) { Serial.println("it's a String"); }
void types(int a) { Serial.println("it's an int"); }
void types(char *a) { Serial.println("it's a char*"); }
void types(float a) { Serial.println("it's a float"); }
void types(bool a) { Serial.println("it's a bool"); }

```

This is the concept of **function overloading** where **multiple functions** with different parameter types are created but with the **same function name**. During run time, the function matching the right number of arguments and argument type(s) will get called. Hope this explanation helps.

# Answer
> 3 votes
Building on @snakeNET's answer (which I regard as function **overload** rather than **polymorphism**)...

A more generic way would be to pass in a pointer to Print, allowing any Print related class to be used (not just Serial); also pass objects by reference e.g.

```
void types(Print* p, const String&) { p->print("it's a String"); } // for each type
...
Serial.print("Type is "); types(&Serial, myStr); Serial.println();

```

Note that I has changed 'println' to 'print'; again, making it more generic.

# Answer
> 1 votes
I tested the template form, the long-hand form, and the `__PRETTY_FUNCTION__` macro and got different results. See the last two rows of the table for the differences.

# Template Form 1

Attribution: Peter Bloomfield

```
MAKE_TYPE_INFO( bool )
MAKE_TYPE_INFO( bool* )
MAKE_TYPE_INFO( char )
MAKE_TYPE_INFO( char* )
MAKE_TYPE_INFO( double )
MAKE_TYPE_INFO( double* )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( float* )
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( int* )
MAKE_TYPE_INFO( short )
MAKE_TYPE_INFO( short* )
MAKE_TYPE_INFO( String )
MAKE_TYPE_INFO( String* )
MAKE_TYPE_INFO( char[5] )
MAKE_TYPE_INFO( char(*)[5] )

```

# Long-Hand Form

Attribution:

1. SnakeNET
2. brewmanz
3. Tweaked by me to be more generic.

```
const char* TypeOf(const bool&)   { static const char type[] = "bool";    return type; }
const char* TypeOf(const bool*)   { static const char type[] = "bool*";   return type; }
const char* TypeOf(const char&)   { static const char type[] = "char";    return type; }
const char* TypeOf(const char*)   { static const char type[] = "char*";   return type; }
const char* TypeOf(const double&) { static const char type[] = "double";  return type; }
const char* TypeOf(const double*) { static const char type[] = "double*"; return type; }
const char* TypeOf(const float&)  { static const char type[] = "float";   return type; }
const char* TypeOf(const float*)  { static const char type[] = "float*";  return type; }
const char* TypeOf(const int&)    { static const char type[] = "int";     return type; }
const char* TypeOf(const int*)    { static const char type[] = "int*";    return type; }
const char* TypeOf(const String&) { static const char type[] = "String";  return type; }
const char* TypeOf(const String*) { static const char type[] = "String*"; return type; }
//const char* const TypeOf(const char[5])    { static const char* type = "char[5]";    return type; }  // Decays to char* so generates compiler redefinition warning.
const char* const TypeOf(const char(*)[5]) { static const char* type = "char(*)[5]"; return type; }

```

# Template Form 2: `__PRETTY_FUNCTION__` Macro

Attribution:

1. Original `String` version by Vladimir Talybin
2. Tweaked `char` array version by me.

## Using `String`

```
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;
    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');
    return s.substring(start, stop);
}

```

## Using `char` array

This variation has lower memory requirements.

```
template <typename T>
char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin = strstr(pf, "[with T = ") + 10;
    char* end = strrchr(pf, ']');
    *end = 0;
    return begin;
}

```

# Test Code

```
bool b = false;
char c = 'a';
double d = 1.2;
float f = 3.4;
int i = 5;
String s = "6789";
char chars[] = "1234";

Serial.println(F("TypeOf() Test"));
Serial.println(TypeOf(b));
Serial.println(TypeOf(&b));
Serial.println(TypeOf(c));
Serial.println(TypeOf(&c));
Serial.println(TypeOf(d));
Serial.println(TypeOf(&d));
Serial.println(TypeOf(f));
Serial.println(TypeOf(&f));
Serial.println(TypeOf(i));
Serial.println(TypeOf(&i));
Serial.println(TypeOf(s));
Serial.println(TypeOf(&s));
Serial.println(TypeOf(chars));
Serial.println(TypeOf(&chars));

Serial.println(F("TYPE_NAME() Test"));
Serial.println(TYPE_NAME(b));
Serial.println(TYPE_NAME(&b));
Serial.println(TYPE_NAME(c));
Serial.println(TYPE_NAME(&c));
Serial.println(TYPE_NAME(d));
Serial.println(TYPE_NAME(&d));
Serial.println(TYPE_NAME(f));
Serial.println(TYPE_NAME(&f));
Serial.println(TYPE_NAME(i));
Serial.println(TYPE_NAME(&i));
Serial.println(TYPE_NAME(s));
Serial.println(TYPE_NAME(&s));
Serial.println(TYPE_NAME(chars));
Serial.println(TYPE_NAME(&chars));

Serial.println(F("type_name() Test"));
Serial.println(type_name(b));
Serial.println(type_name(&b));
Serial.println(type_name(c));
Serial.println(type_name(&c));
Serial.println(type_name(d));
Serial.println(type_name(&d));
Serial.println(type_name(f));
Serial.println(type_name(&f));
Serial.println(type_name(i));
Serial.println(type_name(&i));
Serial.println(type_name(s));
Serial.println(type_name(&s));
Serial.println(type_name(chars));
Serial.println(type_name(&chars));

```

# Results

| TypeOf() | TYPE\_NAME() | type\_name() |
| --- | --- | --- |
| bool | bool | bool |
| bool\* | bool\* | bool\* |
| char | char | char |
| char\* | char\* | char\* |
| double | double | double |
| double\* | double\* | double\* |
| float | float | float |
| float\* | float\* | float\* |
| int | int | int |
| int\* | int\* | int\* |
| String | String | String |
| String\* | String\* | String\* |
| char\* | char\[5\] | char \[5\] |
| char(\*)\[5\] | char(\*)\[5\] | char (\*)\[5\] |

# Some Conclusions

1. `TypeOf()` has an issue with a decaying pointer.
2. `TypeOf()` and `TYPE_NAME()` have to have individual definitions with long-hand form or `MAKE_TYPE_INFO`.
3. `type_name()` uses the `__PRETTY_FUNCTION__` macro to automatically get the type name within the template function, therefore there is no need to individually define the different types.
4. Template Form 1 has the lowest memory requirements.

# Questions

1. Since Template Form 2 has higher memory requirements than Template Form 1, how could it be converted from Form 2 to Form 1?
2. How would a `static const char *` be initialised from a substring of a `char` array obtained from the `__PRETTY_FUNCTION__` macro and passed as a template argument at compile-time?

Something like this pseudo code?

```
static const char * name = substr(__PRETTY_FUNCTION__, begin, end);

```

Perhaps this constant expression which can be assigned to a template struct member at compile-time? (I used a `for` loop because `strstr` and `strrchr` are not `constexpr`.)

```
template <typename T>
constexpr char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin;
    char* end;
    begin = end = pf;
    bool found_open_square_bracket = false;
    for (; *pf != 0; pf++)
    {
      if (!found_open_square_bracket && *pf == '[')
      {
        begin = pf + 10;
        found_open_square_bracket = true;
      }
      if (*pf == ']')
      {
        end = pf;
      }
    }
    *end = 0;
    return begin;
}

```

# Answer
> 1 votes
There also a trick using compiler predefined macro. The advantage is it can print any type.

```
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;

    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');

    return s.substring(start, stop);
}

```

Use it like this

```
double pi = 3.14;
const char* str = "test";

Serial.println(type_name(pi));
Serial.println(type_name(str));

```

## EDIT:

Some improvements based on tim's analyze.

First I have a comment on variation that has lower memory requirements. `__PRETTY_FUNCTION__` is a literal string (a constant) that should not be changed. So my const version that do not use heap is following.

```
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature;
    while (*beg++ != '=');
    ++beg;

    const char* end = signature + N;
    for (; *end != ']'; --end);

    static char buf[N];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}

```

A less safe but more efficient version using the fact that offset to type we want extract is a constant (always the same). If function signature changes (like put it in a namespace) the offset will change too. But come on, set it once, write a comment and it will work forever :).

```
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature + 42;
    const char* end = signature + N - 2;

    static char buf[N - 43];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}

```

While above is ok ofcourse it can be improved further. Here is a my version of constexpr function mentioned by @tim. It uses constant offset as above to keep it short. This code generates only extracted string of type, the proof is here.

```
#include <utility>

template <class T, std::size_t... I>
const char* type_name(std::index_sequence<I...>)
{
    static constexpr char name[] = { __PRETTY_FUNCTION__[I + 60]..., 0 };
    return name;
}

template <class T>
const char* type_name(const T&)
{
    return type_name<T>(
        std::make_index_sequence<sizeof(__PRETTY_FUNCTION__) - 44>());
}

```

The minimum requirement for this is C++14 because of sequence traits. These can be re-implemented (see definition here) to adapt it to C++11.

---
Tags: serial, variables, data-type
---


# Question
Title: Converting Arduino Uno with Ethernet Shield sketch for Arduino Yún
I'm new to the Arduino Yun and I'm trying to convert a sketch written for the Arduino Uno with a Ethernet Shield. The sketch does HTTP posts to Azure Mobile Services.

I've added in the `Bridge.h` and `YunClient.h` libraries in place of the `Ethernet.h` one for the Uno.

My modified sketch compiles, however, I don't think the http posts are working. I don't see my table updating in Azure. /\* \** This sample Arduino sketch uploads telemetry data to Azure Mobile Services \** See the full article here: http://hypernephelist.com/2014/07/11/arduino-uno-azure-mobile-services.html \** \** Thomas Conté @tomconte \*/

```
#include <Bridge.h>
#include <YunClient.h>
//#include <Ethernet.h> // removed as not used by Yun
#include <SPI.h>

// not sure if these libraries are required?
#include <HttpClient.h>
#include <Process.h>

// Ethernet shield MAC address (sticker in the back)
//byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// 90:A2:DA:F8:28:38

// Azure Mobile Service address
// You can find this in your service dashboard
const char *server = "myhost.azure-mobile.net";

// Azure Mobile Service table name
// The name of the table you created
const char *table_name = "my_data";

// Azure Mobile Service Application Key
// You can find this key in the 'Manage Keys' menu on the dashboard
const char *ams_key = "HJRxFXXXXXXXXXXXXXXXXXXXNQoMcXXXXXXx99";

//EthernetClient client;
YunClient client;

char buffer[64];

/*
** Send an HTTP POST request to the Azure Mobile Service data API
*/

void send_request(int value)
{
  Serial.println("\nconnecting...");

    Serial.print("sending ");
    Serial.println(value);

    // POST URI
    sprintf(buffer, "POST /tables/%s HTTP/1.1", table_name);
    client.println(buffer);

    // Host header
    sprintf(buffer, "Host: %s", server);
    client.println(buffer);

    // Azure Mobile Services application key
    sprintf(buffer, "X-ZUMO-APPLICATION: %s", ams_key);
    client.println(buffer);

    // JSON content type
    client.println("Content-Type: application/json");

    // POST body
    sprintf(buffer, "{\"value\": %d}", value);

    // Content length
    client.print("Content-Length: ");
    client.println(strlen(buffer));

    // End of headers
    client.println();

    // Request body
    client.println(buffer);

}

/*
** Wait for response
*/

void wait_response()
{
  while (!client.available()) {
    if (!client.connected()) {
      return;
    }
  }
}

/*
** Read the response and dump to serial
*/

void read_response()
{
  bool print = true;

  while (client.available()) {
    char c = client.read();
    // Print only until the first carriage return
    if (c == '\n')
      print = false;
    if (print)
      Serial.print(c);
  }
}

/*
** Close the connection
*/

void end_request()
{
  client.stop();
}

/*
** Arduino Setup
*/

void setup()
{
Serial.begin(9600);
Serial.println("Starting Bridge");
Bridge.begin();

}

/*
** Arduino Loop
*/

void loop()
{
  int val = analogRead(A0);

  send_request(val);
  wait_response();
  read_response();
  end_request();

  delay(1000);
}

```

# Answer
(Updating answer from comments.)

The OP answered their own question, they missed the code to connect to the web service

`if (client.connect(server, 80))`
> 1 votes

---
Tags: arduino-yun
---


# Question
Title: What are the sizes of each primitive datatype on a Metro M4 Express SAMD51?
What are the data sizes of all the primitive datatypes on a Metro M4 Express SAMD51 C++ implementation? In some C++ implementations, `int` has 16 bits and in other implementations it has 32 bits. Is

# Answer
> 0 votes
And that is the only difference in fundamental type sizes. On 8-bit Arduinos `int` is 16 bit and on 32-bit `int` is 32 bit.

* `short` is 16 bit
* `long` is 32 bit
* `long long` is 64 bit

https://en.cppreference.com/w/cpp/language/types

# Answer
> 0 votes
Here is a sketch to quickly find out **unsigned** maximum values on any architecture and deduce the bit width from them (I had to use sprintf, because Serial.println(unsigned long long) did not work on my Due):

```
#include <limits.h>

#define sprintfln(args...) { char _qsx6_[200]; snprintf(_qsx6_, 200, args); Serial.println(_qsx6_); } // _qsx6_ may collide with local var

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

    unsigned char  uc = 0; uc=~uc; Serial.println(uc);
    unsigned short us = 0; us=~us; Serial.println(us);
    unsigned int   ui = 0; ui=~ui; Serial.println(ui);
    unsigned long  ul = 0UL; ul=~ul; Serial.println(ul);
    unsigned long long ull = 0ULL; ull=~ull; // doesn't work: Serial.println(~ull);

    sprintfln("char:%u short:%u int:%u long:%lu long long:%llu", uc, us, ui, ul, ull);
    sprintfln("char:%u short:%u int:%u long:%lu long long:%llu", UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, ULLONG_MAX);
    sprintfln("char:%u short:%u int:%u long:%u long long:%u", sizeof(uc), sizeof(us), sizeof(ui), sizeof(ul), sizeof(ull));
    sprintfln("pointer:%u", sizeof(&uc));
}

```

On Arduino Due this gives (I expect it to be the same on SAMD51):

```
char:255
short:65535
int:4294967295
long:4294967295
long long:18446744073709551615
char:1 short:2 int:4 long:4 long long:8
pointer:4

```

Usually you could include "limits.h", but it seems that unsigned long long is missing (at least on Due). Hmmm, I didn't expect int and long to be the same, good to know.

---
Tags: c++, data-type
---


# Question
Title: How do I read from a correct data address of LIDAR using Arduino in I2C?
I need to read the distance data from a lidar in I2C using an Arduino Nano. Currently, this is the code I've written.

```
unsigned int readDistance()
{
  unsigned int dist = 0 ; // LiDAR actually measured distance value. static so we can return previous dist

  // step 1: instruct sensor to read echoes
  Wire.beginTransmission(0x10) ; // transmit to device 0x10
  Wire.write(2) ; // sets distance data address (addr)
  Wire.write(3) ; // sets distance data address (addr)
  Wire.endTransmission() ; // stop transmitting

  // step 2: wait for readings to happen
  delay(100) ; // datasheet suggests at least 100ms

  // step 3: request reading from sensor
  Wire.requestFrom(0x10, 2) ; // request 2 bytes (DIST_L, DIST_H) from slave device #0x10
  dist = Wire.read() ; dist += Wire.read() << 8; // calculate distance value, bit shift high distance
  return dist ; // return updated dist
}

```

But I have a feeling I'm requesting from the wrong data address', since I'm not getting the results I expect (ie. varying distance data). Furthermore, I used an I2C scanner which 100% confirms the lidar is on the (default address) of 0x10.

Datasheet of (TF02 Pro): https://www.unmannedtechshop.co.uk/wp-content/uploads/2020/01/TF02-Pro-Product-Manual-Alpha.pdf

**Question: am i reading from the right data address** Any help would be appreciated.

# Answer
> 2 votes
Long story short, some i2c devices are configured such that data is only present in said registers after continually issuing 'read commands'.

In this case, the read command was: 5A 05 00 01 60

Amended code:

```
unsigned int readDistance()
{
  unsigned int dist = 0 ; // LiDAR actually measured distance value

  // step 1: instruct sensor to read echoes
  Wire.beginTransmission(0x10) ; // transmit to device 0x10
  Wire.write(0x5A) ; // some read command.
  Wire.write(0x05) ;
  Wire.write(0x00) ;
  Wire.write(0x01) ;
  Wire.write(0x60) ;
  Wire.endTransmission() ; // stop transmitting

  // step 2: wait for readings to happen
  delay(100) ; // datasheet suggests at least 100ms

  // step 3: request reading from sensor
  Wire.requestFrom(0x10, 4) ; // request first 4 bytes from slave device #0x10
  Wire.read() ; Wire.read() ; //ignore header bytes
  // remaining two bytes for distance (DIST_L, DIST_H)
  dist = Wire.read() ; dist += Wire.read() << 8 ; // calculate distance value, bit shift high distance
  return dist ; // return updated dist
}

```

---
Tags: i2c
---


title: Error using `NtpClientLib.h`

text:
# Question
Title: Error using `NtpClientLib.h`
Since Core of ESP8266 upgraded to v.3.0 (now it is 3.0.2), I encounter errors using this library.

First, the deprecation of `byte` to `uint8` (hoped that an upgrade of NTP lib to 3.0.2 beta will solve it ), but now even using library's built in example file fails, show the same message regarding `byte` error.

Is there a workaround ?

```
In file included from /home/guy/Documents/git/Arduino/libraries/NtpClientLib/examples/NTPClientESP8266/NTPClientESP8266.ino:38:
/home/guy/Documents/git/Arduino/libraries/NtpClientLib/src/NtpClientLib.h:501:32: error: reference to 'byte' is ambiguous
  501 |     bool summertime (int year, byte month, byte day, byte hour, byte weekday, byte tzHours);
      |                                ^~~~
In file included from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/cmath:42,
                 from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/math.h:36,
                 from /home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/cores/esp8266/Arduino.h:34,
                 from sketch/NTPClientESP8266.ino.cpp:1:

```

EDIT 1 :: VERSIONS

# Answer
> 1 votes
The esp8266 Arduino 3 has breaking changes so library authors need to adjust their libraries to this changes. Check the repository of the library for the fixes.

The NtpClient library was marked as deprecated by the author. The reason was that there is a better way to work with NTP on ESP. Now the library was 'restarted' as an alternative to SDK functions because the author solved microseconds accuracy.

If you don't need microseconds accuracy, you don't need to use Arduino NtpClient library on esp8266 or esp32. The Espressif SDK have support to get the NTP time to internal RTC.

Both ESP Arduino cores have examples for NTP. For esp8266 it is the esp8266/NTP-TZ-DST example.

The NTP part should be in setup()

```
configTime(TIME_ZONE, "pool.ntp.org");

```

TIME\_ZONE should be value from `TZ_` constants from `TZ.h`, for example I have

```
#include <TZ.h>
#define TIME_ZONE TZ_Europe_Bratislava

```

The SDK will keep the time with the internal RTC of the ESP and adjust it periodically from NTP server.

You can get the esp8266 RTC time time with

```
time_t t = time(nullptr); // epoch
struct tm *tm = localtime(&t);
uint8_t minute = tm->tm_min;
uint8_t hour = tm->tm_hour;

```

if you want to wait in setup() until the time is retrieved you can use

```
  time_t now = time(nullptr);
  while (now < SECS_YR_2000) {
    delay(100);
    now = time(nullptr);
  }

```

---
Tags: ntpclient
---


# Question
Title: What is the correct way to externally power a MKR 1010 WiFi
I'm a little confused by the powering arrangements of the MKR 1010 WiFi. I need to power it on a breadboard from an external power supply. I will not be using a LiPo battery and I need it to work when the USB is disconnected.

Assuming there is no battery or USB connected, I think I need to apply power on the `Vin` pin (the pinout diagram on `arduino.cc` shows this as an input pin and `5V` as an output pin). However, the `5V` pin has a resettable fuse inline whereas `Vin` does not, which to me is counterintuitive.

So my questions are twofold:

1. What is the correct pin for supplying external power, and
2. What is the correct voltage to apply

# Answer
> 2 votes
> What is the correct pin for supplying external power, and

VIN

> What is the correct voltage to apply

The bq24195 can accept between 3.9V and 17V according to the datasheet. However the power LED on the board may blow if you apply more than about 12v since it only has a 330Ω resistor with it.

---

The polyfuse on 5V is there to protect the USB's power connection incase the user makes a mistake and short circuits it. It's more for the protection of your computer's USB port than the MKR board itself.

---
Tags: power, breadboard, mkr1010
---


# Question
Title: nRF52 non-volatile storage/recall of a variable - is there a simple solution?
I have an Arduino program written for the nRF52 with which runs for a pre-set time-value (i.e. 2 minutes) before shuts off automatically. The variable time-value can be changed via BLE-write by the user from an external device (i.e. from 2 mins to 5 mins). The problem that it defaults to the pre-set (2 mins) value once the program restarts. **How can I have the program "save" the last used time-value variable (i.e. 5 mins) for the next boot up/restart?**

As I understand Nordic's nRF52 does NOT have an onboard EEPROM like AVRs. I read about a Little File System by Adafruit that creates a sort of persistent storage space, but I hope there is something simpler.

# Answer
The arduino-NVM library for nRF51 and nRF52 MCU has EEPROM object which emulates EEPROM in the internal flash memory of MCU.

The EEPROM object in arduino-NVM has the same functions as the EEPROM object in the Arduino EEPROM library for classic ATmega.
> 2 votes

---
Tags: eeprom, variables, memory, nrf52
---


# Question
Title: Arduino ESPTelnet.h library read data from cmd screen
I am new to Arduino. I used Arduino IDE for upload code to ESP8266 module. I wrote an ATM application on the tiva-tm4c123 board. I am trying to connect to the application from the internet using telnet and ip address. I uploaded the example code of the ESPtelnet library to the ESP8266 module and connected the esp wifi module to the tm4c123 card by using uart. The ESP8266 module sends the data from the tiva card to the putty screen that I connect via telnet. But it does not transfer what I write from the putty screen to the tiva card. I couldn't find a function like telnet.read(). Is there a telnet function that will read the data from the Putty screen? I searched a lot but couldn't find it. If I find this function, I know that I can send the read data to the tiva card with Serial.write(telnet.read).ESP's RX and TX are connected to the tiva card. I created a wireless connection to the Putty screen. When a char or string is entered on the telnet screen, it will send it to the tiva card with Serial write from the TX of the ESP8266.I want to write a code that will run in the following logic.

```
 if (telnet.available()) {
    Serial.print(telnet.read());
  }

```

Here is the example code

```

#include "ESPTelnet.h"

/* ------------------------------------------------- */

#define SERIAL_SPEED    115200
#define WIFI_SSID       "****"
#define WIFI_PASSWORD   "****"

/* ------------------------------------------------- */

ESPTelnet telnet;
IPAddress ip;

/* ------------------------------------------------- */

void setupSerial(long speed, String msg = "") {
  Serial.begin(speed);
  while (!Serial) {
  }
  delay(200);
  Serial.println();
  Serial.println();
  if (msg != "") Serial.println(msg);
}

/* ------------------------------------------------- */

bool isConnected() {
  return (WiFi.status() == WL_CONNECTED);
}

/* ------------------------------------------------- */

bool connectToWiFi(const char* ssid, const char* password, int max_tries = 20, int pause = 500) {
  int i = 0;
  WiFi.mode(WIFI_STA);
  #if defined(ARDUINO_ARCH_ESP8266)
    WiFi.forceSleepWake();
    delay(200);
  #endif
  WiFi.begin(ssid, password);
  do {
    delay(pause);
    Serial.print(".");
  } while (!isConnected() || i++ < max_tries);
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
  return isConnected();
}

/* ------------------------------------------------- */

void errorMsg(String error, bool restart = true) {
  Serial.println(error);
  if (restart) {
    Serial.println("Rebooting now...");
    delay(2000);
    ESP.restart();
    delay(2000);
  }
}

/* ------------------------------------------------- */

void setupTelnet() {
  // passing on functions for various telnet events
  telnet.onConnect(onTelnetConnect);
  telnet.onConnectionAttempt(onTelnetConnectionAttempt);
  telnet.onReconnect(onTelnetReconnect);
  telnet.onDisconnect(onTelnetDisconnect);

  // passing a lambda function
  telnet.onInputReceived([](String str) {
    // checks for a certain command
    if (str == "ping") {
      telnet.println("> pong");
      Serial.println("- Telnet: pong");
    }
  });

  Serial.print("- Telnet: ");
  if (telnet.begin()) {
    Serial.println("running");
  } else {
    Serial.println("error.");
    errorMsg("Will reboot...");
  }
}

/* ------------------------------------------------- */

// (optional) callback functions for telnet events
void onTelnetConnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" connected");
}

void onTelnetDisconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" disconnected");
}

void onTelnetReconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" reconnected");
}

void onTelnetConnectionAttempt(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" tried to connected");
}

/* ------------------------------------------------- */

void setup() {
  setupSerial(SERIAL_SPEED, "Telnet Test");

  Serial.print("- Wifi: ");
  connectToWiFi(WIFI_SSID, WIFI_PASSWORD);

  if (isConnected()) {
    ip = WiFi.localIP();
    Serial.print(" ");
    Serial.println(ip);
    setupTelnet();
  } else {
    Serial.println();
    errorMsg("Error connecting to WiFi");
  }
}

/* ------------------------------------------------- */

void loop() {
  telnet.loop();

  // send serial input to telnet as output
  // this part read tiva and transmit to ESP
  if (Serial.available()) {
    telnet.print(Serial.read());
  }
}
//* ------------------------------------------------- */

```

# Answer
> 0 votes
It appears to me that the library has been written to accept input terminated by a newline character.

```
    char c = client.read();
    if (c != '\n') {
      if (c >= 32) {
        input += c;
      }
    // EOL -> send input
    } else {
      if (on_input != NULL) on_input(input);
      input = "";
      }

```

It will keep adding characters to the input buffer until a newline character is detected, and then pass the contents to the `.onInputReceived` recieved handler.

If my understanding is correct, the best you can do without making alterations to the library itself is:-

```

  telnet.onInputReceived([](String str) {
      Serial.println(str);
  });

```

Again, if I'm right then the newline character will always need to be present to push the data through.

Hope this is useful.

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


# Question
Title: Arduino Uno won't connect when using USB-C to USB adapter
So I just got my first Arduino which is an Arduino Uno. I have a newer MacBook Air which doesn't have any USB ports so I thought I'd just use one of those USB-C to USB adapters.

I plugged it in and then searched for the Board in the Tools \> Port menu. It was nowhere to be seen, only the `/dev/cu.Bluetooth-Incoming-Port` showed up.

To be clear, the Arduino did show signs of connectivity, it just didn't show up under the Port list. I'm also not 100% sure if it's an Arduino Uno since the company I bought it from said I should select Arduino/Genuino Uno in the Board menu which isn't an option anymore.

Is it a problem with my Arduino, my Laptop or my adapter?

# Answer
> 4 votes
Maybe it is not original, and it uses different usb-serial chip than the original one. Popular converters for Arduino Uno clones are CH340 and CP2104. You may try to install the driver for these 2 chips.

---
Tags: arduino-uno, usb
---


title: Arduino voltage misunderstanding

text:
# Question
Title: Arduino voltage misunderstanding
For arduino nano. I set digital pins 1,2,3,4,5 to HIGH (I do this using digitalWrite(pin,HIGH) for each pin). Does this mean that 5V is being sent through each of the pins so in total there is 25V going out from the arduino? How is this possible?

# Answer
Every pin gives you 5V on HIGH, yes, but these voltages don't add up.

Voltages are always measured between two points. In electronics we are defining one point in our circuit, that we use for all measurements, and call it ground. This is normally the negative pin of the power source.

Each pin has 5V in reference to the same ground, so they cannot add up (because that would mean the second 5V would be in reference to the 5V of the other pin, not in reference to ground). In the end they are connected in parallel to Vcc (where the power for the microcontroller is connected, in this case the 5V pin) of the Arduino (through the output drivers of the respective pin).

In the end this boils down to kirchoff's laws (if you want to research more about it). At a junction of connections, the voltage stays the same, but the current will be divided up between the connections.
> 12 votes

# Answer
Imagine that I have 5 flagpoles. I go to each of those flagpoles and raise a flag to a height of 2 meters. Since I have 5 flags, each at a height of 2 meters, does that mean that my flags have a total height of 10 meters?

Well, that question doesn't make a whole lot of sense, because "total height of the flags" isn't really a meaningful quantity. It's true that if you add up all the heights, you get 10 meters, but that number doesn't have any real meaning. Nothing in the system is 10 meters high.

Likewise, suppose you set 5 output pins all HIGH. Those output pins are just like flags on flagpoles, and you're raising each pin to a "height" of 5 volts. Nothing in the system is at a voltage of 25 volts; it doesn't make any sense to talk about a "total voltage."
> 14 votes

# Answer
It's a fascinating question. The Nano has 22 pins, all potentially set to output. D0 to D13, and A0 to A7.

So we have a total of 22 outputs. Now if they **did** add up then we could connect up a 5V battery and get 110V out of it! That might kill you! So clearly something is amiss here.

It's like when an employee has "20 years experience". Do they really have 20 times the experience they had in the first year, or do they have the same experience 20 times over?

The fact is that all 22 pins are all referenced to the same ground pin, so we really have 22 x 5V but all from the same starting point. So we really have 5V but with maybe a bit more current.

If you look at the datasheet, you don't even have 22 x the current you might have from one pin. The Atmega328P is specified to have a total of 200 mA current output.

Don't worry, setting all pins to output won't kill you. :)
> 2 votes

---
Tags: arduino-nano
---


title: How do you handle sensor drift?

text:
# Question
Title: How do you handle sensor drift?
I have a pair of potentiometers, on the Arduino, the output seems to drift, by one or 2 digits, back and forth. I would prefer they were read as one fixed value, without variation when their knobs are not turning. You can see in the image, the first and second values are shifting back and forth slightly. How should I address this?

I'm thinking of making a standard deviation function, but then I thought that might be unnecessarily complex.

My code is that the 2 sensor values are setting points in an SVG polyline. Variance means extra points will get plotted, while the device waits for valid input.

How should I deal with the variance in potentiometer readings to avoid outputting noise?

Here's my source:

```
/**Fucntion Defs**/
void svgHeader();
void svgFooter();
void polyLineBegin();
void polyLineEnd();

int Reset = 4;     //programmatically reset the arduino
int potX = A0;
int potY = A1;

int sensorValX = 0;
int sensorValY = 0;
int oldX = 0;
int oldY = 0;

int del = 2;       //a button on pin 2 for deleting drawn content
int delbutton = 0;
void setup() {
  Serial.begin(9600);
  pinMode(del, INPUT);
  svgHeader();
  polyLineBegin();
  delay(1000);
}

void loop() {
  // close the svg and start over
  if (digitalRead(del) == LOW ) {
    delbutton = 1;
    polyLineEnd();
    svgFooter();
    delay(5000);
    digitalWrite(Reset, LOW);
    digitalWrite(Reset, HIGH);
    svgHeader();
    polyLineBegin();
  } else {
    delbutton = 0;
    //Serial.println(delbutton);

  }

  //dont draw if its not changing
  sensorValX = analogRead(potX);
  sensorValY = analogRead(potY);
  if (sensorValX == oldX && sensorValY == oldY) {
    ; //dont do shi.
  } else {
    Serial.print(sensorValX);
    Serial.print(",");
    Serial.print(sensorValY);
    Serial.print(",");
    oldX = sensorValX;
    oldY = sensorValY;
    // Serial.println(delbutton);
    delay(1000);
  }
}
/**Functions**/

void polyLineBegin() {
  Serial.println ("<polyline points=\""); //x,y points go here

}

void polyLineEnd() {
  Serial.println ("0, 0\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");  //a dirty hack to avoid dealing with 1 last trailing comma.

}

void svgHeader() {
  Serial.println("<svg width=\"1023\" height=\"1023\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">");
};

void svgFooter() {
  Serial.println ("</svg>");
};

```

# Answer
> 10 votes
ok, once I got the idea I would need to do it in code, it became simpler to solve. In looking around the terms of quantization, the term thresh-holding came up, and I realized how to solve the problem.

I created a threshold value, and compared the difference between old and new variables.

```
int threshold =3;
int xVariance = abs(sensorValX-oldX);
int yVariance = abs(sensorValY-oldY);
if (xVariance >=threshold && yVariance >= threshold ||xVariance >=threshold || yVariance >=threshold){
  Serial.print(sensorValX);
  Serial.print(",");
  Serial.print(sensorValY);
  Serial.print(",");
 oldX=sensorValX;
 oldY=sensorValY;

}else{
; //dont do shi.
 // Serial.println(delbutton);
delay(1000);
    }

```

now, when I turn either potentiometer, I get a response, and output I desire, but not while the device is just sitting there.

# Answer
> 6 votes
Remove the analog component from your device.

Use a rotary encoder.

It will sense the knob rotation digitally.

One huge advantage is that you can easily select the sensitivity of the input. One click can advance the counter by .001 just as easily as advancing by a 1000.

https://duckduckgo.com/?q=rotary+encoder&iar=images&iax=images&ia=images

# Answer
> 5 votes
Some methods for "dealing" with the noise:

1. Take multiple samples. Calculate the average ("mean"). Discard the decimal. This is "oversampling" along with resolution reduction (but reduction of the now increased oversampled resolution).
2. Take multiple samples. Find the most common value ("mode").
3. Divide the value by 2 (or 4 if needed). This reduces the range of values and the sampled resolution but discards the noise portion.

The problem you are suffering from is "quantisation noise". This is because an analog signal and a digital signal are not completely compatible. The ADC converts the analog signal into a digital value by successively comparing it to smaller and smaller voltages in steps ("quanta"). There is a limit to how small the steps can get (the resolution), but an analog voltage doesn't adhere to those steps, it will always be somewhere between the final two steps. Sometimes it will be detected as the lower step, sometimes the upper step. By taking multiple samples and averaging them you are estimating how close to one step or the other the value is and "refining" the result. This is "oversampling" and is used to increase the resolution of the ADC at the cost of sample speed.

With those extra samples you can either say "It's this much closer to the upper step" (take the "mean"), or say "It's more likely to be nearer the upper step" (take the "mode") to try and "fix" the value to one of the steps.

# Answer
> 2 votes
I think you *should* handle the trailing comma within the Arduino by using leading commas instead, but omit the first leading comma using a flag to indicate the first coordinate:

```
bool firstCoordinate;

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        if (!firstCoordinate)
        {
            Serial.print(",");
            firstCoordinate = false;
        }
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}

void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    firstCoordinate = true;
}

void polyLineEnd()
{
    // Clean line ending.
    Serial.println("\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");
}

```

Alternatively, the first coordinate could be added to the line when it begins, then there is no need for a flag:

```
void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    Serial.println(sensorValX);
    Serial.println(",");
    Serial.println(sensorValY);
}

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        Serial.print(",");
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}

```

The thresholding technique is great, but, as an aside, I recently discovered this excellent statistics library by Majenko while working on a non-blocking averaging function for Arduino and looking at converting it into a class. I found that that library already does what I want.

---
Tags: programming, sensors, potentiometer, signal-processing
---


title: Programming Arduino Micro via RX/TX

text:
# Question
Title: Programming Arduino Micro via RX/TX
I can't access my Arduino Micro's USB programming port when it's in my project. I want to reroute the RX and TX pins outside to a serial-to-usb adapter.

I have this on hand from a while ago. I found the RX and TX pins in the serial connector and I connected them to the RX and TX pins of the Arduino as well as GND but when I try and program the device nothing happens. I usually get an open port error or something like that but the programming LED on the adapter doesn't light up. Conversely if I try using the Basic Stamp software I at least get a programming LED to light up on the adapter.

Do I need an FTDI breakout instead? Or am I wiring something wrong?

# Answer
> 2 votes
RS-232 logic uses a negative voltage typically from -3 to -25V to represent a logical high and a positive +3 to +25V to represent a low. On the flip side TTL used on the AtMega uses +5V or +3.3V as a high (or VCC) and 0V as a low. Read more

Other than that the signals are the same logically so all that is needed is to invert the RS232 from -/+ ~12V to 0-5V using a simple converter.

Possibly the easiest approach is to use another Arduino Uno as a programmer, which needs 3 pins, TX, RX, and RESET. This tutorial seems to have some success. Check out "programming an Arduino with another".

# Answer
> 0 votes
yes you can, use a FTDI 232 USB TO SERIAL then set the Arduino IDE to the board you will be programing, and the serial port the FTDI RS232 Programmer is on.

connect the two rx to tx, and tx to rx, also the vcc of programmer to Arduino 5v pin.

then press and hold the reset button, and upload "regular".

The trick is to let go of RESET just after it finishes compiling, and it will get programed.

i think between 1-2 seconds after it finishes compiling and the compiling line just turned all green.

This is also how wireless programmer work using a Bluetooth module. I tried using the DTR pin to reset, but that did not work for me.

---
Tags: serial, communication, arduino-micro, atmega32u4
---


title: Why I cant get sizeof a pointer Array

text:
# Question
Title: Why I cant get sizeof a pointer Array
well I am trying to get array size to convert hex value to int value. but if I try to get size of array it returns every time 2. Actually .I dont understand. how to get array size, can you help me?

this is my code

```
unsigned long w;

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

  uint8_t * packet = read_packet();
  Serial.println(sizeof(packet)); // PROMLEM IS HERE, IT RETURNS EVERYTIME "2"

  for (int i = 0; i < 4; i++)
  {
    Serial.println(packet[i]); //if i print the packet array all elements are here
  }

  /*
    for (byte i = 0; i < sizeof packet; i++) {
      w = w + ((long)(packet[sizeof packet - (i + 1)]) << (i * 8));
    }

  */
}

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

}

uint8_t *read_packet() {
  static uint8_t buffer[4];

  buffer[0] = 0x00;
  buffer[1] = 0x32;
  buffer[2] = 0x32;
  buffer[3] = 0x32;

  Serial.println(sizeof buffer);
  return buffer;
}

```

if I print the packet array, all 4 elements are there 0,50,50,50. but size of array returns every time "2". even if I increase the array size.

maybe you can think why am I using pointers? because of my previous question answer is using this method. Read serial with header and end marker

# Answer
A pointer is just a pointer. It's not an array. On 8 bit Arduinos the memory address range is a 16 bit value, so a pointer will always be 2 bytes.

You need to return two values from your function - the buffer pointer *and* the length of the buffer. This is usually done by passing an extra integer pointer parameter:

```
unsigned long w;

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

  uint8_t plen;
  uint8_t * packet = read_packet(&plen); // Pass the pointer to the plen variable to store the length in

  Serial.println(plen); // This now prints "4"

  for (int i = 0; i < plen; i++) // You can now use `plen` here
  {
    Serial.println(packet[i]); //if i print the packet array all elements are here
  }
}

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

}

uint8_t *read_packet(uint8_t *len) {

  static uint8_t buffer[4];

  buffer[0] = 0x00;
  buffer[1] = 0x32;
  buffer[2] = 0x32;
  buffer[3] = 0x32;

  if (len != NULL) *len = 4; // Store 4 in the length variable if provided

  return buffer;
}

```
> 4 votes

# Answer
Majenko's answer explains things and shows how to fix your code, but the solution with static buffer inside the function is not common.

Common is to have `int readBuffer(unit8_t* buffer, size_t size)`.

The parameters are the buffer provided by the caller and the size of that buffer. The return value is the count of bytes written by the function into the buffer.

Real example:

```
int WiFiEspAtBuffStream::read(uint8_t* data, size_t size) {
  if (size == 0 || !available())
    return 0;

  size_t l = rxBufferLength - rxBufferIndex;
  if (l == 0 && size > rxBufferSize) // internal buffer is empty and provided buffer is large
    return EspAtDrv.recvData(linkId, data, size); // fill the large provided buffer directly

  // copy from internal buffer
  fillRXbuffer();
  for (size_t i = 0; i < l && i < size; i++) {
    data[i] = rxBuffer[rxBufferIndex++];
  }
  if (size <= l) // provided buffer was filled
    return size;
  return l + read(data + l, size - l); // handle the rest of provided buffer
}

```
> 1 votes

---
Tags: arduino-uno, array, pointer
---


# Question
Title: Why Firmata Test doesn't allow me to choose a port?
I'm a beginner and, sorry, also I don't speak English very well. However, I'm going to try to explain my problem. I'm working on Ubuntu 14.04.2 and Arduino Uno R3. I downloaded Firmata Test binaries for Linux 64 bit, I gave it permissions with `chmod 754 <file>`. Also I uploaded StandardFirmata from Arduino IDE to the board. Afterwards, I quit Arduino IDE and ran Firmata Test with `./file`. But, the Port menu has no items within. I tried restarting the board and the application as well.

What can I do?

# Answer
If your user does not have access to serial ports, rather than running an application as root with sudo, try giving your user the appropriate permissions by adding to the dialout group before you run it.

https://askubuntu.com/questions/112568/how-do-i-allow-a-non-default-user-to-use-serial-device-ttyusb0
> 1 votes

# Answer
I had the same problem until I ran it as: sudo ./file
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: What is the rise time of an output pin of atmega328 changing its state?
I've already searched a lot and didn't found the answer. Also, I don't have an o'scope. Anyone can help me?

# Answer
> 5 votes
I just measured on my Uno with a pocket scope and a cheap 1× probe. I got something around 40 ns, but it was at the bandwidth limit of this basic scope, and I believe this probe has quite high capacitive load. A faster scope and a better probe would probably give a shorter rise time.

**Update**: I tried again with a better scope (an Hameg HM-305) and a decent 10× probe, the observed rise time was somewhere in the 10 ns range, which is about the rise time of the internal amplifier of the scope. Then the higher boundary would be about 10 ns.

# Answer
> 4 votes
Last time I measured on a circuit (it was an i2c network master and with a 2560), it was about 0.3us, so that gives you a high value for that. Also, I believe it cannot be faster than one/half of a CPU cycle which takes: 1/(16E6)=62.5ns/2 = 31.25ns, so here's the lower boundary.

And there you got a possible range.

Then the rise time will definitely depend on the configuration of the circuit. It might be less or more depending on pull ups, capacitance attached at the pin out exit. It might also depend on the configuration of the pin (PWM? Internal Pull-up?…)

Finally, I believe there should some nominal values given in the datasheet.

Edit: Useful knowledge from the datasheet, but there's no definitive answer for *any* pin:

P311: **29.4.3 External Clock Drive**

```
| Symbol | Parameter | Min | Max   | Min | Max   | Min | Max   |
| ------ | --------- | --- | ----- | --- | ---   | --- | ----- |
| tCLCH  | Rise Time |     | 2.0µs |     | 1.6µs |     | 0.5µs |

```

P313: **29.6 SPI Timing Characteristics**

```
| Description    | Mode      | Min | Typ   | Max    |
| -------------- | --------- | --- | ----- | ------ |
| Rise/Fall time | Master    |     | 3.6ns |        |
| Rise/Fall time | Slave     |     |       | 1600ns |

```

P315: **29.7 Two-wire Serial Interface Characteristics**

```
| Symbol | Parameter                      | Condition | Min        | Max   |
| ------ | ------------------------------ | --------- | ---------- | ----- |
| tr     | Rise Time for both SDA and SCL |           | 20 + 0.1Cb | 300ns |

```

HTH

# Answer
> 2 votes
I got 8 ns on both the rising and falling edges. If using the PORT instruction to set and clear bits instead of the much slower digitalWrite() instruction, the highest frequency I got by toggling a pin high and low was 2.666 Mhz. This is slowed down by the excessive time the arduino takes to pass execution back to the top of the Loop() marker. The duty cycle of the pulse output at 2.666 Mhz was somewhere in the region of 15%.

---
Tags: arduino-uno, atmega328
---


# Question
Title: arduino nano with lora only runs once if connected to battery
this code works perfectly if connected with usb cable. but as soon as i connect my **Arduino nano** with battery (two 18650 batteries in series connected to **VIN**) it runs loop only once. it sends only 0 to another **LoRa** module (3.3v) and i assume it runs loop only once. blink works without a problem.

```
#include <SPI.h>
#include <LoRa.h>

int counter = 0;

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

  Serial.println("LoRa Sender");

  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
}

void loop() {
  Serial.print("Sending packet: ");
  Serial.println(counter);

  // send packet
  LoRa.beginPacket();
  LoRa.print(counter);
  LoRa.endPacket();
  counter ++;
  delay(3000);
}

```

**Edit**

*battery pack voltage is 7.01v*.

connections I've tried so far:

1. 2x **18650** -\> **VIN** = Does **not** work
2. 2x **18650** \+ regulator -\> **5v** = Does **not** work
3. 2x **18650** \+ regulator -\> **USB** = Does work
4. **USB** -\> **USB** = Of course works

when I say it works I mean it **Arduino** powers up and **LoRa** module sends data but only once and looks like loop is running only once.

# Answer
Again, it would be nice to looking at how you have it set up. You didn't mention any proper signal level conversion, so I'm going to assume there isn't any. My best guess is one of the signals being produced by the Lora module is near the edge of being correct on the ATMega328P.

In comments I asked:

> If you measure the "5V" pin does the measured value read appear to be lower in the working scenarios and higher in the failing scenarios?

The reason for the question is that the logic levels of the ATmega328P are dependent on its VCC, what we're nominally calling "5V".

> when in working condition 5v output reads 4.48 but when using regulator and its failing 5v pin is constantly at 5.05v

By operating the 328P closer to 3.3V (when you're at 4.48), you're lowering the threshold voltage needed for the Lora's signals to reliably register as a HIGH on the Nano's pins.

You will likely need proper level conversion between the Nano and Lora module, but that will depend on the exact module. Keep in mind that *if* your module says it has "5V tolerant" data pins, that doesn't mean it *produces* logic levels acceptable to a 5V Arduino Nano; it just means the module will accept 5V signals at its own inputs.
> -2 votes

---
Tags: arduino-nano, battery, lora
---


title: Wireless programming of Arduino

text:
# Question
Title: Wireless programming of Arduino
I'm trying to find a convenient way to program my Arduino remotely (by Bluetooth or Wi-Fi) because it will be packed and placed outside of my working place. Found a few ways (Arduino Cloud and Blynk) but most of them are about IoT and this is not an IoT project. Maybe you already faced such a problem. If so, then how have you dealt with this?

# Answer
> 3 votes
My ArduinoOTA library, which is based on Arduino's WiFi101OTA library, was created for upload from IDE. But in some scenarios as for example deployed sleeping battery powered devices it is better to have the update available for download by the device.

In advanced section of examples of the ArduinoOTA library you can find examples of sketch update over download from a http server. The OTASketchDownloadWifi shows update over the InternalStorage object of the ArduinoOTA library with download over the WiFiNINA library.

---
Tags: mkr1010, ota
---


# Question
Title: Multiple MFRC522 RFID reader on Uno bugs
I have a problem!

I need to connect 5 MFRC522 readers on an Arduino Uno but it is not working !

With one or two MFRC522 modules it works, when I use three or more nothing works anymore... The serial reading is not working, nothing is read with more than 2 modules. I'm so sad. So tonight I need your help, tell me what is not working in my code or on my setup!

I first thought that it was the Arduino that was not delivering enough current to the modules (on the 3.3v line) but this does not seem to be the case. We added some external ATX PSU power, and connected grounds. Nothing changed.

So we had a look at the code and we *believe* that it is a library problem. Nobody seems to have successfully connected more than 3 MFRC522 modules. Is there really a problem in the library? How could we achieve success?

```
#include <SPI.h>
#include <MFRC522.h>
#include <EEPROM.h>

#define SS_PIN_1 10 // PIN SDA pour le module RFID (1)
#define RST_PIN_1 9 // PIN RESET pour le module RFID (1)
#define SS_PIN_2 8 // PIN SDA pour le module RFID (2)
#define RST_PIN_2 7 // PIN RESET pour le module RFID (2)
#define SS_PIN_3 6 // PIN SDA pour le module RFID (3)
#define RST_PIN_3 5 // PIN RESET pour le module RFID (3)
#define SS_PIN_4 4 // PIN SDA pour le module RFID (4)
#define RST_PIN_4 3 // PIN RESET pour le module RFID (4)
#define SS_PIN_5 2 // PIN SDA pour le module RFID (5)
#define RST_PIN_5 A0 // PIN RESET pour le module RFID (5)
#define RELAY_PIN A1 // Pin du signal du Relais
#define RELAY_ON 1024 // Valeur de seuil d'activation du relais
#define RELAY_OFF 0 // Valeur de seuil de désactivation du relais
#define MASTER_BUTTON_PIN A2 // Pin du bouton d'ouverture prioritaire
#define CONFIGURE_BUTTON_PIN A3 // Pin du bouton de reprogrammation des badges
MFRC522 rfid1(SS_PIN_1, RST_PIN_1);
MFRC522 rfid2(SS_PIN_2, RST_PIN_2);
MFRC522 rfid3(SS_PIN_3, RST_PIN_3);
MFRC522 rfid4(SS_PIN_4, RST_PIN_4);
MFRC522 rfid5(SS_PIN_5, RST_PIN_5);
byte tag1[4] = {0xD6, 0x92, 0xBF, 0x93};
byte tag2[4] = {0xC6, 0xA3, 0xC0, 0x93};
byte tag3[4] = {0x96, 0x58, 0x68, 0x8E};
byte tag4[4] = {0x06, 0xFB, 0xC1, 0x93};
byte tag5[4] = {0x66, 0xF3, 0x63, 0x8E};

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid1.PCD_Init();
  rfid2.PCD_Init();
  rfid3.PCD_Init();
  rfid4.PCD_Init();
  rfid5.PCD_Init();
  Serial.println("Initialisation du système terminé, en attente de badges...");
}

void activate_relay(){
  analogWrite(RELAY_PIN, RELAY_ON);
  Serial.println("Le relay est activé");
}

void desactivate_relay(){
  analogWrite(RELAY_PIN, RELAY_OFF);
  Serial.println("Le relay est désactivé");
}

void loop() {
  if (! rfid1.PICC_IsNewCardPresent()) {
    return;
  }
  if (! rfid1.PICC_ReadCardSerial()) {
    return;
  }
  if (! rfid2.PICC_IsNewCardPresent()) {
    return;
  }
  if (! rfid2.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid3.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid3.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid4.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid4.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid5.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid5.PICC_ReadCardSerial()) {
    return;
  }
  if (rfid1.uid.uidByte[0] == tag1[0]  & rfid1.uid.uidByte[1] == tag1[1] & rfid1.uid.uidByte[2] == tag1[2] & rfid1.uid.uidByte[3] == tag1[3]) {
    if (rfid2.uid.uidByte[0] == tag2[0]  & rfid2.uid.uidByte[1] == tag2[1] & rfid2.uid.uidByte[2] == tag2[2] & rfid2.uid.uidByte[3] == tag2[3]) {
      if (rfid3.uid.uidByte[0] == tag3[0]  & rfid3.uid.uidByte[1] == tag3[1] & rfid3.uid.uidByte[2] == tag3[2] & rfid3.uid.uidByte[3] == tag3[3]) {
        if (rfid4.uid.uidByte[0] == tag4[0]  & rfid4.uid.uidByte[1] == tag4[1] & rfid4.uid.uidByte[2] == tag4[2] & rfid4.uid.uidByte[3] == tag4[3]) {
          if (rfid5.uid.uidByte[0] == tag5[0]  & rfid5.uid.uidByte[1] == tag5[1] & rfid5.uid.uidByte[2] == tag5[2] & rfid5.uid.uidByte[3] == tag5[3]) {
          } else {desactivate_relay();}
        } else {desactivate_relay();}
      } else {desactivate_relay();}
    } else {desactivate_relay();}
  } else {desactivate_relay();}
}

```

I've tried the code above but it didn't work. I also tried the `ReadUidMultiReader` example code but only one reader is working. Both Readers are working individually but only one when I connect them. I shared the SCK, MISO, MOSI, RST, and have different SS pins.

Thank you in advance.

# Answer
> 5 votes
For convenience, here is a comment: You wrote, “I've tried the code above but it didn't work”. That is inadequate to convey what happened and what you wanted to happen. Please edit your question to include a clear statement of symptoms and desired results.

Now on to an answer.

From “I'm only using 2 readers to find the correct and make it work”, I deduce that you have two readers attached. This by itself is enough to keep the code from producing output. Assuming those two readers identify as `rfid1` and `rfid2`, when execution gets to `if ( ! rfid3.PICC_IsNewCardPresent())`, it executes `return;` which terminates `loop()` processing. That is, execution will never get past `if ( ! rfid3.PICC_IsNewCardPresent())`. To clear up that problem, remove all the code that references `rfid` variables other than `rfid1` and `rfid2` (more properly, other than whichever two you have attached).

That will entail removing 18 lines in the early part of `loop()`, and three lines in the big nested-if part of `loop()`.

Here is another comment: When you are debugging code, it makes sense to report lots of intermediate results, and to report them as soon as they are available. Don't go through a long stack of `if` statements and get no output and then say it doesn't work; instead, display and check results when you first read them in.

# Answer
> 0 votes
after around million of trying and trying I discovered that the correct way to connect 4 RFID RC522 is to put them in the same line on test board except SS pins and the code as usual is ReadUidMultiReader from RFID library ... like this :

---
Tags: arduino-uno, rfid, debugging
---


title: How can I check if my thermostat is on?

text:
# Question
Title: How can I check if my thermostat is on?
I'm working on a project to better understand how my home cooling system behaves. I'd like to produce graphs of temperature in various areas, overlaid with when my existing thermostat turns the A/C compressor and fan on.

Connecting up a few ESP8266's with temperature sensors reporting over WiFi is straightforward enough; I'm comfortable doing that. But I'm struggling with how to detect when my thermostat is calling for A/C cooling.

My (battery-powered) thermostat has red, white, yellow, and green wires:

* Red has ~28Vac
* White enables the heating system
* Green enables the fan
* Yellow enables the A/C compressor

With a multimeter, I easily determined that the thermostat simply closes a relay (I can hear it; that was a dead giveaway) and there's no resistance. So if A/C is called for, it closes relays connected Red to Yellow (and Green).

I don't really want to mess with drawing power from the 28Vac; it's easy enough to power an 8266 with 5V from a wall wart and that's sufficient for this project. Ugly, but acceptable.

I want to detect when the thermostat relay is closed and turning on the air conditioner. Clearly I'm not an EE by trade, and I'm struggling with the right search terms to communicate "detect whether two outside pins are electrically connected". I think something that emulates a multimeter's continuity function would work.

I did find references to the LM\*39 series, but (1) I'm not sure it would like being exposed to AC power, and (2) the 'offset voltage' is usually measured in mV, which suggests to me that I'm barking up the wrong tree.

# Answer
Welcome! I used bidirectional optocouplers. The input has a resistor I believe 27K and the output is a NPN transistor with a pull up to +5. The emitter goes to electronic ground. I connected these across the relay coils. They have not given me any problems since installed about 15 years ago. Nice thing they are not polarity sensitive.
> 6 votes

# Answer
Most straight forward method should be to slap an op amp on the leg of the wire that the relay activates and deactivates by connecting to it. The key is to power the op amp with low voltage so your esp gets that as input. The signal legs can handle whatever the relay gives, and the ac, fan, and heater will handle the pull signal for the not connected state.

That only goes so far as to protect the esp by having the op amp take the high voltage and output low. To turn a potentially AC low voltage signal into a nice dc one, use a diode, capacitor, and resistor (trim pot). Remember that this is going to be discharging that cap through your resistor so figure out a minimum and check the pot before powering the device (or add a regular resistor in series).
> 1 votes

---
Tags: esp8266, electricity
---


title: Why won't this work as a delay?

text:
# Question
Title: Why won't this work as a delay?
I'll start off by saying I'm very very new to coding, so please bare with me.

I'm doing an assignment where the task is to create a traffic light system, but blocking delays aren't allowed. I have looked into "blink without delay", but it seems that option would require me to create far too confusing and long code than is needed. So instead I used for, else and goto functions together since it was a lot simpler and cleaner, but I have heard goto isn't a preferred option,

```
for(int i = 0; i < 20; i = i + 1)
{
    break0:
    digitalWrite(Traffic_R, HIGH);
    long int CurrentMillis1 = millis();

    break1:
    if (millis() - CurrentMillis1 <= 250){
        digitalWrite(Pedestrian_R, HIGH);
        goto break1;
    }else{
        long int CurrentMillis2 = millis();

        break2:
        if (millis() - CurrentMillis2 <= 250){
            digitalWrite(Pedestrian_R, LOW);
            goto break2;
        }
    }
}

```

Then I made another way without goto function,

```
for(int Test1 = millis(); Test1 < 7500; Test1 + millis())
{
  digitalWrite(LED, HIGH);
}

```

**TLDR** So my question is, are either of these methods a "blocking method", like delay is? Also what are the pros and cons of each method? Also I can upload the code for the first method if needed. Thanks heaps in advance!

# Answer
> 2 votes
Here I have a simple example of cycling over 3 LEDs with the same 'delay' for every LED.

```
void loop() {

  static unsigned long previousMillis;
  static uint8_t cycleCounter;

  if (millis() - previousMillis > 100) {
    previousMillis = millis();
    digitalWrite(LEDS_CENTRAL_PIN, cycleCounter == 0);
    digitalWrite(LEDS_LEFT_PIN, cycleCounter == 1);
    digitalWrite(LEDS_RIGHT_PIN, cycleCounter == 2);
    cycleCounter++;
    if (cycleCounter == 3) {
      cycleCounter = 0;
    }
  }
}

```

# Answer
> 2 votes
```
break1:
if (something)
  goto break1;

```

is basically a while loop - just more confusing to read.

---

> Also I can upload the code for the first method if needed.

You can upload it, of course. Personally I would mark you down for using `goto`.

---

> are either of these methods a "blocking method", like delay is?

Neither method literally blocks. The `delay` function blocks because it doesn't return until the time is up. Your loops don't block because you could conceivably do something else in the loop.

---

> I have heard goto isn't a preferred option

For a good reason. Do you think that, if you looked at your code again in a year, you would easily understand it? I have been coding for years and would have to carefully follow all the ways that the `goto` could jump around in unexpected ways.

At least with a `while` loop you have a well-defined start and end of the loop.

---
Tags: arduino-uno, programming
---


title: Pulsein not working when share ground

text:
# Question
Title: Pulsein not working when share ground
I have 3rd party device that create PWM output which I want to measure it with Arduino, the problem I have is when I shared ground between the two boards which cause the Pulsein output to become zero. (why this is happening, and how to fix it)

The reason I am connecting the ground since I need measure other signals on that board. (All other signals are responding fine)

simulate this circuit – Schematic created using CircuitLab

code:

```
#define pulse_ip 3
unsigned long duration;
int ontime,offtime,duty;
float freq,period;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(pulse_ip, INPUT);
}

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

  ontime = pulseIn(pulse_ip, HIGH);
  offtime = pulseIn(pulse_ip, LOW);
  period = ontime + offtime;
  freq = 1000000.0 / period;
  duty = (ontime / period) * 100;
  Serial.print(offtime);
  Serial.print("-");
  Serial.print(ontime);
  Serial.print("-");
  Serial.print(period);
  Serial.print("-");
  Serial.print(freq);
  Serial.print("-");
  Serial.print((duty * 255) / 100);
  Serial.print("-");
  Serial.println(duty);
  delay(1000);

}

```

# Answer
> 1 votes
Without connected grounds the signal on the input pin you read with pulseIn must be random noise.

Two `pulseIn` one waiting for HIGH change and second waiting for LOW don't make sense because for parameter HIGH, `pulseIn` **waits for the pin to go from LOW to HIGH**, starts timing, **then waits for the pin to go LOW** and stops timing. Then it returns the length of the pulse in microseconds.

---
Tags: pulsein
---