title: MAX471 giving too high current readings

text:
# Question
Title: MAX471 giving too high current readings
I want to measure current using the MAX471 sensor that outputs voltage proportional to the current (1V/A according to the datasheet). To test the module, I connected a 330 ohm resistor to the sensor and powered it from 3.3V arduino. Using ohms law, I was expecting an output voltage of around 10 mV (for ~ 10 mA) in my circuit. However, I am getting an output of around 2.17 volts which seems wrong.

Does anyone see any mistake in my circuit or how I am trying to measure the current?

Here is my circuit:

My Code:

```
#include <Arduino.h>

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

void loop()
{
  int adc_val = analogRead(A5);
  float vol = 3.2 / 4095 * adc_val; // using a 12 bit adc

  Serial.println(vol);
  delay(3000);
}

```

# Answer
> 1 votes
Do you have the same operating circuit that is shown on page 1 of the datasheet? do you have the 2K resistor they specifically from OUT to ground? Also, it may be worth adding the 1 uF capacitor they recommend from OUT to ground too

The other thing to consider is the actual voltage over the resistor. Check an see if the voltage over the resistor is 3.3 and that there isn't a voltage drop from the chip

If the voltage is fine, there may be a problem with the chip or the arduino

# Answer
> 1 votes
I've got a few MAX471 modules and instead of current readings i get around 90% of input voltage on all of them.

With increasing load the output voltage decreases a bit and the MAX471 chip gets very hot (for example 12V 0mAh = 10V, 12V 200mAh = 9,6V).

I guess we are just "lucky" to get a bad batch or counterfeit chips...

---
Tags: arduino-uno, current
---


# Question
Title: AVR & PIC 8-bit Microcontrollers - Can you add: external flash memory, external RAM, video & audio output, more address busses?
so I was planning on creating a mini PC out of basic ICs and 8-bit microcontrollers such as ATTinys and/or PICs and I have several questions regarding those:

