message:
How to send non char variables over serial

I'm trying to build a GUI that sends the data from processing to arduino via serial. With the help of a couple of guys on here, I have come up with a basic framework that sends a variable ID, variable value and termination character (\n). So far so good!

However, the [arduino reference][1] advises to only use `char` for storing characters. How would I send a `byte` or `int` over serial, while still being able to use a termination character to ensure everything is working as expected?

**edit:**
Using the arduino code from Edgar's answer below and the following processing code, I get the "could not parse value" error.

    import processing.serial.*;

    SerialConnection serialConnection;

    boolean data_processed = false;
    char[] var_array = new char[31];
    char var_id;
    char var_val;
    char space = ' ';
    char termchar = '\n';

    void setup() {
      serialConnection = new SerialConnection(this, 9600);
    }

    void draw() {
      serialConnection.startSerialCommunication();

      if (serialConnection.isReady) {
        var_id = 'a';
        var_val = 127;
        serialConnection.serialPort.write(var_id);
        serialConnection.serialPort.write(space);
        serialConnection.serialPort.write(var_val);
        serialConnection.serialPort.write(termchar);

        delay(50);
        while (serialConnection.serialPort.available() > 0) {
          for (int i = 0; i < 30; i++) {
            char inchar = serialConnection.serialPort.readChar();
            var_array[i] = inchar;
            print(var_array[i]);
          }
        }
      }
    }

body:
If you want to send numeric values to your Arduino, the simplest option
is to send them formatted as ASCII text. Thus you end up simply sending
characters.

Let's assume for example a simple text-based protocol of the form

```text
foo 42
bar 5678
baz -12
```

Each message is made of a variable name followed by its numeric value.
The name and the value a separated by a space. Each message is
terminated by a line feed (`'\n'`).

In order to parse a message, you first have to split it at the space
character. The [`strsep()`][strsep] function comes handy for this. Then,
you have to parse the second part of the message (the value) as an
integer. I would use [`strtol()`][strtol] for this job. Putting all
together:

```c++
void process(char *message) {
    char *name = strsep(&message, " ");  // split at the space
    if (!message) {
        Serial.println("Error: no value given");
        return;
    }
    char *endp;  // end of the numeric value
    long value = strtol(message, &endp, 0);
    if (endp == message) {
        Serial.println("Error: could not parse value");
        return;
    }
    /* Successfully parsed. */
    Serial.print(name);
    Serial.print(" received value ");
    Serial.println(value);
}
```

Note there are some sanity checks in order to make sure the message does
match the expected format. Obviously, you have to replace the last three
lines by something more meaningful to your application.

Example sketch using this:

```c++
void setup() {
    Serial.begin(9600);
}

void loop() {
    static char buffer[40];
    static size_t buffer_pos = 0;
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') {  // end of message
            buffer[buffer_pos] = '\0';  // terminate the string
            process(buffer);
            buffer_pos = 0;  // reset for next message
        } else if (buffer_pos < sizeof buffer - 1) {
            buffer[buffer_pos++] = c;  // buffer the character
        }
    }
}
```

[strsep]: https://man7.org/linux/man-pages/man3/strsep.3.html
[strtol]: https://man7.org/linux/man-pages/man3/strtol.3.html


sender: user

message:
Why does oscilloscope trigger look shaky when using delayMicroseconds?

I'm new to electronics but I have a Rigol DS1054Z oscilloscope and I'm experimenting to help learn.  I've created an incredibly simple sketch using an ESP32 and Arduino IDE:

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

    void loop() {
      delayMicroseconds(10);
      digitalWrite(32, LOW);
      delayMicroseconds(10);
      digitalWrite(32, HIGH);
    }

However, the square wave is incredibly "shaky" or unstable looking.  Why is that?

[![oscilloscope ][1]][1]

  [1]: https://i.stack.imgur.com/hrobV.gif

sender: assistant

body:
This isn't an answer, but you could compare it to hardware PWM to test the limits of the rest of the system.

### Simple ESP32 PWM per https://www.electronicshub.org/esp32-pwm-tutorial/

    int freq = 48000;
    int ledChannel = 0;
    int resolution = 8;  // 48000*2^8 < 80Mhz on channel 0 per https://www.electronicshub.org/esp32-pwm-tutorial/

    void setup() {

      ledcSetup(ledChannel, freq, resolution);
      ledcAttachPin(32, ledChannel);
      ledcWrite(ledChannel, 127);
    }

    void loop() {
    }


body: Jitter like that is usually caused by the different amount of time it takes to go through loop(). Remember that the tick timer takes time away from loop() at an interval that is not synchronized to the loop() time.


