title: SPI command versus data?

text:
# Question
Title: SPI command versus data?
I have bough an LCD screen display TFT Touch Screen Board For Arduino UNO R3.

Aand the following commands are given to me for the initialization:

```
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
delay_nms(5);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
delay_nms(10);

write_SPI_commond(0xB0);
write_SPI_data(0x00);

write_SPI_commond(0xB3);
write_SPI_data(0x02);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x10);

write_SPI_commond(0xB4);
write_SPI_data(0x11);//0X10

write_SPI_commond(0xC0);
write_SPI_data(0x13);
write_SPI_data(0x3B);//
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0x00);//NW
write_SPI_data(0x43);

write_SPI_commond(0xC1);
write_SPI_data(0x08);
write_SPI_data(0x15);//CLOCK
write_SPI_data(0x08);
write_SPI_data(0x08);

write_SPI_commond(0xC4);
write_SPI_data(0x15);
write_SPI_data(0x03);
write_SPI_data(0x03);
write_SPI_data(0x01);

write_SPI_commond(0xC6);
write_SPI_data(0x02);

write_SPI_commond(0xC8);
write_SPI_data(0x0c);
write_SPI_data(0x05);
write_SPI_data(0x0A);//0X12
write_SPI_data(0x6B);//0x7D
write_SPI_data(0x04);
write_SPI_data(0x06);//0x08
write_SPI_data(0x15);//0x0A
write_SPI_data(0x10);
write_SPI_data(0x00);
write_SPI_data(0x31);//0x23

write_SPI_data(0x10);
write_SPI_data(0x15);//0x0A
write_SPI_data(0x06);//0x08
write_SPI_data(0x64);//0x74
write_SPI_data(0x0D);//0x0B
write_SPI_data(0x0A);//0x12
write_SPI_data(0x05);//0x08
write_SPI_data(0x0C);//0x06
write_SPI_data(0x31);//0x23
write_SPI_data(0x00);

write_SPI_commond(0x35);
write_SPI_data(0x00);

//write_SPI_commond(0x36);
//write_SPI_data(0x00);

write_SPI_commond(0x0C);
write_SPI_data(0x66);

write_SPI_commond(0x3A);
write_SPI_data(0x66);

write_SPI_commond(0x44);
write_SPI_data(0x00);
write_SPI_data(0x01);

write_SPI_commond(0xD0);
write_SPI_data(0x07);
write_SPI_data(0x07);//VCI1
write_SPI_data(0x14);//VRH 0x1D
write_SPI_data(0xA2);//BT 0x06

write_SPI_commond(0xD1);
write_SPI_data(0x03);
write_SPI_data(0x5A);//VCM  0x5A
write_SPI_data(0x10);//VDV

write_SPI_commond(0xD2);
write_SPI_data(0x03);
write_SPI_data(0x04);//0x24
write_SPI_data(0x04);

write_SPI_commond(0x11);
delay_nms(150);

write_SPI_commond(0x2A);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0x3F);//320

write_SPI_commond(0x2B);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0xDF);//480

//write_SPI_commond(0xB4);
//write_SPI_data(0x00);
delay_nms(100);

write_SPI_commond(0x29);
delay_nms(30);

write_SPI_commond(0x2C);

```

These commands do not look like Arduino commands to me. I have placed them like this

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

void setup()
{
    Serial.begin(9600);
    Serial.println("Test!");

    SPI.begin();

    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    delay_nms(5);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    delay_nms(10);

    write_SPI_commond(0xB0);
    write_SPI_data(0x00);

    write_SPI_commond(0xB3);
    write_SPI_data(0x02);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x10);

    write_SPI_commond(0xB4);
    write_SPI_data(0x11);//0X10

    write_SPI_commond(0xC0);
    write_SPI_data(0x13);
    write_SPI_data(0x3B);//
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0x00);//NW
    write_SPI_data(0x43);

    write_SPI_commond(0xC1);
    write_SPI_data(0x08);
    write_SPI_data(0x15);//CLOCK
    write_SPI_data(0x08);
    write_SPI_data(0x08);

    write_SPI_commond(0xC4);
    write_SPI_data(0x15);
    write_SPI_data(0x03);
    write_SPI_data(0x03);
    write_SPI_data(0x01);

    write_SPI_commond(0xC6);
    write_SPI_data(0x02);

    write_SPI_commond(0xC8);
    write_SPI_data(0x0c);
    write_SPI_data(0x05);
    write_SPI_data(0x0A);//0X12
    write_SPI_data(0x6B);//0x7D
    write_SPI_data(0x04);
    write_SPI_data(0x06);//0x08
    write_SPI_data(0x15);//0x0A
    write_SPI_data(0x10);
    write_SPI_data(0x00);
    write_SPI_data(0x31);//0x23

    write_SPI_data(0x10);
    write_SPI_data(0x15);//0x0A
    write_SPI_data(0x06);//0x08
    write_SPI_data(0x64);//0x74
    write_SPI_data(0x0D);//0x0B
    write_SPI_data(0x0A);//0x12
    write_SPI_data(0x05);//0x08
    write_SPI_data(0x0C);//0x06
    write_SPI_data(0x31);//0x23
    write_SPI_data(0x00);

    write_SPI_commond(0x35);
    write_SPI_data(0x00);

    //write_SPI_commond(0x36);
    //write_SPI_data(0x00);

    write_SPI_commond(0x0C);
    write_SPI_data(0x66);

    write_SPI_commond(0x3A);
    write_SPI_data(0x66);

    write_SPI_commond(0x44);
    write_SPI_data(0x00);
    write_SPI_data(0x01);

    write_SPI_commond(0xD0);
    write_SPI_data(0x07);
    write_SPI_data(0x07);//VCI1
    write_SPI_data(0x14);//VRH 0x1D
    write_SPI_data(0xA2);//BT 0x06

    write_SPI_commond(0xD1);
    write_SPI_data(0x03);
    write_SPI_data(0x5A);//VCM  0x5A
    write_SPI_data(0x10);//VDV

    write_SPI_commond(0xD2);
    write_SPI_data(0x03);
    write_SPI_data(0x04);//0x24
    write_SPI_data(0x04);

    write_SPI_commond(0x11);
    delay_nms(150);

    write_SPI_commond(0x2A);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0x3F);//320

    write_SPI_commond(0x2B);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0xDF);//480

    //write_SPI_commond(0xB4);
    //write_SPI_data(0x00);
    delay_nms(100);

    write_SPI_commond(0x29);
    delay_nms(30);

    write_SPI_commond(0x2C);
}

void loop(void)
{
    delay(1000);
}

```

and I get many errors like

```
error: ‘write_SPI_commond’ was not declared in this scope

```

Even fixing the typo to `write_SPI_command` does not work. I have no problem with using the default `SPI.transfer` of the Arduino library. But, I am wondering how to translate `write_SPI_commond` and `write_SPI_data` into a proper `SPI.transfer`?

# Answer
> 2 votes
The “commands” provided by the vendor are not code meant to be copied as-is. They are pseudocode. If you need to know the real difference between “write command” and “write data”, you have to look at the datasheet of the interface chip.

See for example the ILI9481. On pages 28–29 you can see a data transfer mode compatible with SPI (type C interface, option 3). Here you have to wire one digital output of the Arduino to the D/CX pin on the interface chip. This pin is used to tell whether you are writing a command (pin LOW) or data (pin HIGH).

# Answer
> 2 votes
To answer the question in the title "**SPI command versus data?**":

## TLDR

Some SPI drivers will separate the data sent on the COPI/PICO lines into subsections to make it easier on the programmer.

## SPI command versus data?

I am currently working with the ESP32 myself and have come accross the more generic question of "**What is the difference between command and data when using SPI?**". After some reading around, I have come to the conclusion that certain SPI drivers will allow users to separate the generic data sent in SPI protocal into subsections such as ADDRESS, COMMAND, and ADDITIONAL\_DATA. This is simply to make it easier for the programmer to understand what they are sending.

Not all applications will require the an ADDRESS, COMMAND, and ADDITIONAL\_DATA. For example, some chips will have pre-programmed commands such as this Inclinometer (SCA61T) which then may or may not require ADDRESS and ADDITIONAL\_DATA. But others, such as the MAX7219 (which I am using), only require an ADDRESS and ADDITIONAL\_DATA, no COMMAND.

## Example

Using the ESP32 SPI driver, I played around with setting the length of the command bits and address bits from 0 to some nonzero number as seen in the code snippet below.

```
spi_device_interface_config_t devcfg={
                .command_bits=4,           ///< Default amount of bits in command phase (0-16), used when ``SPI_TRANS_VARIABLE_CMD`` is not used, otherwise ignored.
                .address_bits=4            ///< Default amount of bits in address phase (0-64), used when ``SPI_TRANS_VARIABLE_ADDR`` is not used, otherwise ignored.
}

```

Then I specified the data to be sent in the command and address bits (along with the data to be sent in the tx buffer) as seen in the code below.

```
     char data[1]= {0x97};

            spi_transaction_t spi_trans={
                .cmd={0x05},          ///< Command data, of which the length is set in the ``command_bits`` of spi_device_interface_config_t.
                .addr={0x00},         ///< Address data, of which the length is set in the ``address_bits`` of spi_device_interface_config_t.
                .length=8,            ///< Total data length, in bits
                .rxlength=0,          ///< Total data length received, should be not greater than ``length`` in full-duplex mode (0 defaults this to the value of ``length``).
                .rx_buffer=data,      ///< Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used.
                .tx_buffer=data,      ///< Pointer to transmit buffer, or NULL for no MOSI phase

            };

