title: DS3231 is unable to keep record of time

text:
# Question
Title: DS3231 is unable to keep record of time
so i bought a DS3231 clock which i am using with This famous library .

```
// DS3231_Serial_Easy
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
// web: http://www.RinkyDinkElectronics.com/
//
// A quick demo of how to use my DS3231-library to
// quickly send time and date information over a serial link
//
// To use the hardware I2C (TWI) interface of the Arduino you must connect
// the pins as follows:
//
// Arduino Uno/2009:
// ----------------------
// DS3231:  SDA pin   -> Arduino Analog 4 or the dedicated SDA pin
//          SCL pin   -> Arduino Analog 5 or the dedicated SCL pin
//
// Arduino Leonardo:
// ----------------------
// DS3231:  SDA pin   -> Arduino Digital 2 or the dedicated SDA pin
//          SCL pin   -> Arduino Digital 3 or the dedicated SCL pin
//
// Arduino Mega:
// ----------------------
// DS3231:  SDA pin   -> Arduino Digital 20 (SDA) or the dedicated SDA pin
//          SCL pin   -> Arduino Digital 21 (SCL) or the dedicated SCL pin
//
// Arduino Due:
// ----------------------
// DS3231:  SDA pin   -> Arduino Digital 20 (SDA) or the dedicated SDA1 (Digital 70) pin

#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);

void setup()
{
  // Setup Serial connection
  Serial.begin(9600);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
}

void loop()
{
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Wait one second before repeating :)
  delay (1000);
}

```

Now the problem is, after i set a time it shows the time and date perfectly until i cut the power of the DS3231. while being connected to my PC when i disconnected the power of DS3231, i see the timer getting reset while it should have recorded and continued the timer. It outputs 'Monday 1.1.2021 0.0.0'

Is it the problem of my module? or i am doinng something mistake here? or the module works in this way?

whenever i disconnect arduino power from PC, it still continues to count but whenever i disconnect DS3231 from 5 v pin of Arduino, it resets back. Does that mean that the DS3231 need to use the 16Mhz crystal from Arduino to function properly??

# Answer
So you disconnect the 5V to the DS3231, but keep the SDA and SCL pins connected? By doing that, you are working outside of the recommended operating conditions.

If you leave the SDA and SCL pins connected, those pins will be at around 5V. The datasheet specifies that those pins shouldn't be higher that Vcc+0.3V. Where Vcc is 0V, in your case.

Removing power from the Arduino board will also remove the power from the I2C pins, keeping things within specifications.
> 2 votes

---
Tags: ds3231-alarms
---


# Question
Title: Why float and not 16-bit Integer? Mpu6050 with atmega328P
I've been trying to follow this example code for interfacing my atmega328P with Mpu6050: https://www.instructables.com/Accelerometer-MPU-6050-Communication-With-AVR-MCU/

And was wondering a couple of things. First of all, the sensors on an MPU6050 are 16-bit, which means that each sensor value such as Ax, Ay etc. are 2 byte each (8-bit + 8-bit = 16-bit = 2 bytes).

The code itself reads from the following line when obtaining the values: `AcX = Wire.read()<<8 | Wire.read();` where the MSB (8-bit) are first read, and then the LSB (8-bit); which gives us 2 bytes.

So what I don't understand is why he uses float values for storing the sensor-data and not a 16-bit int? Since Floats are 4 byte long; won't that just add a bunch of zeros to the obtained 2 bytes?

# Answer
In the instructables code he's using a `float` because he wants to scale the value to a range of ±2g. The values the accelerometer gives are not the actual values but, like the Arduino's ADC, a representation of the value using a range. By dividing that representation by 16384 you get the actual G value, which is a decimal value.

That value can be more useful than the raw data.

As for that other snippet of code you provide, it cannot work. Not only does it use global variables that don't exist, but it returns a value from a `void` function which cannot happen. I don't know quite what it hopes to achieve.
> 1 votes

# Answer
We can't know this writer's reasons, but a typical reason why someone might use floats vs. ints is that they prefer not to manage the binary-point location and any possible overflows during the following calculations. Instead, they are willing to accept the tradeoff of execution-time vs. programming time, and the increased memory requirements (both RAM and Flash) of letting the floating-point library do it for them.

Update:

Or, as implied elsewhere, the programmer doesn't know how to calculate with integer arithmetic (which to be fair, is a little more complicated than just writing out the formula).
> 1 votes

---
Tags: arduino-ide, mpu6050, bytes
---


# Question
Title: Analog read not working while using WiFi
I have an ESP32, the current program running on it uses WiFi but, if I use WiFi and Analog read at the same time, Analog read does not work.

Why does this happen and what's the way around it?

Hardware - ESP32, Pin 25 for the ADC

Code-

```
#include <WiFi.h>

void setup() {
  Serial.begin(115200);
  WiFi.begin("You really", "Want to know"); // If this line is commented then it works
}

void loop() {
  Serial.println(analogRead(25));
}

```

# Answer
> 11 votes
The ESP32 has two ADCs. One of them, ADC2, is actively used by the WiFi.

From the IDF documentation:

> Since the ADC2 module is also used by the Wi-Fi, only one of them could get the preemption when using together, which means the adc2\_get\_raw() may get blocked until Wi-Fi stops, and vice versa.

That means you can't use the ADC on any of the ADC2 channels while WiFi is on: GPIO4, GPIO0, GPIO2, GPIO15, GPIO13, GPIO12, GPIO14, GPIO27, GPIO25 and GPIO26.

But you can use ADC1, which uses pins GPIO36, GPIO37, GPIO38, GPIO39, GPIO32, GPIO33, GPIO34 and GPIO35.

---
Tags: wifi, esp32, analogread
---


title: playTone function of Buzzer

text:
# Question
Title: playTone function of Buzzer
I am making "Simon says" game using Arduino on TinkerCad. I am facing issue in Buzzer sound function. I want something like this:

1. Use the following steps to generate the tone for the red LED: Play 440 Hz for 150ms Wait for 1136us Play 440 Hz for 150ms
2. Use the following steps to generate the tone for the yellow LED: Play 784 Hz for 150ms Wait for 638us Play 784 Hz for 150ms
3. Use the following steps to generate the tone for the blue LED: Play 587 Hz for 150ms Wait for 851us Play 587 Hz for 150ms
4. Use the following steps to generate the tone for the green LED: Play 880 Hz for 150ms Wait for 568us Play 880 Hz for 150ms

I have following functions for the above:

```
 void playTone2(int tone, int duration) {
  Serial.println(tone);
  for (long i = 0; i < duration * 1000L; i += tone * 2) {
    digitalWriteGeneric(buzzer, true);
    delayMicroseconds(tone);
    digitalWriteGeneric(buzzer, false);
    delayMicroseconds(tone);
  }
}

void playTone(int tone1) {
  Serial.println(tone1);
  if (tone1 == 440) {
    playTone2(440, 150);
    delayMicroseconds(1136);
    playTone2(440, 150);
  }
  if (tone1 == 784) {
    playTone2(784, 150);
    delayMicroseconds(638);
    playTone2(784, 150);
  }
  if (tone1 == 587) {
    playTone2(587, 150);
    delayMicroseconds(851);
    playTone2(587, 150);
  }
  if (tone1 == 880) {
    playTone2(880, 150);
    delayMicroseconds(568);
    playTone2(880, 150);
  }
  if (tone1 == 2700) {
    playTone2(250, 250);
    delay(250);
    playTone2(150, 250);
  }

}

```

First there was only playTone code but I needed different values for different LEDs so I included playTone function and called playTone2 to it. But the tones that I am getting are not accurate may be because of two functions. I will be able to resolve it if I could understand the working of playTone2 function. I tried but no use, kindly share how exactly playtone2 functions here so that I can edit my playTone function accordingly.

# Answer
> 1 votes
Here is a simple sketch to test the tones used for each color of LED. I have not tested it with a speaker, but it compiles in the Arduino IDE, so perhaps it will work as is.

The call to `delayMicroseconds()` is "blocking" code, so you may want to change it to use "non-blocking" code, e.g. Use the `BlinkWithoutDelay` example in the IDE to make a `micros()` based timer.

```
/* Arduino Uno. IDE 1.8.9
   Sketch uses 2540 bytes (7%) of program storage space.
   Global variables use 28 bytes (1%) of dynamic memory.

   red    LED: Play 440 Hz for 150ms Wait for 1136us Play 440 Hz for 150ms
   yellow LED: Play 784 Hz for 150ms Wait for 638us Play 784 Hz for 150ms
   blue   LED: Play 587 Hz for 150ms Wait for 851us Play 587 Hz for 150ms
   green  LED: Play 880 Hz for 150ms Wait for 568us Play 880 Hz for 150ms
*/
byte tonePin = 8;

void setup(){
  pinMode(tonePin, OUTPUT);
  RedLEDSound();
  YellowLEDSound();
  BlueLEDSound();
  GreenLEDSound();
}

void loop(){}

void PlayTone(unsigned int m_frequency, unsigned long m_duration, unsigned long m_pause){
  tone(tonePin, m_frequency, m_duration);
  delayMicroseconds(m_pause);
  noTone(tonePin);
}

void RedLEDSound(){
  PlayTone(440, 150, 1136);
  PlayTone(440, 150, 0);
}

void YellowLEDSound(){
  PlayTone(784, 150, 638);
  PlayTone(784, 150, 0);
}

void BlueLEDSound(){
  PlayTone(587, 150, 851);
  PlayTone(587, 150, 0);
}

void GreenLEDSound(){
  PlayTone(880, 150, 568);
  PlayTone(880, 150, 0);
}

```

---
Tags: arduino-uno, buzzer
---


# Question
Title: Same structure taking different memory space on Uno and NodeMCU ESP8266, leading to data corruption when transferring via nRF24L01+
I'm trying to transfer data between a Arduino Uno board to a NodeMCU ESP8266 board, using nRF24L01+ transceivers module and RF24 library on both side. The data I'm transferring are stored in a `struct` defined this way:

```
// Struct declared in both code
struct sensorData {
    bool doorOpened;
    int light;
    int temperature;
    int humidity;
    float voltage_battery;
};
// Variable in Uno code (source node)
sensorData dataToSend;
// Variable in ESP8266 code (dest node)
sensorData dataToReceive;

```

But the data are not transferred properly between the two boards and I get random values or 0 when trying to display them from ESP8266 (values are correctly displayed from Uno).

Display in Uno (using `signed short` as data type, see following paragraphs):

Display in ESP8266 (using `signed short` as data type, see following paragraphs):

After some testing, I found out that memory-allocation on both boards are different, as Uno takes *2 bytes* to store `int` while ESP8266 takes *4 bytes*. Moreover, sensorData takes *11 bytes* of memory on Uno (1 for `bool`, 2 for `int` and 4 for `float`, which sums up to *11 bytes*), but takes *20 bytes* of memory on ESP8266 (1 for `bool`, 4 for `int` and 4 for `float`, which does NOT sum up to 20 !).

Trying to solve this, I tried changing `int` for `signed int`, `byte`, `short`, `signed short` but the transmission problem remains. When using `short` or `signed short` (which takes *2 bytes* on both boards), my structure `sensorData` still takes *11 bytes* of memory on UNO while it takes *12 bytes* of memory on ESP8266. For some reason, ESP8266 always takes more space than needed to store `sensorData`, probably causing bits to be wrongly placed when receiving data.

I'm sure that both boards, radio module and transmission protocol work as I successfully tested the same code with a smaller struct (`text` was "Hello World !" and `cmp` was increased at each transmission):

```
struct Package {
    char text[16];
    long cmp;
};

```

Does anyone have faced this issue before ? How could I solve that ?