1. Can you add external RAM, say with SRAM, DRAM chips, so the microcontroller can handle larger programs? (ones requiring more memory to be executed). I've seen an excellent discussion here: External Flash Memory for ATtiny85, which exclaims that **I can't** do that with AVRs (but why exactly is that? What about PICs, or any 8-bit uCs for that matter).
2. Can you add external memory, like flash or EEPROM, so that the microcontroller can store some files (sort of a hard drive (but more like an SSD I guess).
3. Also, how would you go around connecting memory chips together to get more memory out of them? Would there be a difference with memory chips like serial flash and parallel flash?
4. Can you use them to output and create basic audio & output HDMI? (or communicate with external ICs to do that task)
5. Can you somehow connect say 2 8-bit ATTinys to get a pseudo 16-bit microcontroller? Would that mean they could process more data at the same time?

Thanks, some guy on the internet.

# Answer
> 4 votes
1. Yes, you can connect external RAM chips through the typical interfaces (mainly SPI or I2C). But you cannot execute code from it. The microcontroller is an IC, meaning Integrated Circuit. It is hard wired internally to execute from internal flash. You cannot change that. That is valid for most microcontrollers, that executes from internal flash (which is somewhat a definition of a microcontroller). A processor - in contrast- like in a computer, is build to execute code from elsewhere. Note: Some microcontrollers have the ability to execute from external flash. The ESP boards are a good example for this, because they already use an external flash chip, which is soldered onto the board. You can extent the available flash over the SPI flash pins (the SPI bus, where the flash is connected); though this is not really a topic for beginners. You might wanna look into that.

If your code, that you want to store externally, isn't that complex, you could save the code there as an own (most likely binary) data format and write code for the microcontroller, that takes that data and executes corresponding functions. So basically an interpreter. Though on the small microcontrollers only code for rather small functionality will fit.
2. Yes, you can add external storage. Which storage depends on many factors. You can by external flash or EEPROM chips, just like external RAM chips. Common storage devices for microcontrollers are SD cards, because they can easily interfaces via SPI. You can even have a file system there (though the size is somewhat limited by the available RAM of your microcontroller, because it needs to load the file table). Maybe you can even connect an SSD, but you will have to look, if you can set up the corresponding interface for it. A microcontroller does not have SATA interfaces or similar. And adding extra chips for these leaves you fastly with interfacing chips, that are way more capable as the main chip itself (see Wifi and the ESPs: You could add Wifi to an Arduino Uno project with it, but the ESP is way more capable, than the Uno). Then you would need to ask yourself: Is this really a good idea?
3. I think most memory chips (whichever kind) are not daisy chainable. Mostly they use a Single-Master-Multiple-Slaves interface like SPI. You could connect multiple memory chips to the SPI bus and communicate sequentially with them. The difference between parallel and serial flash chips is their communication interface. Serial can be something like SPI. Parallel communication will send multiple bits at once over the corresponding amount of wires (mostly 8, means 1 byte). Here you need the corresponding number of free pins on your microcontroller. Though parallel interfacing is often not advisable. Especially the small microcontrollers are too slow, to profit from the faster interface. And instead of using at least 9 pins, you could also use 3 for SPI and get the same transmission speed in the end.
4. Yes, they can. Though it really depends on the used microcontroller and the project topology. When using something like the DFmini player, any microcontroller can play audio (from files on a micro SD card in the player). When the microcontroller should play sounds itself, you can get very different results, depending on the chip capabilities. An ESP32 for example has a dedicated I2S interface, which is build for transmitting sound to an output device.

About video: AVR based microcontrollers (or similar PICs) cannot really handle video. For example: The most, that you can get out of an Arduino Uno (Atmega328p) is a very very limited VGA signal (very small resolution, only a few colors). HDMI is out of range for any of them. Surely you would want to draw on the screen, that is connected to the HDMI interface, to build up a visual interface. I think, that is just not possible with such small microcontrollers. They are not meant for this. Though you might find some very specialized chip, that you could use in such a way. If, that chip would be way more expensive as buying multiple Raspberry Pis. But if you are willig to compromise you may find a smaller sized display (like a few inches) with a connected controller, that you can control via the Arduino. But still you will have very low refresh rate, so no moving images, more like still images.
5. No, just as 2 32-bit computers do not make 1 64-bit computer. That is just not, how everything works. Each microcontroller can still only process 8 bit at a time out of it's own memory. Depending on the task, you may try to give them different tasks. That would give you more computation power in theory, but it's not the same as a 16-bit controller.

I assume, that you are doing this for fun or for the grind, so I will not say, that you should buy a Raspberry Pi. Though I think, you might look into the wrong way. You cannot make a truck out of parts for a mini, though many of the components work in a similar way. To get all the difficult functionality (audio, video, big storage, ...) out of your self build computer, you need to use computer parts, not microcontroller parts.

If you are happy with much less capabilities, many people in the past have build their own computers out of more basic parts as microcontrollers (down to the big range of logic gates). Microcontrollers live in the world between computers and basic logic components. They are too integrated for extending their capabilities much.

# Answer
> 1 votes
Yes you can, and even execute code from it on PIC18 and PIC17 microcontrollers up to 2MB if external program memory can be added but most variants lac the external program memory interface. For example the pic18f8x8x you can even implement a memory bank system to address much more than 2MB like PCs did in the early times of the x86 called XMEM extended memory.

---
Tags: avr, memory
---


title: micros() resolution for Portenta H7

text:
# Question
Title: micros() resolution for Portenta H7
Is there any way to know the resolution of micros() for the Arduino Portenta H7. I have checked for other boards e.g. Nano which is mentioned as 4 uS. However, I couldn't find one for Portenta H7.

Is there any way to measure or look for that

# Answer
The **micros()** language reference states that, "\[The micros() function\] returns the number of microseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 70 minutes. **On the boards from the Arduino Portenta family this function has a resolution of one microsecond on all cores.** On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds.

It seems likely that the doco was updated some time after the OP posted the question.
> 1 votes

---
Tags: arduino-ide, adc, analogreadresolution, arduino-portenta-h7
---


# Question
Title: Interval timer on Arduino: Doubt about TimerOne library
I want to synchronize a timer interrupt from a button is pressed. I want to read a button state 3 seconds later from the first pulse moment (to identify long pressed button, 3 seconds for this example). I'm trying to do with this code:

```
#include <TimerOne.h>
#define pinButton 3
#define POWER_ON_TIME 3 //Long press in seconds

volatile unsigned long pressed_Time = 0;
volatile unsigned long myTime_button = 0;
volatile unsigned long myTimeOn_button = 0;
volatile unsigned long myTime_pressed = 0;

unsigned long holdTime = 0;
bool button_state = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(pinButton, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);

  Timer1.initialize();
  Timer1.attachInterrupt(pressed_check);
  attachInterrupt(digitalPinToInterrupt(pinButton), button_act, CHANGE);
  Serial.begin(9600);
}

void loop() {

  Serial.println("myTime_pressed");
  Serial.println(myTime_pressed);

  if (!digitalRead(pinButton)){Timer1.attachInterrupt(pressed_check,POWER_ON_TIME*1000000 );}
    else {Timer1.detachInterrupt();}

}

void button_act(){
  if (!digitalRead(pinButton)){myTime_button = micros(); //Flanco de bajada
  }
  else{myTimeOn_button = micros(); } //Flanco de subida
}

void pressed_check(){
  myTime_pressed = micros();

}

```

This way I can start the timer interrupt when the button is pressed, but the problem is the time is not the time from the function is attached but from the beginning. Any advice to change this?

# Answer
> 4 votes
Don't know if I understand what you want to do. IMHO TimerOne is a good library for repetitive tasks, not for one shot events.

You should use Timer1.stop and Timer1.resume() to start the 3 seconds count whenever you press the button. But TimerOne has a known issue: when you use restart or start the ISR is fired immediatly

Here is my version of your code. It waits for button press and then starts timer. After 3 seconds pressed\_check is fired and the longPressDetected flas is set. I hope I have correctly interpreted your question

```
#include <TimerOne.h>
#define pinButton 3
#define POWER_ON_TIME 3UL //Long press in seconds

volatile unsigned long pressed_Time = 0;
volatile unsigned long myTime_button = 0;
volatile unsigned long myTimeOn_button = 0;
volatile unsigned long myTime_pressed = 0;

volatile bool firstISR_Call = true;
volatile bool longPressDetected = false;

unsigned long holdTime = 0;
bool button_state = false;

void setup() {
    // put your setup code here, to run once:
    pinMode(pinButton, INPUT_PULLUP);
    pinMode(LED_BUILTIN, OUTPUT);

    Timer1.initialize();
    // Create an ISR that is called every POWER_ON_TIME seconds
    Timer1.attachInterrupt(pressed_check, POWER_ON_TIME * 1000000UL);
    // Stop Timer1 now
    Timer1.stop();

    //Timer1.attachInterrupt(pressed_check);

    attachInterrupt(digitalPinToInterrupt(pinButton), button_act, CHANGE);
    Serial.begin(9600);
}

void loop() {
    if (longPressDetected) {
        longPressDetected = false;
        Serial.println("Long press detected");
    }
    delay(100);
}

void button_act() {
    if (!digitalRead(pinButton)) {
        myTime_button = micros(); //Flanco de bajada
        firstISR_Call = true;       // Set to true toprevent "phantom" interrupt
        longPressDetected = false;  // Clear long press detection flag
        Timer1.restart();           // Restart timer from 0 - ISSUE: this fires immediatly an interrupt
                                    // causing a so called "phantom" interrupt
    }
    else {
      myTimeOn_button = micros() - myTime_button;
      Timer1.stop();
    } //Flanco de subida
}

void pressed_check() {
    // Detect "phantom" interrupt
    if (firstISR_Call) {
        firstISR_Call = false;
        return;
    }
    longPressDetected = true;
    myTime_pressed = micros() - myTime_button;
    Timer1.stop();
}

```

---
Tags: arduino-uno, interrupt, atmega328, timers
---


# Question
Title: Using ESP8266 to program Arduino by serial comm
Since ESP8266 can self program on wifi, can we use it to program arduino too with the binary sent via wifi? my arduino is connected with reset+RX+TX pins and shared power. Has this been already done?

# Answer
If you use Linux, you can use a simple Telnet to Serial sketch in esp8266 to upload with avrdude to Uno over esp8266. Only on Linux can avrdude use telnet to do a serial upload.

For upload from IDE on any OS there is JeeLabs ESP Link firmware for the esp8266.
> 0 votes

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


title: How fast are IR sensors with Arduino

text:
# Question
Title: How fast are IR sensors with Arduino
For an industrial project which requires detecting whether some text is printed on the cable at regular intervals or not, I was wondering if Arduino with IR sensor could work? The cable would be typically black with white text printed at each metre and will be unwounding from a cylindrical drum (To give you an idea of text length, it will contain cable type, metre mark, etc., I'll update the question with the linear velocity of the cable soon).

My approach was to raise an interrupt if the colour change is not recognized in the predetermined time. For this, I think I need to check if I can measure light changes, let's say 4 or 6 times in a time it takes to unwind a metre of the wire. I however don't know how fast IR sensors are to judge whether this approach is feasible.

Also, let me know if this is unfeasible and I should instead move to Raspberry Pi with a camera.

# Answer
> 1 votes
https://www.instructables.com/IR-Transmitter-and-Receiver-Using-Arduino/

As demonstrated in the project linked above an IR sensor connected to an Arduino is capable of reading and decoding the signal from a typical IR remote sending at about 38 KHz. In the ones I've tried the signal is a burst of 10 or 11 digits. Given that, sensing the presence or absence of a contrasting color sounds quite a bit less challenging.

I built the decoder in the linked Instructable with a Nano (author used a Mega) and it worked well.

I believe what you're proposing is feasible.

---
Tags: ir
---


# Question
Title: What is the difference between Bluetooth module HC-05 and HC-42 for Arduino?
I am looking for differences between HC-05 and HC-42 Bluetooth modules for Arduino. I could not find an answer by searching google.

Both products have 6 pins and accept master and slave but I could not find further details on the differences.

# Answer
> 6 votes
It's different technology. the HC-05 uses the old Bluetooth 2.0 standard. The HC-42 in contrast uses BLE (Bluetooth Low Energy) in version 5.0.

So you have to decide what technology you want to use, either classic Bluetooth 2.0 or Bluetooth Low Energy 5.0.

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Arduino ESP8266 Ticker interrupted by DallasTemperature/OneWire?
I have been using the Ticker to blink a led successfully. However, now I am fetching temperature from a DS18B20 in the main loop (which is using the OneWire library) and the blink is now erratic.

Is the Ticker suspended by the DallasTemperature/OneWire library?

It this suspending interrupts or something?

Maybe using the same interrupt?

# Answer
Ticker does not interrupt your code. It is a OS-timer and will call your function once the time is elapsed.

The Tiker callback can be interrupted by a "real" interrupt or another Task with higher priority and does not provide any reliability - it will just be called.

A solution (not the best) would be to disable manually all interrupts, if you can't solve it in another way.

If you just want a blinking led, you should use a Timer interrupt as your callback is short and fast. Maybe with the `ICACHE_RAM_ATTR` attribute.
> 2 votes

# Answer
I ran into a problem using libraries with sensor DS18B20 in ticker. If I request the temperature through millis(), then everything is fine. When I request the temperature in the ticker, I get "Panic core\_esp8266\_main.cpp:137 \__yield". Unfortunately I can't explain it.
> 0 votes

---
Tags: esp8266
---


# Question
Title: How do I instruct the L293D to operate a motor at full speed when using 3.3V GPIO pins?
If the L293D enable and input pins expect \[up to\] 5V inputs; what is the best way to deliver full power to the output pins when using an ESP32 or any other microcontroller which uses 3.3V GPIO pins?

I've seen several projects which combine the L293D with the ESP32, but none of them seem to mention whether or not this is even an issue. Am I missing something? Or should one always use level shifting when using 3.3V logic and the L293D

# Answer
> 4 votes
The voltage level on the control pins does not have any relation to the power provided to the motor.

The inputs are all digital. Above a threshold they are on, and below a threshold they are off. Those thresholds are compatible with both 3.3V and 5V logic.

What controls the power delivered to the motor is the duty cycle of the PWM signal provided to the EN pin.

---
Tags: esp32, pins, l293d
---


# Question
Title: How to build an arduino project with multiple source files?
I'm building an arduino program on linux, using the following `Makefile`:

```
ARDUINO_DIR = /usr/share/arduino
BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyAMA0
ARDUINO_LIBS = Wire
include /usr/share/arduino/Arduino.mk

```

Currently all of my code is spread among a dozen header files and a single `.ino` file - it gets compiled and it runs properly when flashed. I know that's not correct though and I'm trying to split my code into the proper structure of source and header files but when I do and try to build it I get the following output:

```
In file included from gear.c:1:0:
gear.h:19:1: error: unknown type name ‘byte’
 byte GEAR = 3;
 ^

```

Which leads me to believe that the source file is getting compiled separately and does not know what a `byte` is, which is supposedly defined somewhere within the arduino library.

What's the proper way to build my project with source files?

# Answer
> 2 votes
First of all, I recommend you write in C++ (file extension .cpp) rather than in plain C (files in .c). The reason is that the Arduino programming environment is based on C++, some of the libraries are C++-only, and your main .ino file will be compiled as C++ source. Mixing this with C is possible, using some `extern "C"` declarations, but it is probably more hassle that it's worth.

Now, to answer your actual question, just add thsi near the top of your source files:

```
#include <Arduino.h>

```

This includes the type definitions specific to the Arduino environment, together with the core API. This include is added automatically to any file ending in .ino, but you have to add it explicitly to your .cpp files.

---
Tags: programming, c, avrdude, linux, arduino-makefile
---


# Question
Title: I2C missing last byte during transmission- solution isn't clear
I am using a Nodemcu-32S to communicate with an I2C device (touchpads). I noticed while uploading the configuration, the CRC (checksum) always comes back incorrect. After doing a little digging with a logic analyzer, I realized that it never transmits the final byte from my configuration array, which *is* the checksum value. The function I use for writing to the I2C bus is as follows:

```
bool writeI2C(uint16_t address, uint8_t command, uint8_t *data, uint8_t dataLen)
{
    byte err;
    uint8_t dataPos = 0;
    Wire.beginTransmission(address);
    Wire.write(command);
    for (dataPos; dataPos < dataLen; dataPos++)
    {
        Wire.write(data[dataPos]);
    }
    delay(70);
    err = Wire.endTransmission();
    if (err > 0)
    {
        Serial.printf("writeI2C Error Code: 0x0%d\n", err);
        return false;
    }
    else
        return true;
}

```

With the following function call:

```
uint8_t config[128] = {0}; <- (the array is filled with values before the function call)

if (!writeI2C(SLAVE_ADDR, command, config, 128))
        {
            Serial.println("Failed to update config.");
            continue; // try again
        }

```

According to the logic in my function, it should transmit the address, then the register (`command` in this case) followed by 128 bytes of data (130 bytes total). With my logic analyzer, however, I get only 129 'chunks' of data. So I figured I'd add dummy writes if `dataLen` met a condition:

```
bool writeI2C(uint16_t address, uint8_t command, uint8_t *data, uint8_t dataLen)
{
    byte err;
    uint8_t dataPos = 0;
    Wire.beginTransmission(address);
    Wire.write(command);
    for (dataPos; dataPos < dataLen; dataPos++)
    {
        Wire.write(data[dataPos]);
    }
    if (dataLen > 100)
    {
        Wire.write(0x00);
        Wire.write(0x00);
        Wire.write(0x00);
        Wire.write(0x00);
        Wire.write(0x00);
    }
    err = Wire.endTransmission();
    delay(70);
    if (err > 0)
    {
        Serial.printf("writeI2C Error Code: 0x0%d\n", err);
        return false;
    }
    else
        return true;
}

```

None of the dummy writes are outputting and the behavior is the same. The final two bytes should be: `config[126] = 0x45` and `config[127] = 0xC9`, but my logic analyzer is shows that the transmission stops at `0x45 + ACK`.

# Answer
Within `Wire.h.`:

```
#define I2C_BUFFER_LENGTH 128

```

Changed the buffer length to 140 and it's working just fine.
> 4 votes

---
Tags: i2c
---


title: Cubecell AB01 with nRF24L01

text:
# Question
Title: Cubecell AB01 with nRF24L01
I have been trying to connect a nRF24L01 to a Cubecell AB01 without much luck. Most of the time, the radio.available() function always returns true resulting in a bunch of garbage. I have figured out that the nRF24L01 doesn't want to configure properly. With printPrettyDetails() I can confirm that the settings are not stored.

However, with the example sketch contained within the RF24 library, everything works fine (confirming that the AB01 and nRF24L01 are working fine). But as soon as I change the datatype of the receiver payload to uint8\_t, the radio.available() is always true, resulting in a bunch of received messages with garbage. PrintPrettyDetails() also shows the wrong settings.

Does anyone have experience with this? I have also tried the example sketch from Robin2. This results in a lot of garbage as described before.

I am using:

* nRF24L01 with pcb antenna. I am periodicially using an esp32 to test that the nRF24L01 is still functioning okay
* a heltec AB01. The nRF24L01 is connected to the spi interface and CE -\> GPIO3 and CSN -\> GPIO2
* To program I'm using platformio. But in desperation I am also able to use the Arduino IDE (exactly the same behaviour)

RX code: /\** * See documentation at https://nRF24.github.io/RF24 * See License information at root directory of this library * Author: Brendan Doherty (2bndy5) \*/

```
    /**
     * A simple example of sending data from 1 nRF24L01 transceiver to another.
     *
     * This example was written to be used on 2 devices acting as "nodes".
     * Use the Serial Monitor to change each node's behavior.
     */
    #include <SPI.h>
    #include "printf.h"
    #include "RF24.h"

    // instantiate an object for the nRF24L01 transceiver
    RF24 radio(GPIO3, GPIO2); // using pin 7 for the CE pin, and pin 8 for the CSN pin

    // Let these addresses be used for the pair
    uint8_t address[][6] = {"1Node", "2Node"};
    // It is very helpful to think of an address as a path instead of as
    // an identifying device destination

    // to use different addresses on a pair of radios, we need a variable to
    // uniquely identify which address this radio will use to transmit
    bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to                                 transmit

    // Used to control whether this node is sending or receiving
    bool role = false;  // true = TX role, false = RX role

    // For this example, we'll be using a payload containing
    // a single float number that will be incremented
    // on every successful transmission
    float payload = 0;

    void setup() {

      Serial.begin(115200);
      while (!Serial) {
        // some boards need to wait to ensure access to serial over USB
      }
      pinMode(Vext, OUTPUT);
      digitalWrite(Vext, LOW);
      delay(10);
      // initialize the transceiver on the SPI bus
      if (!radio.begin()) {
        Serial.println(F("radio hardware is not responding!!"));
        while (1) {} // hold in infinite loop
      }

      // print example's introductory prompt
      Serial.println(F("RF24/examples/GettingStarted"));

      radioNumber = 1;
      Serial.print(F("radioNumber = "));
      Serial.println((int)radioNumber);

      // Set the PA Level low to try preventing power supply related problems
      // because these examples are likely run with nodes in close proximity to
      // each other.
      radio.setPALevel(RF24_PA_LOW);  // RF24_PA_MAX is default.

      // save on transmission time by setting the radio to only transmit the
      // number of bytes we need to transmit a float
      radio.setPayloadSize(sizeof(float)); // float datatype occupies 4 bytes

      // set the TX address of the RX node into the TX pipe
      radio.openWritingPipe(address[radioNumber]);     // always uses pipe 0

      // set the RX address of the TX node into a RX pipe
      radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1

      // additional setup specific to the node's role
      if (role) {
        radio.stopListening();  // put radio in TX mode
      } else {
        radio.startListening(); // put radio in RX mode
      }

      // For debugging info
      // printf_begin();             // needed only once for printing details
      // radio.printDetails();       // (smaller) function that prints raw register values
       radio.printPrettyDetails(); // (larger) function that prints human readable data

    } // setup

    void loop() {

        // This device is a RX node

        uint8_t pipe;
        if (radio.available(&pipe)) {             // is there a payload? get the pipe         number that recieved it
          uint8_t bytes = radio.getPayloadSize(); // get the size of the payload
          radio.read(&payload, bytes);            // fetch payload from FIFO
          Serial.print(F("Received "));
          Serial.print(bytes);                    // print the size of the payload
          Serial.print(F(" bytes on pipe "));
          Serial.print(pipe);                     // print the pipe number
          Serial.print(F(": "));
          Serial.println(payload);                // print the payload's value
        }

    } // loop

```

I have tried anything I could think of, without success. Any help would be appreciated!

# Answer
> 0 votes
Turned out to be a corrupt library and an SPI speed mismatch

---
Tags: nrf24l01+, platformio
---


title: Can 1 wiegand output for 2 controllers?

text:
# Question
Title: Can 1 wiegand output for 2 controllers?
recently I have this project which needs to read 2 wiegand signal using Arduino Mega 2560.

I have an access control device which will output wiegand signal once the user is allow to enter, and there's a RFID reader which will transmit the card no in wiegand signal to my access control device.

So I need to get card no from the RFID reader and also from the Access control device, so I connect them like the attachment given, using a library here: ( https://github.com/ugge75/Wiegand-V3-Library-for-all-Arduino ), everything works fine at first, but once a while, I can't read signal from the RFID Reader, and sometimes I can. Could anyone let me know why is this happening?

# Answer
In the readers there is switch transistors that pull down voltage provided from controllers, in other words is shutting signal to the ground. In my practice i tested many solutions and simplest one is with diodes from each controller D0 D1 in direction to the reader. In that case is not crossing voltage from controllers. For 2 controllers and 1 reader you need 4 diodes - 2 on each line.

Controller 1 - D0 --\> anode on Diode 1 --\> cathode to common connection for line D0

Controller 1 - D1 --\> anode on Diode 2 --\> cathode to common connection for line D1

Controller 2 - D0 --\> anode on Diode 3 --\> cathode to common connection for line D0

Controller 2 - D1 --\> anode on Diode 4 --\> cathode to common connection for line D1

Common connection D0 --\> reader D0

Common connection D1 --\> reader D1

Works fine up to 20 meters since every diode makes voltage drop. For diodes 1N4001/4007 works fine. Noise is not a problem, this is very slow connection with 5v amplitude.
> 4 votes

# Answer
There is missing information. Assuming a 5V Arduino and all D0s and D1s swing from 5V to 0V as the Wiegand protocol defines. This despite the 12V power supply in the question's diagram.

Examining the driver code on GitHub, we see it's falling edge interrupt driven. So any noise when the line is expected to be at a steady 5V will cause the driver to run. And there are a number of locations in the code where data is dumped because it is considered bad. It appears that any unexpected noise during a valid signal will cause missing data.

Consider the possibility of noise affecting the RFID data. Shorten the length of the RFID's Wiegand cable in an effort to improve the RFID reliability.

Consider re-writing the driver code to improve noise rejection. Currently, it appears the driver code will accept any falling edge as valid data to be processed. Alternatively, the driver code could detect a falling edge then sample the same input a fixed interval of time later. A valid signal is assumed to last longer than noise. Therefor any falling edge interrupt followed by a high sample can assumed to be noise and ignored / not-processed.
> 1 votes

---
Tags: arduino-mega, rfid
---


# Question
Title: Using IN1/ IN2 pins for PWM instead of ENA in L298N
So basically i tried providing PWM directly to the IN1/IN2 Of L298n motor driver instead of using ENA pin i got more or less the same result Im using ESP32 with 30000Hz freq for my PWM My question is if both ways it can be used why aren't people using this method? Or am i missing something? I would love to know the reason if someone has any idea about it.

# Answer
When using only IN1/2 to control **speed** and **direction**, you must apply PWM to IN1 for one direction and to IN2 for the other direction, while the other pin will be connected to ground. This method is easy to implement with a MCU but uses two PWM channels.
I think the EN pin is used for applications without MCUs or where there is only one PWM channel. In these situations, pins IN1/2 are used for STOP/CW/CCW selection and EN for speed from a single PWM source.
> 0 votes

---
Tags: arduino-uno, esp32, pwm, l298n
---


# Question
Title: external power supply for servo motor attached to redboard arduino
I'm new to this page but I was hoping to get some advice on a servo motor arduino project I'm currently working on.

I have a HS-815BB servo motor (4.8~6V, max stall current draw 6,000mA) and a Spark Fun Redboard. I know I should hook up an external power supply to my servo motor to avoid frying my board. I've seen x4 AAA battery packs that can output 6V, as well as breadboard power supply modules with 3.3V/5V output. However, the breadboard power supply module has a max output current of 700mA and I'm not sure about the battery pack.

Where can I find a power supply that is arduino compatible and outputs ~6V while having a max current draw of 6A or over? Am I looking for the right thing?

Thanks in advance

# Answer
> 1 votes
With 6A you are at a very high current.

First about the batteries: I wouldn't trust in 4 AAA batteries in supporting that high of a current. You may get away with it, if you only have very short bursts of 6A, but I guess the voltage will take a significant dip here. I would look into LiIon or LiPo battery packs, like the ones used for drones (which also can have high current spikes). But please take care to also use a fitting charging circuit. You can find many resources about that on the web.

Now about the breadboard: **Just don't pull 6A through a breadboard!** Breadboards are not made for currents this high. The contacts have a resistance that is significant in this situation and the metal strips used in there are also not meant for carrying that much. Going over 1A is probably no good for a breadboard. Instead you should connect the power supply outside of the breadboard by soldering or using proper connectors, which can handle the current. You can hook up your breadboard power regulator to the same battery if you want to provide it from the same source.

> Where can I find a power supply that is arduino compatible and outputs ~6V while having a max current draw of 6A or over?

There is no "Arduino compatibility" with power supplys. For the Arduino its just about having the correct voltage and being able to provide the needed current to the Arduino (excluding the servo, since it shouldn't be plugged into the breadboard in the first place). When you use a battery and also want to charge it in your circuit, then you need to find a charger board compatible with your chosen battery. Often these boards also have a voltage regulator from which you can get the 5V that you need to power an Arduino. Otherwise you can buy voltage regulator boards, which can take a full range of input voltages and output a regulated voltage of your liking (controlled via a small potentiometer on the board). These can also be used if you want to use a power supply connected to mains (like the often seen 12V power supplies for LED strips).

So called "breadboard power supply modules" are often not more than a board with pins in positions fitting for a breadboard. They are a pure convenience product. You can also solder pin to the cable of power source and put these into the breadboard. Sometimes these boards also have a voltage regulator, which you can also get without the breadboard connector part.

---
Tags: power, servo
---


title: Serial read and send to UDP?

text:
# Question
Title: Serial read and send to UDP?
I was trying to send whatever is received from serial by udp, but it doesn't work properly. the receiver side showing number 50 51 53 ..... the result like below screenshot:

can anyone help me please to fix ?

sender sketch:

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

const char* ssid = "MikroTik";
const char* password = "12345678";
unsigned int localPort = 2390;

WiFiUDP Udp;
void setup() {
  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Udp.begin(localPort);
}

void loop() {
  Udp.beginPacket("10.5.50.23", localPort);
  int val = Serial.read();
  Udp.print(val);
  Udp.endPacket();
  delay(10);
}

```

receiver sketch:

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

const char* ssid = "MikroTik";
const char* password = "12345678";
unsigned int localPort = 2390;
char packetBuffer[255];
WiFiUDP Udp;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }
  Udp.begin(localPort);
}

void loop() {
  delay(10);
  if (Udp.parsePacket()) {
    int len = Udp.read(packetBuffer, 255);
    if (len > 0) {
      packetBuffer[len] = 0;
      Serial.println(packetBuffer);
    }
  }
}

```

# Answer
> 2 votes
The problem is with the different interpretations of the binary data and lies in these two lines:

```
int val = Serial.read();
Udp.print(val);

```

What you write into the Serial Monitor is ASCII encoded text. Each byte of data corresponds to one character. If you write an `a` this is taken as the ASCII representation. In hexadecimal this character is `0x61` and in decimal `97`. Thats the actual value that gets transmitted to the ESP over Serial. Then you read that into an integer. SO `val` would have the value 97. Then you use `Udp.print(val)`. All `print()` functions are there for producing a human readable representation of the data, meaning ASCII encoded (Thats a standard Arduino convention). So basically you said here: "Here you have a number (integer). Print it into the UDP packet in human readable (ASCII) form." So the UDP packet now contains the ASCII string "97". You probably typed the digit `5` and then `4` a few times. Their decimal values are 53 and 52.

There probably also is a function called `Udp.write()`. The `write()` functions by convention don't change the data. They just write it without interpretation. So by using `Udp.write()` the actual binary value of the received data would be send and the letter `a` would appear as letter `a` in the Serial output of the receiver.

This works good as long as you only want to send single bytes in your packets. Also note, that `Serial.read()` will return `-1` if there is no data to read in the buffer. So to handle that you need to step up the sender code:

* Only read from Serial, if there is actually data in the buffer. You can use an if statement for this like:

```
  if(Serial.available()){ // read in this if statement

```
* Read all data from Serial up to a specific delimiter character, which marks the end of a complete message. Typically the newline character `\n` is used for that. You can configure the Serial Monitor to use newline as line ending (it then gets appended to the typed text when you press Enter). There are a lot of example codes for this on the web.

---
Tags: esp8266
---


# Question
Title: Safely extend TCNT1 / ICR1 to 24 bits using TOV1
I'm hoping to time external events on a '328p Arduino that will occur slowly enough that they'll overflow the 16-bit counter TCNT1. In a different scenario I'd prescale the counter, but I need the full timer resolution in this case for other purposes.

So I enable the TOV1 interrupt and just increment an 8-bit value, letting it roll over as needed.

Then on an ICP1 interrupt, I shift this value \<\< 16 into a 32-bit variable, and add in the value captured in ICR1, yielding a 24-bit value that I can use to measure the slow interval.

Are there hidden gotchas in this plan? Possible race conditions where TOV1 hasn't yet been updated if ICR1 is latched just when TCNT1 has just rolled over, or generates a TOV1 after capturing ICR1 but before I shift in the overflow count?

# Answer
There is, indeed, a possible race condition. Consider this naive code, which provides 32-bit timestamps:

```
/* Count overflows. */
volatile uint16_t timer1_overflow_count;
ISR(TIMER1_OVF_vect)
{
    timer1_overflow_count++;
}

/* Timestamp input events. */
volatile uint32_t captured_timestamp;
volatile bool did_capture;
ISR(TIMER1_CAPT_vect)
{
    captured_timestamp = timer1_overflow_count << 16 | ICR1;
    did_capture = true;
}

```

Since TIMER1\_CAPT has higher priority than TIMER1\_OVF, then:

* If `ICF1` rises before `TOV1`, `TIMER1_CAPT_vect` runs first, which is fine.
* If `ICF1` and `TOV1` rise simultaneously, `TIMER1_CAPT_vect` runs first, which is still fine, as the captured value is `0xffff`.
* If `TOV1` rises before `ICF1`, either ISR may run first:

+ if the CPU can process the TIMER1\_OVF IRQ right away, then `TIMER1_OVF_vect` runs first and the result is correct
    + if the interrupt processing is delayed until after `ICF1` has risen, then `TIMER1_CAPT_vect` runs first and grabs a wrong value for `timer1_overflow_count`.

## Solution

There is an unhandled overflow when `bit_is_set(TIFR1, TOV1)`. The overflow may have happened at the same time or after the capture, in which case it doesn't affect the timestamp. We know it happened before the capture when the captured value is small, where “small” could be defined as having its most significant bit clear. If this is the case, we have to add `0x10000` to the timestamp we obtained.

A race-proof ISR can be written as follows:

```
ISR(TIMER1_CAPT_vect)
{
    uint16_t captured_low = ICR1;
    uint16_t captured_high = timer1_overflow_count;
    if (bit_is_set(TIFR1, TOV1) && !(captured_low & 0x8000)) {
        captured_high++;
    }
    captured_timestamp = (uint32_t) captured_high << 16 | captured_low;
    did_capture = true;
}

```
> 1 votes

---
Tags: interrupt, atmega328, timers
---


# Question
Title: Arduino Pro Mini doesn't align nor connect in fritzing
When using fritzing (0.9.6) I notice that the Arduino Pro Mini 3.3 V component doesn't align nor connect to breadboard pins like other components.

Is this a bug or a feature?

I've tried to wiggle the board/component, disable/enable 'Align to Grid', but this doesn't help.

For comparison, a PIC or M1 blue pill aligns/connects fine, even after rotating both the board and components.

**Update:** To illustrate the issue:

Note on the left how the Arduino Mini Pro doesn't connect and doesn't align, i.e. its pins are between the rows. For comparison, on the right a blue pill whose pins do align and auto-connect.

# Answer
> 2 votes
There is a mostly corrected part available here:

https://forum.fritzing.org/t/arduino-mino-pro-3-3-v-doesnt-align-connect/15221/2

as noted it needs more corrections before being added to core parts (which will also require obsoleting the current part.)

# Answer
> 1 votes
The Pro Mini component you try to use in Fritzing has a bug in alignment possibly because of position units not specified.

You can fix it by editing the source code of the component as mentioned in this Fritzing forum thread: https://forum.fritzing.org/t/pins-not-aligning-with-board/9142/4

# Answer
> 1 votes
**Short Answer...**

I’m not an expert on the Fritzing sketch tool, however I’ll guess that the graphical anchor point on the board component shown in your question has been specified incorrectly and that if that bug was corrected, the long edge pins would snap to a breadboard component the same way as your comparative example. Noting that this would almost certainly leave some internal or short edge pins out of alignment with the breadboard grid (depending on the component PCB layout).

**More information ...**

(I'm pretty sure OP already knows this, but adding for a more generally usable answer)

Arduino Pro-mini was designed for “installations where space is premium and projects are made as **permanent set ups**”. *Some* of the design choices can be somewhat incompatible with breadboard which has a 0.1” (2.54mm) pitched square grid either side of a 0.3” (7.6mm) centre notch.

The open-source Pro-mini board has been immensely popular and there are many versions of PCB layout in circulation. Just three examples are shown below. There are many more.

When attaching headers for breadboard use, various configurations of pin headers placed above or below the PCB are used to bring out (predominantly) the long edge connections for the breadboard, while allowing the others to be accessible by leads.

# Answer
> 1 votes
Fritzing parts only auto-connect if some pins are declared as male. This can be checked by looking at the part's XML file (search for `<connector.*type=`) or by opening the part in the 'new parts editor' (i.e. right-click-\>edit).

Note that it's ok for a part to have heterogeneous connector types. For example, male ones on the long sides and female ones on the short side. Which is what's used commonly with these parts, in reality. This is how for example the M1 Blue Pill or even the Arduino Pro Mini Rev13 (5V) Fritzing parts are defined, which thus auto-connect fine, as expected.

One can only speculate why the Arduino Pro Mini Rev14 (8 MHz/3.3 V and 16 MHz/5 V) parts were defined differently. Might be a bug or a deliberate design choice. However, for being a deliberate choice it would be only consequential to also draw female up-facing headers on the underlying SVG (cf. the Arduino UNO part, where this is done).

---

To work around this, one can edit the part, change all the connector types on the long sides from female to male and save it as new part - say - using the 'new parts editor', directly inside Fritzing. After that change the new part shows up under the 'MINE' parts category.

After that change the part auto-connects to the bread-board. However, the alignment is still broken, thus, for auto-connection one has to disable View-\>'Align to Grid'.

---

So to also fix the alignment some more sophisticated part editing is necessary.

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


title: How to calibrate an accelerometer?

text:
# Question
Title: How to calibrate an accelerometer?
I'm confused about a few points on how to best calibrate an accelerometer, whose data will be used in an orientation sensor fusion algorithm.

As a summary, the most common approaches I've seen take measurements in 6 different orientations (1G in +x, -x, +y, -y, +z, -z), to then arrive at a max, min measured value. Offsets are then calculated as averages: `(max - min)/2`. And then a scaling factor is calculated. There's a few aspects of this that I'm unclear about, and was hoping it's okay to ask in a single question, since they are related.

**1)** the examples calculate the average as written above, rather than `sum all vals / N vals`. Isn't that approach more error-prone?

**2)** should the offset per axis be calculated once for each orientation, and then summed?

**3)** what's the best approach to calculate scale bias?

Example 1 (pseudo-code):

```
chordlengthX = (max - min)/2
chordlengthY = (max - min)/2
chordlengthZ = (max - min)/2

avg_rad = (chordlengthX + chordlengthY + chordlengthZ)/3

scaleX = avg_rad/chordlengthX

calibratedX = (x - offset)*scaleX

```

Example 2:

```
rawrange = max - min
refrange = refmax - refmin // 1G??

calibratedX = (((x - min)*refrange)/rawrange) +refmin

```

Something else altogether (as you can probably tell I need to revise my maths)?

**4)** if my surface is not completely level, I cannot trust my measurements since my 1G reference is not accurate?

# Answer
Most accelerometers are usable out of the box. (It is the magnetometers that are difficult to use w/o calibration.)

That said, example 1 looks good until the last line. You need an x-offset which is simply the difference between the x-maximum and x-minimum.

Consider how the coordinates of the X, Y and Z values of an accelerometer would appear if plotted in 3D space. One that is perfectly aligned would appear spherical. But if one of the sensors is more sensitive than the others, the 3D plot might take on an egg shape. You have corrected for this in the first 5 lines of example 1.

Now, if one of the sensors is not centered the 3D plot would be shifted off the 0,0,0 point of the 3D plot. You can correct for that by finding the x-offset, y-offset and z-offset.

You should not need to find the value for 1G. You should not need to find a perfectly flat surface. To calibrate you need to rotate the accelerometer smoothly about its center. Take care not to expose the accelerometer to greater than 1G during calibration. Rotate the accelerometer in a random fashion until you are satisfied that all 3 sensors have experienced their most negative and most positive values.
> 1 votes

---
Tags: accelerometer, calibration
---


# Question
Title: Why does the official tutorial for LED matrix scanning writes column pin twice?
I was following the official tutorial and confused by the source code.

Arduino Official built-in example: RowColumnScanning

```
// when the row is HIGH and the col is LOW,
// the LED where they meet turns on:
digitalWrite(col[thisCol], thisPixel);
// turn the pixel off:
if (thisPixel == LOW) {
  digitalWrite(col[thisCol], HIGH);
}

```

Here is my understanding:

1. If `thisPixel` is `LOW`, the pin `col[thisCol]` would be `HIGH`.
2. If `thisPixel` is `HIGH`, the pin `col[thisCol]` would still be `HIGH`.

# Question

Because it `col[thisCol]` is always `HIGH` regardless of `thisPixel`, does it make sense to have an extra `if` statement?

# In case the URL is dead

```
/*
  Row-Column Scanning an 8x8 LED matrix with X-Y input

  This example controls an 8x8 LED matrix using two analog inputs.

  This example works for the Lumex LDM-24488NI Matrix. See
  https://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf
  for the pin connections.

  For other LED cathode column matrixes, you should only need to change the pin
  numbers in the row[] and column[] arrays.

  rows are the anodes
  cols are the cathodes
  ---------

  Pin numbers:
  Matrix:
  - digital pins 2 through 13,
  - analog pins 2 through 5 used as digital 16 through 19
  Potentiometers:
  - center pins are attached to analog pins 0 and 1, respectively
  - side pins attached to +5V and ground, respectively

  created 27 May 2009
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/RowColumnScanning
*/

// 2-dimensional array of row pin numbers:
const int row[8] = {
  2, 7, 19, 5, 13, 18, 12, 16
};

// 2-dimensional array of column pin numbers:
const int col[8] = {
  6, 11, 10, 3, 17, 4, 8, 9
};

// 2-dimensional array of pixels:
int pixels[8][8];

// cursor position:
int x = 5;
int y = 5;

void setup() {
  // initialize the I/O pins as outputs iterate over the pins:
  for (int thisPin = 0; thisPin < 8; thisPin++) {
    // initialize the output pins:
    pinMode(col[thisPin], OUTPUT);
    pinMode(row[thisPin], OUTPUT);
    // take the col pins (i.e. the cathodes) high to ensure that the LEDS are off:
    digitalWrite(col[thisPin], HIGH);
  }

  // initialize the pixel matrix:
  for (int x = 0; x < 8; x++) {
    for (int y = 0; y < 8; y++) {
      pixels[x][y] = HIGH;
    }
  }
}

void loop() {
  // read input:
  readSensors();

  // draw the screen:
  refreshScreen();
}

void readSensors() {
  // turn off the last position:
  pixels[x][y] = HIGH;
  // read the sensors for X and Y values:
  x = 7 - map(analogRead(A0), 0, 1023, 0, 7);
  y = map(analogRead(A1), 0, 1023, 0, 7);
  // set the new pixel position low so that the LED will turn on in the next
  // screen refresh:
  pixels[x][y] = LOW;

}

void refreshScreen() {
  // iterate over the rows (anodes):
  for (int thisRow = 0; thisRow < 8; thisRow++) {
    // take the row pin (anode) high:
    digitalWrite(row[thisRow], HIGH);
    // iterate over the cols (cathodes):
    for (int thisCol = 0; thisCol < 8; thisCol++) {
      // get the state of the current pixel;
      int thisPixel = pixels[thisRow][thisCol];
      // when the row is HIGH and the col is LOW,
      // the LED where they meet turns on:
      digitalWrite(col[thisCol], thisPixel);
      // turn the pixel off:
      if (thisPixel == LOW) {
        digitalWrite(col[thisCol], HIGH);
      }
    }
    // take the row pin low to turn off the whole row:
    digitalWrite(row[thisRow], LOW);
  }
}

```

# Answer
> 3 votes
You are right, the `if` does not make sense. Not all tutorials are correct, and even if, they are often not very good.

The reason for the second `digitalWrite()` is to switch the pixel off after it was potentially on. If it stays on when the row is changed, you could see ghosting.

However, I would switch all pixel of a row, delay a bit, and then **in a second loop**, switch them all off again, before I process the next row.

# Answer
> 1 votes
I'm going to split this answer into two parts, the first about matrix displays in general, and the latter considering this particular dubious example.

The fundamental idea of a matrix display is that the LEDs don't need to be on continuously. If they are illuminated sufficiently often and for a sufficient proportion of the time, then the human eye will average things out.

Exactly what "sufficiently often", and a "sufficient proportion" of the time are can be hard to pin down. The former depends on the particular person viewing, but I would aim for at least 100Hz. The latter depends mostly on how bright your LEDs are when turned on (more on that later).

This is useful because it saves you a lot of IO lines, if you wanted individual control of 256 LEDs you would need 256 IO lines. By using a row/column matrix you only need 16. Of course with a row/colum matrix, it isn't possible to illuminate all combinations of LEDs at the same time, but that doesn't actually matter because as long as you illuminate each active LED sufficiently often the human eye won't notice the difference.

It's good practice to turn off the LEDs that you have turned on for one row before moving on to the next row. Otherwise you can get "ghosting" where an unintended LED illuminates. How much of a problem ghosting is in practice depends heavily on the specifics of your matrix drive code.

---

Several things however set this example apart from a "Normal" matrix drive implementation.

* This example only lights a single LED at a time. Most matrix drive implementations light a whole row (or column) at a time. That means the LEDs are illuminated a much greater proportion of the time, it does have downsides though, it means your row drivers have to have enough current drive capacity to drive a whole row at once.
* This example has no series resistors! the current through the LEDs is limited only by the internal resistance of the LEDs and the IO pin drivers in the AVR. This likely results at the LEDs and the GPIO pins operating significantly above their nominal max current!
* There is nothing to control the timing in the code, and the LED on time is very short. Depending on how well the compiler optimizes the code, it may only be a few clock cycles.

Some of these factors cancel each other out, the drive current is likely very high, but it's only applied very briefly and only to one LED at a time. So the overall result is likely that nothing gets fried and the display has a usable brightness.

But nevertheless, I think it's the sort of example that gets Arduino a bad name. It presumably works (or it wouldn't have been posted), but it's driving components out of specification, and the brightness of the display is totally at the mercy of poorly specified internal resistances and code execution speed.