body: The display moving is what we call jitter. It is normal with the Arduino  and expected. The pulses are not even because of the background tasks such as the interrupt service routine (that does the millies etc whether you use them or not). When an interrupt occurs it causes the processor to stop, save its state, do a new task, then restore its state and continue. During the interrupt service routine (ISR) the processor uses time to execute instructions, this delay causes the jittering. Trust your scope, as usual it is correct. If you use one of the timer outputs the jitter will go away because they are not normally adjusted the just keep going. PWM is one of the more common modes of doing this but there are many others you can also use.


message:
Why do we add delay when using ultrasonic sensors?

I'm a beginner in Arduino and recently i got myself an Ultrasonic sensor (HC-SR04).

I looked up tutorials on how to measure distance with the sensor and the code I'm using is:

    const int trigPin = 8;
    const int echoPin = 7;

    long duration;
    int distance;

    void setup() {
      // put your setup code here, to run once:
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2); //why do we delay 2 microseconds

      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10); //why do we delay 10 microseconds
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distance = duration*0.034/2;
      Serial.print("Distance: ");
      Serial.println(distance);
    }

I would like to know why do we add delays in the loop function? Appreciate if anyone could explain it.

body:
We need to provide the HC-SR04 with a fitting trigger signal. When you read the [datasheet of the HC-SR04][1] you will see that it needs a 10us trigger pulse.

The first delay of 2us is to make sure we are at an established LOW level on the trigger pin, since the pin might have been HIGH before that. We are delaying here to make sure, that the HC-SR04 actually registered the level as LOW, even if it was HIGH before. If we would change from HIGH to LOW and back to HIGH as fast as we can, then the HC-SR04 might not have enough time to actually see the pin going low. Its mostly a measure to ensure the code working correctly here.

The second delay is for the actual trigger pulse. The datasheet specifies it as 10us length, so that is what we delay here. After that we go back to LOW to end the trigger pulse and wait for the echo pulse to come.

You might have read that it is bad to use delays in your code, since they are blocking. That is correct in principle, but normally really short delays in the microsecond range don't really matter for the program flow. Just be away to keep the total delay time in your code low enough to not miss any important events (like button presses).

  [1]: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf


message:
Modify duty cycle of tone on AVR

I'm writing a MIDI - to square wave converter designed to interface between a MIDI instrument and a musical Tesla coil. Essentially, this should act like a monophonic MIDI synthesiser, but the requirements are slightly different to most projects:

 - I only want to generate (audible frequency) square waves.
 - It is *essential* that the pulse on time not exceed a configurable constant value, e.g. 160 microseconds.
 - I'd like to map the 'velocity' of a given note to the duty cycle, scaled appropriately.
 - Ideally, I'd like to generate envelopes for the pulse width with configurable attack, decay, sustain, release parameters.
 - I'd like to write the audio generation code "from scratch" for the sake of my own understanding of how timing registers work.

The gist of what I want is this (untested) sketch, but it obviously doesn't allow for control of the on time.

    #include <MIDI.h>

    MIDI_CREATE_DEFAULT_INSTANCE();
    const static int out_pin = 9;

    void handleNoteOn(byte channel, byte pitch, byte velocity)
    {
        tone(out_pin, pitch);
        digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    }

    void handleNoteOff(byte channel, byte pitch, byte velocity)
    {
        noTone(out_pin);
        digitalWrite(13, LOW);   // turn the LED off
    }

    void setup() {
      MIDI.setHandleNoteOn(handleNoteOn);
      MIDI.setHandleNoteOff(handleNoteOff);

      MIDI.begin(MIDI_CHANNEL_OMNI);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      MIDI.read();
    }

My question is essentially, what the best way to achieve this kind of musical pulse-width control is. The ideas I had were either
a) A large number of manual register-sets to bit-bang the required signal out at the highest frequency I can get, probably in the kHz
b) Create each pulse using a custom pulseOut function, using timer0 for microsecond delays

I'd also be open to using external analog circuitry, e.g. a voltage controlled pulse shortener.

The load here is an LED, so no special allowances need to be made for its behavior.

body:
I would recommend using a hardware PWM signal generated by Timer 1, or
another 16-bit timer if you have more than one (like on the Mega). The
16 bits provide both a decent frequency range and a good time
resolution. This should provide jitter-free timings, unlike any
software-based method. This will also avoid unduly loading the CPU.

The first thing to do would be to choose the prescaler and the operating
mode. These choices will impact both the lowest available frequency and
the time resolution. The latter affects the accuracy of the
highest-pitched notes. Assuming your Arduino is clocked at 16 MHz,
some sensible choices are:

* prescaler = 64, normal PWM
* prescaler = 8, phase correct PWM
* prescaler = 8, normal PWM

|prescaler|PWM mode|time resolution|lowest freq.|lowest note  |
|----------|----------|-----------|-----------|---------------|
|    64    | normal   |   4 µs    |  3.81 Hz  |  C−1 (MIDI 0) |
|   8 | phase correct |   1 µs    | 15.26 Hz  |  B0 (MIDI 11) |
|     8    | normal   | 0.5 µs    | 30.52 Hz  |  B1 (MIDI 23) |