# Answer
> 12 votes
There are three main issues you may need to deal with when passing structures between systems that use different processors.

The first is that data types vary in size between architectures. You can avoid this for integers by avoiding the basic C types and instead using the fixed size types from stdint.h/cstdint. For floating point types this is less of a problem as most systems use the IEEE single and double precision types for float and double.

The second is padding, according to the C standard padding is implementation dependent. In practice most compilers will insert the minimum amount of padding needed to meet alignment requirements. Exactly what the alignment requirements are also depend on the implementation, but the alignment requirement of a type is always a factor of it's size.

You can thus avoid compiler-generated padding on most architectures by designing your structure to place types on "natural" alignment (that is their offset in the structure is a multiple of their size) and to have a size that is a multiple of the largest type in the structure. So you might design your structure as.

```
struct sensorData {
    int8_t doorOpened; //size 1 offset 0
    int8_t spare; //size 1 offset 1
    int16_t light; //size 2 offset 2
    int16_t temperature; //size 2 offset 4
    int16_t humidity; // size 2 offset 6
    float voltage_battery; //size 4 offset 8
};

```

Another option is to use packed structures, but extreme care is needed when using such, especially in C++. It is easy to create unaligned pointers or references.

The final issue is byte order (also known as endian), if your systems use different byte orders for integer or floating point values you will need to insert conversions to deal with this.

# Answer
> 12 votes
`int`, `long`, etc have different sizes depended on the compiler and target.

Use explicit sizes to make sure you're variables have the size you want. Eg. `uint8_t`, `int16_t` or `int32_t`, ... (as @Mat commented)

Also, I wouldn't use `bool` (if writing in `C`) as it's not really standard in `C` and the size is also implementation dependent: https://stackoverflow.com/questions/1608318/is-bool-a-native-c-type

Extra, there are different types of explicit sizes: https://stackoverflow.com/questions/5254051/the-difference-of-int8-t-int-least8-t-and-int-fast8-t (but don't use it here otherwise you'll have again the same problem :))

# Answer
> 9 votes
In addition to the rule of always using fixed and predictable sizes across different architectures, it's also a good idea to *pack* your structs. This prevents the compiler from padding smaller variables with blanks to align them with the architecture's word boundary when needed. For example:

```
struct Package {
    uint8_t doorOpened;
    uint16_t light;
    int16_t temperature;
    uint8_t humidity;
    float voltage_battery;
} __attribute__((packed));

```

Depending on what "bytewise access" instructions are available on your target 32-bit architecture, without the packing you may end up with (worst case) the equivalent of:

```
struct Package {
    uint8_t doorOpened;
    // 3 bytes padding
    uint16_t light;
    // 2 bytes padding
    int16_t temperature;
    // 2 bytes padding
    uint8_t humidity;
    // 3 bytes padding
    float voltage_battery;
} __attribute__((packed));

```

Of course there may be a granular enough access method in the architecture which means the packing is irrelevant - but it's better to have it and it be ignored than to not have it and need it.

# Answer
> 2 votes
The esp8266 has a 32 bit mcu and the uno an 8 bit mcu so their variables have different storage requirements. You need to allow for this in your code.

# Answer
> 2 votes
For all the reasons mentioned in the other answers (different types sizes, alignment requirements and endianness), it's often a bad idea to use structs for data that needs to be sent/received (be it over the network or stored in files), as interoperability is often a problem.

Using a plain array of bytes (i.e. uint8\_t\[\]) is often a much better solution, together with functions to read/write data with specific types at specific offsets.

In many higher-level languages (perl, php, python...) this is often done using `pack`/`unpack` or equivalents, but as far as I know there is no direct equivalent in C.

You then end up using temporary variables, `htons`/`ntohs`/`htonl`/`ntohl` and `memcpy` to copy data between the temporary variables and the transmit buffer. Floats are a bit more tricky because even though their format is well defined, they endianness is not, and may not be the same as integers, but `htonf`/`ntohf` are rare. In your case, I would recommend converting to integers with a factor of 10 (if you need one digit) or 100 (if you need 2) for instance.

If you're using C++ you could consider using Google's Protocol buffers

---
Tags: arduino-uno, esp8266, nrf24l01+, memory, struct
---


title: Safe to power LED strip via ESP32 GPIO

text:
# Question
Title: Safe to power LED strip via ESP32 GPIO
I want to rewire a battery powered LED strip (as shown in the picture below) to power via an ESP32's GPIO pin. I have a ESP32 NodeMCU Development Board, powered via USB.

The LED strip has specified 3,2V/20mA for the 100 LEDs. It originally uses three AA batteries. From what I've gathered the ESP32 should have a max current output of 40mA.

Other than the LED strip, the ESP32 uses WiFi and addresses a DHT22.

The goal would be to turn the LEDs on/off via a GPIO, for example:

```
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
digitalWrite(4, LOW);

```

Would it be safe to power the LED strip via a GPIO pin?

# Answer
Quick answer is probably not. Why? The numbers don't add up:

> ...3,2V/20mA for the 100 LEDs...

From here we find this comment:

> Most common LED’s require a forward operating voltage of between approximately 1.2 to 3.6 volts with a forward current rating of about 10 to 30 mA, with 12 to 20 mA being the most common range.

(Actually there are low current LED on the market now that only need about 3mA to operate. Let us assume this is what you have for our calculations.)

So, given the above is true, and if your string of LEDs were all in parallel and had average specifications, we calculate the current and voltage of the string of 100 LEDs:

```
Current: 100 x 3mA = 300mA or 0.3 Amps
Voltage: About 2 Volts.

```

(Note: When designing with LED you should always refer to that LED's specification. The above 30mA and 2 Volts is only a guess.)

So, even if your LEDs are of the low current type, you can see a string of 100 such LED in parallel exceeds the initial expected current for the entire string of 100 LEDs.

This assumes the LEDs are in parallel and the power source is a constant voltage. What if the LEDs are in series? Then you would need a constant current power source. Again let's assume the individual LED specifications are 2 Volts and 3 mA. Now the calculations might look like this:

```
Current: About 3mA.
Voltage: 100 x 2 Volts = 200 Volts

```

Obviously the voltage far exceeds the capability of three 1.5 Volt batteries.

Ah! Bigclivedotcom gives us some insight in his 2017 youtube video about repairing several variations of low voltage LED strings. The 3 different strings he uses in his video address how these LED strings can be made such that different voltage and current sources can be used to power them.

In conclusion it is likely your string of LED will require more current to power then a GPIO pin who's maximum current rating is only 40mA can provide safely.
> 1 votes

---
Tags: led, esp32, pins, current, led-strip
---


title: Lolin NodeMCU V3 and 5V sensors

text:
# Question
Title: Lolin NodeMCU V3 and 5V sensors
I am new to Arduino and electronics so please correct me if I made a mistake.

Many sensors and actuators require 5V. The Lolin NodeMCU V3 has outputs of 3.3V. I want to have them working together.

I have read that the VIN pin outputs the voltage of the USB power source, which is around 5V. I bet that many sensors and actuators can be connected to VIN.

I guess that the main difference with the VCC pin of other boards is the accuracy and stability of the potential.

**1)** What about the amperage? (I guess that the max amperage of the USB power supply is divided between the board and sensors/actuators connected). How does it compare with the VCC output of, let say, an Arduino UNO?

**2)** How important is in most practical cases not having exactly 5V? (clearly, I am not considering using the sensors for extremely accurate measurements). I am interested in things like movements/distance/light/accelerometers/humidity etc. sensors and LCD displays, relays, small motors, etc..

I have seen that many sensors have a not so narrow range of working voltages. That makes me think that small oscillations in the USB voltage may not be significant.

**3)** Is there a better yet simple way to connect 5V devices to this board?

Thank you in advance.

# Answer
> 2 votes
> What about the amperage? (I guess that the max amperage of the USB power supply is divided between the board and sensors/actuators connected). How does it compare with the VCC output of, let say, an Arduino UNO?

The 5V pin is connected directly to the 5V of the USB. Whatever your USB port can provide the 5V can provide, minus the current used by the ESP8266.

> How important is in most practical cases not having exactly 5V? (clearly, I am not considering using the sensors for extremely accurate measurements). I am interested in things like movements/distance/light/accelerometers/humidity etc. sensors and LCD displays, relays, small motors, etc..

That all depends on the device. Read the datasheet. Look at the Electrical Characteristics. It will tell you the recommended (and the absolute maximum) voltage range.

> Is there a better yet simple way to connect 5V devices to this board?

Again, it all depends on the devices. Many many devices that are marketed as 5V are in fact "anything from 2.8V to 5.5V" or something like that. *Read the datasheets!*

The NodeMCU is a tricky board to use with 5V because there is no isolation between the USB power and the 5V pin's power. You can't power the board through the 5V pin and still be able to use the USB port or you risk destroying the USB port or computer that the NodeMCU is plugged into. If possible you really want to be running as many 3.3V devices as you can, or to keep any external 5V supplies completely separate (except ground, of course) from the 5V of the NodeMCU.

# Answer
> 2 votes
nodemcu gives 3.3 V output voltage. This output voltage is not considered sufficient by many components. So my recommendation is logic converters. The most logical solution to convert 3.3V voltage to 5V. Thus, the elements used with 5V will work stably.

---
Tags: nodemcu, voltage-level, voltage
---


# Question
Title: Can I wire LEDs without resistor with an Arduino like this?
There are four red LEDs and an Arduino in the picture. Each LED has a forward voltage of 2 V. My friend says that just `digitalWrite(9,HIGH)` will make the LEDs light without resistor and they won't be burnt. Is this true?

# Answer
> 1 votes
I am assuming you only have 5VDC available. Your friend is almost correct, it will work for a while however in the long run it will probably fail unless you are one of the lucky ones. What is the Vf (forward voltage drop) range of the LEDS (you state 2V), and are they matched by pairs, if not they will not illuminate evenly. You are forcing the arduino to output its maximum on port D9. I believe the current will not be within the microprocessor specifications. You are assuming a LED is a voltage device, it is not it is a current device. A resistor or constant current source is normally used to drive LEDs. The LED driving circuit must provide sufficient current to light the LED at the required brightness, but must limit the current to prevent damaging the LED and driver. Typically, the forward voltage (Vf) of an LED is between 1.8 and 3.3 volts. It varies by the color of the LED. A red LED typically drops around 1.7 to 2.0 volts, but since both voltage drop and light frequency increase with band gap, a blue LED may drop around 3 to 3.3 volts. across an LED is approximately constant over a wide range but can vary from LED to LED.

LEDs are diodes and have a

# Answer
> 0 votes
Depending on the LEDs, it might or it might not, who knows?
You'll be both safe and in control by adding a small resistor in series (either with each individual LED or, if the LED pairs are balanced, with the whole LED circuit). The resistor value depends on the LEDs and the Arduino's supply voltage.

---
Tags: arduino-nano, led
---


# Question
Title: how can I upload a hex file to an arduino uno?
I have a Rostock Max 3d with an Arduino Uno as the controller. The OEM has a firmware version I would like to upload, but it is in the hex file format.

I have looked all over the Arduino IDE, but did not found a way to upload a hex file to the Arduino. I tried using AVRDUDE, but the Arduino only communicates with my PC when I set the "Programmer" to AVRISP. I have uploaded other codes for blink, and hello\_world, but haven't been able to compile the firmware source. I was hoping I could just use the hexfile included in the firmware package.

My OS is Linux.

# Answer
I use a standalone programmer that uploads a .hex file from an SD card via the ICSP interface.
> 3 votes

# Answer
I recommend looking at the arduino IDE files located at **"(install path)/hardware/arduino/avr/"** (on windows anyway, I should assume the same on linux).

I am unsure if the following files have the .txt extension on them, but if not use just the file name.