```

where `spi_trans.cmd = {0x05}` with 4 bits length corresponds to a binary `0101`, `spi_trans.addr = {0x00}` with 4 bits length corresponds to a binary `0000`, and `spi_trans.tx_buffer = {0x97}` with 8 bits length corresponds to a binary `10010111`.

When using an o-scope to measure the chosen COPI and clock pins, we see the following waveform.

We realize the ordering of the data sent over the COPI pin is command, then address, and lastly tx data. This ordering may differ depending on which driver is used (I am using the ESP32 SPI Master driver).

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


title: Space taken by Global Variables

text:
# Question
Title: Space taken by Global Variables
Using Nano's for small programmes I get compilation reports about the amount of space taken by global variables.

On a typical progamme it says something like Sketch uses 16316 bytes (53%) of program storage space. Maximum is 30720 bytes. Global variables use 1798 bytes (87%) of dynamic memory, leaving 250 bytes for local variables. Maximum is 2048 bytes. Low memory available, stability problems may occur.

If I count up the number of bytes taken by the declared global variables it is 126 bytes, depending on how bool's take up memory ( one bit or one byte ).

Can I get the compiler to give me a dump of what it is actually assigning as global variable space to reconcile the difference between 126 bytes and 1798 bytes. Then I could change the programme to get round the memory problem and keep using the Nano's.

Thanks in advance for any useful insights.

Thanks to those who commented for the help.

Checking the memory requirement for the global variables, includes and begins still only used 34% so I realised that something in the main loop was using extra memory. Then the penny dropped, I had print messages left over from tracing problems and these become stored constants when compiled. Moved these to a conditional compile section so they are only compiled during tracing for bugs. Problem solved. Once again thanks for the helpful hints.

# Answer
> 1 votes
RAM is precious on a microcontroller, PROGMEM (program memory) not quite as much so. On the Arduino Uno and the Nano (using an Atmega328P) you have:

* 1 kB of EEPROM
* 2 kB of RAM
* 32 kB of PROGMEM

Clearly, there is a lot more program memory than RAM.

Variables are copied into RAM at program startup

The problem with constants in general (including string constants like "hello") is that the compiler generates code to copy them into RAM at program startup, because most C functions do not expect to find data in PROGMEM. (It has to generate different instructions to access PROGMEM).

# Benchmark memory use

To test memory use, I'll start off with a sketch that simply returns how much memory is free, without doing anything else. Tested on IDE 1.0.6, Arduino Uno, on Ubuntu.

```
#include "memdebug.h"

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("Free memory = "));
  Serial.println (getFreeMemory ());
  }  // end of setup

void loop () { }

```

Output:

```
Free memory = 1702

```

Since we started with 2048 bytes of RAM, already we have used 2048 - 1702 = 346 bytes. These are used as follows:

```
34 bytes for the HardwareSerial instance (Serial)
64 bytes for the Serial transmit buffer
64 bytes for the Serial receive buffer
4 bytes for the Serial transmit buffer head and tail pointers
4 bytes for the Serial receive buffer head and tail pointers
9 bytes for keeping track of millis / micros
4 bytes for memory allocation (__malloc_heap_start, __malloc_margin)
128 bytes for the heap safety margin
6 bytes for a few nested function calls (main -> setup -> getFreeMemory)
16 bytes for the compiler vtable for HardwareSerial
4 bytes for variables __brkval and __flp (used in memdebug)
2 bytes pushed onto the stack in main (to save registers)
2 bytes pushed onto the stack in setup (to save registers)
4 bytes pushed onto the stack in getFreeMemory (to save registers)
1 byte because the stack pointer starts at 0x8FF rather than 0x900

```

(That's 346 bytes accounted for)

# Tips

The stack starts at the highest possible address and grows downwards. Each function call would add 2 bytes to the stack (the return address) plus any local (auto) variables would be allocated there.

The heap safety margin is a buffer between the top of the heap and the bottom of the stack. Without it, if you did a "malloc" and got all available memory, there would be no memory left for function calls and local variables in functions.

The vtable is used by the compiler to generate late bindings for virtual functions used by classes.

The compiler generates code to push registers onto the stack when you call a function (the registers used inside that function) so that if the same register was used by the calling function, it would not be corrupted.

# Printing constants

Let's print a constant by adding this line:

```
  Serial.println ("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo");

```

Output is now:

```
Free memory = 1630
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo

```

So the free RAM has gone down by 72 bytes, which happens to be be how long that string is (allowing one byte for the 0x00 terminator at the end).

Why? Because the string was copied from PROGMEM, where it must be when the Arduino is turned off, into RAM.

The first thing we can do is use the F() macro, which cunningly expands out to print directly from PROGMEM, thus saving RAM. So we change the line above to read:

```
  Serial.println (F("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo"));

```

Output:

```
Free memory = 1702
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo

```

Back to 1702 bytes of free memory. So, lesson #1 is to use the F() macro as illustrated above whenever printing constants.

# More information

I have more information on my page about RAM usage which discusses putting arrays of constants into PROGMEM as well as what I mention above.

---
Tags: arduino-nano, variables, memory
---


# Question
Title: Multiple Arduinos connected to one display
I have one display screen, and 5 Arduino Nanos. They are checking to see if passwords in a text file hash to a specific hash, then display it on the screen when found.

Since they aren't all sending signals to the screen, is it possible to wire it so that all of them are connected to one screen, and then have the one that finds the correct password send the signal to the screen, and how would I go about doing this?

# Answer
> 0 votes
It should be possible to connect all nanos to the display, just like you would if there was only one nano as long as there is only one nano that *actively drives* the bus (what ever bus that is). All the other nanos need their bus pins to be inputs (not configured for the bus). So you could have them being inactive by default and only access the bus once they found a matching hash.

**But**: if multiple nano's are configured for bus usage at a time, communication would be corrupted. In case the display uses a push-pull bus (SPI, UART, ...) this is even electronically an issue, because their bus pins would short the supply voltage and possibly get destroyed. So you need some kind of protection in that case, a current limiting resistor in the easiest form.

As mentioned in comments, the "clean" solution is to have one dedicated controller to be the coordinator.

Some thoughts:

* there is a real (not just a hypothetic) chance for bus contentions, because multiple passwords lead to the same hash and you even want to compare hashes for multiple passwords. The occurence of such a collision needs to be expected, though it is not predictable *when* or *if* it actually happens.
* you probably want to configure the cluster, e.g. to distribute the hash of interest among the Nanos or to stop the cluster when a match is found. Those things would be easier if there's one dedicated master which you can communicate with directly.
* the coordinator would always have control over the display. What if you wanted to continously display information on the screen, e.g. a progress bar? That would be difficult to implement afterwards when there's no master.

---
Tags: arduino-nano, electronics, display
---


# Question
Title: How to pre-design circuit before buying?
I am wanting to make a simple circuit that takes input from a movement sensor and plays a sound response.

To do this I think an ESP32 microcontroler would be optimal?

But how does one go about identifying parts and making sure they are compatible before buying?

For example I have no idea what sensor, speaker or battery sources to use. How does a total noob go about finding all this out in an efficient way?

# Answer
> 3 votes
* Step #1: Steal! Search engines are your friend.
* Step #2: (see step #1).

Look for published projects using parts that you want to use or to find out what parts someone else used, and how they connected them & coded for them.

Look up the datasheets for the parts you propose to use and read at least the introductions, to decide if they meet your needs. If you're project is for learning, not going into a bigger project (yet), you may not need this step if someone else's project has shown you the way. When you eventually come to designing your own, this step will be important.

As a beginner, copying from others is really the best/quickest way to 1) make stuff happen; and 2) not (or be less likely to...) blow up parts that cost money and take time to replace.

Once you've built a couple of projects you'll start to see common techniques of coding and of building circuits, that will lead you to more questions. (See step #1 above).

There's more, like learning some basic electrical and electronic theory and practice, if you haven't already, but that can come a little later and will make more sense when you have some hands-on experience.

---
Tags: hardware
---


# Question
Title: How can I control neopixels attached to a Digispark?
I want to use a string of Neopixels attached to a Digispark hanging off of a RasPi3 as indicators for various situations. For example: a motor (connected to a driver hat on the I2C bus of the RasPi) turns on or reverses direction. Can I use Firmata, or is there something like it for the Digispark that I can use with Python?

# Answer
> 1 votes
You need a dedicated microcontroller since you need very precise timing for controlling the neopixels. It works well on an ATTiny85, we are using Adafruit Trinket boards to control Neopixels and work well. So far up to 12 pixels :)

You can download a Trinket Neopixel library, which is modded for an internal osc ATTiny85 from Adafruit.

Then your Raspi can talk to the microcontroller. It is a little problematic, though, since the software serial port handling consumes too much memory on ATTiny, and the ATTiny will ignore all serial input while refreshing the neopixels. Therefore you may get it easier by using an Arduino UNO, or Leonardo or Micro which is powerful enough for many pixels, and have a built-in hardware serial port.

As a matter of fact, you can talk to these Arduino boards as if it would be a serial port, so just plug in a Leonardo over USB and you'll get a new serial port in Rpi to talk to.

# Answer
> 0 votes
A circuit can be made using two 74HC121s and an OR gate that would be connected to the SPI peripheral in the microcontroller. The timing would be accomplished by the multi-vibrators while each byte would be output through the serial port.

---
Tags: serial, python, neopixel, raspberrypi
---


# Question
Title: Error loading Blink sketch in esp01 (esp8266)
I have the esp01 connected the serial port using a usb to ttl serial cable and also using the Arduino UNO as suggested in some tutorials. I can execute AT commands. But loading a sketch from Arduino IDE results in error messages show below. If anyone can help, it would be greatly appreciated. Note the error message:

> serialport\_receive\_C0: F0 instead of C0

```
Build options changed, rebuilding all

Sketch uses 219,211 bytes (50%) of program storage space. Maximum is 434,160 bytes.     Global variables use 31,416 bytes (38%) of dynamic memory, leaving 50,504 bytes for local variables. Maximum is 81,920 bytes.
      /Users/syedtariq/Library/Arduino15/packages/esp8266/tools/esptool/0.4.8/esptool -vv -cd ck -cb 115200 -cp /dev/cu.usbmodem14221 -ca 0x00000 -cf /var/folders/hx/m49nxmvn0799w816ct3tgsjm0000gp/T/build10f6b721887f9efd16f05460daf22810.tmp/Blink.ino.bin
esptool v0.4.8 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
setting board to ck
setting baudrate from 115200 to 115200
setting port from /dev/tty.usbserial to /dev/cu.usbmodem14221
setting address from 0x00000000 to 0x00000000
espcomm_upload_file
espcomm_upload_mem
opening port /dev/cu.usbmodem14221 at 115200
tcgetattr
tcsetattr
serial open
opening bootloader
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: FF instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