---
Tags: led, led-matrix
---


title: Arduino HX711 load cell lots of drift

text:
# Question
Title: Arduino HX711 load cell lots of drift
I am trying to make this 50kg load cell work with this HX711 chip. I currently have the following connections :

* Load cell red -\> E+
* Load cell black -\> E-
* Load cell white -\> A-
* Load cell green -\> A+

I am using this library and this code :

```
#include "HX711.h"

#define calibration_factor -7050

HX711 scale;

void setup()
{
  Serial.begin(9600);
  scale.begin(2, 3);
  scale.set_scale(calibration_factor);
  scale.tare();
}

void loop()
{
  Serial.println(scale.get_units(1));
  delay(100);
}

```

The load cell appears to register load changes but the value is constantly going up (or down if the calibration\_factor is positive). The value change rate is very high (from 0 to 300 in a couple of seconds).

Edit : I have 2 load cells and both of them do the same thing (with different HX711 chips).

Edit 2 : My question is : has anyone experienced this ? Or does anyone have an idea as to why this is happening ?

# Answer
The solution was to solder all the wires, now the drift seems to be very minimal or non existant.
> 1 votes

---
Tags: arduino-uno, sensors, library
---


# Question
Title: Are resistors necessary for 8x8 LED matrix?
I was following the official tutorial of LED matrix integration and couldn't figure out why there is no resistor.