---

Open and look in "boards.txt" and find the associated entries starting with "**uno.**" keeping this file open.

Next open "platform.txt" looking for the entries "**tools.avrdude**" (the avrdude part comes from boards.txt "uno.upload.tool" entry) and copy into a new text editor the value of "**tools.avrdude.upload.pattern**" you can fill in the parameters later.

With the command you copied replace the following:

from platform.txt

* "**{cmd.path}**" = "**tools.avrdude.cmd.path**"
* "**{config.path}**" = "**tools.avrdude.config.path**"
* "**{upload.verbose}**" = "**tools.avrdude.upload.params.verbose**"
* "**{upload.verify}** = "**tools.avrdude.upload.verify**"

now from boards.txt

* "**{build.mcu}**" = "**uno.build.mcu**"
* "**{upload.protocol}** = "**uno.upload.protocol**
* "**{{serial.port}**" = Your serial port (according to research something like **/dev/ttyS0**)
* "**{upload.speed}**" = "**uno.upload.speed**"
* "**{build.path}**" and "**{build.project\_name}** = path to file you are trying to upload

So with the above set out for me to upload a program to an Arduino uno I would use something like the following in windows:

assuming install path was "C:\Arduino\\"

> "C:\Arduino\hardware\tools\avr\bin\avrdude.exe" "-CC:\Arduino\hardware\tools\avr\etc\avrdude.conf" -v -patmega328p -carduino "-PCOM1" -b115200 -D "-Uflash:w:C:\MyArduinoProject\build.hex:i"

for linux it could possibly be (I really am unsure):

assuming install path was "/opt/Arduino/"

> "/opt/Arduino/hardware/tools/avr/bin/avrdude" "-C/opt/Arduino/hardware/tools/avr/etc/avrdude.conf" -v -patmega328p -carduino "-P/dev/ttyS0" -b115200 -D "-Uflash:w:/usr/MyArduinoProject/build.hex:i"

---

The above should work for you, I have previously written my own program to upload a hex file to the Arduino utilizing the above commands and avrdude.
> 2 votes

# Answer
I think you can use this software http://www.mediafire.com/file/tx2l85gsdkpf5d4/HEXtoArduino\_V1.0.0.zip/file
> 1 votes

# Answer
I found the definitive answer to this.

1. Start Arduino IDE
2. To to File...Preferences...
3. Turn on Show verbose output during: \[X\] upload (image 1 below)
4. Upload a sketch to your Arduino Uno
5. I used the sample blink sketch and saw the following (image 2 below):

**AVRDude: is used to upload**

You want that first line shown in white --- when you expand it you'll see that it is the entire line of code that is used to upload the HEX file of your program to the Uno.

The entire command on my computer looks like the following:

```
C:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\<username>\dev\arduino\STK2UPDI\build\blink.ino.hex:i

```

I'm going to break this down into a few lines:

First, it's the full path to the avrdude exe. Then it is passing the -C argument with the full path to the `avrdude.conf` file

`c:\longpath\avrdude -C C:\avrdude.conf`

Then a bunch of params to set up avrdude properly: `-v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:`

And finally the full path to the HEX file you want to upload

`c:\longpath\blink.ino.hex:i`

**All You Have To Do**

All you have to do is take that extremely long line and replace the full-path to the hex file to be your target HEX file and then run the entire command and you'll see something **like what is shown in image 3 below**.

**Image 1**

**Image 2**

**Image 3**
> 1 votes

---
Tags: programming, avrdude
---


# Question
Title: ATMega4809 via Nano Every marked as 20Mhz, but does this confirm it is actually at 16Mhz?
If you go to the official Arduino Nano Every page and click the *Tech Specs* tab, you'll see that it lists it as running at 20Mhz.

**Turn On Verbose Compile**

However, if you go into the Arduino IDE and go to File...Preferences... and turn on the *Show Verbose Output during: compilation* then you can examine how the board is actually set when a program is uploaded.

**Examining the Output**

When you look at that output you will see that it seems to be setting the board to run at 16Mhz.

**Am I Looking At This Properly?**

It looks to me as if the board is actually set to run at 16Mhz, right? Am I looking at that properly?

**Extra Question**

I'm attempting to confirm this because I am :

1. writing code in Arduino IDE
2. Compiling in Arduino IDE (to generate HEX file).
3. Uploading to a stand-alone 40-pin ATMega4809

The ATMega4809 datasheet states the following:

If I upload that sketch to the ATMega4809 40-pin chip, that means it will expect to run at 16Mhz, right?

**Set Fuses?**

Will the 40-pin chip be set to 16Mhz by the HEX file or will I need to set fuses on the chip to insure the chip is running at 16Mhz?

**FYI - Compiled For Correct Board**

Also you may wonder if I had the wrong board selected when I compiled, but here you can see I chose the Nano Every.

# Answer
With the Nano Every they went out of their way to make it look like as much like original Nano, to the point of providing that "register emulation" feature to make it appear that it has the 328P's older style of GPIO registers. Running at 16MHz just make sense if you want to behave like the common Nano as much as possible.

If you want to convince yourself that it's running at 16 MHz, you can blink an LED with causes of `__builtin_avr_delay_cycles(16000000);` in between. This busy-waits for the requested number of cycles. If it's running at 20 MHz instead of 16, you would see something faster than a 1 second delay.

~~They keep the configuration fuse values in a file fuses\_4809.bin.~~ On further investigation, it's not entirely clear what that file is for, despite containing the correct values. The actual OSCCFG value being used (which is the same in the file) is defined there directly in the boards.txt:

```
nona4809.bootloader.OSCCFG=0x01

```

So you can see it's set for 16 MHz on the Nano Every. The `-DF_CPU` in the command line originates from a line in boards.txt for the Nano Every:

```
nona4809.build.f_cpu=16000000L

```

and works its way into the compile command-lines via a line in platfrom.txt:

```
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} "-I{build.core.path}/api/deprecated" {includes} "{source_file}" -o "{object_file}"

```

The `D_CPU` macro exists to inform the compiled code what frequency it will be running at. The OSCCFG is controlling the actual frequency, it's important that they agree for any timing related code.

When you upload it's the `"-Ufuse2:w:{bootloader.OSCCFG}:m"` that becomes `"-Ufuse2:w:0x01:m"` in the avrdude command line generated from the upload recipe in platform.txt that has the actual effect of configuring the chip for 16 MHz.

If you really wanted to run at 20 MHz, you could try tweak the definitions of these, but it probably makes more sense to look at something like MCUdude MegaCoreX which appears to have a board definition for the ATMega4809 at 20 MHz.
> 5 votes

---
Tags: arduino-mega, arduino-ide, frequency, atmega
---


# Question
Title: MKR1400-how do I troubleshoot a POST request?
I'm successfully sending a GET request (in the setup function, to load certificates,) but my POST request fails with a bunch of AT errors. I suspect this has to do with the way I'm formatting the POST. Any ideas would be appreciated.

Code follows:

```
// MKRGSM - Version: 1.5.0
#include <MKRGSM.h>
#include <ArduinoJson.h>
#include <Arduino_MKRGPS.h>

const char PINNUMBER[]     = "";
// APN data

const char GPRS_APN[]      = SECRET_GPRS_APN;

const char GPRS_LOGIN[]    = "";

const char GPRS_PASSWORD[] = "";

DynamicJsonDocument doc(1024);

// initialize the library instance

GSMSSLClient client;

GPRS gprs;

GSM gsmAccess(true);

// Specify IP address or hostname

char server[] = "webhook.site";
char path[] = "/ce480c43-95a8-4f1e-b996-bc02f6d1adaa";
int port = 443;

void setup() {

  // initialize serial communications and wait for port to open:

  Serial.begin(9600);

  while (!Serial) {

    ; // wait for serial port to connect. Needed for native USB port only

  }

  // If you are using the MKR GPS as shield, change the next line to pass

  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  delay(200);

  if (!GPS.begin()) {

    Serial.println("Failed to initialize GPS!");

    while (1);

  }
  Serial.println("Starting Arduino GSM ping.");
  // connection state
  bool connected = false;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected)
  {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY))
    {
      connected = true;
    }
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  // Use this to load Root Certs the first time
  if (client.connect(server, port))
  // Use this to not load Root Certs anymore as done last time and stored in modem's flash
//  if (client.connect(server, port, false))
  {
        Serial.println("connected");

    // Make a HTTP request:

    client.print("GET ");

    client.print(path);

    client.println(" HTTP/1.1");

    client.print("Host: ");

    client.println(server);

    client.println("Connection: close");

    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {

  ...GPS stuff happens here

  // print GPS values

  Serial.println();

  Serial.print("Location: ");

  Serial.print(latitude, 7);

  Serial.print(", ");

  Serial.println(longitude, 7);

  Serial.print("Altitude: ");

  Serial.print(altitude);

  Serial.println("m");

  Serial.print("Number of satellites: ");

  Serial.println(satellites);

  doc["latitude"] = latitude;
  doc["longitude"] = longitude;
  doc["altitude"] = altitude;

  String location;
  serializeJson(doc, location);
  Serial.print("Location string: ");
  Serial.println(location);

  Serial.println();

  Serial.println("Starting Arduino web client.");

  // connection state

  if (client.available()) {
    Serial.println("Sending location");
    client.print("POST ");
    client.print(path);
    client.println(" HTTP/1.1");
    delay(5);
    client.println("Content-Type: application/json;");
    delay(5);
    client.print("Content-Length: ");
    client.println(location.length());
    client.print("Host: ");
    client.println(server);
    delay(5);
    client.println("Connection: close");
    delay(5);
    client.println();
    delay(5);
    client.println(location);
    Serial.print("Successfully sent location");

    if (!client.available() && !client.connected()) {

      Serial.println();

      Serial.println("disconnecting.");

      client.stop();
    }
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }

}

```

Here's what the output looks like:

> Location: 32.1208382, 35.2468376 Altitude: 640.40m Number of satellites: 5 Location string: {"latitude":32.12084,"longitude":35.24684,"altitude":640.4}
>
> Starting Arduino web client. Sending location AT+USOWR=0,13,"504F53542068747470733A2F2F"
>
> ERROR AT+USOWR=0,37,"2F63653438306334332D393561382D346631652D623939362D626330326636643161646161"
>
> ERROR AT+USOWR=0,9,"20485454502F312E31"
>
> ERROR AT+USOWR=0,2,"0D0A"
>
> ERROR AT+USOWR=0,31,"436F6E74656E742D547970653A206170706C69636174696F6E2F6A736F6E3B"
>
> ERROR AT+USOWR=0,2,"0D0A"
>
> ERROR AT+USOWR=0,16,"436F6E74656E742D4C656E6774683A20"
>
> ERROR AT+USOWR=0,2,"3539"
>
> ERROR AT+USOWR=0,2,"0D0A"
>
> ERROR AT+USOWR=0,6,"486F73743A20"
>
> ERROR AT+USOWR=0,12,"776562686F6F6B2E73697465"
>
> ERROR AT+USOWR=0,2,"0D0A"
>
> ERROR AT+USOWR=0,17,"436F6E6E656374696F6E3A20636C6F7365"
>
> ERROR AT+USOWR=0,2,"0D0A"
>
> ERROR AT+USOWR=0,2,"0D0A"
>
> ERROR AT+USOWR=0,59,"7B226C61746974756465223A33322E31323038342C226C6F6E676974756465223A33352E32343638342C22616C746974756465223A3634302E347D"
>
> ERROR AT+USOWR=0,2,"0D0A"
>
> ERROR

I could send the data as parameters in the GET query, but that's ugly.

# Answer
Your HTTP request is badly formatted. You have:

```
POST https://webhook.site/ce480c43-95a8-4f1e-b996-bc02f6d1adaa HTTP/1.1
Content-Type: application/json

```

Instead the protocol is implied by the port you are connecting to, and the domain name does *not* go in the path on the server component - it has its own header.

Your request should look more like:

```
POST /ce480c43-95a8-4f1e-b996-bc02f6d1adaa HTTP/1.1
Host: webhook.site
Content-Type: application/json
Content-Length: [x]
Connection: close

[location]

```

Where `[x]` is `location.length()` and `[location]` is the content of the `location` string.
> 2 votes

# Answer
The problem was that `GSM gsmAccess;` needed to be `GSM gsmAccess(true)`. Unfortunately, while that solves the immediate problem, which is that the client was not initializing, there are other issues which deserve a separate question.
> 1 votes

---
Tags: mkr-gsm-1400
---


title: Normally-Open opto-coupler board

text:
# Question
Title: Normally-Open opto-coupler board
I'm looking for a Normally-Open optocoupler board for arduino. I need to control power of a device (DC 12v, 500mA). I tried to use TLP281 board, which works, except that it inverts the output: device is powered when there is no control signal (i.e., it is Normally-Closed).

For this reason, the TLP281 board is not useful in my project.

This is picture and schematics for TLP281 board:

I need an optoisolator board which works analogous to normally open mechanical relay: when there is no signal, device must not be powered; and when there is signal, device must be powered.

*NOTE: workaround by inverting the control signal in microcontroller firmware is not permitted, as the device must not be powered when microcontroller is off*

# Answer
> 2 votes
I don't think there is a need for a specific "normally-open" opto-coupler. Same result can be easily achieved by using "normally-closed" opto-coupler and making a slightly modified "NOT" logic gate using three resistors and NPN transistor.

**1. When INPUT is LOW:**

Base of Q1 is shorted to ground through R1 so Q1 not letting the magic pixies go through. This makes OUTPUT show 5V and be in HIGH logic state.

**2. When INPUT is HIGH:**

Base of Q1 is powered by voltage divider R/R1. R needs to be much lower than R1 to keep Q1 saturated. This makes Q1 to be passing current and setting OUTPUT to LOW state by creating a voltage divider R2/Q1(collector-emitter resistance) This means that value of R2 should be much higher then c-e resistance of Q1.

**3. When INPUT is floating (microcontroller is turned off):**

Any voltage on INPUT caused by imperfections of the hardware, E-M noise induction, static electricity, etc. should be discharged to ground by resistors R+R1 keeping INPUT in LOW state. (This means that R+R1 cannot have to high value or the discharge speed might be to slow)

# Answer
> 1 votes
For those, who are stumbling over this old thread and @igor-liferenko, since this board is still quite common:

This board definitely does *NOT* invert the inputs.

The comment of Igor Liferenko "tested it and I can say for sure that this board inverts the signal (on low input, there is power on output, on high input, there is no power on output)." is wrong. I don't know what he has tested, but both the schematics and tests show, that the board does not invert (or actually inverts twice -- once by the TLP281-4 itself and once by the following S8050-transistors).

So: low on input -\> low on output; high on input -\> high on output.

---
Tags: relay, opto-isolator
---


# Question
Title: Arduino Nano skips statements after Interrupt
I am using an Arduino to control an AC Phase Control Circuit to control some lamps. The problem is that the interrupts seem to break the code inside the `loop()`. This Code should just blink one lamp. But it doesnt! What I found out so far: The Led always has `dim_level[22]` so it seems like (at least the first) delay in the `loop` is skipped. The strange thing: When i add a statement that takes some time between the delays everything is working For example

```
void loop() {
  CH[0] = dim_level[0];
  Serial.println("---------------------------------------------------------");
  delay(500);
  CH[0] = dim_level[22];
  Serial.println("---------------------------------------------------------");
  delay(500);
}

```

The not working code:

```
#include <TimerOne.h>

unsigned char channel_1 = 7;    // Output to Opto Triac pin, channel 1
unsigned char channel_2 = 6;    // Output to Opto Triac pin, channel 2
unsigned char channel_3 = 5;    // Output to Opto Triac pin, channel 3
unsigned char channel_4 = 4;    // Output to Opto Triac pin, channel 4
unsigned char CH1, CH2, CH3, CH4;
unsigned char i = 0;
unsigned char delay_time = 1;   // delay ms or flashing SPEED
unsigned char clock_tick;        // variable for Timer1
unsigned char CHANNEL_SELECT;    // variable for channel select

unsigned char CH[] = {CH1, CH2, CH3, CH4};

unsigned char dim_level[] = {5, 8, 10, 12, 15, 18, 20, 25, 30, 35, 45, 50, 55, 60, 65, 70, 75, 80, 82, 85, 88, 92, 95}; // don't use this massive for 60Hz
// create new massive for 60Hz
void setup() {
  Serial.begin(2000000);
  pinMode(channel_1, OUTPUT);// Set AC Load pin as output
  pinMode(channel_2, OUTPUT);// Set AC Load pin as output
  pinMode(channel_3, OUTPUT);// Set AC Load pin as output
  pinMode(channel_4, OUTPUT);// Set AC Load pin as output
  attachInterrupt(1, zero_crosss_int, RISING);
  Timer1.initialize(100); // set a timer of length 100 microseconds for 50Hz or 83 microseconds for 60Hz;
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here

}

void timerIsr()
{
  clock_tick++;
  if (CH[0] == clock_tick)
  {

    digitalWrite(channel_1, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_1, LOW);    // triac Off
  }

  if (CH[1] == clock_tick)
  {
    digitalWrite(channel_2, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_2, LOW);    // triac Off
  }

  if (CH[2] == clock_tick)
  {
    digitalWrite(channel_3, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_3, LOW);    // triac Off
  }

  if (CH[3] == clock_tick)
  {
    digitalWrite(channel_4, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_4, LOW);    // triac Off
  }
}

void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  clock_tick = 0;
}

void loop() {
  CH[0] = dim_level[0];

  delay(500);
  CH[0] = dim_level[22];

  delay(500);
}

```

Im new to arduino maybeIi miss some concepts but I read that interupts should not break delays outside interrupt

# Answer
> 2 votes
Like timemage mentioned i had to qualify `ch` as `volatile`. so:

```
volatile unsigned char CH[] = {CH1, CH2, CH3, CH4};

```

is the fix

---
Tags: arduino-uno, interrupt
---


title: Arduino DUE wheel encoder

text:
# Question
Title: Arduino DUE wheel encoder
I have an Arduino due, I am trying to keep track of ticks on two wheel encoders, polling in an infinite loop results in terrible performance. Have any suggestions?

It looks like the due might have an internal counter but I don't know how to use it, is there a library?

# Answer
> 1 votes
You can use an interrupt handler to measure frequency. Works quite well.

```
volatile int32_t _ticks = 0;
public void FrequencyIsr()
{
    _ticks++;
}

// Add this to setup()
// Mode can be FALLING, RISING or CHANGE
attachInterrupt(digitalPinToInterrupt(pin), FrequencyIsr, mode);

// Add this to loop()
int32_t currentTime = millis();
// Clear the interrupt flag, so that we can read out the counter
noInterrupts();
int32_t ticks = _ticks;
interrupts();
// and then calculate the amount of ticks since the last update (if you need the speed)
int32_t timeDelta = currentTime - _lastTime;
int32_t tickDelta = ticks - _lastTicks;
double ticksPerMs = (double)tickDelta/timeDelta;
_lastTime = currentTime;
_lastTicks = ticks;

```

---
Tags: arduino-due, rotary-encoder
---


# Question
Title: Arduino parsing of a string using sscanf
Hello I am new to Arduino and C programming. I wanted to parse string using sscanf fuction

This is my Program

```
String hith;
int field1,field2;
float field3;
int F1=0,F2=0;
float F3=0;
int h1,h3;
float h2;

void setup() {

  Serial.begin(9600);

}

void loop() {
  field1=5;
  field2=6;
  field3=56.67;
  F1=field1;
  F2=field2;
  F3=field3;

  hith =hith+F1+","+F3+","+F2;
  Serial.println(hith);

sscanf(hith.c_str(),"%d,%f,%d",&h1,&h2,&h3);

Serial.println(h1);
Serial.println(h2);
Serial.println(h3);
  hith="";

  delay(1000);
}

```

I am only able to Parse Integer values but not Floating points.

# Answer
On 8-bit Arduinos support for %f from `printf` and `scanf` (and related functions) has been removed to save space.

Instead you should look at parsing the string into chunks with `strtok()` and use `atof()` to convert relevant chunks to floating point.
> 1 votes

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


# Question
Title: How to sue Arduino Nano to control Stepper motor with Firmata
I have a stepper motor and at present it is controlled by a sketch all working fine. I need now to add it to a Win32 app to control it in circuit with existing Servo Motor. The servo Motor is working well via Firmata from Win32 app as follows

in setup part

```
arduino.pinMode(9, Arduino.SERVO);

```

In loop

```
 private void btn_set_servo_Click(object sender, EventArgs e)
        {
            int angle = Convert.ToInt32(Math.Round(numupdwn_degrees.Value, 0));
            arduino.servoWrite(9, angle);//tell the servo motor go to the position
        }

```

How do you drive the stepper motor using Firmata has anyone got an example I can see please?

# Answer
**Update:** I have created a C# .Net App to connect and control the stepper Motor. The code and a Readme file is available at

https://github.com/zizwiz/Arduino\_Projects/tree/main/FirmataStepperMotorTest

---

**Initial Answer:**

After a bit of thinking time I have managed to start the stepper motor running with Firmata protocol from my C# Win32 app. This post is just a basic outline I use to get it running I need lots more thinking and tinkering till I get what I need but in case this is helpful here it is.

Create a button to press to start. Create a thread when the button is clicked

```
   private void btn_stepper_start_Click(object sender, EventArgs e)
        {
           var thread = new Thread(() =>
           {
               while (true)
               {
                   RunStepper();
               }

           });

            thread.IsBackground = true;
            thread.Start();

        }

```

In the function RunStepper() create the following

```
 private void RunStepper()
        {
            while (true)
            {
                arduino.digitalWrite(7, Convert.ToByte(255));
                arduino.digitalWrite(8, 0);
                arduino.digitalWrite(9, 0);
                arduino.digitalWrite(10, 0);
                Task.Delay(10);
                arduino.digitalWrite(7, 0);
                arduino.digitalWrite(8, Convert.ToByte(255));
                arduino.digitalWrite(9, 0);
                arduino.digitalWrite(10, 0);
                Task.Delay(10);
                arduino.digitalWrite(7, 0);
                arduino.digitalWrite(8, 0);
                arduino.digitalWrite(9, Convert.ToByte(255));
                arduino.digitalWrite(10, 0);
                Task.Delay(10);
                arduino.digitalWrite(7, 0);
                arduino.digitalWrite(8, 0);
                arduino.digitalWrite(9, 0);
                arduino.digitalWrite(10, Convert.ToByte(255));
                Task.Delay(10);
            }
        }

```

As mentioned this small basic example is just a start to prove I may be able to do what I need.
> 0 votes

---
Tags: arduino-nano, stepper-motor, firmata
---


# Question
Title: Why does starting the serial monitor restart the sketch?
If I upload any sketch that sends serial data, I immediately see the TX/RX LEDs flash once the sketch is uploaded. If I then start the serial monitor, the sketch appears to restart.

A bare minimum sketch that shows this behaviour:

```
    void setup()
    {
        Serial.begin(9600);
        Serial.println("Setup");
    }

    void loop()
    {
      Serial.println("Loop");
      delay(1000);
    }

```

Tested with several boards and Mac and Windows versions of the IDE.

Example output - it goes back to "Setup" when I open the serial monitor:

Why is this?

# Answer
The Arduino uses the RTS (Request To Send) (and I think DTR (Data Terminal Ready)) signals to auto-reset. If you get a serial terminal that allows you to change the flow control settings you can change this functionality.

The Arduino terminal doesn't give you a lot of options and that's the default. Others will allow you to configure a lot more. Setting the flow control to none will allow you to connect/disconnect from the serial without resetting your board. it's quite useful for debugging when you want to be able to just plug in the connector and see the output without having to start the sketch over.

Another way to disable the auto reset is to put a pull up resistor on the reset pin.

Disabling Auto Reset On Serial Connection
> 42 votes

# Answer
The truth is always in the datasheets, the schematics and the code:

The Arduino UNO actually uses the `/DTR` line to trigger a reset, as you can see on the following datasheet:
> 13 votes

# Answer
This fixes the problem

```
import os
import sys
import termios
import fcntl

        self.fd = sys.stdin.fileno()

        # Stop resetting the arduino on serial connect

        self.newattr = termios.tcgetattr(self.fd)
        self.newattr[2] = self.newattr[2] & ~termios.HUPCL
        termios.tcsetattr(self.fd, termios.TCSANOW, self.newattr)

```
> 2 votes

# Answer
Arduino uses the **DTR line** (data terminal ready)

So, with the Arduino Serial Monitor it is not possible to change the restart when established the rs232 connection.

But I'm using for example the freeware "HTerm" (under Windows). By default, it does not use the DTR signal. Meanwhile I changed to the freeware "**CoolTerm**" (a bit more comfortable...): You have to deactivate "DTR Off" unter "Connection Options". In Linux I'm using the "moserial". Under "PortSetup" you must deactivate the "handshake" ;-)

This way is more comfortable for me then adjusting the RESET pin. Also, its a nice benefit saving all the data in a log file for later analyzing…
> 2 votes

---
Tags: serial, arduino-ide
---


# Question
Title: Serial monitor can't display float and double values with absolute greater than 4294967040=2^32-2^8
I have the following sketch:

```
void setup() {}

void loop() {
  float af = 4294967040.0;
  float bf = 4294967240.0;
  double ad = 4294967040.0;
  double bd = 4294967040.00001;
  Serial.println(af);
  Serial.println(bf);
  Serial.println(ad);
  Serial.println(bd);
}

```

The values of `af`, `bf`, `ad` and `bd` are way smaller than 3.402823466e38 which is the maximum for float values. The values can still be correctly operated with, but the result on the serial monitor however is `ovf` for `bf` and `bd`.

Why is that?

# Answer
> 10 votes
It's not the data type, it's the printing routine that sets that limit. In `Print.cpp`:

```
227   if (isnan(number)) return print("nan");
228   if (isinf(number)) return print("inf");
229   if (number > 4294967040.0) return print ("ovf");  // constant determined empirically
230   if (number <-4294967040.0) return print ("ovf");  // constant determined empirically

```

Don't ask why...

---
Tags: serial, float
---


# Question
Title: How do I set a 25 kHz PWM signal on an ESP-WROOM-32?
I want to control a single pin of an ESP-WROOM-32 to have a 25 kHz PWM signal. How do I do that in Arduino Studio? I compiled a "hello world" program for such a device successfully in Arduino Studio, now what steps do I need to take? (Other libraries? Source Code?)

FYI: I'd like to do quite the same as provided in Set PWM frequency to 25 kHz but not on an AVM micro-controller but an ESP32. There are tons of explanations for original Arduinos and ESP8266s using bit banging in various forms. But how do I do that on an ESP-WROOM-32 using no bit banging but built in PWM?

Background: I'd like to control a standard 12V PWM fan with this signal. As far as I learned I just can connect a pin with the PWM input of the fan. I just don't seem to be able to figure out how to produce such high frequent PWM signals on an ESP32 :-/ Please help!

# Answer
> 6 votes
It is very simple to set up a PWM signal at any frequency you desire, with any resolution you desire, provided you don't exceed the maximum 'bandwidth': the frequency multplied by the resolution must be less than half the clock speed of the device.

The full explanation with relation to the ESP-IDF is available here. The article explains the intricacies of all the channels and their configurations. I must confess I have not read it all, because my application was very basic.

In `setup()`, the code required to instantiate a PWM signal on channel *`chan`* at frequency *`freq`*, with a resolution of *`bit_num`* bits is:

```
double ledcSetup(uint8_t chan, double freq, uint8_t bit_num)

```

The code to attach the channel *`chan`* to an output pin *`pin`* is:

```
void ledcAttachPin(uint8_t pin, uint8_t chan)

```

Within `loop()`, or otherwise, inflict a duty cycle *`duty`* to a given channel *`chan`* using:

```
void ledcWrite(uint8_t chan, uint32_t duty)

```

I recommend perusing `esp32-hal-ledc.c` in the core files you installed that enabled you to program the ESP32 in Arduino Studio. You don't need to include any files to get the above functionality, but it's always good to know a bit about what goes on behind the scenes.

A few things to note, if reading through the core code is too much:

* `chan` can only be between 0 and 15, and the function will return 0 if you try an number outside these bounds;
* you can't attach the PWM output to *all* of the GPIO pins, as some are input only and others might have secondary functions that you need;
* `duty` is a 32-bit type but the maximum value is determined by the resolution you used for `bit_num`. For example, if `bit_num` is 8 then the range of `duty` is from 0 to 255. I don't know what happens if you put higher number: the duty may stay at 100%, or the `duty` may be bitmasked such that writing 256 is the same as 0, 257 is 1, etc.

Once you have mastered this, the ESP32 includes 'fading' functionality, whereby the duty cycle changes from `x%` to `y%` in `z milliseconds`. There are a number of tutorials on the internet for such a thing.

**FINAL NOTE:**

If you haven't already, take a look at Intel's PWM fan specs. It states that you need an open-collector or open-drain source provided, in your case, by the ESP32. There's a chance that the PWM pin is pulled up to 5.25V within the fan; this will hurt the ESP32 if you just wire the two together. Likewise, the Tachometer output is pulled all the way up to 12V. This will kill the ESP32 if you wire it directly to the fan.

# Answer
> 3 votes
I know it is an old topic, but at the moment I'm also busy with it.

To be sure the ESP32 doesn't get to much voltage from the pwm input, you have to measure on the PWM input if the signal is not above 3V3, otherwhise you need a resistor divider or work with a transistor in between to pull the signal down. Mine is around 3V3 so I can directly connect the ESP32 to the fan, but just like you I put a serie resistor (330) in between for a bit protection. If this input is around 5.25 V and you connect it to the ESP32, it will probably not directly go broke, but this depends on the input resistance of the fan and how much current the internal protection diode can take in the ESP32.

For the tacho signal, it is very simple, just connect it with a pullup resistor (10K) to the desired voltage you want. In my case I will connect it to 3V3 because the ESP32 is working on 3V3. The fan controller pulls it down if rotating.

I use this schematic as guide, PWM Input:

Tacho open collector output:

website: Fan controller

Hope this helps, just as reference.

---
Tags: pwm, esp32
---


title: Input vs input_pullup

text:
# Question
Title: Input vs input_pullup
I'm a beginner in Arduino and can't understand some things. How does input pin in Arduino work? I want to set one of the pins as input. When should I use input and when input\_pullup? What are the differences between them?

# Answer
> 4 votes
**Input pin working**-

An input pin on an arduino board uses something called Tristate buffer to expect a voltage at the pin.

**Input pullup**-

When a pin is configured just as an input (without a definite voltage connected to it), the pin will return random values based on the electrical interference present around it, for example the neighbouring pin.

So to solve this issue, input pullups are used. Essentially it sets the default state of the pin to HIGH or 1, so that the pin is not affected by interference.

You can experience this yourself using the following program, with a pushbutton from Ground to pin 7, and the Serial monitor-

No pullup-

```
void setup(){
// Dont have to put any pin definitions here as by default it input
// This code will return random values until the button is pressed
Serial.begin(9600);
}

void loop(){
Serial.println(digitalRead(7));
}

```

Now for the one with Pullup-

```
void setup(){
pinMode(7, INPUT_PULLUP);
Serial.begin(9600);
// This code will return 1/HIGH until the button is pressed
}

void loop(){
Serial.println(digitalRead(7));
}

```

Random info- There's input pulldown on some boards, guess what that does?

# Answer
> 1 votes
The pin inputs are sensitive enough to nearby electrical noise that if the pin is floating - not positively pulled up to the supply voltage, or down to ground - the input will read randomly HIGH or LOW. A pullup resistor of 10K Ohms or so connected between the pin and the supply voltage is strong enough to overcome the noise, but is itself easily overcome by a signal applied to at the pin input:

simulate this circuit – Schematic created using CircuitLab

This means that when the pin is not connected, it will have stable HIGH reading. While you can put the pullup on your circuit board, as in the schematic above, Arduinos have a built-in pullup resistor that can be connected to the pin simply by selecting 'INPUT\_PULLUP' in your code, and it does exactly the same thing. It is a convenient way to save space and a component on your circuit board or make it slightly quicker to wire your breadboard. And in the case of a breadboard in particular, the plug-wires are excellent antennas for picking up noise, while the built-in pullup resistor is within the chip, close the pin-receiver, and it makes the circuit dramatically more stable.

---
Tags: pins
---


title: Unwanted Wi-Fi Jamming by ESP8266

text:
# Question
Title: Unwanted Wi-Fi Jamming by ESP8266
I bought an ESP8266-01 module. I attempted to upload following code onto it.

```
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.println("I'm working");
Serial.println(millis());
}

```

Then I powered it and there was nothing in Serial monitor. Also my computer lost wifi connection. What's the cause of this error? How to solve it?

# Answer
**Solved**: I catched more details. ESP creates Wi-Fi network. It causes jamming.
> 1 votes

---
Tags: esp8266, wifi, nodemcu, wireless
---


# Question
Title: How to properly send bytes between RPI and Arduino over I2C while using ISR without IOerrors?
I have a I2C connection between an RPI 3B+ and Arduino Nano. I want to send a key and a corresponding value byte, and the arduino does something with that inside a timed ISR. Which works. But I get IOerrors at the RPI side, probably because the ISR is busy. So I did a little test. Every 10000 messages send:

* 245 IOerrors at 51,281 Hz ISR
* 104 IOerrors at 25,600 Hz ISR
* 28 IOerrors at 6,400 Hz ISR

Is there any way to have less or no IOerrors? I need about 25,600 kHz for my ISR.

RPI side:

```
bus.write_i2c_block_data(0x60, 0x00, [key, val])

```

Arduino side message handler called as Wire.onReceive(msg\_handler);:

```
void msg_handler(int bitstream) {
     Wire.read();
     int pin = Wire.read();
     int val = Wire.read();
     Serial.println(pin);
     Wire.begin(0x60);

```

I do the wire begin every time because otherwise once it had a IOerror it stops printing on the serial. My wiring is 18 AWG and about 20cm. The error:

```
[Errno 121] Remote I/O error

```

# Answer
> 1 votes
What i2c clock speed are you using?

Even at the faster "fairly standard" speed of 400kHz, that's 2.5us per bit. For a two byte transfer, that's 4us for the data alone, which is 25000 transfers per second. Add on the start and stop bits, plus processing time and you can see that your target data rate isn't possible.

i2c just isn't that fast as standard, though there are much faster "non standard" modes.

---
Tags: arduino-nano, i2c, raspberrypi, isr
---


# Question
Title: How to GET HTTP Request from Arduino to Firebase?
I have an Arduino UNO and SIM808 and I'm trying to send my GPS data to the Firebase. I have successfully created a website which I can post data from the website to the Firebase. However I'm trying to send my data from Arduino to the website which failed constantly. I have no idea what is the error.