For the sake of having accurate notes, I would go for the lowest time
resolution that is compatible with the music you want to play.

Once this is configured, you can control the music by writing to three
registers:

* TCCR1A turns the PWM on and off
* the register holding TOP (OCR1A or ICR1, depending on the mode)
  controls the frequency (the pitch)
* a compare match register (OCR1A or OCR1B, depending on the channel)
  controls the duration of the pulses

Your program would then need to set the frequency as a function of the
requested note, then continuously adjust the pulse duration in order to
create the desired envelope while obeying the requested velocity and
ensuring the value of 160 µs is never exceeded.

The main code does not even need to be synchronized with the timer: the
PWM modes guarantee glitch-free PWM even when you change the duty cycle.
Be careful though when changing the frequency: you may get huge glitches
when increasing the frequency. It is safer to stop, clear and restart
the timer when changing notes.


message:
How to distinguish identical Arduinos from Linux?

I have two identical (but with different software) Arduinos connected to Linux box. Their serals are identical

    # udevadm info -a -n /dev/ttyUSB1 | grep '{serial}'
        ATTRS{serial}=="0000:00:1d.0"

    # udevadm info -a -n /dev/ttyUSB0 | grep '{serial}'
        ATTRS{serial}=="0000:00:1d.0"

Can I make these Arduinos to differ somehow programmatically?

body:
You can't change the USB information programmatically. The fact that you're referencing `/dev/ttyUSB*` means you have hardware USB interface chips (CH340, PL2302, FT232, etc) which you can't change from your sketch (some can be adjusted using tools provided by the chip manufacturer though, so you may be able to tweak it using that).

Instead your only option is to have some kind of "fingerprint" that software on your computer can request from your firmware. If you stick to a common serial protocol for all your firmwares you can implement a standard "Firmware Version" command which will respond with what code and version you have installed.

It's up to you to decide how best to implement such a system, of course.


message:
arduino 28BYJ-48 stepper only whining, not rotating

***Edit, this question has been answered in the comments by chrisl, and also after retesting the code with delay() which showed I forgot to update my lastupdate variable(eerst), I have answered it in the comments and chrisl possibly also will post their findings in a answer***
*TLDR- 28BYJ-48 unipolar 5v not working only whining. run using transistors and code in the bottom of the post. transistors connected to 5V and resistors ranging from 100ohm to 1000ohm tried from Arduino to the transistors Trigger/Gate. - END TLDR*

More Detailed
I have some 5v and 12v 28BYJ-48 unipolar stepper motors,(I only connect one to the Arduino at a time) the common(tested with resistance meter) is connected to +, and I the other pins are connected to one BC336 transistor per pin so 4 in total. these transistors should handle 0.8A a piece and I measured the maximum amperage used by the coils to be 0.2+-0.02A for the 5v version at 5v, and 0.045 +- 0.001A for the 12v version at 5v. it makes sense if the 12v version doesn't work at 5v, I just wanted to test it to have an ultra-low-power stepper motor. however the 5v version should work, My setup allows a higher voltage drop in the coils in the motor and can handle a higher amperage than a normal driver however this is limited by the motors resistance ofcource.
I drive it according to the steps in the datasheet with the standard method. and simplified my code to leave out all extra things and even hardcoding the values but still it only whiles and doesn't run the motor. I use the Arduino 5v to run the stepper motor but according to the datasheet and my measurements, you could drive more than one stepper motor on the 5v pin, even when running from USB power. I also set it really slow so that it should work(based on datasheet). I want to get this working like this because I am working on a custom budget stepper driver for Arduino which allows much simpler control, and which is much cheaper than the current drivers as well as that it by default can run higher voltage stepper motors as well, and one very specific functionality which almost everyone who has ever used one stepper motor or more has hoped that their stepper motor driver had.

I used pin 8 9 10 and 11
**Broken Code:**

    unsigned long eerst=0;
    unsigned long nu=0;
    int state=0;
    byte vals[8]={0b00000001,0b00000011,0b00000010,0b00000110,0b00000100,0b00001100,0b00001000,0b00001001};//made hardcoderd aray to make sure fault wasn't in the cyclic bitshifting

    void setup() {
      //0b76543210 portD <-- direction right is low num left is high num, keep confusing this since it differs on some platforms and not having used arduino for a while
      DDRB=DDRB | 0b00001111;//only set 8,9,10, 11 as output do not change resst.
      PORTB=0b00000000;//simplified from only turning of 8,9,10,11 to turning of all of portb
      delay(1000);
      eerst=millis();
    }

    void loop()
    {
      nu=millis();
      if(nu-20>=eerst)
      {
//forgot to update here
        PORTB=vals[state];
        state++;
        if(state>7)//resets state
          {
            state=0;
          }
      }
    }