I assumed there are built-in resistors in the LED matrix, so I did an experiment by connecting pin 9 of the LED matrix to v5 of my Arduino Leonardo board and pin 13 of the LED matrix to GND of the same board. You can refer to the schematic diagram below to know I was trying to lit up the LED at the position \[0, 0\].

Unfortunately, the LED next to \[0, 0\] burned immediately and I still couldn't figured out it.

# Question

1. Are resistors necessary for 8x8 LED matrix?
    1. If yes, why the official example doesn't have any resistor?
    2. If no, why my experiment failed?
    3. If no, why are there so many unofficial examples use resistors for each wire?

# Source

https://docs.arduino.cc/built-in-examples/display/RowColumnScanning

# Circuit

# Schematic

# Answer
> 3 votes
Well done Arduino, you did a great job providing a magic-smoke tutorial \[sarkasm off\]. IDK how this tutorial could make it into their official docs, it should not be there!

You definitely need series resistors at each column or at each row to protect the LEDs/GPIOs (that's 8 resistors). There may be matrices that integrate resistors, but your one and the one they use in their docs does not.

An alternative is to configure the column GPIOs as inputs with enabled pullups and the row GPIOs as ordinary outputs. This way, current will be limited by the pullup resistors. But as those are quite large (several 10kOhm depending on MCU) the LEDs will be very dim.

---
Tags: led, led-matrix
---


title: High frequency sampling with Arduino

text:
# Question
Title: High frequency sampling with Arduino
I need to sample signals up to about 200 kHz using the Arduino as a kind of oscilloscope. I have already seen that by itself it is unable to do it, since the sample frequency is about 9.6 kHz. But would it be possible to connect it with an external ADC?

Thanks.

# Answer
> 1 votes
The rule of thumb for scopes is about 5X the frequency. 2X will give you some information but a lot will be missing. What is the voltage range of the input signals? How many bits of accuracy do you need. How about probes? Then there is memory.

You cannot access the internal memory of the Arduino so it will have to be external and dual ported. Dual ported indicates two different sources can access it. How are you going to refresh the memory if dynamic? Static would work but is more expensive.

I would highly recommend you purchase your scope unless this is a learning experience. You can get some very inexpensive scopes for under $100 or even a used one. I think these would work much better then anything you can build for for the same cost.

Many scopes have a interface to external devices can access them, this may be just what you need?

---
Tags: arduino-uno
---


# Question
Title: How can I connect an ESP8266-01 to a shift register?
I am connecting this shift register to my ESP8266-01 for more GPIO options.

It appears there is a GPIO 16, but it's tied to a RESET pin.

I checked both datasheets, the ESP8266 datasheet, and I also checked the datasheet for the shift register for more information on what kinds of pins can be hooked to each of the input pins.

I am also thinking whether it's viable to connect one of the other available pins of the ESP8266 and use it for this connection with the shift register (either RX or TX).

My understanding is that I need to connect three pins of the ESP8266 directly to the shift register for its latch, clock, and serial pin.

I am also wondering if I can connect the serial pin of the ESP8266 to the serial pin of the shift register?

# Answer
You have several options. Your drawing shows a 74HC595 which is a serial in parallel output. You need a minimum of two pins to operate it, one for clock and another for data. Adding a third for reset will make it much easier to use. You can use any GPIO pins you like but be cognisant of any other uses those pins may be performing in your system such as boot etc.

The part also has SPI, this will directly interface to the shift register. You can cascade them to as many deep as you want. The SPI operates concurrently input and output at the same time. You actually have to send something to get something, that is what cycles the clock. There technically is no limit to the number of devices but there are practical limitations. Since the data transfer is only one way on a pin you can easily buffer it. This generally is one of the fastest I/O you can get.

The second which only requires is I2C which is a synchronous buss that directly addresses the peripheral devices. Originally it had 7 address bits giving you 127 seperate devices you can access. Each device can have as many individual locations/registers as it needs but normally only one address. A lot of chips have this built in and have a preassigned address or address range. For example there are FRAM chips that are 32K x 8 bits at a single address.

There are a lot more options available but I mentioned these because modules that implement these functions are inexpensive and readily available. You can look up "SPI" and "I2" to get a lot more information. Good luck and enjoy your project.
> 1 votes

---
Tags: esp8266, shift-register
---


# Question
Title: Limit on connector cable for HC-SR04 ultrasonic sensor
Is there a limit for the connector distance between an arduino and a HC-SR04 ultrasonic sensor?

I have a set-up for measuring a liquid's level in a tank. The benchtop version worked OK, but when I deployed it, I introduced a 10meter cat5 cable connecting the HC-SR04 to the arduino, it is giving me strange distance readings (they are showing the same distance, even though the level has changed significantly).

The 10m of cat5 is the only element that has changed from the benchtop tests.

Is this length of cat5 a potential problem? If so how can I diagnose it? I have a multimeter and basic oscilloscope?

Update: I measured 4.77v across the sensor's 5v/GND on the breadboard with arduino and 4.65v on the sensor itself.

# Answer
> 2 votes
Cat 5.e cable is specially designed to carry on differential (or balanced) signals (that is why it consists of four twisted pairs - each pair is like tunnel for signal)

On the other hand, the ultrasonic sensor utilizes non-balanced, non-differential signal of high frequency, so, the valid length of cable, that couldn't destroy the data in the signal accuracy is about 0.3-0.5 meter only.

You can check my words by comparing a plots of the signal (on controller input pin) with 10cm and 10m cables.

The digital signal must have nice, square form like this:

But the signal, which is passed through long line of wire can be look like this:

And this is bad, because now the controller could not interpret this signal shape correctly.

---
Tags: communication, hc-sr04
---


# Question
Title: How to install the application + its configuration to many devices of the same kind? (ESP32)
Being the newbie in the Arduino area... Having more devices, how can I upload some configuration parameters *after* the code was uploaded? Is it possible?

**Situation:** I have the simple application for ESP32 with a simple sensor. It is to be used on many physical locations. Each location has its own Wi-Fi with its own SSID and password. An IT person on the location should be able to set the configuration parameters *somehow*. I would like to learn the possibilities -- to choose what is more suitable.

**Separate compilation and upload:** If I understand correctly, I can use the `arduino-cli compile ...` to compile the sketch to binary, and then `arduino-cli upload ...` to put the binary into the device. This way, I am able to prepare many devices with exactly the same binary content. (If I understand it correctly, then `arduino-cli config ...` is for setting the development environment, not for configuring the application on the board.)

**Configuration:** I have noticed the existence of *Arduino Preferences Library* (`Preferences.h`). I understand how to use it from inside the code of the application. Can the wanted preferences be uploaded to the board similarly as the sketch is? (I guess no, but asking to be sure.)

I have also noticed the existence of a *lightweight file system* (`SPIFFS`), and the ability to create (say) `/config.json` on the device from inside the application code. There is the plug-in to Arduino IDE to appear as a new tool (`.../tool/esp32fs.jar`). Then the `data/` subdirectory is created in the sketch directory, and its content can be uploaded by another IDE command. That seems to be nice way to upload the configuration in my case; however, ...

Is there any **command-line alternative to upload the configuration data** that way? Can a single file be uploaded, or is it necessary to erase whole file system area, and upload whole content of the `data/` like directory?

# Answer
> 3 votes
If you don't want to include the individual config data in the sketch for each location there are mainly two possibilities to handle that:

* As consumer IOT devices often do you can write your code to create a hotspot with a website, where the IT staff can then connect to and config the device by inputting the config data into the website.
* You can use SPIFFS/LittleFS (The second is the successor of the first) to create a config file, which you then can read at the start of your sketch. This file system is saved in flash and can be written with an extra tool.

I would go for the second option. I'm currently still using SPIFFS, so I don't know if the following will be different for LittleFS. Your paths might vary (depending on core/version/OS).

1. First create your data directory, where you then place your config.json file. The standard is a directory named "data" inside the sketch folder.
2. Then you need to invoke `mkspiffs` to create a binary image for your data folder. I'm doing it like this:

```
 ~/.arduino15/packages/esp32/tools/mkspiffs/0.2.3/mkspiffs -c ./data -d 5 -b 4096 -s 0x170000 -p 256 ${file_path}/spiffs_image.bin

```

`{file_path}` is the path of the sketch folder for me. That way the image is placed directly besides the sketch. The options mean the following (I will also paste the help page of the command below):

```
 -d 5  -->  Debug Level at max (goes from 0 to 5)
 -b 4096  --> block size in bytes
 -s 0x170000  -->  image size in bytes
 -p 256       -->  page size in bytes
 -c ./data    -->  data directory

```

You can get these information when you look at the verbose output in the Arduino IDE while uploading the filesystem over the tool. They depend on your board and the settings that you use (mostly the partition scheme).

* Then you can upload the image file via the `esptool.py`:

```
  ~/.arduino15/packages/esp8266/tools/python3/3.7.2-post1/python3 ~/.arduino15/packages/esp32/hardware/esp32/1.0.5/tools/esptool.py --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash 0x290000 ${file_path}/spiffs_image.bin

```

`0x290000` is the position in flash, where the data should be written. This also depends on your partition scheme and it should also appear in the Arduino IDE output, where you can copy it from. Note, that I'm invoking the python version here, that comes with the ESP32 core.

This works great for my ESP32 board (using the Wemos LOLIN32 with the "Standard" Partition scheme). Now you will have to think of a fitting workflow. You can have individual data directories and images for each location. Or you can change the file everytime you invoke the commands above (you can even do this in a script).

---

Here the help output of `mkspiffs`:

```
~/.arduino15/packages/esp32/tools/mkspiffs/0.2.3/mkspiffs --help

USAGE:

   /home/christian/.arduino15/packages/esp32/tools/mkspiffs/0.2.3/mkspiffs
                                        {-c <pack_dir>|-u <dest_dir>|-l|-i}
                                        [-d <0-5>] [-a] [-b <number>] [-p
                                        <number>] [-s <number>] [--]
                                        [--version] [-h] <image_file>

Where:

   -c <pack_dir>,  --create <pack_dir>
     (OR required)  create spiffs image from a directory
         -- OR --
   -u <dest_dir>,  --unpack <dest_dir>
     (OR required)  unpack spiffs image to a directory
         -- OR --
   -l,  --list
     (OR required)  list files in spiffs image
         -- OR --
   -i,  --visualize
     (OR required)  visualize spiffs image

   -d <0-5>,  --debug <0-5>
     Debug level. 0 means no debug output.

   -a,  --all-files
     when creating an image, include files which are normally ignored;
     currently only applies to '.DS_Store' files and '.git' directories

   -b <number>,  --block <number>
     fs block size, in bytes

   -p <number>,  --page <number>
     fs page size, in bytes

   -s <number>,  --size <number>
     fs image size, in bytes

   --,  --ignore_rest
     Ignores the rest of the labeled arguments following this flag.

   --version
     Displays version information and exits.

   -h,  --help
     Displays usage information and exits.

   <image_file>
     (required)  spiffs image file

```

And for the `esptool.py`:

```
~/.arduino15/packages/esp8266/tools/python3/3.7.2-post1/python3 ~/.arduino15/packages/esp32/hardware/esp32/1.0.5/tools/esptool.py --help
usage: esptool [-h] [--chip {auto,esp8266,esp32,esp32s2beta}] [--port PORT]
               [--baud BAUD]
               [--before {default_reset,no_reset,no_reset_no_sync}]
               [--after {hard_reset,soft_reset,no_reset}] [--no-stub]
               [--trace] [--override-vddsdio [{1.8V,1.9V,OFF}]]
               [--connect-attempts CONNECT_ATTEMPTS]
               {load_ram,dump_mem,read_mem,write_mem,write_flash,run,image_info,make_image,elf2image,read_mac,chip_id,flash_id,read_flash_status,write_flash_status,read_flash,verify_flash,erase_flash,erase_region,version,get_security_info}
               ...

esptool.py v2.9-dev - ESP8266 ROM Bootloader Utility

positional arguments:
  {load_ram,dump_mem,read_mem,write_mem,write_flash,run,image_info,make_image,elf2image,read_mac,chip_id,flash_id,read_flash_status,write_flash_status,read_flash,verify_flash,erase_flash,erase_region,version,get_security_info}
                        Run esptool {command} -h for additional help
    load_ram            Download an image to RAM and execute
    dump_mem            Dump arbitrary memory to disk
    read_mem            Read arbitrary memory location
    write_mem           Read-modify-write to arbitrary memory location
    write_flash         Write a binary blob to flash
    run                 Run application code in flash
    image_info          Dump headers from an application image
    make_image          Create an application image from binary files
    elf2image           Create an application image from ELF file
    read_mac            Read MAC address from OTP ROM
    chip_id             Read Chip ID from OTP ROM
    flash_id            Read SPI flash manufacturer and device ID
    read_flash_status   Read SPI flash status register
    write_flash_status  Write SPI flash status register
    read_flash          Read SPI flash content
    verify_flash        Verify a binary blob against flash
    erase_flash         Perform Chip Erase on SPI flash
    erase_region        Erase a region of the flash
    version             Print esptool version
    get_security_info   Get some security-related data

optional arguments:
  -h, --help            show this help message and exit
  --chip {auto,esp8266,esp32,esp32s2beta}, -c {auto,esp8266,esp32,esp32s2beta}
                        Target chip type
  --port PORT, -p PORT  Serial port device
  --baud BAUD, -b BAUD  Serial port baud rate used when flashing/reading
  --before {default_reset,no_reset,no_reset_no_sync}
                        What to do before connecting to the chip
  --after {hard_reset,soft_reset,no_reset}, -a {hard_reset,soft_reset,no_reset}
                        What to do after esptool.py is finished
  --no-stub             Disable launching the flasher stub, only talk to ROM
                        bootloader. Some features will not be available.
  --trace, -t           Enable trace-level output of esptool.py interactions.
  --override-vddsdio [{1.8V,1.9V,OFF}]
                        Override ESP32 VDDSDIO internal voltage regulator (use
                        with care)
  --connect-attempts CONNECT_ATTEMPTS
                        Number of attempts to connect, negative or 0 for
                        infinite. Default: 7.

```

# Answer
> 1 votes
I usually use BLE to set the WiFi credentials.

After the WiFi connection is taken care of, I usually provision the rest of the configuration data by having a web application in the LAN that I put into "pairing" mode with the MAC address of the ESP. The ESP then downloads the config from the web application. Although I don't have super secret config data, for good measure the application ends the pairing mode after one download and will not serve further config requests.

---
Tags: c++, esp32, compile, upload, spiffs
---


# Question
Title: My ESP32 WROOM clone will not register touch sensor when using a 5v power bank with usb cable
I have a very simple touch sensor program that works fine and lights an led to show the sensor works; while hooked up to the computer via usb cable it works fine. When using a power bank with the same usb cable the board lights up but does not read the touch sensor. I have tried other cables with the same result.

# Answer
This is hard to explain but your problem in not unique. I hope this helps. It is your ground reference. When connected to the computer which is grounded either/or a ground wire or capacitive coupling to earth. Your body is capacitively connected to ground that way and when you touch the switch it is recognized. To make it work with the battery pack you need to couple to the person touching it. You can do that capacitively by adding a ground plain to your circuit. This can be a conductive plate that will capacitively couple the ground to the atmosphere or any other practical means.
> 1 votes

---
Tags: esp32, battery
---


# Question
Title: How to convert serialized JSON string back to JSON object?
How to convert JSON String for example

```
{"f0":100,"f1":100,"f2":100}

```

It is what I get from my esp01 side from I2C communication

Now I want it to get it back to my Arduino side variables `int f0 ,int f1 ,int f2`

But example shown in web site uses kind of different serialized JSON

Example shown,

`char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";`

Can I convert the data I got from I2C communication for using in the method for `deserializeJson(jsonobj, stringofdata)`

I2C communication side of arduino looks like,

```
void receiveEvent(size_t howMany) {
  String datain = "";
  while (0 < Wire.available()) {
    char c = Wire.read();
    datain += c;
  }
  Serial.println(datain);
//be careful can't send too much json data I2C crash!
  Serial.println(datain.length());
  DynamicJsonDocument datajson(100);
  if (deserializeJson(datajson, datain)) {
    Serial.print("deserialization ok ");
    digitalWrite(13, HIGH);
    delay(250);
    digitalWrite(13, LOW);
    f0 = datajson["f0"];
    f1 = datajson["f1"];
    f2 = datajson["f2"];

    Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
  }

}

```

In serial monitor I only see this no deserialization worked

```
{"f0":0,"f1":0,"f2":0}
22

```

# Answer
The mistake I did was thinking `deserializeJson(datajson, datain)` gives a Boolean as `true` for correct deserialization but accually it gives an object of `DeserializationError err` so need to check if there is no error thus

The new code

```
// need ! here
  if (!deserializeJson(datajson, datain)) {
    Serial.println("yay it worked");
    Serial.print("deserialization ok ");
    digitalWrite(13, HIGH);
    delay(250);
    digitalWrite(13, LOW);
    f0 = datajson["f0"];
    f1 = datajson["f1"];
    f2 = datajson["f2"];

    Serial.print(f0);
    Serial.print(" ");
    Serial.print(f1);
    Serial.print(" ");
    Serial.println(f2);

//also tested this way and it works too
    Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
  } else {
    // I was coding here thinking its Boolean before
    //error
  }

```
> 2 votes

---
Tags: arduino-uno, json, convert
---


# Question
Title: How to detect ESP32 vs ESP8266 automatically when uploading the application?
I have the same application for both ESP32 and ESP8266 (the same functionality). The person, who is not an IT expert is expected to launch the dedicated installer program to upload the (first/new) version of the application. How can the installer (the program) detect what version of hardware is connected through USB? The goal is to upload the correct variant of he application. Is it possible at all?

# Answer
> 3 votes
You can attempt to get the "chip ID" from the target board using `esptool.py`. The ESP8266 has a chip ID, but the ESP32 doesn't.

Running `esptool.py --port <serial port> chip_id` will either tell you, amongst other things:

```
Detecting chip type... ESP8266
Chip is ESP8266EX
....
Chip ID: 0x00a70414

```

Or:

```
Detecting chip type... ESP32
Chip is ESP32-PICO-D4 (revision 1)
...
Warning: ESP32 has no Chip ID. Reading MAC instead.

```

You can do similar with the `read_mac` command. In fact any operation on `esptool.py` that interacts with the target first probes the target to find out what the target is and report it - commands like `chip_id` and `read_mac` are just nice simple examples that return minimal information and don't interact with the target more than just querying the chip.

---
Tags: esp8266, esp32, uploading
---


# Question
Title: ESP32 SerialBluetooth disconnects within a second after connecting but not BLEDevice/BLEServer
Code using BluetoothSerial api disconnects immediately after establishing connection with my laptop running Ubuntu 18.04. If instead of BluetoothSerial BLEDevice api is used, the connection stays connected. See minimal examples below. Another peculiar observation is that connection with my Android phone is stable when running BluetoothSerial example below.

How to make BT connect properly with both the phone and laptop? The chip running the code is esp32-wroom-32d.

Minimal code with BT disconnecting from laptop Ubuntu 18.04 after roughly a second (from SerialToSerialBT example):

```
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup() {
  SerialBT.begin("ESP32 SerialBT");
}

void loop() {
}

```

Minimal code with stable BT connection (from BLE\_notify example):

```
#include <BLEDevice.h>
#include <BLEServer.h>

BLEServer* pServer = NULL;

void setup() {
  BLEDevice::init("ESP32");

  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new BLEServerCallbacks());

  BLEDevice::startAdvertising();
}

void loop() {
}

```

UPDATE:

* Updating Ubuntu to 20.04 did not help.

# Answer
I know this is old but I had the same issue using bluetoothserial.h. But by using rfcomm

```
rfcomm bind 0 <bluetooth MAC ADDRESS>

```

and then my example command sent to serialBT

```
echo -ne ">LOOOCR" > /dev/rfcomm0

```

/dev/rfcomm0 being the device created with the bind. It even still shows as disconnected in the Ubunutu 20.04 bluetooth GUI. For what it's worth I think it is the same on all devices. Until you connect to the BT serial port it is only Paired. But someone with greater knowledge than myself can explain.
> 1 votes

---
Tags: arduino-ide, bluetooth, esp32
---


# Question
Title: Connecting ACS 712 30A to my Solar Panel with Arduino
I am trying to connect my Solar Panel (array of 2 x 265Wp 24v panels connected in series) to my Arduino UNO R3/Nano so that I can make a current/voltage measurement system that can be connected to the internet for remote data access.

I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps. I can relate the ACS712 to a simple ammeter which is connected in series of the load where a shunt resistance is used between the two connecting ends of the ammeter.

The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Can anyone help me with a suggestion or better with a diagram showing the suggested system.

# Answer
> I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps.

Easily. It's designed for mains voltages up to 30A. You're using a fraction of that. You could even use the 20A version to get more accuracy and resolution.

> The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Why is that confusing? If you're monitoring the feed between the solar panel and the charge controller what comes out of that system at the other end is of no concern. Just because you are drawing a larger current from the output doesn't mean that the solar panels are providing that current - that comes from the batteries. Now if you were monitoring the current to/from the batteries that would be a different matter. You'd need to calculate the peak current that your house would draw at mains voltage then convert that to the current at the battery voltage (converting to watts in between is a good step. Note that Wh is meaningless when you want a peak value - Wh is a total power over a period of time \["area under a curve"\], but you don't care about time, only peak \["maximum value of curve"\]).
> 1 votes