These are my codes:

```
  /*
    ### Get GPS data
    1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
    2. Open the SIM808_GetGPS example or copy these code to your project
    3. Download and dial the function switch to Arduino
    4. open serial helper
    4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

    create on 2016/09/23, version: 1.0
    by jason

  */
  #include <DFRobot_sim808.h>
  #include <SoftwareSerial.h>

  #define PIN_TX    10
  #define PIN_RX    11
  SoftwareSerial mySerial(PIN_TX, PIN_RX);
  DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

  #define APN "diginet"
  #define USER ""
  #define PASS ""
  unsigned long previousMillis = 0;
  long interval = 60000;

  String the_year, the_month, the_day, the_hour, the_minute, the_second, the_time;
  String latitude, longitude;

  //DFRobot_SIM808 sim808(&Serial);

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

    //******** Initialize sim808 module *************
    while (!sim808.init()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
    }

    //************* Turn on the GPS power************
    if ( sim808.attachGPS())
      Serial.println("Open the GPS power success");
    else
      Serial.println("Open the GPS power failure");

  }

  void loop() {
    //************** Get GPS data *******************
    getGPS();

    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis > interval) {
      previousMillis = currentMillis;
      sendtoFirebase();
    }

  }

  void getGPS() {

    if (sim808.getGPS()) {
      delay(500);
      the_year = sim808.GPSdata.year;
      the_month = sim808.GPSdata.month;
      the_day = sim808.GPSdata.day;
      the_hour = sim808.GPSdata.hour;
      the_minute = sim808.GPSdata.minute;
      the_second = sim808.GPSdata.second;
      the_time = the_year + " / " + the_month + " / " + the_day + " " + the_hour + ": " + the_minute + ": " + the_second;
      Serial.print(the_time);
      //Serial.print(sim808.GPSdata.year);
      //types(sim808.GPSdata);

      latitude = String(sim808.GPSdata.lat, 6);
      longitude = String(sim808.GPSdata.lon, 6);
      Serial.println(latitude);
      Serial.println("longitude : ");

      Serial.println(longitude);

      sim808.latitudeConverToDMS();
      sim808.LongitudeConverToDMS();
      //Serial.print("latitude : ");
      //        Serial.print(sim808.latDMS.degrees);
      //        Serial.print("\^");
      //        Serial.print(sim808.latDMS.minutes);
      //        Serial.print("\'");
      //        Serial.print(sim808.latDMS.seconeds,6);
      //        Serial.println("\"");
      //    Serial.print("longitude :");
      //    Serial.print("longitude :");
      //    Serial.print(sim808.longDMS.degrees);
      //    Serial.print("\^");
      //    Serial.print(sim808.longDMS.minutes);
      //    Serial.print("\'");
      //    Serial.print(sim808.longDMS.seconeds, 6);
      //    Serial.println("\"");

      //    Serial.print("speed_kph :");
      //    Serial.println(sim808.GPSdata.speed_kph);
      //    Serial.print("heading :");
      //    Serial.println(sim808.GPSdata.heading);

      //************* Turn off the GPS power ************
      //sim808.detachGPS();
    }
  }

  void sendtoFirebase() {

    boolean newData = false;
    for (unsigned long start = millis(); millis() - start < 2000;) {
      while (sim808.getGPS()) {
        newData = true;
      }
    }

    if (newData) {
      newData = false;

      String deviceId = "ABC1235";

      Serial.print("Device ID:");
      Serial.println(deviceId);

      Serial.print("Time:");
      Serial.println(the_time);
      Serial.print("latitude:");
      Serial.println(latitude);
      Serial.print("longitude:");
      Serial.println(longitude);

      String temp;

      //build the URL to the proxy
      String url = "http://myfypproject.epizy.com/firebase.php?arduino_data=25.00";
      //  url += "&deviceid=";
      //  url += String(deviceid);
      //  url += "&lat=";
      //  url += String(latitude);
      //  url += "&lon=";
      //  url += String(longitude);

      Serial.println(url);
      sendATcommand("AT+CFUN=1", "OK", 2000);
      //AT+CGATT = 1 Connect modem is attached to GPRS to a network. AT+CGATT = 0, modem is not attached to GPRS to a network
      sendATcommand("AT+CGATT=1", "OK", 2000);
      //Connection type: GPRS - bearer profile 1
      sendATcommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\"", "OK", 2000);
      //sets the APN settings for your network provider.
      sendATcommand("AT+SAPBR=3,1,\"APN\",\"diginet\"", "OK", 2000);
      //enable the GPRS - enable bearer 1
      sendATcommand("AT+SAPBR=1,1", "OK", 2000);
      //Init HTTP service
      sendATcommand("AT+HTTPINIT", "OK", 2000);
      sendATcommand("AT+HTTPPARA=\"CID\",1", "OK", 1000);
      //Set the HTTP URL sim800.print("AT+HTTPPARA="URL","http://ahmadssd.000webhostapp.com/gpsdata.php?lat=222&lng=222"\r");
      //sendATcommand("AT+HTTPPARA=\"URL\",\"http://myfypproject.epizy.com/firebase.php?arduino_data=25.00\"", "OK", 1000);
      mySerial.print("AT+HTTPPARA=\"URL\",\"");
      mySerial.print(url);
      sendATcommand("\"", "OK", 1000);
      //Set up the HTTP action
      sendATcommand("AT+HTTPACTION=0", "0,200", 1000);
      //Terminate the HTTP service
      sendATcommand("AT+HTTPTERM", "OK", 1000);
      //shuts down the GPRS connection. This returns "SHUT OK".
      //sendATcommand("AT+CIPSHUT", "SHUT OK", 1000);

    }

    return 1;
  }

  int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout) {
    uint8_t x = 0, answer = 0;
    char response[100];
    unsigned long previous;

    //Initialize the string
    memset(response, '\0', 100);
    delay(100);

    //Clean the input buffer
    while (mySerial.available() > 0) mySerial.read();

    if (ATcommand[0] != '\0') {
      //Send the AT command
      mySerial.println(ATcommand);
    }

    x = 0;
    previous = millis();

    do {
      //if there are data in the UART input buffer, reads it and checks for the asnwer
      if (mySerial.available() != 0) {
        response[x] = mySerial.read();
        //Serial.print(response[x]);
        x++;
        // check if the desired answer (OK) is in the response of the module
        if (strstr(response, expected_answer) != NULL) {
          answer = 1;
        }
      }
    } while ((answer == 0) && ((millis() - previous) < timeout));

    Serial.println(response);
    return answer;

  }

```

I keep get the error of 603.

```
AT+HTTPACTION=0
OK
+HTTPACTION: 0, 603, 0

```

Below are my PHP, website to firebase codes:

```
    <?php
require_once 'firebaseLib.php';
// --- This is your Firebase URL
$url = 'https://projectname-default-rtdb.asia-southeast1.firebasedatabase.app/';
// --- Use your token from Firebase here
$token = 'XXXXXXXXXXJYszyqIJxr3UuGl1Zr6qHG03K';
// --- Here is your parameter from the http GET
$arduino_data = $_GET['arduino_data'];
// --- Set up your Firebase url structure here
$firebasePath = '/GPSdata';

/// --- Making calls
$fb = new fireBase($url, $token);
$response = $fb->set($firebasePath, $arduino_data);
echo $url;
sleep(2);

```

**UPDATE:**

I can get code 200, but there isn't any result in my firebase or my website.

# Answer
> 1 votes
It is just the server problem. I just changed a website and it works.

---
Tags: arduino-uno, sim808
---


# Question
Title: Arduino serial port reset in Serial monitor & Python
So am I using an Arduino with a shield to gain some voltage values for an ECG. I am then plotting that data in Python. However whenever I "observe" the serial port, be that through the Arduino serial monitor or in attempting to plot the values of time (using millis()) against ECG (voltage) the values reset, so millis() resets the zero, which is fine, except that some of the older values still show up. Now this is especially a problem in Python because it means the plot is malfunctioning at the start of the script, because it is plotting some of the older values and then after a couple of seconds it resets and the plot looks normal again.

To demonstrate this I have recorded it on video and put it on YouTube, here it is:

https://www.youtube.com/watch?v=dNpUakcRPec

Now initially I thought the problem was with Python or the Pyserial module so I labelled the video as such, but since it occurs in the serial monitor I realised the solution would be in the Arduino sketch. I have tried flushing, didn't work, I have tried even to not start the data till I send a start byte, but this didn't work on Python.

Ideally I could start the Python plotting script and it would skip, or ignore those initial values from the serial port before beginning again.

Here is the Arduino sketch I am using:

```
#include <eHealth.h>

unsigned long time;
// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);

}

// The loop routine runs over and over again forever:
void loop() {

  float ECG = eHealth.getECG();
  time = millis();
  Serial.print(time);
  Serial.print(" ");
  Serial.print(ECG, 3);
  Serial.println("");

  delay(50);    // wait for 50 millisecond
}

```

# Answer
> 2 votes
The Arduino is designed to reset when a Serial monitor or script connects to it. The best way to mitigate this would be to send the Arduino some kind of "start sending" signal when you connect to the serial port. It would then send the data when your script was ready.

# Answer
> 1 votes
Take a look at if(Serial)

That makes the Sketch wait for the serial port before continuing.

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

```

I have a sneaking suspicion that may only work on the Leonardo.

If so you could try an alternative:

1. Have Python send something to Arduino after it connects.
2. Wait until this is received in setup(): if (Serial.available() \> 0) {...}
3. Execute the loop() normally

e.g.

```
// send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);
    }

```

# Answer
> 0 votes
I the answer from @TheDoctor. An alternative is for the client listening on serial port to wait for a "successful reset" signal from the Arduino.

```
void setup() {
//Initialize serial and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect.
    }
    Serial.println('reset successful')
}

```

There are pros and cons to each solution. In the @TheDoctor solution, it seems like there is an edge cases where the Arduino is already sending when the client connects and you'll get some junk before the reset occurs.

---
Tags: arduino-uno, serial, python, reset
---


title: DS1337 with shared I2C pull-up

text:
# Question
Title: DS1337 with shared I2C pull-up
I have a project using an ATMEGA328P and a DS1337 RTC chip. The DS1337 is an 8 pin IC with VCC at pin 8 and GND at pin 4. According to the datasheet both pin 5 (SDA) and pin 6 (SCL) need an external pull-up. From what I read elsewhere, a pull-up of 4.7K to 10K for each I2C pin should be good enough. Considering the position of both I2C pins to each other and the VCC pin, I was thinking of simplifying things by using a shared 10K pull-up. This post suggests that it should be possible, but I am still not sure. Does anyone have experience with this, that is using a shared pull-up to an I2C connection? What could be some problems, if any, by doing this?

# Answer
> 3 votes
You need *at least* one pull-up on the SDA pin and *at least* one pull-up on the SCL pin. You cannot use the same pull-up for both pins as you will be shorting the two pins together.

The pull-ups are required on the I2C signals, not the pins of a chip. If you have multiple chips on the I2C bus you only need one pull-up on each signal. It really doesn't matter (given that I2C buses are intended to be short) where on the signal the pull-up is in relation to any one chip.

I would personally say that 4.7kΩ to 10kΩ is too high. I don't use more than 3.3kΩ pull-ups for I2C, and more likely 1kΩ if I am using higher speed (e.g., 1MHz) I2C.

---
Tags: i2c, atmega328, rtc, pull-up
---


# Question
Title: Custom library for Arduino to encode and decode JSON Web Tokens
So I have been recently been trying to create a library for Arduino to encode and decode JSON Web tokens(JWT) using HMAC-SHA256.

For those unfamiliar, JWT has 3 parts - The header, body and signature. The header and body are in JSON format.
The header contains the hashing algorithm and token type while The body contains the data to be transmitted.
The header and body are converted to base64 format and arranged as "\[header\].\[body\]". The signature is created by running the hashing algorithm (HMAC-SHA256 in my case) on the "\[header\].\[body\]" and converting the result to base64 format.
Finally, the token is arranged as "\[header\].\[body\].\[signature\]"
More information can be found on - https://jwt.io/introduction

So far, I successfully managed to create the encoding part. I wanted to test the code for consistency, so I tried to run the code on an Arduino UNO and kept on calling the encoding function in void loop. Initially, the results were as expected -

The long line of text is the expected output. But suddenly, it does this -

Then there is a period where the output is blank and finally, this comes-

For some reason, only the signature part gets printed. Also, I have no idea what the last 2 outputs are. Finally, it goes blank for a second and then repeats the entire process
Can anyone please help me in figuring out what is going on and how do I solve it?

This is my code in the library- custom\_jwt.h

```
#ifndef _CUSTOM_JWT_H_
#define _CUSTOM_JWT_H_