**Working Code (might be changed for the long overflow stabilizing), changed variable names to make it clearer for others to read:**

    unsigned long TimeOfLastStep=0;
    unsigned long CurrentTime=0;
    int step=0;
    byte vals[8]={0b00000001,0b00000011,0b00000010,0b00000110,0b00000100,0b00001100,0b00001000,0b00001001};//made hardcoderd aray to make sure fault wasn't in the cyclic bitshifting

    void setup() {
      DDRB=DDRB | 0b00001111;//only set 8,9,10, 11 as output do not change resst.
      PORTB=0b00000000;
      CurrentTime=millis();
    }

    void loop()
    {
      CurrentTime=millis();
      if(CurrentTime-2>=TimeOfLastStep)//increased speed from 20ms delay to 2 ms
      {
        TimeOfLastStep=CurrentTime;//forgot this
        PORTB=vals[state];
        state++;
        if(state>7)//resets state
          {
            state=0;
          }
      }
    }

body:
I found the problem(s) in my design, everything was right but I forgot to add eerst=nu;(first=now;, used a different language because now is used by the arduino ide).
Also I didn't read the datasheet properly and so assume 100step/revolution causing me to use delays which where to large, and so even if it worked the movement would be super slow and possibly missed.

New working code:

    unsigned long eerst=0;
    unsigned long nu=0;
    int state=0;
    byte vals[8]={0b00000001,0b00000011,0b00000010,0b00000110,0b00000100,0b00001100,0b00001000,0b00001001};//made hardcoderd aray to make sure fault wasn't in the cyclic bitshifting.
    //in PortB you have the pins 8,9,10,11,12,13. you start at the back of the byte, so if 0b00000001 then only pin 8 is on. if 0b00000010, then only pin 9 is on, if 0b00000011 then pin 8 and 9 are on. PortB has 8 bits, but only 6 settable pins, so do not change the first 2 bits. you can do it more secure this should be done when using port D since that one is connected to serial. however for simplicity I did not add that code here, you can ask for it and I will probably respond with it.

    void setup() { since it differs on some platforms and not having used arduino for a while
      DDRB=DDRB | 0b00001111;//only set 8,9,10, 11 as output do not change resst.
      PORTB=0b00000000; // disabling all port B outputs
      eerst=millis();//eerstm means first, set first to milis to have delay without pausing the code.
    }

    void loop()
    {
      nu=millis();//nu is now, store this lets the code know for how long the arduino ran in milliseconds, needed for non blocking delay, only one now/nu is needed.
      if(nu-2>=eerst)// if 2 milliseconds have passed(have been waited), execute the following code.
      {
        eerst=nu;//reset the non blocking delay timer
        PORTB=vals[state];//Hardcoded values in the array above, this turns on and off pins and is much faster than digital write, selects item at number [state] of aray.
        state++;//go to next state/step
        if(state>7)//resets state
          {
            state=0;//resets state/back to state 0(1 of 8)
          }
      }
    }

edit: solution was also referenced to in the comments below the post. it was really a problem about having it in mind but forgetting to type something down. anyway I will probably soon start to test with that custom driver don't know how to publish it, but will probably link it back here if I remember it. will be open source probably if I find the proper methods.


message:
Will the arduino uno still work if I replace the onboard 16Mhz crystal with a 12Mhz crystal?

I have recently bought an arduino uno R3 (the type where the atmega328 is surface mount and not removable on a mainly blue PCB); the board has two crystals on it one for the clock for the USB serial and the other for the atmega328 clock. Suppose I have built a fully completed circuit using the arduino (this means the arduino needs not to be further connected to a PC).  Will my arduino uno based circuit still work if I  simply replace (desolder) the 16Mhz (for the atmega328)  crystal with a 12Mhz crystal (soldered in its place)? The circuit doesn't use the serial ports or the the crystal for USB serial. Actually the circuit is simply the blink LED example built into the IDE.  I am guessing it will still work but blink slower-but I don't know the answer for sure.

body:
Assembling an answer from the comments. Ever-terse *@jsotola* points the OP to page two of the [data sheet][1] which *@Dave X* summarizes as saying that yes, the chip will operate at 0 to 16 MHz. There is a caveat though, [discussions][2] on the Arduino forum suggest that the reduction in clock speed proposed by OP might interfere with the boot loader. The same discussion provides guidance for compiling for lower speed operation.

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
  [2]: https://forum.arduino.cc/t/arduino-with-internal-oscillator-on-1mhz/24547/4


body: Sure the device will work, but all time related peripherals won't behave. The USART will run at the wrong baud rate, the millisecond timer's intervals will be too long, and so on.


message:
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.