# Answer
I know what you mean. It can read it, but sure the terminals and the power going though it are tiny and therefore have to take a current at the terminals.

Try a ASC758LCB-100U-PFF-T.

You say your 60V 5 Amps. therefore for I will say "yes" this is 300 watts There are two terminals per side for the connection 1-2 and 3-4.. I would Solder Join them to enure it can hold the current. Im looking at this issue and I have made the suggestion above on what you could use as a alternative. it has been used for more powerful systems, in a 30 amp MPPT charge controller.

The area of each terminal is 0.51x0.25x1.27 (0.6477mm2) AWG puts it as a 1.8 amp current area or AWG 19

At worst case, the chip legs will be like a fuse and it will just "pop". so dont go to the fuse box first. they are also internally fused.
> 0 votes

---
Tags: arduino-uno, current, solar, voltage
---


# Question
Title: Is it possible to use mathematical sets and their operations in arduino?
In python there is the object set that resembles a mathematical set, namely, you can remove elements from it, add elements to it, you can calculate the intersection/union between two sets, etc.

Is there a library or built-in functions that have those capabilities? I have been unlucky because when I use the word "set" as query term for the engine search, it always sends me to something related to the verb to set.

# Answer
The Standard Template Library (STL) can be installed on the Arduino. It is not there by default. That includes things like sets.