```

# Answer
> 1 votes
The problem is related to the Arduino Uno, seems that you haven’t bypassed the Arduino board (since you need to program the esp you should communicate directly with it). To do this you need to wire the reset pin of Arduino to the ground (also the GPIO1 of esp should be connected to the ground in order to go in programming mode).

---
Tags: esp8266
---


# Question
Title: How many ADS1115 ADCs can I connect to a single Arduino Mega 2560
I know we can connect 4 ADS1115s to an Arduino Mega 2560.

Is there any limit on the number of ADS1115s we can connect to the Mega giving each a different address? I have to connect at least 36 ADS1115s.

# Answer
256(+?)

With 8 TCA9548A 1-to-8 I2C Multiplexers on different I2C addresses, it is a multiplication problem: You can expand the Arduino Mega's I2C port on Digital Pins 20&21 to 8 multiplexers * 8 multiplexer ports * 8 ADS1115 addresses to 256.

It might be possible to go much further if you can wire and code multiple levels of multiplexers.
> 1 votes

---
Tags: arduino-mega, i2c, adc
---


# Question
Title: How can I get an external program to change values inside the Arduino C++ code?
How can I get some constantly changing values from a separate C++ program entered and uploaded into the Arduino?

I notice when I upload code to the Arduino in the IDE it takes about a second to start moving. This is also a problem. I would like there to be no delay after instructions to the motor change.
My goal is to get a trained neural network model from the PyTorch C++ version to control the motor's spin and speed. I would assume the IDE does not allow one to import PyTorch?

I tried looking around on the Arduino website for this, but it seems like the IDE is the only option. My solution would be something that imports the Arduino library into a C++ program just like I import the PyTorch library into my C++ program.

My ficticous C++ code. Just written to illustrate what I would like to happen.

```
import pytorch
import arduino

// if I had an encoder on the motor giving position readings as inputs (I know this isn't how it's done in real code)
sensors = arduino_encoder_sensors

// trained model
m = pytorch.load_torch_model('model')

// model taking sensors as inputs and outputting desired speed and distance executions to the motor
speed, dist = m(sensors)

```

**Arduino Code:**

```
const int stepPin = 8;
const int dirPin = 9;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  for(int x = 0; x < dist; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(speed);
    digitalWrite(stepPin,LOW);
  delay(1000); // One second delay
}

```

# Answer
Your question seems very confused, so I will try to shine a light on some basic distinctions.

> How can I get some constantly changing values from a separate C++ program entered and uploaded into the Arduino?

In your whole question you seem to confuse program and data. The program on the Arduino doesn't need to change with every changing of the values. Instead you would have a constant program, which receives changing values from the PC.

So it seems you want to send data from your python program on your PC to the Arduino. This data doesn't have anything to do with the actual program on the Arduino. The program just should use the data to act accordingly. You can use any of the communication interfaces that are usable with Arduinos and PCs, though the simplest option would be the `Serial` interface, which gets bridged to your PC via the USB port. The `Serial` interface is what you see in the Serial Monitor.

How to use a serial port in python can be googled quite easily. For the Arduino side there are many tutorials and examples about it online. You would also need to think about your communication protocol, which you want to impose on the `Serial` byte stream. For example you could use ASCII encoded text, each message delimited to the next by a newline character `'\n'`, each message containing first the command and then needed parameters. Since only you know what exactly you want to send to the Arduino, you need to design this yourself.

> I notice when I upload code to the Arduino in the IDE it takes about a second to start moving. This is also a problem.

This is due to the bootloader. When you upload a program this is done via the `Serial` interface. Normally microcontrollers can only be programmed over specialized interfaces (like ISP). But Arduinos (and other microcontrollers) can be programmed with a bootloader. That is a program sitting on the microcontroller, which runs anytime you power the microcontroller on your reset it. On Arduinos it will listen on the `Serial` port for a moment in the case that you want to upload a new code. If yes, then it handle the communication and write the new code to the Arduinos flash memory. If not, it will execute whatever program currently is saved in flash.

So you cannot avoid this delay without changing or deleting the bootloader. Deleting it would mean that you need a programmer board to upload new code (another Arduino can do that). Changing it would also require a programmer board, because you would need to write the new bootloader version to the Arduino with it.

I would debate if this delay is really a problem. It only appears on a reset, like when you upload new code. And why would you want to reset the Arduino or upload new codes that fast? For doing your motor movement you don't need new programs on the Arduino for every movement; you need a code that will move according to data send through the `Serial` interface. And that doesn't require resetting. And it works fast.

That said, with your current code (ignoring the obvious syntax problems most likely from copy and past errors) you will still have delays, even when you implement `Serial` communication. In general you shouldn't use long `delay()` calls. You use `delay(1000)`, which makes the Arduino twiddle its thumbs for one whole second each loop iteration. Instead use the non-blocking coding style shown in the `BlinkWithoutDelay` example that comes with the Arduino IDE. It uses the `millis()` function as a clock, checking it regularily for the time to do something. There are many tutorials about that online.

> My goal is to get a trained neural network model from the PyTorch C++ version to control the motor's spin and speed. I would assume the IDE does not allow one to import PyTorch?

No, it doesn't. It is based on Java, not on python. As described above you need to write your own python program and use a fitting serial port python module for the communication over the `Serial` interface. In that python program you can import `PyTorch`, do your neural network processing and then send the resulting commands over `Serial` to the Arduino.

> I tried looking around on the Arduino website for this, but it seems like the IDE is the only option. My solution would be something that imports the Arduino library into a C++ program just like I import the PyTorch library into my C++ program.

It is not really clear what you mean here. For communicating with an Arduino over `Serial` you can use any program that can interface with a serial port on your PC. There are many programs dedicated for this. Since you want to do your neural networking stuff in python, just use a fitting python module that handles serial port connections.

If you talk about writing programs for Arduinos and uploading them: This can be done in many other IDEs other than the Arduino IDE. Dave Newton mentioned some in his comment: VS Code and CLion. I also remember the Atom IDE. Or you can write your code in any text editor of your liking and then compile and upload the code with the Arduino CLI tool (that's what I do mostly).

---

I hope this clears up the confusion a bit so that you now can work toward a working solution.
> 2 votes

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


# Question
Title: FastLED and Adafruit Gemma M0 - Getting started
I just bought a Gemma M0 and I'm trying to use it with FastLED. There are several forums that discuss the same errors I get when I try to upload my code, but they all involve editing .h files, something I'm not comfortable doing without understanding the reason behind the change. Is there a place where I can get a basic starting point for using FastLED with the Gemma M0?

I tried the Quick Example in the FastLED Overview:

```
#include "FastLED.h" CRGB leds[1];

void setup() {
  FastLED.addLeds<NEOPIXEL, 6>(leds, 1); }

void loop() {
  leds[0] = CRGB::White; FastLED.show(); delay(30);
  leds[0] = CRGB::Black; FastLED.show(); delay(30); }

```

and I get these errors:

```
Arduino: 1.8.13 (Mac OS X), Board: "Adafruit Gemma M0, Small (-Os) (standard), Arduino, Off"

In file included from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:14:21: note: #pragma message: FastLED version 3.004.000
   14 | #    pragma message "FastLED version 3.004.000"
      |                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:65,
                 from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastspi.h:135:23: note: #pragma message: No hardware SPI pins defined.  All SPI access will default to bitbanged output
  135 | #      pragma message "No hardware SPI pins defined.  All SPI access will default to bitbanged output"
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:48,
                 from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h: In instantiation of 'class FastPin<6>':
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h:242:29:   required from 'class FastPinBB<6>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/platforms/arm/d21/clockless_arm_d21.h:10:54:   required from 'class ClocklessController<6, 12, 30, 18, GRB, 0, false, 50>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/chipsets.h:578:7:   required from 'class WS2812Controller800Khz<6, GRB>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:92:34:   required from 'class NEOPIXEL<6>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:314:28:   required from 'static CLEDController& CFastLED::addLeds(CRGB*, int, int) [with CHIPSET = NEOPIXEL; unsigned char DATA_PIN = 6]'
/Users/jaireaux/Documents/Arduino/blink/blink.ino:4:60:   required from here
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h:210:24: error: static assertion failed: Invalid pin specified
  210 |  static_assert(validpin(), "Invalid pin specified");
      |                ~~~~~~~~^~
exit status 1
Error compiling for board Adafruit Gemma M0.

```

Thanks in advance for your help.

# Answer
The Gemma does not have a pin 6. `FastLED.addLeds<NEOPIXEL, 6>(leds, 1);` I changed to pin 2 and it works. `FastLED.addLeds<NEOPIXEL, 2>(leds, 1);`
> 1 votes

---
Tags: led, adafruit
---


# Question
Title: How to use d0 and d1 pins of arduino uno (Others) as a digital output when I don't want to use Serial
I have searched this topic almost everywhere also got different results that couldn't satisfy me

My new project is a 4x4 LED cube

Of which

Will contain 4 Rows and each Row will contain 16 LEDs

So, I need to use all the digital pins 0-15 as digital output.

And other pins 16-20 for grounding.

But the problem is, this project needs d0 and d1 pin to be connected as a digital output pin. (Not Serial communication)

In some places I have seen that Experts saying

> 1. If you want to use Serial communication, then you can't use them.

> 2. You can't use it while your arduino is connected to PC.

> 3. You Can't do this ,as this may harm the device

> 4. You must turn off serial connection first.

OK, reading this, I got confused, I don't need to use any serial connection (console and others) in this LED cube project so I tried to turn off serial connection by not writing the code below.

```
Serial.begin(9600);

```

So, will that free those d0 and d1 pins as digital for me ? Or USB connection is also considered as a serial connection?

So, how can I do it? And will doing it really harm my board?

# Answer
> 4 votes
If you don't use the serial port, pins 0 and 1 are regular I/O pins. It's just as simple as that.

> If you want to use Serial communication, then you can't use them.

Correct.

> You can't use it while your arduino is connected to PC.

Wrong. You can keep the USB cable connected as a power supply. You will not be able to use it for communication though.

> You Can't do this, as this may harm the device

What is “this”? The device can be harmed if you drive too much current to/from an I/O pin, irrespective of whether it's a pin that could be used for serial communication.

> You must turn off serial connection first.

Only if you did turn it on before. If you never enable `Serial`, you don't have to do anything more.

# Answer
> 0 votes
The bootloader always turns UART0 on upon the loading of the code to your Arudino Nano. So at the end of the day pins D0 and D1 are used for their alternate functions as a UART receiver and transmitter without you doing so in your code.

Copy the following code to whatever your sketch or C program to disable the UART0 module before you initalize pins d0 and d1 as digital IO, then you can set the two pins as digital I/Os as usual and they will work perfectly.

```
UCSR0B &= ~(1<<3);
UCSR0B &= ~(1<<4);

```

---
Tags: arduino-uno
---


# Question
Title: Arduino fade in/out 5 leds circuit acting wierd
I have a simple arduino project with 5 leds, the project should start with led 1 fade through 50 millisec to reach full brightness, then led 2 and so on until led 5 then turn them all off and loop.

here is an image for the circuit (pardon the messy look my first time):

"all leds cathod are connected" and here is the code :

```
 int led[5]={3,5,6,9,10};
// led pins array (pwm)
void setup() {
  // put your setup code here, to run once:
  for (int i = 0; i < 5; i++){
    pinMode(led[i], OUTPUT);
    }
    // set each pin as an output
}