body:
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](http://www.gammon.com.au/forum/?id=12615) which discusses putting arrays of constants into PROGMEM as well as what I mention above.


message:
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.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/CJCJ3.png

body:
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


message:
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?

body:
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.


message:
reading strings from multiple Arduinos

So I have 5 Nanos all trying to crack a password, the idea is each one has one fifth of the list so they can test 5 at a time, then when it is found, I want it to be displayed on a screen I have, the idea is to connect them all to a hub which would be the arduino uno, the Uno would then take the char was sent, and send it to the screen, it does not know which Arduino will send the char and the idea is to use serial.write but I am open to other options. What is the best way to go about accomplishing this task, is there some way I can have it reading the serial from all 5 Nanos, and can this be done without it being plugged into a computer?

body: The Nano devices can be wired in a daisy chain. Any character coming in must be immediately sent out. The chain would end where it connects to the Arduino.


body:
Presumably you will avoid having two Nanos try the same item from the
list. Then, only one Nano can find the answer, and only one will try to
transmit data at any given time. In such a situation, yes, you could
connect all five Nanos to the same serial link:

* Connect the Uno's TX directly to the RX each Nano. They will all
  receive the data transmitted by the Uno.
* Connect the Uno's RX to the TX of each Nano through this circuit:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/pPEaC.png)

<!-- End schematic -->

As long as at most one Nano tries to `Serial.print()` (or
`Serial.write()`) at any given time, the Uno will receive the data just
fine, although it will not be able to tell which of the Nanos sent it.


message:
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?

body:
 - 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.


message:
How many ADS1115 ADCs can I connect to a single Arduino Mega 2560

I know we can connect 4 [ADS1115](https://www.ti.com/lit/ds/symlink/ads1115.pdf)s 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.

body:
256(+?)

With 8 [TCA9548A][1] 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]: https://www.ti.com/lit/ds/symlink/tca9548a.pdf?ts=1639975466543


message:
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
    }

body:
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.


message:
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):
[![leds connected to the first 5 pwm pins 3-10][1]][1]

  [1]: https://i.stack.imgur.com/3qjhw.png

"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 ?

body:
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):

```c++
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.


body:
Here is the @Majenko code output

[![enter image description here][1]][1]

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.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/Bvzfo.gif
  [2]: https://i.stack.imgur.com/1Ljwo.png


message:
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?

body:
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.


message:
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](https://www.amazon.de/gp/product/B07V72T1T9/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1),
[DC 5V Fan](https://www.amazon.de/gp/product/B07X93XGBD/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1)

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.

[![Circuit of the fan connected to arduino. Fogger was hooked up the same way][1]][1]

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

[![How it actually looked - but missing a resistor which I forgot to add in this (Refer to circuit)][2]][2]

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.

[![enter image description here][3]][3]

Thanks in advance!

  [1]: https://i.stack.imgur.com/z19Rm.jpg
  [2]: https://i.stack.imgur.com/qUO6i.jpg
  [3]: https://i.stack.imgur.com/gEGh4.jpg

body:
**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.


body:
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](https://arduino.stackexchange.com/questions/35121/max-current-of-vin-and-5v-pin-on-arduino-nano). 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.


message:
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?

body:
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);
```


message:
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();
    }

body:
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.


message:
How to use ESP32 ESP32 config flag in platformio?

I build my ESP32 project from platformio and I'd like to change CONFIG_MBEDTLS_DYNAMIC_FREE_PEER_CERT in order to reduce the RAM footprint.
I don't get how to do that: should I modify my platformio.ini?

body:
Simply put, you have to update your platformio.ini as assumed in the question as follows (see last line):

```ini
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
 adafruit/Adafruit NeoPixel@^1.10.0
 plerup/EspSoftwareSerial@^6.13.2
 miwagner/ESP32CAN@^0.0.1
 nilsminor/TMP117-Arduino@^1.0.2
 lbernstone/Tone32@^1.0.0
board_build.partitions = no_ota.csv
build_flags = -DCONFIG_MBEDTLS_DYNAMIC_BUFFER
```


message:
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?

body:
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`](https://github.com/arduino/ArduinoCore-avr/blob/master/variants/micro/pins_arduino.h#L31) file in the `micro` variant:

```c++
#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.