One implementation is here.
> 5 votes

---
Tags: library, mathematics
---


# Question
Title: Is possible to use heap_trace_init_standalone() on arduino framework with esp32?
I need to trace memory leak but I can't find a way. on IDF you can use heap\_trace\_init\_standalone but there is not present on arduino framework.

# Answer
> 1 votes
If you add `#include <esp_heap_trace.h>` (and define `CONFIG_HEAP_TRACING`) at the top of your sketch, the method should be available.

It is defined in `esp32\tools\sdk\esp32\include\heap\include\esp_heap_trace.h`

---
Tags: esp32
---


# Question
Title: Is there any standard for colors of Serial Peripheral Interface wires?
Having DuPont cables like on the picture...

... and the RFID RC522 reader with colored wires as found in one of the tutorials.

I know that copper is the same inside of the wires. Anyway, **is there any standard or de-facto standard of assigning colors to the meaning of the pins?** Black for ground and red for +voltage are known from elsewhere. But what about all the other pins? Here is the detail view for better readability:

# Answer
> 7 votes
No, there is no standard. However:

* Red is often +5V
* Black is often GND
* I often assign colours numerically according to the resistor colour code:
    + 0 - Black
    + 1 - Brown
    + 2 - Red
    + 3 - Orange
    + 4 - Yellow
    + 5 - Green
    + 6 - Blue
    + 7 - Purple
    + 8 - Grey
    + 9 - White