#include <Arduino.h>

class CustomJWT{
private:
    char* secretKey;

public:
    char* header;
    char* payload;
    char* signature;
    String out;

    CustomJWT(char* secret);

    char* getSecret();

    void changeSecret(char* secret);

    void encodeJWT(char* string);

    void decodeJWT(char* string);

};

#endif //_CUSTOM_JWT_H_

```

custom\_jwt.cpp

```
#include "custom_jwt.h"
#include "sha256.h"
#include <Arduino.h>

const char b64[]  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const char head[] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";

void decodeblock(unsigned char in[], char *clrstr) {
    unsigned char out[4];
    out[0] = in[0] << 2 | in[1] >> 4;
    out[1] = in[1] << 4 | in[2] >> 2;
    out[2] = in[2] << 6 | in[3] >> 0;
    out[3] = '\0';
    strncat(clrstr, reinterpret_cast<const char *>(out), sizeof(out));
}

void b64_decode(char *b64src, char *clrdst)
{
    int c, phase, i;
    unsigned char in[4];
    char *p;

    clrdst[0] = '\0';
    phase = 0; i=0;
    while(b64src[i]) {
        c = (int) b64src[i];
        if(c == '=') {
            decodeblock(in, clrdst);
            break;
        }
        p = strchr(b64, c);
        if(p) {
            in[phase] = p - b64;
            phase = (phase + 1) % 4;
            if(phase == 0) {
                decodeblock(in, clrdst);
                in[0]=in[1]=in[2]=in[3]=0;
            }
        }
        i++;
    }
}

void encodeblock( unsigned char in[], char b64str[], int len ) {
    unsigned char out[5];
    out[0] = b64[ in[0] >> 2 ];
    out[1] = b64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
    out[2] = (unsigned char) (len > 1 ? b64[ ((in[1] & 0x0f) << 2) |
                                             ((in[2] & 0xc0) >> 6) ] : '=');
    out[3] = (unsigned char) (len > 2 ? b64[ in[2] & 0x3f ] : '=');
    out[4] = '\0';
    strncat(b64str, reinterpret_cast<const char *>(out), sizeof(out));
}

void b64_encode(char *clrstr, char *b64dst) {
    unsigned char in[3];
    int i, len = 0;
    int j = 0;

    b64dst[0] = '\0';
    while(clrstr[j]) {
        len = 0;
        for(i=0; i<3; i++) {
            in[i] = (unsigned char) clrstr[j];
            if(clrstr[j]) {
                len++; j++;
            }
            else in[i] = 0;
        }
        if( len ) {
            encodeblock( in, b64dst, len );
        }
    }
}

void b64_encode(unsigned char *clrstr, char *b64dst)
{
    unsigned char in[3];
    int i, len = 0;
    int j = 0;

    b64dst[0] = '\0';
    while(j < 32) {
        len = 0;
        for(i=0; i<3; i++) {
            in[i] = clrstr[j];

            if(clrstr[j] && j < 32) {
                len++; j++;
            }
            else in[i] = 0;
        }
        if( len ) {
            encodeblock( in, b64dst, len );
        }
    }
}

CustomJWT::CustomJWT(char *secret)
{
    CustomJWT::secretKey = secret;
}

char * CustomJWT::getSecret()
{
    return CustomJWT::secretKey;
}

void CustomJWT::changeSecret(char *secret)
{
    CustomJWT::secretKey = secret;
}

void CustomJWT::encodeJWT(char *string)
{
    //Create header and body
    int len = (strlen(string) + 2)/3*4;
    char str[len];
    b64_encode(string, str);
    while(str[strlen(str) - 1] == '=')
        str[strlen(str) - 1] = '\0';
    String temp = head;
    temp = temp + ".";
    temp = temp + str;
    //Convert passkey to unsigned int
    char* msg1 = CustomJWT::secretKey;
    size_t length = strlen(msg1 + 1);
    char* beg = msg1;
    char* end = msg1 + length + 1;
    uint8_t* key = new uint8_t[length + 1];
    size_t i = 0;
    for (; beg != end; ++beg, ++i)
    {
        key[i] = (uint8_t)(*beg);
    }
    //Initialise HMAC
    Sha256.initHmac(key, length + 1);
    //Convert string to char array
    char temp1[temp.length() + 10];
    temp.toCharArray(temp1, temp.length() + 10);
    //Obtain result
    Sha256.print(temp1);
    uint8_t* hash = Sha256.resultHmac();
    //Encode to b64
    len = ((32 + 2)/3)*4;
    char str1[len];
    b64_encode(hash, str1);
    while(str1[strlen(str1) - 1] == '=')
        str1[strlen(str1) - 1] = '\0';
    temp = temp + ".";
    temp = temp + str1;
    CustomJWT::out = temp;
}

```

This is the code on the Arduino:

```
#include <custom_jwt.h>

int i;
char key[] = "tester";
char string[] = "{\"temp\":22.5,\"speed\":25.1}";
CustomJWT jwt(key);

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

void loop()
{
  jwt.encodeJWT(string);
  Serial.println(jwt.out);
}

```

I have used the SHA256 library that I found in this link with some minor modifications as mentioned here HMAC SHA256 in Arduino use case? so that it can compile: https://github.com/Cathedrow/Cryptosuite

Any help will be appreciated.

# Answer
> 1 votes
As @Majenko had pointed out in the comments, it was temp variable causing the problem. Or rather, strings in general seem to have a bad effect on the memory of the Arduino UNO. After I rewrote the code without using any strings at all, the problem was fixed and the program gave a consistent output.

---
Tags: arduino-uno, library, json
---


# Question
Title: Error compiling ESP32 Wrover Module in Linux Virtual Machine
SO i have been getting this error window when i compile a simple code to run different LED lights on the ESP32-S2-SOLA (Wrovere) module

Code:

```
int LED_BUILTIN = 2;

void setup() {
    pinMode (LED_BUILTIN, OUTPUT);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
}

```

error:

```
Arduino: 1.8.15 (Linux), Board: "ESP32 Wrover Module, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), QIO, 80MHz, 115200, None"

Traceback (most recent call last):
  File "/home/student/.arduino15/packages/esp32/tools/esptool_py/3.0.0/esptool.py", line 38, in <module>
    import serial
ImportError: No module named serial
exit status 1
Error compiling for board ESP32 Wrover Module.

```

# Answer
> 1 votes
The error can be solved by installing Python serial package via these two commands

$ sudo apt-get update -y $ sudo apt-get install -y python-serial

# Answer
> 0 votes
As Juraj and Majenko pointed out in the comments, your python installation lacks the module `serial`. In Linux the best way to install it would be `pip` or rather `pip3` for Python 3:

```
sudo pip3 install serial

```

If you don't have `pip3` on you system, install `python3-pip` first, e. g. using `apt`:

```
sudo apt install python3-pip

```

---
Tags: arduino-ide, esp32, linux, cpp
---


title: Weird assembly output

text:
# Question
Title: Weird assembly output
I was taking a look at the disassembly for a loop of mine that seemed to be taking too long and I found these assembly instructions that I don't understand. Why does it load `0` into `r25` and then do two `adc r25, 25` instructions (which wouldn't do anything since `r25` is `0`). This is for an ATTiny84 by the way.

**EDIT**: In general I'm confused about why there are so many instructions required to set DDRA, DDRB, PORTA, and PORTB in the last loop. I feel like an `LD` to read portOuts\[j\], `OUT` to output, and increment of j should be all that's required. I've tried to separate what I think is the relevant part in the disassembly.

```
void loop() {
  set_sleep_mode(SLEEP_MODE_IDLE);
  button = false;
  DDRA = 0;
  DDRB = 0;
  PORTA = 255;
  PORTB = 255;
  do {
    sleep_mode();
  } while (!button);

//  int digits[4];
//  getTime(digits);
//
//  long lights = calcDisp(digits);
  static const byte highLow[28][2] = {{2, 0}, {2, 1}, {0, 3}, {1, 3}, {1, 0}, {3, 1}, {0, 1},
                                     {0, 2}, {3, 0}, {2, 4}, {3, 4}, {4, 3}, {0, 4}, {4, 0},
                                     {4, 1}, {1, 4}, {1, 5}, {5, 1}, {1, 2}, {5, 3}, {2, 3},
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
    if (bitRead(lights, b)) {
      byte high = highLow[b][0];
      byte low = highLow[b][1];
      byte highA = regs[high][0];
      byte highB = regs[high][1];
      byte lowA = regs[low][0];
      byte lowB = regs[low][1];
      portOuts[4 * nLed] = (highA)|(lowA);
      portOuts[4 * nLed + 1] = (highB)|(lowB);
      portOuts[4 * nLed + 2] = (highA)|(1<<PA6);
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }
  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
      DDRA = portOuts[j++];
      DDRB = portOuts[j++];
      PORTA = portOuts[j++];
      PORTB = portOuts[j++];
    }
  }