```c++
#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.


body:
> **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.


message:
How to make Arduino to read 1X4 keypad multiple times?

I want to use 1X4 membrane keypad to enter  3 working parameters for LED string controlled by  Arduino mini. Keypad is attached to D2-D5 pins and LED is attached to pin 12. My objective is to set the following parameters:
frequency (4 values),
duty cycle (4 values),
run time 4 (values).
I need  Arduino to read keypad 3 times so I can enter  3 parameters. "Run time" In the sketch below has not been set. I want to use “while” to force Arduino to read the keys but arduino reads it once.  Only first “while” is working in the code and I can set cycle period. Second “while” does not work because the key has been already pressed and Arduino does not read keypad second time. Are there any means to use more than 1 "while" in the code or to use one while to read keypad 3 times?

Thank you.

       #define Key1 3 // key 1 attached to pin 3
        #define Key2 2 // key 2 attached to pin 2
        #define Key3 5 // key 3 attached to pin 5
        #define Key4 4 // key 4 attached to pin 4
        float period; // cycle time
        float power; // duty cycle
        float ontime; // ontime  time LED is on
        float rest;  // rest time LED is off
        const int ledPin =  12;      // the number of the LED pin

        void setup()
        {
          pinMode(Key1, INPUT_PULLUP);
          pinMode(Key2, INPUT_PULLUP);
          pinMode(Key3, INPUT_PULLUP);
          pinMode(Key4, INPUT_PULLUP);
          pinMode(ledPin, OUTPUT);
        }
        void loop() {
          digitalWrite(ledPin, LOW);
          while (digitalRead(Key1) == HIGH && digitalRead(Key2) == HIGH && digitalRead(Key3) == HIGH && digitalRead(Key4) == HIGH) {};

          int key1a = digitalRead(Key1);
          int key2a = digitalRead(Key2);
          int key3a = digitalRead(Key3);
          int key4a = digitalRead(Key4);

          if (!key1a) {
            period = 1000;
          }
          if (!key2a) {
            period = 2000;
          }
          if (!key3a) {
            period = 3000;
          }
          if (!key4a) {
            period = 4000;
          }

          while (digitalRead(Key1) == HIGH && digitalRead(Key2) == HIGH && digitalRead(Key3) == HIGH && digitalRead(Key4) == HIGH) {};

          int key1b = digitalRead(Key1);
          int key2b = digitalRead(Key2);
          int key3b = digitalRead(Key3);
          int key4b = digitalRead(Key4  );

          if (!key1b) {
            power = 10;
          }
          if (!key2b) {
            power = 20;
          }
          if (!key3b) {
            power = 50;
          }
          if (!key4b) {
            power = 80;
          }

          ontime = period * power / 100;
          rest = period - ontime;

          digitalWrite(ledPin, HIGH);
          delay(ontime);
          digitalWrite(ledPin, LOW);
          delay(rest);
        }

body: Do something to wait until a key is released before advancing to the next section. It would be wise to structure your program to have only one function that processes key presses, and then call it for each key. (Pass key identification, pin number, into the function.)


message:
Doubt in coding part in blink without delay

Code 1 (here `unsigned long currentmillis = millis()` is in loop area):

```c++
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()`):

```c++
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?

body:
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.


message:
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

body:
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.


message:
`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:

```c++
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.
```python
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.
```python
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.

body: 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.


message:
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][1] 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?

  [1]: https://arduinojson.org/

body:
`httpClient.getStream()` returns an instance of [`Stream`](https://www.arduino.cc/reference/en/language/functions/communication/stream/) that you can pass to [`deserializeJson()`](https://arduinojson.org/v6/api/json/deserializejson/), like so:

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

However, by doing so, you bypass the code in `HTTPClient` that handles [chunked transfer encoding](https://en.wikipedia.org/wiki/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?](https://arduinojson.org/v6/how-to/use-arduinojson-with-httpclient/)


message:
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?

body:
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.


message:
Is possible to use ESP-NOW in LR mode (long range) simultaneously with WIFI STA (to connect to internet over wifi)

I am building esp-now gateway with mqtt but need long distance (200 meters).
I try to use LR mode but when I enable de LR mode I lost connection with WiFi.

Is licit to make use of LR and STA at the same time?

body:
you can easily use both ESPnow and WiFi - you just configure it as WiFi.mode(WIFI_MODE_APSTA);
no need to switch between AP and STA
And I have not experienced any delays for my gateway - sending MQTT message over WiFi to MQTT broker takes 6ms


message:
Blinking a led using assembly language at different frequencies using two push buttons

I want to blink a led using assembly language and arduino
I want the circuit to have a normal state of 5 hz blinking frequency
Then use two push buttons to increase or decrease the blinking frequency
The up button will increment the blinking frequency by 5 hz step until the led seems to be continuously on
While the down button will decrement the blinking frequency by 5 hz step until the normal state again
Is this achievable ?
And if any one can point me where to start as this the first time i am using assembly language but i am familiar with arduino

body:
Here is one example of how to blink an LED in assembly coding on an Arduino UNO. You can attempt to solve your challenge. If you are stuck, please post the code and the connections and I am sure, you will get help again.

The code is here

    #define __SFR_OFFSET 0

    #include "avr/io.h"

    .global main

    main:
      sbi   DDRB, 5     ; Set PB5 as output

    blink:
      sbi   PINB, 5     ; Toggle PINB
      ldi   r25, hi8(1000)
      ldi   r24, lo8(1000)
      call  delay_ms
      jmp   blink

    delay_ms:
      ; Delay about (r25:r24)*ms. Clobbers r30, and r31.
      ; One millisecond is about 16000 cycles at 16MHz.
      ; The inner loop takes 4 cycles, so we repeat it 3000 times
      ldi   r31, hi8(4000)
      ldi   r30, lo8(4000)
    1:
      sbiw    r30, 1
      brne    1b
      sbiw    r24, 1
      brne    delay_ms
      ret

Link to the project: https://wokwi.com/arduino/projects/290348681199092237
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/GQdKY.png


message:
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.

body:
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.


message:
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...

body:
I believe the [servo library][1] 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()][2] on designated *PWM* pins only.

The servo library source code is on github [here][3].

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

See also: https://arduino.stackexchange.com/questions/1348/how-can-the-arduino-uno-support-up-to-12-servos-if-it-only-has-6-digital-pwm-pin

  [1]: https://www.arduino.cc/reference/en/libraries/servo/
  [2]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
  [3]: https://github.com/arduino-libraries/Servo
  [4]: https://en.wikipedia.org/wiki/Bit_banging


message:
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);
          }
        }
    }