You may have noticed that that's the same order they appear in the cable too, which is helpful. It's handy when working with things like 8 bit data buses, since you can then easily identify which wire is which.

In some disciplines there are standards, like for audio ***r**ed is **r**ight and left is white* (that's the little rhyme I use to remember), and of course there's regulations defining colours for mains cables, but for this kind of thing just use whatever makes sense to you.

---
Tags: spi
---


title: Does the SIM800L works in the US?

text:
# Question
Title: Does the SIM800L works in the US?
I want to know if the SIM800L works on US soil? I can´t get it to work on the H2O network! Does it work wit ATT or I only need the APN settings? If so what are the commands for data connection and configuration? Does the SIM800C works then?

# Answer
I wanted to post an update in April 2021 on the status of this question.

The SIM800L will work in the US, but T-Mobile is the only carrier that it can interface with. AT&T shut down its compatible towers in 2017. T-mobile will shut down its 2G network at the end of 2022.

So, the SIM800L is only good for another year and a half. Maybe you're better off finding a different module!
> 3 votes

# Answer
Both SIM800C and SIM800L (you mention both modules in your question) are compatible with the US GSM networks. It is not possible for me to tell if H2O or AT&T have GSM coverage whereever you are trying to use the module. AT&T is planning to shut down their GSM network by the end of 2016. If you issue the `AT+COPS=?` command, the module will list all available networks at your location.

Documentation on the commands required to handle voice calls, SMS or internet connections can be found in the 'SIM800 Series AT Command Manual'.
> 2 votes

# Answer
As far as I know 2G and 3G is still around however ATT and Verizon are not taking on anymore subscribers for 2G and 3G. However you might still could use a 3rd party such as ting.
> 1 votes

---
Tags: arduino-nano, gsm, communication
---


title: Set time() on ESP8266

text:
# Question
Title: Set time() on ESP8266
If I call configTime() on a ESP8266 using ESP8266 Core, then time() gets changed from uptime to unixtime. However this sends a SNTP request. I have a DS3231 RTC attached without internet. How can I set time() without calling configTime()?

Thanks in advance

# Answer
> 4 votes
Whenever you have `epoch` time, either from RTC, NTP, etc., use the POSIX function settimeofday() to set system time as @Majenko said

The sample code is as follows:

```
// Assuming we already have Unix `epoch` time, which is time from Jan 1 1970.
// From RTC, NTP, etc.
time_t epoch_t = epoch;

// set the time to UTC
setTime(epoch_t);

// set the system time to UTC
timeval tv = { epoch_t, 0 };
settimeofday(&tv, nullptr);

// Now we can have system time by calling time()
time_t timeNowUTC;
struct tm * timeInfo

timeNowUTC = time(nullptr);
timeInfo = localtime(&timeNowUTC);

```

---

For the record, the issue has been solved in Arduino Forum : **Update time() from DS3231**

---
Tags: esp8266, time
---


# Question
Title: esp8266 - server.handleClient() fails to call assigned function
I'm trying to get one esp to send integers to a second as a part of a simple remote control, but after multiple days I can't get it to work. The transmitter seems like it's connecting and sending properly as best I can tell, and the receiver is sending some kind of response, but the function I attached with server.on() never gets called.

The code is basically copy and pasted from a tutorial, the only thing I changed was removing code to display the read data to an LCD and display to serial instead.

This is the receiver's code.

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char *ssid = "controllerReceiver";
const char *password = "password";

ESP8266WebServer server(80);

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

  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();

  server.on("/data/", HTTP_GET, handleSentVar);
  server.begin();
  Serial.println("server online");
}