void loop() {
  for (int i = 0; i < 5; i++){
    int pin = led[i];
    // storing the value of the current pin in a variable
    int j = 0;
    while(j <= 50){
      j++;
      delay(1);
      analogWrite(pin,j*2);
    }
    /* the while loop is used to make the fade effect
    by increasing the duty cycle by 2% each millisec
    over 50 millisec */
  }
  delay(200);

  for (int z = 5; z > -1; z--){
    int pin = led[z];
    analogWrite(pin,0);
    }
    // turning off all leds
    delay(50);
}

```

the problem is as follows : the first round of the loop the circuit acts as expected led 1 on then 2 etc then they all turn off and loops again, on loop 16 led 1 turns off and the loop continues only with leds from 2-5 and on loop 31 led 4 and 5 turns off and only led 2 and 3 keep on going.

Edit 1 : i just found something interesting on arduino's official page (pins supporting pwm 3, 5, 6, 9, 10, 11 ) pwm frequency 490 Hz (pins 5 and 6: 980 Hz) so could the frequency result in this error?

Edit 2 : the issue was resolved with a really wierd change in the code the very first line of code " int led\[5\]={3,5,6,9,10};" i changed the size of the array from 5 to 6 like this " int led\[6\]={3,5,6,9,10};" and the issue was resolved, I discovered this while i was trying to use 4 leds and i forgot to change the size, if anyone could explain how did this change helped solve the problem ?

# Answer
Your problem may be in your count down code. Specifically this loop:

```
for (int z = 5; z > -1; z--){

```

Z starts at 5, and you then try and access element 5 of a 5-element array. That sounds reasonable until you remember arrays are 0-based, so there is no element 5, only elements 0-4.

So you're reading data that you shouldn't be reading. Just reading shouldn't have any effect though, so :shrug:...

Anyway, there's some "best practice" things you should do to improve your code:

1. Use 8-bit values to store your pins (`uint8_t`)
2. Make your pins array `const` so it's never modifyable
3. Replace your `while` loop with a simpler to understand and follow `for` loop
4. Keep your loops as simple count-up and use math to work out which array entry you want.
5. Keep variables to the smallest storage size needed for the values you're working with.

For example (untested):

```
const uint8_t led[5] = { 3,5,6,9,10 };
// led pins array (pwm)

void setup() {
  for (uint8_t i = 0; i < 5; i++) {
    pinMode(led[i], OUTPUT);
  }
}

void loop() {
  for (uint8_t i = 0; i < 5; i++){
    int pin = led[i];
    for (uint8_t j = 0; j < 50; j++) {
      delay(1);
      analogWrite(pin, j * 2);
    }
  }

  delay(200);

  for (int z = 0; z < 5; z++) {
    int pin = led[4 - z];
    analogWrite(pin, 0);
  }

  delay(50);
}

```

Also as noted in the comments you *must* have one resistor *per LED* and *never* connect all the cathodes together like that. The brightness of each LED is determined by the current flowing through it. That current is the current through the resistor, which is determined by the forward volgage of the LEDs. The more LEDs you have on the more that current is split between the LEDs. And different LEDs will have different forward voltages, and the lowest one will "win" affecting the current that the resistor allows. It's all a horrible mess and must be avoided at all costs. The only times you can have just one resistor for multiple LEDs are a) if you have a series chain of LEDs making them in effect just one LED with a higher forward voltage, or b) can absolutely guarantee that one and only one LED will ever be turned on at a time.
> 2 votes

# Answer
Here is the @Majenko code output

The code same as the one posted in the other answer. You can find the simulation link here --\> https://wokwi.com/arduino/projects/318609194610590292

I also hooked up a logic analyser and here is how it looks :) You can look how the Duty cyle is becoming larger afer every cycle.
> 1 votes

---
Tags: arduino-uno, led, pwm, loop, analogwrite
---


# Question
Title: NodeMCU dev board shows 13 for ADC when grounded - why?
I have a NodeMCU 1.0 ESP-12E development board. Trying to hook up a LM35 to measure temperature. For that I need to use the analog pin A0. However it seems my sensor is out by about 4C. I traced this to an offset error - when the board is connected via USB to the PC, and I connect analog pin A0 to analog ground with a jumper on the board, I read 13 from analogRead(A0). I should be getting 0. I confirmed with a voltmeter that A0 is at ground potential. I have nothing else connected to the board. When I feed in 3.3V to A0, I get 1024. When I hook up the LM35 which outputs 210mV, I get a reading of 81 which is 13 off (based on the standard analogValue / 1024 * 3300 calculation).

What am I doing wrong?

# Answer
The input A0 is not actually an ADC input. Instead it's the input to a voltage divider which *then* goes to the ADC input. The ESP8266's ADC is only capable of reading up to about 1.1V, so the makers of the NodeMCU helpfully created a small voltage divider (two resistors) to drop the input voltage to the range the ADC can cope with.

Except it's not perfect.

The resistors used aren't 100% precise, so the actual values you get from the ADC vary slightly from board to board. To get more precise readings you will have to first calibrate your ADC by providing known stable voltages to the ADC and logging the read values. Or you can measure the resistors used on your board and use those in the calculation to determine actually what value is being seen by the ADC.

Or you can use an external ADC that doesn't require the voltage divider circuit to function, which would be my preferred method, since the internal ADC is not great.
> 1 votes

---
Tags: analogread, adc
---


# Question
Title: FastLED: "Invalid pin specified" when specifying LED_TYPE from WS2811 to WS2801
I'm trying to run the "DemoReel 100" code from FastLED.

Out of the box, it can be verified. But when I switch from `#define LED_TYPE WS2811` to `#define LED_TYPE WS2801`, I get the error:

> error: static assertion failed: Invalid pin specified static\_assert(validpin(), "Invalid pin specified");

the line this error originates from is:

```
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

```

I can't think of any reason that the LED\_TYPE argument should change whether or not a data-pin is valid. What's going on?

# Answer
> 1 votes
I figured it out. There's two lines for `FastLED.addLeds`, and one needed to be commented out and the other enabled in order have a clock pin work.

```
//  FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

```

---
Tags: led
---


# Question
Title: Brushless Motor "twitches" on its own when connected to battery
I've been trying to make a Bluetooth slider app that can control the spin speed of a brushless motor. The transmitter I am using is Arduino Mega. **The problem I'm having is that my motor will start twitching at very random times even though my Arduino code specifies `ESC.write(0)`**, meaning the ESC should remain completely still.

Furthermore, I've noticed that the twitching begins the exact moment I connect my HM10 Bluetooth module to the Arduino. The motor is still able to be controlled by the slider on my app, however, even when the slider is set at zero, the motor turns on its own! I will attach a video to the problem in this link.

A couple of things I've noticed that may be of interest: when the ESC bullet connectors touch each other, there are audible sparks as well as burn holes.

Here is my arduino code

```

/*
   -- New project --

   This source code of graphical user interface
   has been generated automatically by RemoteXY editor.
   To compile this code using RemoteXY library 2.4.3 or later version
   download by link http://remotexy.com/en/library/
   To connect using RemoteXY mobile app by link http://remotexy.com/en/download/
     - for ANDROID 4.7.12 or later version;
     - for iOS 1.4.7 or later version;

   This source code is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
*/

//////////////////////////////////////////////
//        RemoteXY include library          //
//////////////////////////////////////////////

// RemoteXY select connection mode and include library
#define REMOTEXY_MODE__SOFTSERIAL
#include <SoftwareSerial.h>

#include <RemoteXY.h>

#include <Servo.h>

Servo ESC; //create servo object

// RemoteXY connection settings
#define REMOTEXY_SERIAL_RX 10
#define REMOTEXY_SERIAL_TX 11
#define REMOTEXY_SERIAL_SPEED 9600

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,2,0,0,0,60,0,11,13,1,
  4,0,23,16,17,64,2,26,2,0,
  31,5,22,11,2,26,31,31,79,78,
  0,79,70,70,0,129,0,5,7,18,
  6,17,76,69,68,0,129,0,15,85,
  37,6,17,83,101,114,105,97,108,32,
  111,117,116,112,117,116,0 };

// this structure defines all the variables and events of your control interface
struct {

    // input variables
  int8_t slider_1; // =0..100 slider position
  uint8_t switch_1; // =1 if switch ON and =0 if OFF

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

int power = 8;
int ledPin = 2;

void setup()
{
  RemoteXY_Init ();

  digitalWrite(LED_BUILTIN, HIGH);
  // TODO you setup code

  pinMode (LED_BUILTIN, OUTPUT);
  pinMode (power, OUTPUT);
  pinMode (ledPin, OUTPUT);
  //pinMode (7, OUTPUT);
  //int ledMapping;

  ESC.attach(6, 1000, 2000); //attach ESC to output from pin 6

  Serial.begin(9600);
}

void loop()
{
  RemoteXY_Handler ();

  //Serial.println(RemoteXY.slider_1);
  digitalWrite(power, HIGH); //supply power to Bluetooth module through pin 8
  //digitalWrite(7, HIGH);
  int ledMapping = map(RemoteXY.slider_1, 0, 100, 0, 255);
  //Serial.println(ledMapping);
  analogWrite(ledPin, ledMapping);

  int spinMapping = map(RemoteXY.slider_1, 0, 100, 0, 180); //map the slider to the servo
  if (RemoteXY.switch_1 == 1){
  ESC.write(spinMapping); //write to the ESC the value of mapped slider
  }
  else if (RemoteXY.switch_1 == 0){
  ESC.write(0);
  }
  Serial.println(spinMapping);

  if(RemoteXY.switch_1 == 1){
  digitalWrite(LED_BUILTIN, HIGH);
  }
  else if (RemoteXY.switch_1 == 0){
   digitalWrite(LED_BUILTIN, LOW);
  }

  // TODO you loop code
  // use the RemoteXY structure for data transfer
  // do not call delay()

}

```

But I don't think it is the problem. The reason is because even though I have ESC.write(0) when the LED switch is off, the ESC still turns (as is apparent in the video) randomly and twitches.

Any help would be greatly appreciated. I am trying to use this as a prototype for an eletric skateboard, but obivously if the motor is turning on its own even when it should be stopped, it is very dangerous to use.

# Answer
try detaching the ESC instead of ESC.write(0)
> 1 votes

---
Tags: arduino-mega, motor, bluetooth, servo
---


title: "EVERY_N_MILLISECONDS"

text:
# Question
Title: "EVERY_N_MILLISECONDS"
One of the FastLED examples that I've seen was using code that looks like this:

> EVERY\_N\_MILLISECONDS( 300 ) { transition\_step(); }

I've copied it and successfully used it in the same context - but I have no idea what it is or how it works.

A Google search finds no reference anywhere at all.

I'm still a beginner with C but this looks like a Define to me - all being in uppercase - is it defined somewhere in the FastLED library?

# Answer
Yes, it is defined in the FastLED library. It is a *preprocessor macro* which is replaced by a block of code when compiled:

It is a very convoluted bit of preprocessing code that is difficult (even for me) to follow through with lots of concatenations and multiple layers of definition, so my advice is to just not worry about it and just use it.

If you want to try and decypher it all it's in the file `lib8tion.h` in the FastLED library.
> 5 votes

# Answer
As @Majenko has said it is defined in the FastLED library http://fastled.io/. There is also EVERY\_N\_SECONDS.

It is not necessary to call any other FastLed function in the run loop (such as FastLED.delay()) in order to use these functions.

```
include <FastLED.h>

void loop() {
   ....
   EVERY_N_MILLISECONDS( <mseconds> ) {
     <your timed code here>;
   }

   EVERY_N_SECONDS( <seconds> ) {
     <your timed code here>;
   }
}

```
> 3 votes

# Answer
Its a macro that wraps the code you put inside of it to only be run based on the time interval you pass to it. The purpose of it is to allow for timer based code to be ran without having to block the main `loop()`. When the code is compiled it gets wrapped by other code that governs how the code inside it should run.

Lets say you want to run a method every 100ms. A simple approach would be the following:

```
// loop() runs the code within it over and over at a rate based on the
// how fast the microprocessor runs - specifically how long it takes
// for the processor to get through the code inside of it.
void loop(){

doMethod();
delay(100);

checkForButtonInput();

}

```

The issue here is that during the `delay()`, the `delay()` function, by its design, hogs all the processor time for 100ms, and so the `checkForButtonInput()` is not able to check for input, as the program is currently stuck looping inside of `delay()` until 100ms has passed.

`EVERY_N_MILLISECONDS( <mseconds> ){}` is the answer here, and you can think of it working to add code to you code like this (although this isn't exactly accurate):

```
void loop() {
   EVERY_N_MILLISECONDS( 100 ){
  //pseudocode
  //if ( it has been 100ms since last time we did doMethod() ) {
      doMethod();
      // reset time since we did doMethod() to 0
  //}
  //else {
  //  continue...
  //}
  }
  checkForButtonInput();
}

```

so if it hasn't been 100ms since the last time we were in the `EVERY_N_MILLISECONDS` wrapped code then we just move on, and so the `checkForButtonInput()` is called as much as possible and inputs wont be missed.
> 2 votes

---
Tags: c
---


# Question
Title: Controlling a 5V fan and ultrasonic fogger with an arduino - do I need an external power supply?
I know the whole controlling a fan with an arduino thing is getting old, but somehow I still don't get it to work. Tried to answer it based on other questions but I am too much of a newbie to extrapolate the info there to my specific problem.

For my project of building an arduino-controlled mushroom grow box, I need to control a PC fan and ultrasonic fogger. I chose these two products:

DC 3-12V Ultrasonic Fogger, DC 5V Fan

I hoped that by using 5V devices, I could connect them to the 5V pin of the arduino to power them. However, with the whole setup (see circuit and photo), they don't run. I'm using a BC337 transistor. I tried them both separately, but nothing.

I know that there is a resistor missing in the photo, I forgot to put it back in when I took it.

The fan works if I just insert it between 5V and GND but the fogger doesn't do anything.

The code works (and is fairly hard to mess up) but I'm including it anyway.

```
const int fan = 3;

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

void loop() {
  digitalWrite(fan, HIGH);
}

```

**Do I need a higher voltage power supply or is something wrong with my transistor choice? Which parts would be a better fit? Or am I entirely on the wrong track?**

In the end the full thing should also contain an LCD display and a SCD41 sensor, both connected via I2C.

Thanks in advance!

# Answer
**About the ultrasonic fogger:**

The product description is misleading. This is a pure transducer. That means it does **not** generate its own ultrasonic frequency and is thus not DC. You need to provide an AC voltage at the frequency of 113kHz (though one reviewer states to have received products with a resonance frequency of 108kHz. Maybe just try out what you have). You can use utilize Timer1 to generate a fitting square wave at one of its output compare pins.

Note: Since you are more at the lower end of the foggers voltage rating you might see a bad performance when you get it to work. For it to work with its full power you should probably drive it with 12V, utilizing its full range.

**About the fan:**

As jsotola already stated in the comments, the red wire of the fan is not connected to the circuit. If you look at your breadboard you will see that the blue and red lines are interrupted in the middle of the breadboard. This means, that the rails are disconnected here (divided into the left and the right part of the breadboard). Move the red fan cable to the left of the red LED jumper wire. Then you should be connected.
> 7 votes

# Answer
In regards with your schematics

1. Are you sure you want your stuff working only when both D3 and D5 are up? Because it seems to me you connected them in series, so if one transistor is down, nothing's gonna work.
2. check the power rating of the ultrasonic transducer, if you get your power source from the computer USB port, you will get at best about 2.2W from the 5V pin. It may turn out that it may be insufficient to produce any notable effect from the transducer with that, especially if you have the fan powered too.
> 0 votes

---
Tags: power, motor, transistor, ultrasonics
---


title: State machine problem

text:
# Question
Title: State machine problem
I am trying to record the pulses from a water flow sensor using a state machine. My goal is to count the pulses until the flow stops (i.e. the rotor inside comes to rest). This will constitute a single reading. if there is no new pulse/interrupt 5 seconds after the rotor is stopped, the total pulse count is printed and pulse count is reset to zero for the subsequent readings.

However, in practice, I get a pulse count even when the sensor rotor is moving. The pulse count gets resets after 5 sec but the pulses between the new reading and until the rotor is stopped are somehow missed.

Could you please help me figure what am I doing wrong?

```
#include <Arduino.h>
#include <TelnetStream.h>

const byte pulsePin = 22;
byte volatile triggerCounter = 0;

byte newState = 0;

unsigned long newTime = 0;
unsigned long oldTime = 0;

unsigned long pulseCountNew = 0;

portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

void IRAM_ATTR handleInterrupt()
{
  portENTER_CRITICAL_ISR(&mux);
  triggerCounter++;
  portEXIT_CRITICAL_ISR(&mux);
}

void stateMachine()
{

  switch (newState)
  {

  case 0 /* Reset */:
    newState = 1;

    break;

  case 1 /* Start */:

    if (triggerCounter > 0)
    {
      newState = 2;
    }
    break;

  case 2 /* Pulse count start */:

    pulseCountNew++;
    triggerCounter--;
    newTime = millis();
    newState = 3;

    break;

  case 3 /* Pulse count stop */:

    if (triggerCounter > 0)
    {
      newState = 2;
    }

    if (newTime - oldTime >= 5000)
    {
      oldTime = newTime;
      newState = 4;
    }
    break;

  case 4 /* Cycle complete */:
    newState = 0;
    TelnetStream.println("State 4");

    break;
  }
}

void setup()
{
  pinMode(pulsePin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pulsePin), handleInterrupt, FALLING);
  TelnetStream.begin();
}

void loop()
{

  if (newState == 4)
  {

    TelnetStream.println(pulseCountNew);
    pulseCountNew = 0;
  }

  stateMachine();
}

```

# Answer
I do this usually without an extra state variable.

```
unsigned long readSensor() {
  const unsigned long READING_TIMEOUT_MILLIS = 5000;
  static unsigned long lastReadingMillis;
  static unsigned long lastCounterValue;

  noInterrupts();
  unsigned long counter = triggerCounter;
  interrupts();

  if (counter != lastCounterValue) { // if new reading
    lastReadingMillis = millis(); // reset timout timer
    lastCounterValue = counter;
  } else if (counter > 0 && (millis() - lastReadingMillis) > READING_TIMEOUT_MILLIS) { // if something was counted and is timeout
    noInterrupts();
    triggerCounter = 0;
    interrupts();
    lastCounterValue = 0;
    lastReadingMillis = 0;
    return counter;
  }
  return 0;
}

void loop() {
  unsigned long value = readSensor();
  if (value) {
    Serial.println(value);
  }
}

```

sorry, the code is not tested.
> 0 votes

---
Tags: c++, interrupt
---


# Question
Title: Using 4-digit 7-segment display on Arduino Nano
I want to merge two projects: a "Don't touch your face" hat for Nano and a 7-segment 4-digit display for Uno. I tested both independently and they work. I added an RGB LED to the first, so I use 6 digital pins: 2 for the ultrasonic sensor, 1 for the buzzer, and 3 the RGB LED.

The Nano project takes 6 digital pins and no analog pins, leaving 4 digital pins and 8 analog pins. The Arduino Uno takes 12 digital pins. So I suppose that it's possible to replace the digital pins of the Uno with analog ones at the right voltage.

Even without the Nano project claiming 6 digital pins, the Nano only has 11 digital pins (D2-D12), not enough for a 7-segment 4-digit display. But I couldn't find a tutorial online on how to do so.

Is it possible to use a 7-segment 4-digit display on Arduino Nano?

# Answer
> 1 votes
There are chips such as the MAX7219 designed to control 7 segment displays from devices such as an Arduino, there are also some well-established libraries such as LEDCONTROL to drive them. In fact the MAX7219 doesn't have to drive 7 seg displays, you can use it to drive any collection of up to 64 LEDs, I use one for a simple illuminated Christmas tree. You'll need some basic soldering skills to connect the chip to an Arduino but it's very simple.

E.g. see: https://www.maximintegrated.com/en/products/power/display-power-control/MAX7219.html

---
Tags: arduino-nano, 7-segment
---


# Question
Title: Multiple Arduinos, same name - Windows 10 Game Controllers
I am making some SimPit panels and SimRacing devices, and I've run into an annoying issue. I have multiple Arduinos (Leonardos and ProMicros) that show up as the same "Controller Names" (See Image)

EDIT: **In the Game Controllers (joy.cpl) windows of Windows 10**, where does the name "Arduino Leonardo" come from?, so that I can rename each, so they show up listed as something different like: Leonardo 1, Leonardo 2, Leonardo 3?

I imagine this is a change to the boot-loader and nothing to do with anything via Arduino IDE?

Thank you for your time, and let me know if more info/explanation is needed.

# Answer
Windows is likely assigning the inbox driver to use based on the VID/PID of the USB device. Take care changing those values, as you may not be able to easily reprogram the devices.

There is a Device Firmware Update (DFU) technique where if a pin is low at startup / USB init, the VID/PID are returned as different values
> 2 votes

---
Tags: arduino-leonardo, arduino-pro-micro
---


title: Disable Keyboard.h status LED

text:
# Question
Title: Disable Keyboard.h status LED
As soon as I include keyboard.h my pro micros LED starts flashing (as far as I know this indicates a serial connection is stablished or so.)

But it's really annoying having a flashing led on my desk all the time.

Is there an option to disable this 'debugging' behaviour from the keyboard.h libary?

# Answer
Those LEDs are controlled by the USB Core code, and are defined in the board variant. For the pro micro that's the `pins_arduino.h` file in the `micro` variant:

```
#define TXLED0          PORTD &= ~(1<<5)
#define TXLED1          PORTD |= (1<<5)
#define RXLED0          PORTB &= ~(1<<0)
#define RXLED1          PORTB |= (1<<0)
#define TX_RX_LED_INIT  DDRD |= (1<<5), DDRB |= (1<<0), TXLED0, RXLED0

```

If you edit that file and remove everything after the macro name, so you have 5 empty macros, it should disable the LEDs completely.

```
#define TXLED0
#define TXLED1
#define RXLED0
#define RXLED1
#define TX_RX_LED_INIT

```

---

**Edit:**
For the **Sparkfun Pro Micro**, edit the file at

```
...\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.13\variants\promicro

```

This is because it has an extra package that is not installed by default.
> 1 votes

# Answer
> **it's really annoying having a flashing led on my desk all the time.**

As a software engineer I know we often fall into the trap of thinking that all problems must have a software solution. Try thinking of this as a hardware problem.

* Cut out a small piece of a sticky label and stick it over that annoying LED.
* Use a soldering iron to remove the offending LED.
* Use needle-nosed pliers to crush the offending LED.

The more destructive solutions can be reversed with a soldering iron and maybe a new SMD LED. For Arduinos with female or stacking headers you could instead reinstate the feature by plugging a thru-hole LED and resistor into the appropriate positions in the Arduino's header sockets. E.g. D13 and GND. For other Arduinos by adding LED and resistor in adjacent positions in a breadboard.

There might be a good software solution but it can be worth considering other approaches.
> 1 votes

---
Tags: serial, arduino-pro-micro, hid
---


# Question
Title: Doubt in coding part in blink without delay
Code 1 (here `unsigned long currentmillis = millis()` is in loop area):

```
const int LED = 2;
unsigned long previousmillis = 0 ;
const long delaytime = 1500;
int ledstate = HIGH;

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

void loop() {
  unsigned long currentmillis = millis();
  if (currentmillis - previousmillis >= delaytime) {
    previousmillis = currentmillis;
    if (ledstate == HIGH) {
      ledstate = LOW;
    } else{
      ledstate = HIGH;
    }
    digitalWrite(LED,ledstate);
  }
}

```

Code 2 (here `unsigned long currentmillis = millis()` is above `void setup()`):

```
const int LED = 2;
unsigned long previousmillis = 0 ;
unsigned long currentmillis = millis();
const long delaytime = 1500;
int ledstate = HIGH;

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

void loop() {
  if (currentmillis - previousmillis >= delaytime) {
    previousmillis = currentmillis;
    if (ledstate == HIGH) {
      ledstate = LOW;
    } else {
      ledstate = HIGH;
    }
    digitalWrite(LED,ledstate);
  }
}

```

Code 1 is working and Code 2 is not working. What is the significance of the position of `unsigned long currentmillis = millis()` here and why?

# Answer
This is a common misunderstanding for Arduino beginners.

In the second code you do

```
unsigned long currentmillis = millis();

```

outside of any function, meaning at global scope. These variables are declared at the very start of the program, even before the initial Arduino stuff is configured (like the configuration of Timer0 for getting `millis()` to work). The variable will have the value zero. And variables are not magically tied to a source. What you are doing there is a one-time assignment. `currentmillis` will not have future values of `millis()`. It will stay the same until you change it in your code. In your second code you do not ever change `currentmillis`, thus is will stay at the same value forever, preventing the code from working correctly.

In the first code the value is assigned at every `loop()` iteration, so you can be sure that it has a very up-to-date value of `millis()` when you use it afterwards.

This coding principle works exactly like you would bake a pizza, regularly looking at the clock to check the time while you are doing other things. With your first code you look very regularly at the clock to not miss the time to get the pizza out of the oven. With the second code you only look once at the clock, even before you have put the pizza in the oven, and then never again; so your pizza will burn.
> 4 votes

---
Tags: arduino-uno, coding-standards
---


title: variable or field declared void Error

text:
# Question
Title: variable or field declared void Error
For a larger sketch, I have separated a chunk of code in a separate .cpp file

```
#include "msg.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv)
{

    String json = payload;

    // Serial.println(json); // enable to debug

    StaticJsonDocument<128> filter;

    JsonObject filter_current = filter.createNestedObject("current");
    filter_current["temp_c"] = true;
    filter_current["wind_mph"] = true;
    filter_current["pressure_mb"] = true;
    filter_current["precip_in"] = true;
    filter_current["humidity"] = true;
    filter_current["feelslike_c"] = true;
    filter_current["uv"] = true;

    StaticJsonDocument<256> doc;

    // Deseriliaze and display error description if there is any
    DeserializationError error = deserializeJson(doc, json, DeserializationOption::Filter(filter));

    if (error)
    {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return;
    }

    JsonObject current = doc["current"];
    temp = current["temp_c"];          // 80
    wind = current["wind_mph"];        // 5.6
    pressure = current["pressure_mb"]; // 1005
    humid = current["humidity"];       // 93
    feel = current["feelslike_c"];     // 6.9
    uv = current["uv"];                // 1
}

```

together with its header file as below:

```
#ifndef MSG_H
#define MSG_H

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

#endif

```

I have included all the relevant libraries in the .cpp files. However, when I try to compile the code I get multiple errors such as

```
In file included from src/weatherapi.cpp:1:0:
include/weatherapi.h:4:17: error: variable or field 'getRequest' declared void
 void getRequest(String &payload);
                 ^
include/weatherapi.h:4:17: error: 'String' was not declared in this scope
include/weatherapi.h:4:25: error: 'payload' was not declared in this scope
 void getRequest(String &payload);
                         ^
Archiving .pio\build\lolin32\liba47\libPubSubClient.a
In file included from src/msg.cpp:1:0:
include/msg.h:4:20: error: variable or field 'parseResponse' declared void
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                    ^
include/msg.h:4:20: error: 'String' was not declared in this scope
include/msg.h:4:28: error: 'payload' was not declared in this scope
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                            ^
include/msg.h:4:37: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                     ^
include/msg.h:4:50: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                  ^
include/msg.h:4:63: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                               ^
include/msg.h:4:78: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                              ^
include/msg.h:4:90: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                                ^
include/msg.h:4:103: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

```

The function parseResponse doesn't return anything so I don't know why it's complaining about being declared as void. Same is true for the function getRequest. Also, is there something wrong in the function prototype as I am passing references?

Edit: Here is the weatherapi.cpp & .h file

```
#include "weatherapi.h"
#include <HTTPClient.h>
#include <Arduino.h>

const char url[] = "http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

void getRequest(String &payload)
{

     HTTPClient getClient;

    getClient.begin(url);

    int httpCode = getClient.GET();

    //get response and check HTTP status code returned
    if (httpCode > 0)
    {
        payload = getClient.getString();
        Serial.print("HTTP Status: ");
        Serial.println(httpCode);
    }
    else
    {
        Serial.println("Error on HTTP request");
    }

    getClient.end();
}

```

weatherapi.h file

```
#ifndef WEATHERAPI_H
#define WEATHERAPI_H

void getRequest(String &payload);
#endif

```

# Answer
> 2 votes
In C order is important. Everything is parsed sequentially, and header file inclusions are replaced literally with the header contents at compile time.

Things *must* be defined before they can be used, and that includes anything that is defined in the `Arudino.h` header file - that file *must* be included *before* anything that uses it - and of course that means that it must come before any headers that use things from `Arduino.h`

To be safer it's good to include `Arduino.h` in *every* file that uses anything from it so you don't run into these problems in future.

---
Tags: c++, compilation-errors, functions, header
---


# Question
Title: `time.sleep` in python script reading serial output causes erratic behavior
I am attempting to control the position of my computer's cursor using a potentiometer hooked up to my arduino nano. The arduino is running the following code:

```
int potPin = 3;    // select the input pin for the potentiometer
int val = 0;       // variable to store the value coming from the sensor

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

void loop() {
  val = analogRead(potPin);    // read the value from the sensor
  Serial.println(val);
}

```

When I ran the following python script, it worked properly and the sensor values were printing out in my terminal.

```
import serial
import pyautogui

ser = serial.Serial("/dev/cu.usbserial-141220", 9600, timeout=0.1)

while True:
    data = ser.readline().decode("UTF-8").strip()
    if data:
        print(data)

```

However, when I added a small time delay in the while loop, the output would either get stuck on a single value or take multiple seconds to reflect a change to the potentiometer.

```
import serial
import pyautogui
import time

ser = serial.Serial("/dev/cu.usbserial-141220", 9600, timeout=0.1)

while True:
    data = ser.readline().decode("UTF-8").strip()
    if data:
        print(data)
    time.sleep(0.01)

```

I'd appreciate any help fixing this issue.

# Answer
> 2 votes
Thanks to chrisl and timemage's comments, I figured out the issue: the Arduino was sending the data too fast and the bytes were piling up in the computer's inbound buffer. I solved this by adding a delay to the `loop()` function of the Arduino code.

---
Tags: serial, arduino-nano, communication, python
---


title: L298N motor controller board EN pins

text:
# Question
Title: L298N motor controller board EN pins
For this device are the enable pins meant to be connected to PWM pins? If so then how am I able to use this device with an arduino uno? The uno does not have any pwm pins right?

# Answer
The uno pins are 3, 5, 6, 9, 10, 11.

See https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

Usage:

```
analogWrite(pin, value);

```
> 1 votes

# Answer
The people over at How to Mechatronics have a great introduction to this board and using it with an Arduino Uno.

The enable pins are for turning the motors on and off. See the table for the different settings.  But the EN pin is also used for controlling the motor speed.

PWM is used to adjust the speed the motors turn at. Rather than simply turning the enable pin fully “on” (i.e, full speed), PWM is used to adjust the voltage and thereby control the speed the motors turn.

So the short answer is yes, you can connect a PWM signal to the EN pins. Yes a UNO can produce PWM (as answered by others)
> 0 votes

---
Tags: arduino-uno, motor, pwm
---


title: Parsing JSON response from Stream

text:
# Question
Title: Parsing JSON response from Stream
I want to parse JSON response from a GET Request. I do this usually by using a String variable to store the response and later parse this string using ArduinoJSON library like shown below:

```
#include <Arduino.h>
#include "OTA.h"
#include "Credentials.h"
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char url[] = "http://date.jsontest.com/";

HTTPClient getClient;

void getRequest(String &payload)
{
  getClient.begin(url);

  int httpCode = getClient.GET();

  if (httpCode > 0)
  {
    payload = getClient.getString();
    // Serial.print("HTTP Status: ");
    // Serial.println(httpCode);
  }
  else
  {
    Serial.println("Error on HTTP request");
  }
  getClient.end();
}

void parseResponse(String &payload)
{

  StaticJsonDocument<128> doc;

  DeserializationError error = deserializeJson(doc, payload);

  if (error)
  {
    Serial.print("deserializeJson() failed: ");
    Serial.println(error.c_str());
    return;
  }

  const char *time = doc["time"]; // "03:53:25 AM"
  // unsigned long *epoch = doc["milliseconds_since_epoch"]; // 1362196405309
  const char *date = doc["date"]; // "03-02-2013"

  Serial.println(date);
}

void setup()
{
  setupOTA("ESP-N2", mySSID, myPASSWORD);

  Serial.begin(115200);
}

void loop()
{
  ArduinoOTA.handle();

  unsigned long newTime = millis();
  static unsigned long oldTime = 0;
  String payload;

  if (newTime - oldTime >= 5000)
  {
    oldTime = newTime;
    getRequest(payload);
    parseResponse(payload);
    Serial.println();
  }
}

```

I want to avoid using String and ArduinoJSON offician reference page mentions that it's possible to deserialize directly from input Stream e.g. wifiClient, ethernetclient or serial but I couldn't find any example showing it's usage. So I am curious to learn how to use it.

From my basic understanding of a Stream, I suppose I need define a buffer or memory location that will hold the incoming bytes and using the address of this buffer need to read data bit by bit. So do I need to do something like this:

```
char buffer[]= httpClient.getStream();

```

and then pass this buffer as input to deserialize function? or have I gotten it completely wrong?

# Answer
> 2 votes
`httpClient.getStream()` returns an instance of `Stream` that you can pass to `deserializeJson()`, like so:

```
deserializeJson(doc, httpClient.getStream());

```

However, by doing so, you bypass the code in `HTTPClient` that handles chunked transfer encoding, so you must call `httpClient.useHTTP10(true)` before calling `GET` to make sure the server won't return a chunked response.

See How to use ArduinoJson with HTTPClient?

---
Tags: json, esp, stream
---


# Question
Title: Can Arduino go in and out of Sleep or Deep Sleep Automatically?
I am wondering if an Arduino Uno can go in and out of deep sleep automatically with some sort of cue such as a certain time. In my case I have a small light connected to my Arduino Uno as well as a DS1302 clock module which is being powered via a phone charger but overnight the light will be off and I do not want the Arduino idling overnight. So can it be programmed to turn on/off based on the time being read from the clock which would be the same time as the light turning on? I have seen many videos of entering/exiting deep sleep but they all require a manual input such as a button. If not possible are there any other power saving options out there?

# Answer
> 4 votes
The Arduino goes into deep sleep when you tell it to. It wakes up when it gets an interrupt. What that interrupt is is (pretty much) up to you.

If you are using an RTC most will have an alarm function that will trigger an IO pin which can be used as an input (like a button) to the Arduino. Or you can use a timer (the watchdog is common for that) to wake up periodically and check the time, then go back to sleep again.

The datasheet for the MCU on your chosen Arduino will tell you all you need to know about sleep modes and what interrupts can be used to wake from which modes.

---
Tags: sleep
---


# Question
Title: Setting serial number on CH340 USB-Serial device
Reading http://playground.arduino.cc/Linux/Udev there appears to be a way to write out to a FTDI USB-Serial EEPROM to set a given SerialNumber, allowing you to identify a given nano/other arduino to handle it specifically in UDEV.

I have a nano-style boad with a QinHeng Electronics HL-340 USB-Serial adapter, which clearly isn't an FTDI chip, and the FTDI programmer therefore doesn't work. Does anyone know of an alternative utility/where I can find information to do the same with this chip?

Currently the device identifies itself with:

```
[ 6850.608080] usb 2-1.2: new full-speed USB device number 7 using ehci-pci
[ 6850.701496] usb 2-1.2: New USB device found, idVendor=1a86, idProduct=7523
[ 6850.701505] usb 2-1.2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[ 6850.701510] usb 2-1.2: Product: USB2.0-Serial
[ 6850.702201] ch341 2-1.2:1.0: ch341-uart converter detected
[ 6850.704210] usb 2-1.2: ch341-uart converter now attached to ttyUSB0

```

Which is essentially useless, as I can't identify the given board attached (when I attach two, their details are the same).

# Answer
> 6 votes
There is no storage on the CH340 and family of UARTs where you could put a unique ID. This is also a problem for the PL2303 type. I have been trying to find solutions for this problem. First and easiest is the position of the device on the USB bus. It will be unique for each device. If you're using linux you can find each device under /dev/serial/by-path . There is also a /dev/serial/by-id but there will only be one entry there for this device because it shows the last one connected. FTDI chips will each have unique entries here. Cheap chips won't, but they each have an entry under /dev/serial/by-path. This position, and the device names, should persist across reboots. If you have a lot of changes to your USB devices, plug all the CH340 devices into the same hub, then plug that in. The devices will enumerate in the order that they are plugged in to the hub. This one-hub trick should work for MacOS and windows too, they should come up in the same order.

Harder method- udev rules. For devices with a unique ID such as FTDI you can set a udev rule that sees it's serial number and then creates a symlink to that device, it's straightforward.

For devices with the same or no Serial number, it's a lot more complex. I created a udev rule that looks like this:

SUBSYSTEM=="tty", ATTRS{product}=="USB2.0-Serial", RUN+="/usr/local/bin/cheapduino.py %k", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", ENV{ID\_MM\_DEVICE\_IGNORE}="1"

when the device matches the product and vendor of the cheap arduino, it runs the script 'cheapduino.py' with the device as argument, for instance

cheapduino.py ttyUSB0

Then the cheapduino script connects by serial to the device and sends the string 'ID' and the software on the device responds DEVID=THX1138 or whatever. The script then creates a symlink /dev/THX1138 that points to /dev/ttyUSB0

There are a lot of drawbacks to this method. The script must time out if the software on the cheapduino doesn't answer. Also this is not using the SYMLINK function of udev so it won't clean up dead links on disconnect, but it will overwrite them on reconnect. All of your cheapduinos must have this functionality in their software, with different device IDs set. They all must use the same baud rate as the script unless you want to write a very complex script that takes a long time. Finally, this method works much better at low baud rate than at high baud rate, which for timing reasons may not succeed every time. (cheapduinos are cheap!) 9600 works much better than 115200 which works after several tries. But since all your CH340 arduinos must be the same speed with this method, you can only go as slow as your fastest device.

This method DOES work though, and it's what I'm using because I bought way too many of these cheap things.

In the end, buy genuine Arduinos or at least ones with FTDI chips or something else that sends a unique device ID.

=Rich

# Answer
> 2 votes
If what you want is to tell apart 2 devices that are basically identical, you have 2 ways:

* always plug them in the same ports and use the USB tree to differentiate them
* create an handshake protocol, where each Arduino uses a code that you have previously stored in their respective EEPROMs. It might even be possible to write a helper function for UDEV, so that the helper function does the handshake and tells UDEV the serial that is stored in each EEPROM. That would allow to write a UDEV rule for your devices.

# Answer
> 2 votes
I hate to say it, but the answer is no, there is not way to uniquely identify multiple 340 based usb-serial converters.

I have the same problem, where I have multiple (4+) usb-serial converters, any one could be plugged into any port, and they were purchased at the same time and therefore are identical in every way (including iSerial of 0).

Basically, if I move things around, I have to connect by hand to see what's attached, peruse dmesg output, etc. It's a big pain.

tom

# Answer
> 2 votes
CH340B (not the G) has an EEPROM where you can store the serialnumber.

https://www.mpja.com/download/35227cpdata.pdf

There is a windows tool as well to read/write it:

http://www.downxia.com/downinfo/196126.html

Will try to install and see how the G version behaves...

# Answer
> 1 votes
Put a Maxim DS18S20 on your board, each has a unique serial number and are very inexpensive. There are a lot of software examples on the internet using this device. You could dead-bug it to the nano. to operate it needs a 4.7K resister connected to +5 and a ground connection. You can connect both the 5V and Ground connections of the device to ground. It would be easy to dead bug this to the nano then by simple communication via one pin you can get the serial number. There are several packages available. With care you could use an input pin, read the serial and save it for future use. When it Inits it will do this again. Just be sure the input is not driven low during the init process.

Good Luck,

Gil

# Answer
> 0 votes
Here is a software tool that I wrote which can be used to update serial number of WinChip Head CH340B. This will be useful for some one who wants to connect multiple CH340B Virtual COM Port devices to their Windows PC.

You can get the source code of this tool from the following github repository.

https://github.com/senthilnathant/tools-ch340b-configuration

---
Tags: arduino-nano, ch340
---


# Question
Title: How does Arduino Servo.h library manage to output PWM when a Servo motor is connected to a non-PWM pin?
While learning more about Servos, the main thing i have learned is that, Servos (SG90) need PWM signal with the frequency of 50Hz. And the duty cycle of the frequency is used to rotate the angle of the motor.

I know generating PWM with variable duty cycle is possible in PWM pins using Timers but i don't understand how the arduino Servo.h library makes digital pins act like PWM too , whenever i connect the servo to any one of the digital pins of the arduino and code accordingly.

So how does Arduino 'Servo.h' Library manage to make a digital pin act like a PWM and what should the native AVR C code for this action look like?

I am trying to avoid third party libraries as much as possible and trying to learn Embedded systems thoroughly.

Please do not suggest big banging PWM method.

Thanks...

# Answer
I believe the servo library uses one (or more depending on board architecture) inbuilt 16 bit timers (timer1 on the UNO) to produce PWM directly on a *digital* pin using a low level equivalent of a digital write. The direct use of the timer prevents the use of that timer for other purposes like analogWrite().

In comparison a frequently used, more user-friendly method of producing PWM on Arduino is to use analogWrite() on designated *PWM* pins only.

The servo library source code is on github here.

You may have already answered your own question, as you did mention the bit-banging PWM method. That's what it looks like to me, but I'm not an expert on lower level programming.

See also: How can the Arduino Uno support up to 12 servos if it only has 6 digital PWM pins?
> 0 votes

---
Tags: arduino-uno, servo, pwm, digital
---


# Question
Title: Arduino Uno 3: Stuck at 'uploading...' sketches
I was playing around with my Arduino Uno R3 board with Sublime Text 2 & 'Stino' as IDE
I am not sure if it is my code is the problem or if I broke something...
I pressed upload while another sketch didn't finish uploading, even the original Arduino IDE can't upload new sketches anymore!

This is my code:

```
// singleServo.ino

#include <Servo.h>

Servo servo;
const int button = 2;
const int led = 13;
const int buzzerPin = 10;
const int duration = 180;

int stateLED = LOW;
int previous = LOW;

void setup() {
    pinMode(led, OUTPUT);
    pinMode(button, INPUT);
    pinMode(buzzerPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    int stateButton;

    stateButton = digitalRead(button);

    if (stateButton == LOW && previous == LOW) {
        if (stateLED == HIGH)
        {
            stateLED = LOW;
            initAction(duration);
        }
        else
        {
            stateLED = HIGH;
        }
    }

    digitalWrite(led, stateLED);
    previous = stateButton;
    servo.detach();
}

void initAction(int time_iA){
    tone(buzzerPin, 523, 200);
    delay(200);

    shiftServo(180, time_iA);

    tone(buzzerPin, 262, 200);
}

void shiftServo(int angle, int time_sS) {
    servo.attach(9);
    delay(500);
    int position;

    for(position=0; position <= angle; position += 1)
    {
        servo.write(position);
        delay(time_sS / 180);
        Serial.println(servo.read());
    }
    // for(position=angle; position >= 0; position -= 1)
    // {
    //  servo.write(position);
    //  delay(time_sS / 90);
    // }
}

```

I am a newbie with all things Arduino - Please help!

EDIT: After rebooting the system (Ubuntu Linux 14.04) everything was working just fine again!
But I'm going to take the serial functions out too.

# Answer
> 1 votes
You have to wait for the first and all other uploads to fail.

If you are not sure, a reboot is the most reliable solution.

Also note that if your sketch sends a lot of data over serial, a manual reset of the board may be needed.

# Answer
> 1 votes
I've got the same problem on my Ubuntu. Eventually, I was stuck at every uploading, even after unplugging+replugging the device.

Killing all avrdude process, remove the problem.

```
sudo killall avrdude

```

or with new IDEs:

```
sudo killall avrdude_bin

```

# Answer
> 0 votes
I had this happen to me on an UNO R3. I solved the issue by disabling Bluetooth on my laptop. It was causing a conflict on COM5.

I had ruled out the board, cable, and IDE. Finally noticed in Device Manager that COM5 had entries (one being the Arduino and the other being Bluetooth)

Hope that helps someone else that might have this issue in the future.

# Answer
> 0 votes
I had the same problem with arduino uno r3 on win10. The solution was simple:

1. open the task manager (Ctrl + Shift + Esc)
2. stop all open COM processes and the arduino upload worked again.

---
Tags: ide
---


# Question
Title: Using arduino framework how many instances of SoftwareSerial can use simultaneously with esp32
Ussing popular library https://github.com/plerup/espsoftwareserial/ can I have multiple softwareSerial ports (for example 6 ports).

I’m the readme say “ several instances can be active at the same time” but don’t answer a quantity just say several. Also don’t say if the instances will operate normal or will have some issue. Ref: https://github.com/plerup/espsoftwareserial/#readme

Will be great to read an answer from someone with experience with the this specific library and arduino framework.

# Answer
This is not a question that has an answer. There are far too many variables to say "You can have X ports at once".

How many you can have depends on such things as:

* **The baud rates you are using:** faster baud rates will mean more processing and thus less processing for other ports to run.
* **How often data is received:** A port that's not receiving anything isn't using any processing. You could have lots and lots of ports, but if only one is receiving anything it's not much different to only having one port.
* **What else your program is doing:** You have finite resources. The more you use in your program the less are available for other things. You're running an RTOS, and resources and processing are time-sliced between tasks.

You can maximise your port availability by being crafty and careful with executing certain things on each core - for example if you have two heavily used ports it could be good to have one bound to each of your two cores (assuming a dual core ESP32) so they don't interfere with each other as much.

So a quantity cannot be given. Nor can a prediction about how reliable they would be. From the way it's purported to operate, though, the quantity is likely to be "quite a few" and there should be no problems, as long as you don't have too many.
> 1 votes

---
Tags: esp32, softwareserial, uart
---


# Question
Title: i am tying to make a automated parking lot with a gate, sensor, button, keypad, how can i time how long has each car spent inside?
the project requires a automated parking lot, I have been able to connect and function the sensor and button for exit and enter, and the led(red lights when parking is full, green when there is spots). the maximum cars are 5. and the lcd prints the spots available and the spaces taken. the keypad is also connected. now what I need is to make a code that times each car that enters in the order that they enter in and for each car that leaves it has to enter its order of entering to calculate the price it has to pay with this equation: Parking Fee (fils) = time(sec) x 0.29fils here is the code i have at the moment:

```
#include <Servo.h>
#include <LiquidCrystal.h>
#include <Keypad.h>
LiquidCrystal lcd(12,11,5,4,3,2);
Servo myservo;

#define Servo 7
#define exit SDA
#define power 6 // extra
#define ground 10 // extra
#define capacity 5
#define R_led SCL
#define G_led 13
int val;
int n = 5;
int s = 0;

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
 {'1','2','3'},
 {'4','5','6'},
 {'7','8','9'},
 {'*','0','#'}
};
byte rowPins[ROWS] = {A4, A3, A2, A1}; //Arduino Pins
byte colPins[COLS] = {8, 9, 10}; //Arduino Pins

void setup(){
  for(int i=0;i<4;i++){
    pinMode(rowPins[i],INPUT);  //set row pins as inputs
    pinMode(colPins[i],OUTPUT); //set column pins as outputs
  }
  Serial.begin(9600);
  myservo.attach(Servo);
  lcd.begin(16,2);
  pinMode(power,OUTPUT);
  pinMode(ground,OUTPUT);
  pinMode(exit,INPUT);
  pinMode(G_led,OUTPUT);
  pinMode(R_led,OUTPUT);
  digitalWrite(ground,LOW);
  digitalWrite(power,HIGH);
  myservo.write(0);
  digitalWrite(R_led,LOW);
  digitalWrite(G_led,LOW);
}

void loop(){
  if (n>=1){
    lcd.clear();
    lcd.setCursor(1,0);
    lcd.print("Spots left: ");
    lcd.print(n);
    lcd.setCursor(1,1);
    lcd.print("Cars inside: ");
    lcd.print(s);
    digitalWrite(G_led,HIGH);
    digitalWrite(R_led,LOW);
    delay(30);

  }
  else {
    lcd.clear();
    lcd.setCursor(1,0);
    lcd.print("The parking is");
    lcd.setCursor(0,1);
    lcd.print("full!");
    digitalWrite(G_led,LOW);
    digitalWrite(R_led,HIGH);
    delay(30);
  }
val = analogRead(A0);
// Serial.println(val);
if (val>950)
{
  if (n!=0){
    n--;
    s++;
    myservo.write(90);
    delay(3000);
    myservo.write(0);
  }
}
if (digitalRead(exit)==1)
{
  if (n!=capacity){
    n++;
    s--;
      myservo.write(90);
    delay(3000);
    myservo.write(0);
  }
}
delay(20);
  int keyValue=0;
    digitalWrite(colPins[0],HIGH); //Set column1 as high
    digitalWrite(colPins[1],LOW);
    digitalWrite(colPins[2],LOW);
    digitalWrite(colPins[3],LOW);
    for(int i=0;i<4;i++){             //iterate over rows to find if key is pressed
      keyValue = digitalRead(rowPins[i]);
      if(keyValue== 1){
            //display either 1,4,7 or *
        Serial.println(keys[i][0]); //display key pressed
        delay(500);
      }
    }

    digitalWrite(colPins[0],LOW);
    digitalWrite(colPins[1],HIGH); //Set column2 as high
    digitalWrite(colPins[2],LOW);
    digitalWrite(colPins[3],LOW);
    for(int i=0;i<4;i++){              //iterate over rows to find if key is pressed
      keyValue = digitalRead(rowPins[i]);
      if(keyValue== 1){
        //display either 2,5,8,0
         Serial.println(keys[i][1]); //display key pressed
        delay(500);
      }
    }
    digitalWrite(colPins[0],LOW);
    digitalWrite(colPins[1],LOW);
    digitalWrite(colPins[2],HIGH);//Set column3 as high
    digitalWrite(colPins[3],LOW);
    for(int i=0;i<4;i++){
      keyValue = digitalRead(rowPins[i]);
      if(keyValue== 1){               //iterate over rows to find if key is pressed
        //display either 3,6,9,#
         Serial.println(keys[i][2]); //display key pressed
        delay(500);
      }
    }
    digitalWrite(colPins[0],LOW);
    digitalWrite(colPins[1],LOW);
    digitalWrite(colPins[2],LOW);
    digitalWrite(colPins[3],HIGH);//Set column4 as high
    for(int i=0;i<4;i++){
      keyValue = digitalRead(rowPins[i]);
      if(keyValue== 1){               //iterate over rows to find if key is pressed
        //display either A,B,C,D
         Serial.println(keys[i][3]); //display key pressed
        delay(500);
      }
    }
}

```

# Answer
For measuring the time for each parking lot:

Declare an array of `unsigned long` with one element per parking lot (so 5 in this case) and initialize it with zeros:

```
#define N_PARKING_LOTS 5
unsigned long timestamps[N_PARKING_LOTS] = {0};

```

Then go to the place in your code where a new car arrives in its parking lot. You need the number of the used parking lot. Set the corresponding element in the array to `millis()` (for example here element 3, so the 4th parking lot):

```
timestamps[3] = millis();

```

When the corresponding car leaves you can get the time by calculating the difference and by that calculate the price:

```
unsigned long park_duration = millis() - timestamp[3];
float price = (park_duration/1000)*0.29;

```

How you know the parking lot depends on your actual process. It is difficult to understand what you want to say in your question. You could guide the arriving car to a parking spot chosen by you.

Btw: The code will get much easier for you when you actually use the `Keypad` library, instead of just including it. Then your current code will get way shorter.
> 1 votes

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