body:
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.


message:
Insufficient RX signal delta when using MKR RS485 + Nano, but not Mega

I'm having an issue where an arduino Mega has been used to communicate with an RS485 bus, using an MKR shield [1] as a breakout board. When I build it with a Mega, the system works fine. I've torn down and rebuilt multiple times, and it works every time, no troubles.

However when I build it with a nano it does not work - rx is faulty. Devices on the bus can hear the nano, and a response pulse train is sent back correctly, so outgoing communication is fine.  However at the RX pin on the nano, the serial signal is present when viewed on an oscilloscope, but ranges between +5V and 4.5V, and the RX LED never flashes.

The layout is a simple wiring, there are no (relevant) external components (there is an LCD, but this works fine), just pin-pin connections.

Why is it the mega seems to work, but the nano not? I'm currently guessing that the /RE pin on the MKR RS485 device (MAX3157 [2]) is not being powered properly, and I am seeing the un-amplified serial output? I can't understand why this would be, though, as both the mega and the nano have the same rated max current per-pin.

I've checked the /RE line alone when disconnected, and it is correctly at 5V when not driven, and drives to 0V when the pin is pulled low.

Is there an alternative fix I could use to bring the +5V-4.5V to +5V-0V ? Do I need to have the

[1] MKR Shield schematic : https://www.jameco.com/Jameco/Products/ProdDS/2294031Schematic.pdf

[2] Max datasheet : https://datasheets.maximintegrated.com/en/ds/MAX3157.pdf

body:
OK, answering myself here. It looks like the output of the shield is unable to drive hard enough against the internal pullups of the nano, for some reason. (Yes, its definitely in input mode, you check check the port values, and it is correct)

Leaving the RX output from the shield to float, it works fine, but if connected to an external pullup resistor, then it does not - and I get the same behaviour as when the RX is tied to the nano.

I've been unable to disable the nano's internal pullups in software for some reason. It looks like I will need to add a buffer to increase the drive current. This is a little irritating as it means another breakout board!


message:
Can I use STL on an Arduino Uno?

I started using an Arduino Uno days ago. I'm an experienced C++ dev and I'm kind of confused.

Is the Arduino compiler different than a C++ one? What C++ version does Aruidno Uno use? Why it doesn't it support STL? Is it possible to use STL?

Also, can I configure their cpp file and use my own main function? The loop / setup thing really does annoy me. Thanks!

body:
Yes, there are STL implementations for the Arduino Uno (check the library manager). Note that some of them are unsupported and/or outdated quite a bit. The downside of using STL on the Arduino is also that these classes may use to much memory. Because of it's very limited memory (only 2kb), dynamic memory allocation is quite risky, as memory fragmentation will quickly cause the program to crash.

The Arduino build system uses a pre-build step around the ino files that remove a lot of pain locating header files and setting up build paths from the user. This is a bit confusing at first for an experienced C++ programmer, but it simplifies things a lot, particularly when it comes to using different libraries. This build step automatically locates the include paths for all .h files referenced in the .ino. The system requires that you declare the `loop()` and `setup()` methods, but what you do with them is up to you. You can leave either of them empty, or never return from the loop function, calling into whatever main function you want to use.

As a side note: There are other C++ compiler features that are disabled or unsupported on the Uno because they would make the code to big. These include dynamic type casting using `dynamic_cast<>` and exception handling.


message:
ESP32 heap problem

I wrote a simple C++ program (just main.cpp and corresponding platform.io files & libraries) to get BME280 sensor readings. It worked fine until I decided to use good programming practices, using header files and separating the read function from main.cpp, I get a heap error, stated below:
~~~
CORRUPT HEAP: Bad head at 0x3ffb8444. Expected 0xabba1234 got 0x3ffb84c4
abort() was called at PC 0x40083b99 on core 1