void loop() {
  server.handleClient();

}

void handleSentVar() {
  Serial.println("Handling");
  if (server.hasArg("x_value")) { // this is the variable sent from the client
    int readingInt = server.arg("x_value").toInt();
    Serial.println(readingInt);
    server.send(200, "text/html", "Data received");
  }

}

```

And here is the transmitter

```
#include <ESP8266WiFi.h>

const char *ssid = "controllerReceiver";
const char *password = "password";

int outputValue = 999;

void setup() {

  Serial.begin(115200);
  delay(10);

  // Explicitly set the ESP8266 to be a WiFi-client
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

}

void loop() {

  char intToPrint[5];
  itoa(outputValue, intToPrint, 10); //integer to string conversion for OLED library

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const char * host = "192.168.4.1";
  const int httpPort = 80;

  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");

    return;
  }

  // We now create a URI for the request. Something like /data/?sensor_reading=123
  String url = "/data/";
  url += "x_value=";
  url += intToPrint;

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");

      client.stop();
      return;
    }
  }

}

```

# Answer
Replace "/data/" with "/data" and `url += "x_value="` with `url += "?x_value="`.

The HTTP GET parameters are separated from the *path* by "?". The `on` function is executed for *a path* ("/data").
> 1 votes

---
Tags: esp8266, wifi, nodemcu, esp8266webserver
---


title: Different time betweenTiny RTC and IDE

text:
# Question
Title: Different time betweenTiny RTC and IDE
I have time late in my Tiny RTC when i try to set time at sketch downloading. Library: RTClib.h

Setup line:

```
if (rtc.lostPower()) {
Serial.println("RTC lost power, lets set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

```

The problem is that my computer displays 15:45 and Serial.print displays 15:12. How can i fix that ?

# Answer
I just removed "if" condition and keep `rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));` Solved!
> 0 votes

---
Tags: rtc
---


# Question
Title: ELEGOO Mega 2560 USB and Vin simultaneously?
I'm powering my Arduino clone with an LM317 circuit that regulates Vin voltage to 10V (measured with a multimeter). While the Arduino is powered by USB only, everything works. When it's powered using Vin, I get odd behavior. I then tried plugging in the USB to see what was happening via the serial monitor and my laptop shut down. I read the Arduino is supposed to handle both USB and Vin simultaneously without shorting out, but now I'm scared to try it again. Is it safe to try again? Any idea what would cause my laptop to shut down, or what I could be doing wrong? Thanks.

# Answer
> 1 votes
It should be fine if you don't have Vin less than 6V6. There is a circut that compares half of Vin against 3V3 "reference" and if it's less, then it enables "ideal diode" switch from Vusb (but it also allows backfeeding) Another way how to bakcfeed usb from the Arduinos 5V is short 3V3 to 5V and having 9V on Vin (eg. less than 10V).

However backfeeding USB port shouldn't be causing restarts. Maybe there are a power supply issues and you've got a big voltage potential difference before connecting it into the USB? You can try to measure it

---
Tags: arduino-mega, power, usb
---


# Question
Title: I need to run 2 for() loops simultaneously but I cant seem to do it without one executing, then the other after it
I'm controlling 2 servo motors but would like to adjust their variables separately, specifically their upper and lower values, and their speeds. This code is one that I had found online then separated, since the original code didn't have adjustable variables for both. I'm using an adafruit servo controller

```
for (uint16_t microsecL = mainServoClosedL; microsecL < mainServoOpenL; microsecL +=5)
for (uint16_t microsecR = mainServoClosedR; microsecR < mainServoOpenR; microsecR -=5) {
        pwm.writeMicroseconds(mainServoL, microsecL);
        pwm.writeMicroseconds(mainServoR, microsecR);
      }

```

# Answer
The answer is simple, but the solution isn't.

The simple part: don't use for loops.

The harder part: you have one `loop()` function which runs repeatedly. For each iteration of that function you make decisions about what to do during that loop and act on them. Decisions like "Is it time to increase this PWM value?" or "Has this value reached the limit I want for it?" etc.
> 2 votes

# Answer
The micro-controller can't do any more than one thing at a time. What it *can* do is do that one thing *way* faster than your servos need it to. So it has (more than) enough time to evaluate each motor's condition and needs and to do it fast enough that you won't notice and they won't be affected by the difference.

The one thing your code *mustn't* do is to wait for a single something to happen, unless that is absolutely the only thing of interest that could possibly happen next. That is seldom the case in the real world, so the controller must check for all possible events of interest, over and over again, to be able to respond to whichever one *does* happen next.

In your code snippet, you increase microsecL and decrease microsecR, but not at any particular rate(s). Your loop code probably needs to look at the execution-time clock (the functions \`millis()' and 'micros()' will read that for you), and when a suitable interval has passed, adjust one or both of those values and do anything else that might need doing, such as stopping a motor when a time has elapsed or it has reached a final position.
> 1 votes

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