```

DISASSEMBLY

void loop() {
  set_sleep_mode(SLEEP_MODE_IDLE);
  button = false;
  DDRA = 0;
  DDRB = 0;
  PORTA = 255;
 228:   bb 24           eor     r11, r11
 22a:   ba 94           dec     r11
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
    if (bitRead(lights, b)) {
 22c:   cc 24           eor     r12, r12
 22e:   ca 94           dec     r12
 230:   dc 2c           mov     r13, r12
 232:   e1 2c           mov     r14, r1
 234:   f1 2c           mov     r15, r1
  }
  return lights;
}

void loop() {
  set_sleep_mode(SLEEP_MODE_IDLE);
 236:   85 b7           in      r24, 0x35       ; 53
 238:   87 7e           andi    r24, 0xE7       ; 231
 23a:   85 bf           out     0x35, r24       ; 53
  button = false;
 23c:   10 92 a6 00     sts     0x00A6, r1      ; 0x8000a6 <button>
  DDRA = 0;
 240:   1a ba           out     0x1a, r1        ; 26
  DDRB = 0;
 242:   17 ba           out     0x17, r1        ; 23
  PORTA = 255;
 244:   bb ba           out     0x1b, r11       ; 27
  PORTB = 255;
 246:   b8 ba           out     0x18, r11       ; 24
  do {
    sleep_mode();
 248:   85 b7           in      r24, 0x35       ; 53
 24a:   80 62           ori     r24, 0x20       ; 32
 24c:   85 bf           out     0x35, r24       ; 53
 24e:   88 95           sleep
 250:   85 b7           in      r24, 0x35       ; 53
 252:   8f 7d           andi    r24, 0xDF       ; 223
 254:   85 bf           out     0x35, r24       ; 53
  } while (!button);
 256:   80 91 a6 00     lds     r24, 0x00A6     ; 0x8000a6 <button>
 25a:   88 23           and     r24, r24
 25c:   a9 f3           breq    .-22            ; 0x248
 25e:   ac e6           ldi     r26, 0x6C       ; 108
 260:   b0 e0           ldi     r27, 0x00       ; 0
 262:   90 e0           ldi     r25, 0x00       ; 0
 264:   80 e0           ldi     r24, 0x00       ; 0
  static const byte highLow[28][2] = {{2, 0}, {2, 1}, {0, 3}, {1, 3}, {1, 0}, {3, 1}, {0, 1},
                                     {0, 2}, {3, 0}, {2, 4}, {3, 4}, {4, 3}, {0, 4}, {4, 0},
                                     {4, 1}, {1, 4}, {1, 5}, {5, 1}, {1, 2}, {5, 3}, {2, 3},
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
 266:   60 e0           ldi     r22, 0x00       ; 0
 268:   30 e0           ldi     r19, 0x00       ; 0
 26a:   20 e0           ldi     r18, 0x00       ; 0
 26c:   a9 01           movw    r20, r18
 26e:   44 0f           add     r20, r20
 270:   55 1f           adc     r21, r21
 272:   44 0f           add     r20, r20
 274:   55 1f           adc     r21, r21
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
    if (bitRead(lights, b)) {
 276:   26 01           movw    r4, r12
 278:   37 01           movw    r6, r14
 27a:   08 2e           mov     r0, r24
 27c:   04 c0           rjmp    .+8             ; 0x286 <__stack+0x27>
 27e:   75 94           asr     r7
 280:   67 94           ror     r6
 282:   57 94           ror     r5
 284:   47 94           ror     r4
 286:   0a 94           dec     r0
 288:   d2 f7           brpl    .-12            ; 0x27e <__stack+0x1f>
 28a:   40 fe           sbrs    r4, 0
 28c:   3d c0           rjmp    .+122           ; 0x308 <__stack+0xa9>
      byte high = highLow[b][0];
      byte low = highLow[b][1];
      byte highA = regs[high][0];
 28e:   ec 91           ld      r30, X
 290:   f0 e0           ldi     r31, 0x00       ; 0
 292:   ee 0f           add     r30, r30
 294:   ff 1f           adc     r31, r31
 296:   e0 5a           subi    r30, 0xA0       ; 160
 298:   ff 4f           sbci    r31, 0xFF       ; 255
 29a:   70 81           ld      r23, Z
      byte highB = regs[high][1];
 29c:   a1 80           ldd     r10, Z+1        ; 0x01
      byte lowA = regs[low][0];
 29e:   11 96           adiw    r26, 0x01       ; 1
 2a0:   ec 91           ld      r30, X
 2a2:   11 97           sbiw    r26, 0x01       ; 1
 2a4:   f0 e0           ldi     r31, 0x00       ; 0
      byte lowB = regs[low][1];
 2a6:   ee 0f           add     r30, r30
 2a8:   ff 1f           adc     r31, r31
 2aa:   e0 5a           subi    r30, 0xA0       ; 160
 2ac:   ff 4f           sbci    r31, 0xFF       ; 255
 2ae:   91 80           ldd     r9, Z+1 ; 0x01
      portOuts[4 * nLed] = (highA)|(lowA);
 2b0:   21 e0           ldi     r18, 0x01       ; 1
 2b2:   30 e0           ldi     r19, 0x00       ; 0
 2b4:   2c 0f           add     r18, r28
 2b6:   3d 1f           adc     r19, r29
 2b8:   24 0f           add     r18, r20
 2ba:   35 1f           adc     r19, r21
 2bc:   e0 81           ld      r30, Z
 2be:   7e 2e           mov     r7, r30
 2c0:   77 2a           or      r7, r23
 2c2:   f9 01           movw    r30, r18
 2c4:   70 82           st      Z, r7
      portOuts[4 * nLed + 1] = (highB)|(lowB);
 2c6:   e2 e0           ldi     r30, 0x02       ; 2
 2c8:   f0 e0           ldi     r31, 0x00       ; 0
 2ca:   ec 0f           add     r30, r28
 2cc:   fd 1f           adc     r31, r29
 2ce:   e4 0f           add     r30, r20
 2d0:   f5 1f           adc     r31, r21
 2d2:   2a 2d           mov     r18, r10
 2d4:   29 29           or      r18, r9
 2d6:   20 83           st      Z, r18
      portOuts[4 * nLed + 2] = (highA)|(1<<PA6);
 2d8:   e3 e0           ldi     r30, 0x03       ; 3
 2da:   f0 e0           ldi     r31, 0x00       ; 0
 2dc:   ec 0f           add     r30, r28
 2de:   fd 1f           adc     r31, r29
 2e0:   e4 0f           add     r30, r20
 2e2:   f5 1f           adc     r31, r21
 2e4:   70 64           ori     r23, 0x40       ; 64
 2e6:   70 83           st      Z, r23
      portOuts[4 * nLed + 3] = (highB);
 2e8:   24 e0           ldi     r18, 0x04       ; 4
 2ea:   30 e0           ldi     r19, 0x00       ; 0
 2ec:   2c 0f           add     r18, r28
 2ee:   3d 1f           adc     r19, r29
 2f0:   42 0f           add     r20, r18
 2f2:   53 1f           adc     r21, r19
 2f4:   fa 01           movw    r30, r20
 2f6:   a0 82           st      Z, r10
      ++nLed;
 2f8:   6f 5f           subi    r22, 0xFF       ; 255
 2fa:   26 2f           mov     r18, r22
 2fc:   30 e0           ldi     r19, 0x00       ; 0
 2fe:   a9 01           movw    r20, r18
 300:   44 0f           add     r20, r20
 302:   55 1f           adc     r21, r21
 304:   44 0f           add     r20, r20
 306:   55 1f           adc     r21, r21
 308:   01 96           adiw    r24, 0x01       ; 1
 30a:   12 96           adiw    r26, 0x02       ; 2
                                     {4, 1}, {1, 4}, {1, 5}, {5, 1}, {1, 2}, {5, 3}, {2, 3},
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
 30c:   80 31           cpi     r24, 0x10       ; 16
 30e:   91 05           cpc     r25, r1
 310:   09 f0           breq    .+2             ; 0x314 <__stack+0xb5>
 312:   ac cf           rjmp    .-168           ; 0x26c <__stack+0xd>
 314:   68 ec           ldi     r22, 0xC8       ; 200
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }

####################### START OF RELEVANT SECTION #############################

  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
 316:   41 15           cp      r20, r1
 318:   51 05           cpc     r21, r1
 31a:   99 f1           breq    .+102           ; 0x382 <__stack+0x123>
 31c:   30 e0           ldi     r19, 0x00       ; 0
 31e:   20 e0           ldi     r18, 0x00       ; 0
 320:   80 e0           ldi     r24, 0x00       ; 0
      DDRA = portOuts[j++];
 322:   e1 e0           ldi     r30, 0x01       ; 1
 324:   f0 e0           ldi     r31, 0x00       ; 0
 326:   ec 0f           add     r30, r28
 328:   fd 1f           adc     r31, r29
 32a:   2e 0f           add     r18, r30
 32c:   3f 1f           adc     r19, r31
 32e:   f9 01           movw    r30, r18
 330:   90 81           ld      r25, Z
 332:   9a bb           out     0x1a, r25       ; 26      STORE IN DDRA
 334:   e1 e0           ldi     r30, 0x01       ; 1
 336:   e8 0f           add     r30, r24
      DDRB = portOuts[j++];
 338:   21 e0           ldi     r18, 0x01       ; 1
 33a:   30 e0           ldi     r19, 0x00       ; 0
 33c:   2c 0f           add     r18, r28
 33e:   3d 1f           adc     r19, r29
 340:   2e 0f           add     r18, r30
 342:   31 1d           adc     r19, r1
 344:   f9 01           movw    r30, r18
 346:   90 81           ld      r25, Z
 348:   97 bb           out     0x17, r25       ; 23      STORE IN DDRB
      PORTA = portOuts[j++];
 34a:   e3 e0           ldi     r30, 0x03       ; 3
 34c:   e8 0f           add     r30, r24
    }
  }
  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
      DDRA = portOuts[j++];
      DDRB = portOuts[j++];
 34e:   a2 e0           ldi     r26, 0x02       ; 2
 350:   a8 0f           add     r26, r24
      PORTA = portOuts[j++];
 352:   21 e0           ldi     r18, 0x01       ; 1
 354:   30 e0           ldi     r19, 0x00       ; 0
 356:   2c 0f           add     r18, r28
 358:   3d 1f           adc     r19, r29
 35a:   2a 0f           add     r18, r26
 35c:   31 1d           adc     r19, r1
 35e:   d9 01           movw    r26, r18
 360:   9c 91           ld      r25, X
 362:   9b bb           out     0x1b, r25       ; 27      STORE IN PORTA
      PORTB = portOuts[j++];
 364:   8c 5f           subi    r24, 0xFC       ; 252
 366:   21 e0           ldi     r18, 0x01       ; 1
 368:   30 e0           ldi     r19, 0x00       ; 0
 36a:   2c 0f           add     r18, r28
 36c:   3d 1f           adc     r19, r29
 36e:   2e 0f           add     r18, r30
 370:   31 1d           adc     r19, r1
 372:   f9 01           movw    r30, r18
 374:   90 81           ld      r25, Z
 376:   98 bb           out     0x18, r25       ; 24      STORE IN PORTB
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }
  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
 378:   28 2f           mov     r18, r24
 37a:   30 e0           ldi     r19, 0x00       ; 0
 37c:   24 17           cp      r18, r20
 37e:   35 07           cpc     r19, r21
 380:   84 f2           brlt    .-96            ; 0x322 <__stack+0xc3>   JUMP BACK TO START OF LOOP
 382:   61 50           subi    r22, 0x01       ; 1
      portOuts[4 * nLed + 2] = (highA)|(1<<PA6);
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }
  for (byte i = 0; i < 200; ++i) {
 384:   41 f6           brne    .-112           ; 0x316 <__stack+0xb7>

        setup();

        for (;;) {
                loop();
                if (serialEventRun) serialEventRun();
 386:   01 15           cp      r16, r1
 388:   11 05           cpc     r17, r1
 38a:   09 f4           brne    .+2             ; 0x38e <__stack+0x12f>
 38c:   54 cf           rjmp    .-344           ; 0x236
 38e:   38 de           rcall   .-912           ; 0x0 <__vectors>
 390:   52 cf           rjmp    .-348           ; 0x236 ```
</code></pre>

# Answer
The compiler optimized the computation `nLed * 4` into a bit shift, as `Led << 2`. It seems `nLed` is a single byte quantity. However, `nLed * 4` may not fit in one byte, and the semantics of the language demands that `nLed` is promoted to an `int` before the computation. This is done by extending the variable by a byte of zeros:

```
    ldi r25, 0

```

Now the register pair r25:r24 contains `nLed` extended to 16 bits.

Next step is to shift the whole thing left by two positions. This is done by repeating this sequence twice:

```
    lsl r24
    rol r25

```

The first instruction shifts r24 to the left. The most significant bit is stored as the carry flag. The second instruction “rotate left through carry”, is similar to a shift except that the rightmost bit position is filled by the carry. This is the way to shift a 16-bit value without loosing a bit.

The instruction `lsl` and `rol` are actually aliases of `add` and `adc` respectively. The disassembler does not care about aliases, and translates the machine code to the most “canonical” instructions, which is what you see.
> 1 votes

# Answer
Simple: `adc` has three operands. You seem look at it as if it had two :)
> 0 votes

---
Tags: attiny, avr-gcc, assembly
---