ELF file SHA256: 0000000000000000

Backtrace:
0x400857f0:0x3ffb1aa0
0x40085a65:0x3ffb1ac0
0x40083b99:0x3ffb1ae0
0x40083cc5:0x3ffb1b10
0x400d90a3:0x3ffb1b30
0x400d55bd:0x3ffb1df0
0x400d5558:0x3ffb1e40
0x4008a0f1:0x3ffb1e70
0x40081dee:0x3ffb1e90
0x40083a91:0x3ffb1eb0
0x4000bec7:0x3ffb1ed0
0x400e89b5:0x3ffb1ef0
0x400d13ab:0x3ffb1f10
0x400d0f75:0x3ffb1f30
0x400d3ba9:0x3ffb1fb0
0x40086a75:0x3ffb1fd0

Rebooting...
~~~
Any ideas on that?

By the way, I also used pointers for both the function and the variable passed to it, to no avail.

I also tried a series of combinations with the libraries I am using - Adafruit BME280 and Adafruit Unified Sensor.

Going back to having all the code in one file works...

Thanks

My code:

<!-- language: lang-cxx -->

    //main.cpp
    #include <sensor_readings.h>
    #include <settings.h>

    void refresh_readings();  // Declare in the header so that the compiler knows about it before it is called in loop()

    Adafruit_BME280 bme; // I2C

    void setup() {
      pinMode(LED_BUILTIN,OUTPUT);
      Serial.begin(9600);
      bool status;

      // (you can also pass in a Wire library object like &Wire2)
      status = bme.begin(0x76);
      if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
      }
    }

    void loop() {
      void (*fcnPtr)(Adafruit_BME280){ &refresh_readings };
      (*fcnPtr)(bme);
      //refresh_readings(bme);
      delay(4000);
    }

    ;platformio.ini
    [env:esp32dev]
    platform = espressif32
    board = esp32dev
    framework = arduino
    lib_deps =
     Adafruit_Sensor
     adafruit/Adafruit Unified Sensor@1.1.4
     adafruit/Adafruit BME280 Library@^2.2.2
    upload_port = /dev/cu.SLAB_USBtoUART
    monitor_port = /dev/cu.SLAB_USBtoUART
    monitor_speed = 9600

    //sensor_readings.cpp
    #include <sensor_readings.h>
    #include <settings.h>

    void refresh_readings(Adafruit_BME280 bme) {
      float f_temperature;
      float f_humidity;
      float f_pressure;
      float f_altitude;

      digitalWrite(LED_BUILTIN, HIGH);

      f_temperature = bme.readTemperature();
      f_humidity = bme.readHumidity();
      f_pressure = bme.readPressure() / 100.0F;
      f_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);

      // Temperature

      Serial.print(f_temperature);
      Serial.println(" °C");

      // Humidity
      Serial.print(f_humidity);
      Serial.println(" %");

      // Pressure
      Serial.print(f_pressure);
      Serial.println(" hPa");

      // Appx altitude
      Serial.print(f_altitude);
      Serial.println(" m");

      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("------------");
    }

    //sensor_readings.h
    #ifndef SENSOR_READINGS_H

        #define SENSOR_READINGS_H

        #include <Arduino.h>
        #include <Adafruit_Sensor.h>
        #include <Adafruit_BME280.h>

        #define SEALEVELPRESSURE_HPA (1013.25)

        void refresh_readings(Adafruit_BME280 bme);

    #endif

    //settings.h
    #ifndef SETTINGS_H
        #define SETTINGS_H
        #define LED_BUILTIN 2   // This is valid for my devkit
    #endif

body:
There's a couple problems with your code.

    void refresh_readings();  // Declare in the header so that
                              // the compiler knows about it
                              // before it is called in loop()

This is a lie! Don't tell your compiler there's a `refresh_readings` function that takes no arguments when you haven't defined one. Remove that line, you already have the function declaration in your header.

    void (*fcnPtr)(Adafruit_BME280){ &refresh_readings };
    (*fcnPtr)(bme);

This is just a very convoluted way of typing:

    refresh_readings(bme);

So just use the normal function call syntax.

The main issue as far as I can tell though is that you are copying the `bme` object when passing it to the readings function, which is not advisable in general for this sort of object (they represent a piece of hardware that you can't really copy). That class in particular has a bunch of pointer members, a destructor that deletes them, but no copy constructor as far as I can tell, which [is a bad thing][1].

Change your function to this signature (both in the header and the C++ file):

    void refresh_readings(Adafruit_BME280& bme);
    //                 pass by reference ^

And use the normal call syntax (`refresh_readings(bme);`).

[1]: https://en.cppreference.com/w/cpp/language/rule_of_three