message:
Controll the dc motor that works with 2xAA bateries using 5v

I have a toy that has a dc motor and is runing with 2xAA bateries ( i think it is 3v motor)

So i want to run it with 5v power supply.

First question: Can 5v damage the motor

Second question: i think i need to add diode but dont know what diode to add and how to determine what i need

Third question: is there a combination that i can add series of diode so i can drop voltage to 3v

body:
[DC electric motors][1] are usually rated to run over a range of voltages.  If you are unsure of the specifications of the DC electric motors you have, consider buying new motors which are specified to operate in a rage that includes 5VDC.

Consider not running both the processor (Arduino) and any high current demanding device off the same power source.  Such as solenoids or motors.  This is especially true for mobile devices supplied by battery voltage.  Often is the case the processor will reset (behave unexpectedly) should the supply voltage drop because of activating a solenoid or motor.

Diodes and other components are added to suppress or mitigate undesired effects of a solenoid or motor.  Inductive loads such as solenoids or motors resist changes in current flow and can damage connected components if the undesired current flow is beyond the connected component's abilities.  Read [this stackexchange question/answer][2] for more about this.

A silicon diode has a forward bias voltage drop of about 0.6 volts.  Other diodes have different forward bias voltage drops.  [This wikipedia article lists a few different diodes][3]. It may be possible to arrange enough diodes in series to drop 5 volts to 3 volts.

Consider searching for a 5VDC controllable Arduino relay module.  There are plenty on the web.  Such a device should include the circuitry to safely control the relay and the relay should provide more than adequate isolation from the DC motor.

For a learning experience, consider following [this Arduino / Motor tutorial provided by Adafruit][4].

  [1]: https://en.wikipedia.org/wiki/DC_motor
  [2]: https://electronics.stackexchange.com/questions/95140/purpose-of-the-diode-and-capacitor-in-this-motor-circuit
  [3]: https://en.wikipedia.org/wiki/Diode#Forward_threshold_voltage_for_various_semiconductors
  [4]: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors


sender: user

message:
I don't understand what's wrong with this code

```
int ledy = 5 ;
int leds = 4 ;
int ledk = 3;
int button = 2 ;
int count = 0 ;

void setup()
{
  pinMode(ledy, OUTPUT);
  pinMode(leds, OUTPUT);
  pinMode(ledk, OUTPUT);
  pinMode(button,INPUT);
  randomSeed(analogRead(A0));
}

void loop()
{
  if(digitalRead(button)== HIGH)
  {
  count = count++ ;
  }
    if (count==1)
  {
    digitalWrite(ledk, HIGH);
    digitalWrite(leds, LOW);
    digitalWrite(ledy, LOW);

   }
    else if (count==2)
   {
    digitalWrite(ledk, LOW);
    digitalWrite(leds, HIGH);
    digitalWrite(ledy, LOW);

    }

   else if (count==3)
   {
    digitalWrite(ledk, LOW);
    digitalWrite(leds, LOW);
    digitalWrite(ledy, HIGH);
   }

     delay(1000);

}
```
I don't undertstand why it isn't working.
I want it three leds to light up one by one as loop. But none of them lights up.

sender: assistant

body:
One thing that jumps out to me as a possible cause of your issue here is that many push buttons require a [pull-up resistor](https://docs.arduino.cc/learn/microcontrollers/digital-pins#properties-of-pins-configured-as-input_pullup), which is provided as an internal component of most microcontrollers, but needs to be specifically requested in the `pinMode` instantiation of the button. Try changing your `setup()` function to the following:

```
void setup()
{
  pinMode(ledy, OUTPUT);
  pinMode(leds, OUTPUT);
  pinMode(ledk, OUTPUT);
  pinMode(button,INPUT_PULLUP);
  randomSeed(analogRead(A0));
}
```
however if you do this, you must also change your if statement to `if(digitalRead(button) == LOW)`, as a pullup resistor will make it so that when the button is not pressed, the pin is pulled high, and vice-versa.

Another way to troubleshoot this is to see if the LEDs light up when you remove the reliance on the button altogether by removing the
```
if(digitalRead(button)== HIGH)
  {
  count = count++ ;
  }
```
and changing it to
```
count++;
delay(1000);
```
and see if the LED changes every 1 second (delay requires a millisecond value). I agree with @StarCat that `count = count++;` possibly isn't doing what you think it is.


message:
How to pass Strem object to my class

I'm trying to creaper class wraper to use an `Stream`object but I've an error when I try to compile.
My `.h`file :
````
#include <Arduino.h>

class TestSerialListener {
public:
  TestSerialListener(Stream &serial);
  void testPrint(void);
private:
  bool _listener_start;
  Stream &_serial;

  void startListener(void);

};
````

my `cpp`file
````
#include "TestSerialListener.h"
#include <Arduino.h>

TestSerialListener::TestSerialListener(Stream &serial) : _serial(serial)
{
}

void TestSerialListener::testPrint(){
 _serial.begin(115200);      <---------- error compilation
 _serial.println("test");
}

void TestSerialListener::startListener(void)
{
 if(!_listener_start){
  _listener_start = true;
 }
}
````

And when i try to compile it I got this error : `error: 'class Stream' has no member named 'begin'`Why I can't use `begin()`in my classe ?

body:
the `begin()` method is defined in the `HardwareSerial` class, not in `Stream`. You can look that up yourself in your Arduino installation. For me these files are placed under `~/.arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino/` and are named `Stream.h` and `HardwareSerial.h`.

And if you  think about it, this is quite logical. The `Stream` class can represent any object, that can stream data. It doesn't know anything about how exactly the data is streamed on a hardware level. It just provides the convenient functions for handling the data. The `HardwareSerial` class then derives from `Stream` to get those data handling methods and adds its own methods to handle the hardware side of the problem, including setting a baudrate.

When providing a `Stream` reference to a class constructor you want to `begin()` the corresponding object outside of the class, before you start to stream any data through it. Doing it this way makes your class widely usable, since you could use any `Stream` object, even a file on an SD card.

So move the `begin()` line from your class to the `setup()` function in your main code.

---

For reference: Juraj showed the inheritance between the classes in his answer to [this question][1]. Have a look at it, since it is quite enlightening.

  [1]: https://arduino.stackexchange.com/questions/78719/can-you-use-serial-port-as-a-variable/78725#78725


message:
Arduino 3.3v pro mini, most efficient use of AA batteries for power

I want to use a 3.3V pro mini that uses a BME 280 to take temp/pressure/humidity, and nRF24L01 module to transmit the data, at ?10 minute intervals. I want to use 1, 2,3 or 4  AA batteries to power it. I've read all about the techniques to reduce power consumption, by removing the power LED and using sleep functions.
But I would like to know the most efficient combination of batteries to use. If I can get a year out of 1 battery and a step-up converter, I would be happiest with that. But perhaps 3 duracell or 4 (rechargeable) batteries  connected directly to the Vcc pin (ie no regulator) might be better. Does anyone have first-hand experience to know what works best?

body:
You can definitely do better with another regulator that the on-board ones, which are not energy efficient because they drop the supply voltage through a resistance, wasting the excess current as heat. An external boost regulator would waste much less current (charge, really, since we're trying to make maximum use of the battery capacity, or equivalently, trying to minimize the capacity & space needed to run your system for a year).

So you need two things:
1. The most space-efficient way (I assume...) to store a year's energy needs; and
2. A pretty good idea of what the energy requirement will be.

For (2.), you'll need an energy budget for your system:
1. How much current your system draws when it is awake;
2. How much current your system draws when it is asleep;
3. It's duty cycle (e.g.: 3% awake time, 97% sleep time), and use that to calculate the total charge in milliAmp-hours the system draws during the 1 year.

Don't forget to account for the batteries' inefficiency when they're cold, if that will be an issue, and add in a safety factor so it won't die before you arrive a year hence to change the batteries.

You'll need to consider powering down the sensor(s) and radio(s) during CPU sleep; their idle draw would make sleeping the CPU ineffective (as far as saving battery is concerned).

Once you have an energy budget, you can look at the available ways to store and deliver a year's worth - regulator type, size and efficiency; battery size and count) to see what combination will meet your needs for cost, simplicity, and space limitations.


message:
Unable to flash arduino pro micro from Terminal

I am trying to upload an hex file to my arduino pro micro using Avrdude . The thing is that I cannot upload any code using the Avrdude terminal commands , but when I use arduino IDE to upload any code it perfectly uploads the code to Arduino.

**The command I am using on the terminal:**

    avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -patmega32u4 -cavr109 -PCOM15 -b57600 -D -U flash:w:C:\Users\santi\Documents\keyboard\corne\crkbd_rev1_layout_split_3x6_3_mine.hex:i

I already have avrdude on the environment variables on my windows 10 machine.

**Output**:

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM15
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

I keep waiting but it does not upload the code.

I added a push button for RST and GND pins to enter bootloader mode, and I am pressing the reset button. I even tried resetting twice quickly, but I get the same result.

I tried using the Arduino and the code gets uploaded.

I uploaded the following code:

    int RXLED = 17;
    void setup(){
      pinMode(RXLED, OUTPUT);
    }

    void loop() {
      digitalWrite(RXLED, LOW);
      delay(1500);
      digitalWrite(RXLED, HIGH);
      delay(1500);
    }

The command ran in the IDE is:

    "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

Arduino IDE output:

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM16
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .
    Found programmer: Id = "CATERIN"; type = S
        Software Version = 1.0; No Hardware Version given.
    Programmer supports auto addr increment.
    Programmer supports buffered memory access with buffersize=128 bytes.

    Programmer supports the following devices:
        Device code: 0x44

    avrdude: devcode selected: 0x44
    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e9587 (probably m32u4)
    avrdude: reading input file "C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex"
    avrdude: writing flash (3852 bytes):

    Writing | ################################################## | 100% 0.29s

    avrdude: 3852 bytes of flash written

    avrdude done.  Thank you.

I tried using the same Avrdude command in the terminal.

    "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

**Output:**

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM16
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
    avrdude: ser_open(): can't open device "\\.\COM16": El sistema no puede encontrar el archivo especificado.

I don´t know why it uses a different port.
I tried changing the port in that command but I get the same result as before

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM15
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

I could just use the arduino IDE to flash my device but the problem is that I only have the hex file. I am trying to flash my device with a hex file from [QMK Configurator][1]. I am trying to build a custom keyboard.

  [1]: https://config.qmk.fm/

body:
You have to reset the Arduino using a very special procedure in order
for it to accept being programmed. This involves opening the port at
1200 bps, toggling some control lines, and closing the port again.
You may try using this [ard-reset-arduino][] Python script with the
option `--caterina`.

By the way, this script belongs a project called “Arduino-Makefile”. You
may want to take a look if you want to program your Arduino from the
command line. Alternatively, you can use [arduino-cli][].

[ard-reset-arduino]: https://github.com/sudar/Arduino-Makefile/blob/master/bin/ard-reset-arduino
[arduino-cli]: https://arduino.github.io/arduino-cli/


message:
What is the difference between ":i" and ":a" in avrdude command?

What is the difference between `:i` and `:a` after my hex file path in avrdude command.

    avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM8 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:i

and

    avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

body:
These are Avrdude file format specifiers.

```
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

```

The final `:a` in this case is a format specifier meaning "auto detect; valid for input only, and only if the input is not provided at stdin."

An `:i` in the same position means "Intel Hex"

A complete list can be found here: https://www.nongnu.org/avrdude/user-manual/avrdude_3.html#Option-Descriptions


message:
Serial port stops receiving data after random amount of time

EDIT: Things I have tried so far:
1. Increasing the baud rate, but this didn't make any difference as it still continued to stop receiving data after random amount of time.

2. I tried testing one sensor and reducing the sketch to something that only prints in a sketch. I can get the sketch to work up to 2 sensors where it prints the results continuously. 3 or 4 sensors and I get the issue mentioned.

Link to the VL53L4CD library: https://github.com/stm32duino/VL53L4CD

Datasheets:

https://cdn-learn.adafruit.com/downloads/pdf/adafruit-vl53l4cd-time-of-flight-distance-sensor.pdf

https://www.st.com/resource/en/datasheet/vl53l4cd.pdf

----------

I'm currently working on a project where I need to measure distances at two different points using distance sensors (I'm currently using VL53L4CD laser distance sensors). However, this project requires a high sampling rate of 100Hz. To achieve this, I have 4 distance sensors arranged into 2 sensor sets. Each sensor set consists of 2 distance sensors (So for example, sensor set 1 consists of distance sensor 2&3 and sensor set 2 consists of distance sensor 1&4) and I would alternate between reading each sensor set.

This seemed to work at first, I did get a new distance reading every 8ms. However, the serial port stops receiving the distance readings after a very random amount of time. Sometimes the serial port stops receiving new data after 5 seconds, sometimes 30s, sometimes 60 and even 180s.

I'm not sure what's causing this issue what I can do to fix it. Any help is appreciated
(I'm using the Arduino Nano 33 IOT)

Thanks!

Here is my code below:
```
// Included libraries
#include <Arduino.h>
#include <Wire.h>

// Libraries required for VL53L4CD sensors
#include <vl53l4cd_class.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <stdlib.h>

// Definitions
#define DEV_I2C Wire
#define SerialPort Serial

// variables
int alternate = 0; // Variable used to alternate between sensor sets

// Components.
VL53L4CD sensor_vl53l4cd_1(&DEV_I2C, 2); // xshut pin of distance sensor 1 connected to pin 2
VL53L4CD sensor_vl53l4cd_2(&DEV_I2C, 3); // xshut pin of distance sensor 2 connected to pin 3
VL53L4CD sensor_vl53l4cd_3(&DEV_I2C, 5); // xshut pin of distance sensor 3 connected to pin 5
VL53L4CD sensor_vl53l4cd_4(&DEV_I2C, 6); // xshut pin of distance sensor 4 connected to pin 6

/* Setup ---------------------------------------------------------------------*/

void setup()
{
  // DISTANCE SENSOR SETUP
  // Initialize serial for output.
  SerialPort.begin(9600);
  SerialPort.println("Starting...");

  // Initialize I2C bus.
  DEV_I2C.begin();

  // Configure VL53L4CD number 1
  Serial.println("Configuring distance sensor 1");
  sensor_vl53l4cd_1.begin();
  sensor_vl53l4cd_1.VL53L4CD_Off();
  sensor_vl53l4cd_1.InitSensor();
  sensor_vl53l4cd_1.VL53L4CD_SetI2CAddress(0x40);
  sensor_vl53l4cd_1.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 2
  Serial.println("Configuring distance sensor 2");
  sensor_vl53l4cd_2.begin();
  sensor_vl53l4cd_2.VL53L4CD_Off();
  sensor_vl53l4cd_2.InitSensor();
  sensor_vl53l4cd_2.VL53L4CD_SetI2CAddress(0x42);
  sensor_vl53l4cd_2.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 3
  Serial.println("Configuring distance sensor 3");
  sensor_vl53l4cd_3.begin();
  sensor_vl53l4cd_3.VL53L4CD_Off();
  sensor_vl53l4cd_3.InitSensor();
  sensor_vl53l4cd_3.VL53L4CD_SetI2CAddress(0x44);
  sensor_vl53l4cd_3.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 4
  Serial.println("Configuring distance sensor 4");
  sensor_vl53l4cd_4.begin();
  sensor_vl53l4cd_4.VL53L4CD_Off();
  sensor_vl53l4cd_4.InitSensor();
  sensor_vl53l4cd_4.VL53L4CD_SetI2CAddress(0x46);
  sensor_vl53l4cd_4.VL53L4CD_SetRangeTiming(10, 0);

  // Start Measurements
  sensor_vl53l4cd_1.VL53L4CD_StartRanging();
  sensor_vl53l4cd_2.VL53L4CD_StartRanging();
  sensor_vl53l4cd_3.VL53L4CD_StartRanging();
  sensor_vl53l4cd_4.VL53L4CD_StartRanging();
}

void loop()
{
  // Read results from sensor set 1
  if (alternate == 0){
    VL53L4CD_Result_t results2;
    VL53L4CD_Result_t results3;

    // Read results from sensor set 1 (Sensors 2 and 3)
    sensor_vl53l4cd_2.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_2.VL53L4CD_GetResult(&results2);
    sensor_vl53l4cd_3.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_3.VL53L4CD_GetResult(&results3);

    Serial.print("Distance 1-1 = ");
    Serial.print(results2.distance_mm);
    Serial.println(" ");
    Serial.print("Distance 1-2 = ");
    Serial.print(results3.distance_mm);
    Serial.println(" ");

    alternate = 1; // Change value so sensor set 2 is read in the following loop
  }

  // Read results from sensor set 2
  else if (alternate == 1){
    VL53L4CD_Result_t results1;
    VL53L4CD_Result_t results4;

    // Read results from sensor set 1 (Sensors 1 and 4)
    sensor_vl53l4cd_1.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_1.VL53L4CD_GetResult(&results1);
    sensor_vl53l4cd_4.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_4.VL53L4CD_GetResult(&results4);

    Serial.print("Distance 2-1 = ");
    Serial.print(results1.distance_mm);
    Serial.println(" ");
    Serial.print("Distance 2-2 = ");
    Serial.print(results4.distance_mm);
    Serial.println(" ");

    alternate = 0; // Change value so sensor set 2 is read in the following loop
   }
   Serial.println(millis());
}
```

body: I tried powering all of the sensors with an external power source and this seems to solve the issue, I got consistent readings from all the distance sensors and the serial port did not stop receiving data. It might have been the USB port on my laptop that was causing these issues.


message:
Arduino MEGA - How to send and receive data asynchronously?

i am newbie to this so i hope i can explain my problem clearly;

Arduino MEGA connected to PC via USB port.

I am using an encoder to trigger function to send data to pc, data is a simple string "A01" or "A02" when i turn encoder to opposite direction, when arduino sends that string to serial port PC answers with another string from serial and its something like "MCPHDGxxx" and arduino does if serial available gets the string and filter it to get and show that number on my 7-segment display.
(xxx is a number between 000 and 359, and that number changes on PC screen when arduino send "A01" or "A02" string to PC)

When i don't send display data from PC to arduino, encoder function works as intended, changes numbers up and down rapidly on PC screen but when i try to send that "number" data to Arduino from serial port number on the PC screen changes so slowly like 1 point up/down per 2 sec even if i turn encoder continuously. Seems like receiving data from PC blocking my send data function until it's done.

Is it possible to make it work asynchronously?

Here is my sketch:

    #include "DigitLedDisplay.h"
     #define outputA 24
     #define outputB 25

     int aState;
     int aLastState;
     unsigned long lastButtonPress = 0;
     long finalMCPHDGLong;
     String ReceivedSerialString;

     DigitLedDisplay ld = DigitLedDisplay(21, 22, 23);

     void setup() {
       pinMode (outputA,INPUT);
       pinMode (outputB,INPUT);

       Serial.begin (115200);
       // Reads the initial state of the outputA
       aLastState = digitalRead(outputA);

         /* Set the brightness min:1, max:15 */
      ld.setBright(10);

      /* Set the digit count */
      ld.setDigitLimit(8);

     }

     void loop() {
       aState = digitalRead(outputA); // Reads the "current" state of the outputA
       // If the previous and the current state of the outputA are different, that means a Pulse has occured
       if (aState != aLastState){
         // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
         if (digitalRead(outputB) != aState) {
           if (millis() - lastButtonPress > 25) {
             Serial.println("A01");
      }

      // Remember last button press event
      lastButtonPress = millis();

         } else {
           if (millis() - lastButtonPress > 25) {
             Serial.println("A02");
      }

      // Remember last button press event
        lastButtonPress = millis();

         }

       }
       aLastState = aState;

        while (Serial.available() > 0){
          ReceivedSerialString = Serial.readString();
          if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
            String value = ReceivedSerialString.substring(6,9);
              long val = value.toInt();
              finalMCPHDGLong = val;
              if((finalMCPHDGLong <= 99)){
                  ld.printDigit(0,7);
                }if((finalMCPHDGLong <= 9)){
                  ld.printDigit(0,6);
                }
              ld.printDigit(val, 5);
          }
        }
     }

body:
> Seems like receiving data from PC blocking my send data function until it's done.

You may be saying the same thing, but I'd put it that it's waiting for more data to arrive that isn't going to.

> Is it possible to make it work asynchronously?

Depending on how you're defining "asynchronously" that may be unnecessary.

```c++
while (Serial.available() > 0){
  if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
    String value = ReceivedSerialString.substring(6,9);
```

There's a lot that could be said about using `String` and conversion to `int` and choosing a simple message format and so forth, but I'll elide most of that. Finding a good approach to what you're doing would require understanding a lot more about what you're doing and why. But, taking your code and question as written, the **main thing is that `readString()` here is terminating based on the value of `Serial.setTimeout()`, which by default is `1000` or 1 second.  So you are spending a lot of time doing nothing following receipt of your command from the PC. So during that 1 second you are not tending to the "encoder".**

You could play with `setTimeout`, but it would be better to avoid a timeout altogether by not attempting to read when there's no more command to be read. If this protocol you're using is line-oriented then you have a terminator you can use in the form of '\r' or '\n'. This can be done with `Serial.readStringUntil(whatever_your_terminator_is);` If you have both '\r' and '\n' you will need to read other part of the termination sequence and then throw it away. Either it will come in as part of the read string or it will not and you will need to do a second read to discard it. There are more sophisticated ways to go about this, but that maybe sufficient for what you're doing.

When it comes to not blocking (or significant blocking) of serial reads, you have to assure that the data is there to be read. Either because you know it's sent (and are willing to trust that it was received okay). Or you use `Serial.setTimeout` with a 0 or sufficiently small number, `.read()` indicates no data with a negative return value, or by checking `.available()`, and it all of these cases deciding what to do when you have not received everything, or everything... yet. Doing it well, manually, is a bit of a pain.

For writing/printing to serial there's a counterpart `.availableForWrite()` which
you can use to determine ahead of time whether or not you're going to be stuck in waiting (in `.print()`/`.println()`/`.write()`) for the serial data to go out, in turn not tending to the encoder. Basically you can choose where and how to throttle your writing to serial so as not overly interfere checking the encoder rather than causing throttle to happen within `Serial.write`. With the way your code is currently written, with events coming in at the rate they apparently are (according to your debouncing code) this is probably not currently a problem for you. But it's worth keeping in mind if you begin handling events at a higher rate. Placing a character in the outbound serial buffer is significantly faster than waiting for space for a character to become available in the serial buffer.


message:
Error coming from specified code

#### Error

```txt
Arduino: 1.8.19 (Windows 10), Board: "Arduino Uno"

AnalogInOutSerial:8:56: error: no matching function for call to 'PID::PID(int*, int*, double*, double&, double&, double&, int)'
 PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);
                                                        ^
In file included from C:\Users\USER\AppData\Local\Temp\arduino_modified_sketch_407168\AnalogInOutSerial.ino:1:0:
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:24:5: note: candidate: PID::PID(double*, double*, double*, double, double, double, int)
     PID(double*, double*, double*,        // * constructor.  links the PID to the Input, Output, and
     ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:24:5: note:   no known conversion for argument 1 from 'int*' to 'double*'
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:20:5: note: candidate: PID::PID(double*, double*, double*, double, double, double, int, int)
     PID(double*, double*, double*,        // * constructor.  links the PID to the Input, Output, and
     ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:20:5: note:   candidate expects 8 arguments, 7 provided
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note: candidate: constexpr PID::PID(const PID&)
 class PID
       ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note:   candidate expects 1 argument, 7 provided
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note: candidate: constexpr PID::PID(PID&&)
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note:   candidate expects 1 argument, 7 provided
exit status 1
no matching function for call to 'PID::PID(int*, int*, double*, double&, double&, double&, int)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
```

#### Actual Code

```c++
#include <PID_v1.h>

int analogPin = A3;
int Rawval ;  // variable to store the value read
double setpoint = 169; // target value for the system is set to 169
double kp = 1, ki = 0.1, kd = 0.01; // PID constants
int RELAY_pin = 10;    // Relay is connected to pin D10
PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);

void setup()
{
  Serial.begin(9600);           //  setup serial
  pinMode(RELAY_pin, OUTPUT);
  pid.SetMode(AUTOMATIC);
}

void loop()
{
  Rawval = analogRead(analogPin);
  Serial.print("Rawvalue from Analog input  =");
  Serial.println(Rawval);
  pid.Compute();
  digitalWrite(RELAY_pin, Rawval < setpoint ? HIGH : LOW);
}
```

body:
The first two parameters need to be of type double.

    PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);
            ^^^^^^^  ^^^^^^^

It also makes probably no sense to have input and output both wired to &Rawval.

Take a look [on this example.](https://arduino.stackexchange.com/q/24652/87849)


body:
The error message is quite clear about the problem (extracted and formatted for clarity):

> no matching function for call to
> `PID::PID(int*, int*, double*, double&, double&, double&, int)`
> _[...]_
> candidate:
> `PID::PID(double*, double*, double*, double, double, double, int)`
> _[...]_
> no known conversion for argument 1 from '`int*`' to '`double*`'
> _[other candidates left out due to non-matching number of arguments]_

You need to provide pointers to `double` as the first two arguments, and the candidate will match.

---

**EDIT:**

I hesitated a while to provide your this, because you learn much better by doing it yourself. Anyway, here it is.

Your original variable declaration is:
```c++
int Rawval ;  // variable to store the value read
```

Replace the data type `int` by `double`, as the called constructor expects:
```c++
double Rawval ;  // variable to store the value read
```

Now there is this line, assigning an `int` to a `double`:
```c++
Rawval = analogRead(analogPin);
```
And you might ask yourself, is this OK? Well, try it. You will find that the compiler implicitly converts the value. If you want to make it explicitly, change the line to:
```c++
Rawval = static_cast<double>(analogRead(analogPin));
```

A final point, as datenheim states: Read and learn about the `PID`. It is for sure an error to use the _same variable_ for input and output.


message:
Need help figuring out how to organise a system to run a stepper motor at low speed without Steps-skipping

TL;DR : How to prevent step-skipping with a NEMA gearbox motor at low speed.

I am in the process of creating a system in which I want an object to turn on a plate and to show a letter depending on the angle of the rotation. The object is quite heavy hence the rotation should be quite slow, this is why I took a Planetary Gearbox NEMA Stepper.

My system consists in:
- An Arduino Uno
- [A NEMA Stepper Motor][1]
- [A A4988 Driver][2]
- Some wires
- 2 Iron plates
- [A ball bearing element in between the Iron plates][3]
- Screws to fit everything together.

This is the code I ended up with:

    // Define stepper motor connections and steps per revolution:
    #define dirPin 6
    #define stepPin 7
    #define stepsPerRevolution 5373
    int degree_init = 1;

    int mouvement=0;

    // create a mapping between letters and degrees
    int letterToDegree[33] ;
    int degree;
    // function to map letters to degrees
    int mapLetterToDegree(char letter) {
      if (letter=='.'){
        return letterToDegree[27];
      }
      else if (letter==':'){
        return letterToDegree[28];
      }
      else if (letter=="\'"){
        return letterToDegree[29];
      }
      else if (letter==' '){
        return letterToDegree[30];
      }
      else {
      int letterIndex = letter - 'A'; // get the index of the letter in the alphabet
      return letterToDegree[letterIndex]; // return the degree associated with that letter
      }
    }

    void setup() {
      // Declare pins as output:
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
        Serial.begin(9600);
        for (int i = 0; i < 33; i++){
        letterToDegree[i]= degree_init;
        degree_init=degree_init+10;
      }
    }

    void loop() {
      int p= NULL;
      // Set the spinning direction clockwise:
      digitalWrite(dirPin, HIGH);
      String input= "NOW THE NOW THE AAAAA";
      // loop through the letters
      for (int i = 0; i < input.length(); i++) {
        // get the degree for each letter
        degree = mapLetterToDegree(input[i]);
        Serial.print("Letter: ");
        Serial.print(input[i]);
        Serial.print(" Degrees: ");
        Serial.println(degree);
        // wait for the movement to complete
        delay(1000);

      int p_new= map(degree,0,360,0,5373);
      Serial.print(" position: ");
      Serial.println(p_new);
      if (p!=NULL){
        mouvement=p_new-p;
        p=p_new;
      Serial.print(" mouvement: ");
      Serial.println(mouvement);
      }
      else{
        p = p_new;
      }
      if (mouvement<0){
        digitalWrite(dirPin, LOW);
        mouvement=abs(mouvement);
        Serial.println("change de direction");
      }
      Serial.print(" stepper: ");
      Serial.println(mouvement);

      // Spin the stepper motor 1 revolution slowly:
      for (int i = 0; i < mouvement; i++) {
        // These four lines result in 1 step:
        digitalWrite(stepPin, HIGH);
        delay(20);
        digitalWrite(stepPin, LOW);
        delay(20);
      }

      delay(1000);
      digitalWrite(dirPin, HIGH);
    }
    }

I tried following [this tutorial][4] and it works in broad terms **but sometimes the motor skips steps, especially when changing direction.**

I can't seem to understand how torque works within this system and how to minimise the stress I put on the motor.
My hypothesis is that since the system is at equilibrium and the friction is minimised due to the ball bearing, there should be no need for a lot of power from the motor, and that this motor should suffice.

My hypothesis of why steps are skipped:
- Too high a speed for the motor
- Not enough torque power supplied
- Not good enough electricity supply to the motor.

I am not sure how to go about and test these hypothesis and if those are correct.
I am also having a lot of trouble understanding the relationship between the time delay in the code and the movement of the motor.

Especially this bit:

      for (int i = 0; i < mouvement; i++) {
        // These four lines result in 1 step:
        digitalWrite(stepPin, HIGH);
        delay(20);
        digitalWrite(stepPin, LOW);
        delay(20);
      }

Is it ok to change them as I did? do they need to be symetrical (same delay for high and low)?

I am also looking for an explanation of how to apply acceleration and decceleration algorithms for stepper motor, even though I am not sure it makes sense at this speed.

**My questions are:**
- How to calculate the best speed for such a system and how to implement it?
- Is there need for acceleration/ decceleration?
- Does microstepping makes sense when using a gearbox?
- Are there some obvious flaws in my system/ code that I am missing out?

[![Arduino and Driver][5]][5]
[![stepper and ball bearing plate][6]][6]
[![Behaviour description][7]][7]
[![System description][8]][8]

  [1]: https://www.amazon.de/dp/B077YXF759?psc=1&ref=ppx_yo2ov_dt_b_product_details
  [2]: https://www.amazon.de/dp/B083V59HTB?psc=1&ref=ppx_yo2ov_dt_b_product_details
  [3]: https://www.amazon.de/dp/B0B98YSRQS?psc=1&ref=ppx_yo2ov_dt_b_product_details
  [4]: https://www.makerguides.com/a4988-stepper-motor-driver-arduino-tutorial/
  [5]: https://i.stack.imgur.com/gOyRh.jpg
  [6]: https://i.stack.imgur.com/zpbeT.jpg
  [7]: https://i.stack.imgur.com/r9STh.jpg
  [8]: https://i.stack.imgur.com/p4YUy.jpg

body:
> How to calculate the best speed for such a system and how to implement it?

There is no one best speed. This depends on your requirements, the motor torque with the supplied power and driver and the rotational inertia of the object on the motor axis. You can measure the rotational inertia and set yourself a value for the acceleration (even if you don't write the program for acceleration, it will accelerate on the first steps), that you want to have. Then you can check, if your motor has enough torque for this.

Speaking about the motor: Check the ratings of the motor. A good supplier should also give you information on how much torque your motor has at specific currents. Then check if your driver can handle the current (these small stick drivers often cannot handle much current, like 1 or 2A max). These drivers also have a small potentiometer on board, which controls the motor current. Your supplier should also provide information on how to set it correctly (by checking the voltage on one of the pins). You can even find information about this online, when you search for your type of driver. Setting this wrong can lead to either an underperforming motor or the motor overheating. So when setting the motor current with the potentiometer, check the motor temperature afterwards while it is running. Every motor has its own temperature rating, but I would suggest not letting it get too hot to touch.

Having done all above you can drive a test for checking motor speeds. Forget about your current code for a while. Just drive the motor with specific speeds, starting from only a few steps per second and going up until you notice the motor skipping. Then you know how fast you can drive the motor in your configuration without skipping and acceleration. If that is fast enough for you, you can just stick to that.

> Is there need for acceleration/ decceleration?

That depends on the above. If the non-skip speed is not fast enough, you can accelerate by gradually increasing the steps per second (aka decreasing the delay between step pulses). To halt at a specific position you then need to decelerate, so you need to plan the movement and control the steps per second accordingly. If you don't want to do that yourself I would suggest using the `AccelStepper` library. There you can set the target speed and the maximum acceleration and the library will then handle the motor for you.

You wrote in a comment, that you tried the `AccelStepper` library and that it didn't help. Though you didn't state how exactly it didn't help and what exactly you tried. Maybe you just didn't use the library correctly.

> Does microstepping makes sense when using a gearbox?

With microstepping you can get a smoother movement, though I doubt, that this is the problem here. Activating microstepping will of course mean, that you need to send more pulses to the driver for the same speed. Just keep that in mind.

> Is it ok to change them as I did? do they need to be symetrical (same delay for high and low)?

The first delay establishes the pulse for the driver. It needs to be big enough, that the driver recognizes the pulse. 20ms is very long for that. If you look at the datasheet of the your driver chip, there should be some information on that. I used a delay of about 50us in the past (so `delayMicroseconds(50)`), though you might even get shorter.

The second delay then handles the time between pulses, aka the speed of the motor. Though keep in mind, that the first delay is also still a constant in that equation. The speed in steps per second would then be `1/(delay1+delay2)` (ignoring the time for the execution of the rest of the code, because only relevant at high speeds).


message:
Arduino + HC-05 Problem: AT Commands are not working

Device: Laptop, HC-05, Resistor 2.2k and 4.7k, Arduino Uno R3

So im trying to rename and change password of my HC-05. for full detail schematic diagram. Here(the difference is, i also used the STATE Pin from HC-05 then connected it to Pin 9
since according to Instructubles it is used for activating AT Mode): [![enter image description here][1]][1]

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

Now for coding, i got it from Instructables.com and here: https://www.instructables.com/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/
or

    #include <SoftwareSerial.h>
    SoftwareSerial BTSerial(10, 11);
    #define Key 9
    void setup()
    {
      pinMode(Key, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(Key, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);  // HC-05 default speed in AT command more
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(BTSerial.available()){
        Serial.write(BTSerial.read());
      }

      if(Serial.available()){
        BTSerial.write(Serial.read());
      }
    }

The problem: i tried to follow the instructuble's instruction. but it didnt work. then i tried doing my own from what several tutorials i have read:
for the details,
1. i set my circuit and do the necessary wiring as shown in the picture + STATE Pin -> Arduino Pin 9.
2. I then connected my Arduino Uno to my Laptop, the HC-05 is blinking per half second, if you need the detail. Then uploaded the code...then finally, I opened the Serial Monitor(note that my HC-05 is not Paired to any devices in the first place. i "Forgot" them just incase).
3. then go to 9600 Monitor and enter simple command like **AT, AT+NAME? or AT+PSWD?** but nothing appeared in my terminal.
4. i also checked the 38400 monitor and did the same things. nothing happened.
5. then just maaaaybe it was just not showing but actually working, I tried AT+NAME=JULIE trying to rename my HC-05 to JULIE for each Terminal, going back and trying at 9600 then 38400. nothing happened at any Terminal. my HC-05 is still HC-05 name and the LED in my HC-05 are still blinking per half sec.

5. Then a bit annoyed, i then do a try-and-error. i tried to upload the code, then Paired it now, this time with my Phone. Then enter AT Commands in my Bluetooth Terminal App(from Playstore) and try to AT Command there. but still, nothing works.

My HC-05 is working as intended when i used it a simple LED on and off, and Servo using my Phone wirelessly few hours ago. But when i tried to do AT Command codes, nothing appears in my Serial Monitor such as the OK() or other AT Command replies.

so i would like to know where i did go wrong and why i cant use AT Command whether 9600, 38400 or even trying to do AT Command in my Phone's BT Terminal App? if you think i have missed an important details that i should mention, feel free to let me know.

body:
Ok, MAYBE I solved it^^ so the thing is, i noticed that my LED is still blinking intense instead of 2 sec light off and on. which means that i am still not in AT Mode.

but the thing is if i followed Instructables and other website tutorial. I SHOULD be able to be in AT Mode. im not exactly sure why im still not in AT Mode. So tried something:

the wiring/circuit is still THE SAME. but add something:
I took another wire, connect the **EN Pin of HC-05** **-> 5V of Arduino**.  since days ago i was trying to do tinker my HC-05 here and there and i remember that i tried to put EN in 5V then it start blinking differently. so i tried the same thing today. then i went back and Forget Paired Device, connect my Arduino to my Laptop, then reupload my code, then go to Serial.Monitor 9600 set **No Ending Line -> Both NL & CR**. then i reenter the AT Commands.

**AT+NAME?** then **AT**,then **AT+PSWD?**
all worked. the AT+Name shows the name of my HC-05, and the AT+PSWD shows the password. so then i decided to finally rename my HC-05.
**AT+NAME=USER_FAIZ** and **AT+PSWD=ARDUINO** individually in the Serial Monitor...and now my HC-05 has different name which is ***USER_FAIZ*** and password which is ***ARDUINO***. i then went to my Phone, scan for bluetooth device and there it is. USER_FAIZ and password is ARDUINO.

^^what im not really sure if it is the solution im searching for. i searched some tutorials again but none of them mention of using EN Pin and most of them use STATE Pin of HC-05.So because of that, i wont "Check" this Answer as maybe this is not the best solution out. maybe just not yet. but it did solve MY problem so it may solve other users problem too so ill add it here to inform.


message:
Why is my analog output limited to 2.7V?

I have an MKR WIFI1000 (v2.0 [Arduino:XYZ]) with a "real" analog output pin (DAC0/A0/PIN15). According to the documentation, this is a 10 bit DAC, so I assume I can write `analogWrite(15, 1023)` to have an output of 3.3V on that pin.

However, I don't seem to get it higher than 2.7V, which is already reached well before a value of 256.

This is my code:

    #include <Arduino.h>

    #define AN_OUTPUT 15

    int counter = 0;

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

    void loop ()
    {
      counter++;
      if (counter > 1023) {
        counter = 0;
      }

      analogWrite(AN_OUTPUT, counter);
      delayMicroseconds(1);
    }

And this is the corresponding signal:

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

  [1]: https://i.stack.imgur.com/qA4Ry.jpg

body:
[This link][1] had the answer, you have to **remove** the `pinMode(PIN, OUTPUT)` line.

  [1]: https://learn.adafruit.com/adafruit-feather-m0-basic-proto/adapting-sketches-to-m0


message:
Tools > Board settings: how are they captured?

In the Arduino IDE, the Tools menu can be used to make some board-specific settings like this:

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

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

... such as Processor Version = "Atmega168P", Processor Speed = "16MHz Crystal Resonator" and so on. These end up choosing fuses when burning a bootloader.  They may or may not also set constants that influence library behavior, I'm not sure.

What I'd like to know is how such settings stored, as they don't seem to be stored in any file associated with the sketch. And that being the case, they seem to be lost when using different boards or settings for subsequent projects.

So what files store these settings, at least temporarily, and how might one associate those settings more permanently with the project/sketch, so that they are repeatable later?

body:
The board settings from Tools menu are stored in the IDE preferences file.

You can open the file from the Preference dialog of the Arduino IDE. The path to the file is shown at the bottom of the dialog and it is clickable.


message:
How to power LILYGO ESP32-S3 1.9" T-Display without USB?

Noob question, I'm sure, but - I have one of these little LILYGO ESP32-S3 1.9" T-Display boards. Linked up with my PC, downloaded my code, runs fine, but I can't get the thing to power up from the 5v rail, or through a 5v supply through the li-po connector on the back, as I have with several other ESP32 boards.

Works fine through the USB-C connector, and I'm measuring 5v on the rail when it's running off the USB.

I assume I'm missing something really obvious to do with either booting without a USB being involved or something, but despite spending half a day hunting t'interwebs, and trying various things, I still can't get it to fire up with anything but a USB-C plugged in. I'm stumped!

(I have read something about attaching a capacitor to the "en" button on a different board in order to pull it to ground on boot, but this board has a reset switch which doesn't seem to reset anything unless attached to a USB supply so not sure if it applies in this case.)

This is the [product](https://www.aliexpress.com/item/1005004496543314.html?spm=a2g0o.productlist.main.5.23f638e32RICMa&algo_pvid=d7e12943-7bce-4ace-9582-581435aa9e06&algo_exp_id=d7e12943-7bce-4ace-9582-581435aa9e06-2&pdp_ext_f={"sku_id":"12000030128898262"}&pdp_npi=3@dis!GBP!17.34!17.34!!!!!@21021d7b16758432423558352d0688!12000030128898262!sea!UK!1871708403&curPageLogUid=vjPPTzDNlj1S) and an image of the pinout is [here](https://ae01.alicdn.com/kf/S49e0b5f973694c679760bff54b3e6ec2U.jpg
) in question.

Can anyone give me a nudge in the right direction please?

body:
For anyone that has the same issue, here's what I've found with the kind help of VolosProjects from YouTube:

Pin 15 needs to be set to HIGH (or 1) in order to boot.

    void setup()
    {
    pinMode(15, OUTPUT); // to boot with battery...
    digitalWrite(15,1);  // and/or power from 5v rail instead of USB
    ...
    }

Including the code above allows boot with either battery or power on the 5v pin. LILYGO also advised the same thing (and mentioned that pin 38 can be set to adjust LCD screen brightness).


message:
Strange Character In Tempurture Reading

Can anyone identify this character?
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/up4sj.jpg

body:
The degree sign (°) is Unicode character U+00B0 (i.e. code point 0xb0).
In UTF-8, it is encoded as the two-byte sequence 0xc2 0xb0. Your browser
is not aware that the page is encoded as UTF-8, and for some reason it
believed it is ISO-8859-1. This two-byte sequence, interpreted as
ISO-8859-1, represents the two characters “Â” and “°”.

The simplest solution might be to add

```html
<meta charset="utf-8">
```

at the top of the `<head>` element of the Web page.


message:
How to compile Arduino-ESP32 core with ESP_LOGx

**Why?**
In Arduino IDE you can set the core debug level, however, this only sets debug level for files in Arduino-esp32 but the core which is distributed as a precompiled library in .sdk files, located in your Arduinio installation folder, is unaffected - the debug level remains the default “error”.

body:
**What?**
If you want to change the core code or debug level, you need to clone the repo: [https://github.com/espressif/esp32-arduino-lib-builder](https://github.com/espressif/esp32-arduino-lib-builder), make the modifications there, compile and apply the changes (automatically by the build script).

**How?**
There are 2 basic approaches. Both of them involve editing file `esp32-arduino-lib-builder/configs/defconfig.common`.

The first option is to edit the file directly and then build.
Later you can `git restore configs/defconfig.common` to go back.

The second option is to copy the file `cp configs/defconfig.common configs/defconfig.debug`, edit the debug version and then compile.

Open the defconfig file
`vim configs/defconfig.common` or `vim configs/defconfig.debug`

Edit `line 45` containing by default `CONFIG_LOG_DEFAULT_LEVEL_ERROR=y` to one of the following lines depending on your desired log level:
```
CONFIG_LOG_DEFAULT_LEVEL_NONE=y # No output
CONFIG_LOG_DEFAULT_LEVEL_ERROR=y # Errors - default
CONFIG_LOG_DEFAULT_LEVEL_WARN=y # Warnings
CONFIG_LOG_DEFAULT_LEVEL_INFO=y # Info
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y # Debug
CONFIG_LOG_DEFAULT_LEVEL_VERBOSE=y # Verbose - All of the above
```
Then simply build the libs for all SoCs or one specific SoC. Note that building for all SoCs takes a lot of time, so if you work only with one specific SoC, build only for that one.
If you have copied the defconfig file and the debug settings are in file `configs/defconfig.debug` add flag `debug`
example : `./build.sh debug`
Build all SoCs: `./build.sh`
Build only selected SoC: `./build.sh -t <soc>`
The exact text to choose the SoC:
- esp32
- esp32s2
- esp32c3
- esp32s3
Example: `./build.sh -t esp32`
A wrong format or non-existing SoC will result in the error `sed: can't read sdkconfig: No such file or directory`


message:
variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type

I have a problem with lcd, I have  NUCLEO64 L746RG , I have Lcd Display and I2C connected to it.
When I verify code it gives me and long error and I can not find the solution or cause of this error:

    In file included from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l4xx.h:149,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/stm32/stm32_def.h:48,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/stm32/clock.h:19,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/wiring_time.h:23,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/wiring.h:38,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/Arduino.h:36,
                     from C:\Users\User\AppData\Local\Temp\arduino-sketch-B028C48DF91C28F6EAA5B0CE34D27EE2\sketch\Displaylcd1.ino.cpp:1:
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected identifier before '(' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
      169 | class LCD : public Print
          |       ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                              ~            ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
      169 | class LCD : public Print
          |       ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ~             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
      169 | class LCD : public Print
          |       ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected class-name before '(' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected '{' before '(' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                              ~            ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ~             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\Documents\Arduino\Displaylcd1\Displaylcd1.ino:2:22: error: variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type
        2 | LiquidCrystal_I2C lcd(0x27,16,2);  /*I2C scanned address defined + I2C screen size*/
          |                      ^
    Multiple libraries were found for "LiquidCrystal_I2C.h"
      Used: C:\Users\User\Documents\Arduino\libraries\LiquidCrystal
      Not used: C:\Users\User\Documents\Arduino\libraries\LiquidCrystal_I2C
    exit status 1

    Compilation error: variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type

This is my code:

    #include <LiquidCrystal_I2C.h>  /*include LCD I2C Library*/
    LiquidCrystal_I2C lcd(0x27,16,2);  /*I2C scanned address defined + I2C screen size*/
    void setup() {
      lcd.init();  /*LCD display initialized*/
      lcd.clear();     /*Clear LCD Display*/
      lcd.backlight();      /*Turn ON LCD Backlight*/
      lcd.setCursor(2,0);   /*Set cursor to Row 1*/
      lcd.print("I2C LCD Nano"); /*print text on LCD*/
      lcd.setCursor(2,1);   /*set cursor on row 2*/
      lcd.print("Linuxhint.com"); /*print message on LCD*/
    }
    void loop() {
    }

I do not know why, I am not including anything else so why is it giving me this error?

PLEASE HELP, I AM WORKING ON IT for 8 hours AN I STILL COULD NOT FIGURE OUT WHAT IS THE PROBLEM, PLease help

body:
Normally I wouldn't answer this, but the error is not exactly in your code but (seemingly at least) in two common things in the Arduino ecosystem.

**Roughly speaking, the library you're trying to use is incompatible with the STM32 board support you're using.**

The error message sort of tells this. It may help to read it backwards:

```
<sketchbook>\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
  169 | class LCD : public Print
      |       ^~~
```

So, it is in your installed LiquidCrystal library trying to process the definition of the LCD class, and having a problem with `LCD`, or rather `in expansion of macro 'LCD'`.  So, there's macro called LCD that it's trying to expand at that point, which should be a red flag.

The top part is where the compiler proper is having issues with the macro expansion where it causes a more fundamental error, `error: expected identifier before '(' token`  This is because it is trying to insert the macro definition directly into where it has found it resulting in this code effective after preprocessing:
```c++
class ((LCD_TypeDef *) LCD_BASE) : public Print
```
which is gibberish. It's pointing to the first open parenthesis there and saying `expected identifier`, the `identifier` being the class name it expected to see, not this cast and other stuff that follows. Whoever wrote your LiquidCrystal library did not expect `LCD` to already be defined as something via macro. This is one of a number of reasons why macros are hated.

The bulk of this is indicating the how the macro got to where it came from to where it wound up. The macro started in `stm32l4xx.h` in CMSIS and wound it's way into the LiquidCrystal header through Arduino.h and everything in between:

```c++
In file included from <Arduino15>\<STM32boardSupport>\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l4xx.h:149,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/stm32/stm32_def.h:48,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/stm32/clock.h:19,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/wiring_time.h:23,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/wiring.h:38,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/Arduino.h:36,
                 from <Temp>\arduino-sketch-B028C48DF91C28F6EAA5B0CE34D27EE2\sketch\Displaylcd1.ino.cpp:1:
```

To oversimply a bit CMSIS is the semi-standard header files that ARM chip makers are supposed to provide that among other things define hardware registers. Although I haven't investigated it, it seems likely that whatever chip you're using has a built in LCD driver, and so there are things, macros namely, that have "LCD" in the name. Unfortunately for you, one just called LCD.

You could try renaming all of the uses all of the uses of `LCD` within the LiquidCrystal library that you have to some other name. Or you could try inserting `#undef LCD` after the include of Arduino.h in the LCD.h header in an attempt to undefined the macro so that the LCD in the class definition is not expanded. But, I would be looking for different versions of the library and making sure the library is even the one you think it is, because everyone and their dog seems to have made some library called LiquidCrystal at some point or another. It would be a pity if you went through all trouble to find out you weren't even looking at the right library.


message:
WS2812b - Interpolate pixels on neopixel matrix with mask

simplified my goal is to display a transitional Background and some shapes. This shapes are not moving hard rasterized by 1 pixel, more like .1 each cycle. So I need a way to interpolate the movement between the surrounding Neopixels.

Background works fine, so it's not relevant for now.

For the shapes the **first try** was to show a smooth movement of a square hardcoded. This works suitable, even its not bug free. I put the Code of the first attempt at the very end.

**After** that I wanted to implement an bitmap mask to show something more complex . That's where I am at currently. First of this attempt is to assume the whole mask is completly filled (again hardcoded).

The LEDs mostly keep completely on or off.

How do I get them fade them in an out at the outer sides?

I use an AI Thinker ESP 32 and 200 WS2812Bs.

Please ask any more infos that are required. Of course if you spot that my approach is unsuitable to begin with, pls tell me.

Infos for the Code: don't get lost on the "circle" variables. At the eary steps I showed a circle and soon realized its easier to step back to a Circle while working at the interpolation.

My Code with the bitmap
```
#include <Adafruit_NeoPixel.h>

#define PIN_NEO_PIXEL  13
#define NUM_PIXELS     400
#define num_row 20
#define num_col 20
#define circle_size_body 4
#define circle_size_border 5
#define circle_size_corona 7
#define DELAY_INTERVAL  100

float circle_PosX = 10;
float circle_PosY = 10;
int circle_direction = 1;
enum eIntersectingPart { None, Body, Border, Corona };

Adafruit_NeoPixel NeoPixel(NUM_PIXELS, PIN_NEO_PIXEL, NEO_GRB + NEO_KHZ800);

void setup()
{
  NeoPixel.setBrightness(100);
  NeoPixel.begin();
  Serial.begin(115200);           // set up Serial library at 9600 bps
}

float backgroundShift = 0;
float worldSpeed = .05;

void loop()
{
  if(circle_PosY <= 0 && circle_direction < 0
     || circle_PosY >= 10 && circle_direction > 0)
    circle_direction *= -1;
  circle_PosY += worldSpeed * circle_direction;
  circle_PosX += worldSpeed * circle_direction;
    Serial.print("circle_PosX ");
    Serial.print(circle_PosX);
    Serial.print(", circle_PosY ");
    Serial.print(circle_PosY);
 NeoPixel.clear();
    //Hintergrund setzen
    // setBackgroundColor();

 //Kreis malen
 drawCircle();

  // Serial.print("bgShift: ");
  // Serial.flush();
  NeoPixel.show(); // send the updated pixel colors to the NeoPixel hardware.
  // Serial.println(backgroundShift);
  backgroundShift += worldSpeed;
  delay(100);     // off time
}

uint32_t setBackgroundColor() {

  for(int led = 0; led < NUM_PIXELS; led++) {
    int coordinates[2];
    coordinateByLed(coordinates, led);

 byte ambientColors[3] = { 0, 0, 255 };
    int ambientCcolorS = (int)( sin( 0.3 * coordinates[0] + backgroundShift) * 127.0 );
    int ambientCcolorC = (int)( cos( 0.3 * coordinates[1] + backgroundShift) * 128.0);
    int amberC = (ambientCcolorS + ambientCcolorC + 255) / 2;

    NeoPixel.setPixelColor(
        led,
        NeoPixel.Color(amberC, amberC ,255));
  }
}

bool firstIteration = false;
void drawCircle() {
 //   x     y       Anteil
 byte bitmap[circle_size_corona + 1][circle_size_corona + 1];

 float startPositonX = circle_PosX - .5f * (float)circle_size_corona;
 float startPositonY = circle_PosY - .5f * (float)circle_size_corona;

 int lowerStartX = floor(startPositonX);
 int upperStartX = ceil(startPositonX);
 int lowerStartY = floor(startPositonY);
 int upperStartY = ceil(startPositonY);

 float proportionForLowerX = abs(upperStartX - startPositonX);
 float proportionForUpperX = 1 - proportionForLowerX;
 float proportionForLowerY = abs(upperStartY - startPositonY);
 float proportionForUpperY = 1 - proportionForLowerY;

 firstIteration = true;

 for(byte x = 0; x < circle_size_corona; x++) {
  for(byte y = 0; y < circle_size_corona; y++) {
   float proportion = 0;

   int lowerLedX = lowerStartX + x;
   int lowerLedY = lowerStartY + y;
   int upperLedX = upperStartX + x;
   int upperLedY = upperStartY + y;

   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
    byte currentX = x;
    byte currentY = y;
    proportion = proportionForLowerX * proportionForLowerY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);

    if(lowerLedX == 6 && lowerLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
    byte currentX = x + 1;
    byte currentY = y;
    proportion = proportionForUpperX * proportionForLowerY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    if(upperLedX == 6 && lowerLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }
   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
    byte currentX = x;
    byte currentY = y + 1;
    proportion = proportionForLowerX * proportionForUpperY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    if(lowerLedX == 6 && upperLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
    byte currentX = x + 1;
    byte currentY = y + 1;
    proportion = proportionForUpperX * proportionForUpperY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    if(upperLedX == 6 && upperLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }

   firstIteration = false;
  }
 }

 firstIteration = true;
 for(int x = 0; x < circle_size_corona + 1; x++) {
  for(int y = 0; y < circle_size_corona + 1; y++) {
   int lowerLedX = lowerStartX + x;
   int lowerLedY = lowerStartY + y;
   int upperLedX = upperStartX + x;
   int upperLedY = upperStartY + y;

   if(
   // firstIteration
    lowerLedX == 6 && lowerLedY == 6
                  ||
     upperLedX == 6 && lowerLedY == 6) {
    Serial.print(", startPositonX ");
    Serial.print(startPositonX);
    Serial.print(", x ");
    Serial.print(x);
    Serial.print(", y ");
    Serial.print(y);
    Serial.print(", lowerLedX ");
    Serial.print(lowerLedX);
    Serial.print(", lowerLedY ");
    Serial.print(lowerLedY);
   }

   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
    setLedColorWithProportion(lowerLedX,lowerLedY, .01f * bitmap[x][y]);
   }

   firstIteration = false;
  }
 }

 Serial.print(" ");
 Serial.println();
}

void setLedColorWithProportion(
 int coordX, int coordY,
 float proportion)
{
 int led = ledByCoordinate(coordX, coordY);
 uint32_t ledColor = NeoPixel.getPixelColor(led);
 uint8_t partialColor = (uint8_t)((proportion ) * 255.0f );

 uint8_t white = (ledColor>>24) & 255;
 uint8_t red = (uint8_t)((1.0f - proportion) * ((ledColor>>16) & 255))
  + partialColor;
 uint8_t green = (ledColor>>8) & 255;
 uint8_t blue = ledColor & 255;

 if(
 // firstIteration
 coordX == 6 && coordY == 6
 ) {
  Serial.print(", prop ");
  Serial.print(proportion);
  Serial.print(", redValOld ");
  Serial.print(((ledColor>>16) & 255));
  Serial.print(", redValNew ");
  Serial.print(red);
 }

 ledColor = white;
 ledColor = (ledColor<<8) + red;
 ledColor = (ledColor<<8) + green;
 ledColor = (ledColor<<8) + blue;
 NeoPixel.setPixelColor(
  led,
  ledColor);
}

int ledByCoordinate(byte column, byte row) {
  return (row  * num_col) + (column);
}

void coordinateByLed(int coordinates[2], int led) {
  coordinates[0] = led % num_col;
  coordinates[1] = led / num_col;
}

```
[![neoopixel][1]][1]

---

First attempt without bitmap
```
#include <Adafruit_NeoPixel.h>

#define PIN_NEO_PIXEL  13
#define NUM_PIXELS     400
#define num_row 20
#define num_col 20
#define circle_size_body 4
#define circle_size_border 5
#define circle_size_corona 7
#define DELAY_INTERVAL  100

float circle_PosX = 10;
float circle_PosY = 10;
int circle_direction = 1;
enum eIntersectingPart { None, Body, Border, Corona };

Adafruit_NeoPixel NeoPixel(NUM_PIXELS, PIN_NEO_PIXEL, NEO_GRB + NEO_KHZ800);

void setup()
{
  NeoPixel.setBrightness(100);
  NeoPixel.begin();
  Serial.begin(9600);           // set up Serial library at 9600 bps
}

float backgroundShift = 0;
float worldSpeed = .01;

void loop()
{
  if(circle_PosY <= 0 && circle_direction < 0
     || circle_PosY >= 10 && circle_direction > 0)
    circle_direction *= -1;
  circle_PosY += worldSpeed * circle_direction;
  circle_PosX += worldSpeed * circle_direction;
    // Serial.print("circle_PosX ");
    // Serial.print(circle_PosX);
    // Serial.print(", circle_PosY ");
    // Serial.print(circle_PosY);
 NeoPixel.clear();
    //Hintergrund setzen
    // setBackgroundColor();

 //Kreis malen
 drawCircle();

  // Serial.print("bgShift: ");
  // Serial.flush();
  NeoPixel.show(); // send the updated pixel colors to the NeoPixel hardware.
  // Serial.println(backgroundShift);
  backgroundShift += worldSpeed;
  //delay(100);     // off time
}

uint32_t setBackgroundColor() {

  for(int led = 0; led < NUM_PIXELS; led++) {
    int coordinates[2];
    coordinateByLed(coordinates, led);

 byte ambientColors[3] = { 0, 0, 255 };
    int ambientCcolorS = (int)( sin( 0.3 * coordinates[0] + backgroundShift) * 127.0 );
    int ambientCcolorC = (int)( cos( 0.3 * coordinates[1] + backgroundShift) * 128.0);
    int amberC = (ambientCcolorS + ambientCcolorC + 255) / 2;

    NeoPixel.setPixelColor(
        led,
        NeoPixel.Color(amberC, amberC ,255));
  }
}

bool firstIteration = false;
void drawCircle() {
 float startPositonX = circle_PosX - .5f * (float)circle_size_corona;
 float startPositonY = circle_PosY - .5f * (float)circle_size_corona;

 int lowerStartX = floor(startPositonX);
 int upperStartX = ceil(startPositonX);
 int lowerStartY = floor(startPositonY);
 int upperStartY = ceil(startPositonY);

 float proportionForLowerX = abs(upperStartX - startPositonX);
 float proportionForUpperX = 1 - proportionForLowerX;
 float proportionForLowerY = abs(upperStartY - startPositonY);
 float proportionForUpperY = 1 - proportionForLowerY;

 // int endX = lowerStartX + circle_size_corona;
 // int endY = lowerStartY + circle_size_corona;

 firstIteration = true;

 for(int x = 0; x < circle_size_corona; x++) {
  for(int y = 0; y < circle_size_corona; y++) {
   int lowerLedX = lowerStartX + x;
   int lowerLedY = lowerStartY + y;
   int upperLedX = upperStartX + x;
   int upperLedY = upperStartY + y;

   /*if(firstIteration) {
    Serial.print(", startPositonX ");
    Serial.print(startPositonX);
    Serial.print(", x ");
    Serial.print(x);
    Serial.print(", y ");
    Serial.print(y);
    Serial.print(", lowerLedX ");
    Serial.print(lowerLedX);
    Serial.print(", lowerLedY ");
    Serial.print(lowerLedY);
   }*/

   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
     setLedColorWithProportion(lowerLedX,lowerLedY, proportionForLowerX * proportionForLowerY);
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
     setLedColorWithProportion(upperLedX,lowerLedY, proportionForUpperX * proportionForLowerY);
   }
   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
     setLedColorWithProportion(lowerLedX,upperLedY, proportionForLowerX * proportionForUpperY);
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
     setLedColorWithProportion(upperLedX,upperLedY, proportionForUpperX * proportionForUpperY);
   }

   firstIteration = false;
  }
 }
 // Serial.print(" ");
 // Serial.println();
}

void setLedColorWithProportion(
 int coordX, int coordY,
 float proportion)
{
 int led = ledByCoordinate(coordX, coordY);
 uint32_t ledColor = NeoPixel.getPixelColor(led);
 uint8_t partialColor = (uint8_t)((proportion ) * 255.0f );

 uint8_t white = (ledColor>>24) & 255;
 uint8_t red = (uint8_t)((1.0f - proportion) * ((ledColor>>16) & 255))
  + partialColor;
 uint8_t green = (ledColor>>8) & 255;
 uint8_t blue = ledColor & 255;

 ledColor = white;
 ledColor = (ledColor<<8) + red;
 ledColor = (ledColor<<8) + green;
 ledColor = (ledColor<<8) + blue;
 NeoPixel.setPixelColor(
  led,
  ledColor);
}

int ledByCoordinate(byte column, byte row) {

 /*if(firstIteration) {
  Serial.print(", column ");
  Serial.print(column);
  Serial.print(", row ");
  Serial.print(row);
  Serial.print(", ergebis ");
  Serial.print(((row  * num_col) + (column)));
 }*/
  return (row  * num_col) + (column);
}

void coordinateByLed(int coordinates[2], int led) {
  coordinates[0] = led % num_col;
  coordinates[1] = led / num_col;
}
```

  [1]: https://i.stack.imgur.com/j4XN5.jpg

body:
thanks for your advice. I stepped back to a 1D model, simplified, altered and it worked, with complex models (in 1D XD), a hard coded Array. So finally I went on for 2D and extended the code. Now it works.

Yes, it's kind of anti-aliasing.

For next I am thinking how to display multiple Elements with transparency (caused by anti aliasing or pregiven transparency).

Thats all for now.

For all who may be interested, heres my current Code.

    #include <Adafruit_NeoPixel.h>

    #define PIN_NEO_PIXEL  13
    #define NUM_PIXELS     200
    #define num_col 20
    #define num_row 10
    #define DELAY_INTERVAL  100

    float circle_PosX = 6;
    float circle_PosY = 6;
    int circle_direction = 1;

    Adafruit_NeoPixel NeoPixel(NUM_PIXELS, PIN_NEO_PIXEL, NEO_GRB + NEO_KHZ800);

    void setup()
    {
      NeoPixel.setBrightness(255);
      NeoPixel.begin();
      // Serial.begin(115200);           // set up Serial library at 9600 bps
    }

    float worldSpeed = .01;

    void loop()
    {
     if(circle_PosX <= 0 && circle_direction < 0
      || circle_PosX >= 20 && circle_direction > 0
      || circle_PosY <= 0 && circle_direction < 0
      || circle_PosY >= 10 && circle_direction > 0)
     circle_direction *= -1;
     circle_PosX += worldSpeed * circle_direction;
     circle_PosY += worldSpeed * circle_direction;

     NeoPixel.clear();

     //Kreis malen
     drawCircle();

     NeoPixel.show(); // send the updated pixel colors to the NeoPixel hardware.
     // delayMicroseconds(500);     // off time
     // readInput();
    }
    uint8_t bitmap[5][5] = {
     {0,0,1,0,0},
     {0,1,0,1,0},
     {1,0,0,0,1},
     {0,1,0,1,0},
     {0,0,1,0,0},
    };

    void drawCircle() {
     for(uint8_t pixelX = 0; pixelX < 5; pixelX++) {
      for(uint8_t pixelY = 0; pixelY < 5; pixelY++) {
       if(bitmap[pixelY][pixelX] == 1) {
        writeCircleToLEDs(
         pixelX + circle_PosX,
         pixelY + circle_PosY);
       }
      }
     }
    }

    uint8_t writeCircleToLEDs(float circlePosX, float circlePosY) {
     int lowerLedX = floor(circlePosX);
     int upperLedX = ceil(circlePosX);
     int lowerLedY = floor(circlePosY);
     int upperLedY = ceil(circlePosY);

     float upperLedXAmount = circlePosX - lowerLedX;
     float lowerLedXAmount = 1.0 - upperLedXAmount;
     float upperLedYAmount = circlePosY - lowerLedY;
     float lowerLedYAmount = 1.0 - upperLedYAmount;

     float amountLowerXLowerY = lowerLedXAmount * lowerLedYAmount;
     float amountUpperXLowerY = upperLedXAmount * lowerLedYAmount;
     float amountLowerXUpperY = lowerLedXAmount * upperLedYAmount;
     float amountUpperXUpperY = upperLedXAmount * upperLedYAmount;

     setColorOfLed(lowerLedX, lowerLedY, amountLowerXLowerY);

     // if(lowerLedX != upperLedX)
     {
      setColorOfLed(upperLedX, lowerLedY, amountUpperXLowerY);
     }
     // if(lowerLedY != lowerLedX )
     {
      setColorOfLed(lowerLedX, upperLedY, amountLowerXUpperY);
     }
     // if(lowerLedY != upperLedY )
     {
      setColorOfLed(upperLedX, upperLedY, amountUpperXUpperY);
     }
     /*
     Serial.print("circlePosX ");
     Serial.println(circlePosX);
     Serial.print("lowerLedX ");
     Serial.println(lowerLedX);
     Serial.print("lowerLedXAmount ");
     Serial.println(lowerLedXAmount);
     Serial.println("--------------------");*/

    }

    void setColorOfLed(uint8_t ledX, uint8_t ledY, float amount) {
     int ledNumber = ledByCoordinate(ledX, ledY);
     uint32_t  baseColor = NeoPixel.getPixelColor(ledNumber);
     uint8_t newRedColor = ((baseColor >> 16) & 255);
     newRedColor += (255 * amount);

     baseColor &= ~(255 << 16);
     baseColor |= (newRedColor << 16);

     NeoPixel.setPixelColor(
      ledNumber,
      baseColor);
    }

    uint8_t ledByCoordinate(uint8_t coordinateX, uint8_t coordinateY) {
     return coordinateX + num_col * coordinateY;
    }

    uint8_t rowReadPosY = 0;
    void readInput() {
     bool changed = false;
     uint8_t rowReadPosX = 0;

     while(Serial.available() > 0) {
      char input = Serial.read();

      if(!isDigit(input)) continue;

      bitmap[rowReadPosY][rowReadPosX] = atoi(&input);

      rowReadPosX++;
      if(rowReadPosX >= 5) {
       rowReadPosY = ++rowReadPosY % 5;
       rowReadPosX = 0;
      }

      changed = true;
     }

     if(changed) {
      Serial.println("Ergebnis: ");

      for(uint8_t pixelX = 0; pixelX < 5; pixelX++) {
       for(uint8_t pixelY = 0; pixelY < 5; pixelY++) {
        Serial.print(bitmap[pixelY][pixelX]);
       }
       Serial.println();
      }

      Serial.print("Aktueller Cursor: (x,y) {");
      Serial.print(rowReadPosX);
      Serial.print(", ");
      Serial.print(rowReadPosY);
      Serial.println("}");
     }
    }


message:
RGB LED randomized colors and LDR fading at the same time

Im trying too make an RGB LED that keeps changing color's randomly, and makes the brightness fade at the same time with an LDR, yet I keep getting an error that says too many arguments to functions.

could anyone possibly help me?

EDIT:
(this is the correct code sorry)

     const int LED_D_RGB_G_PIN = 11;
    const int LED_D_RGB_B_PIN = 10;
    const int LED_D_RGB_R_PIN = 9;
    const int LDR = A1;

    int inputval=0;
    int outval =0;

    void setup() {
      pinMode(LED_D_RGB_R_PIN, OUTPUT);
      pinMode(LED_D_RGB_G_PIN, OUTPUT);
      pinMode(LED_D_RGB_B_PIN, OUTPUT);
      pinMode(LDR, INPUT);

    }

    void loop() {
        inputval = analogRead(LDR);
        outval = map(inputval, 0, 380, 255, 0);

        int lightval = constrain(outval, 0,255);

        analogWrite(LED_D_RGB_R_PIN, lightval, random(0,255));
        analogWrite(LED_D_RGB_G_PIN, lightval, random(0,255));
        analogWrite(LED_D_RGB_B_PIN, lightval, random(0,255));
        delay (50);
    }

body:
I will assume that you can correct any errors in your code and I want to get at a suggestion for a possibly better approach to what I think that you are trying to do.

When you are setting the "color", you are setting the brightness of each of the LEDs; R,G,B, or at least you are trying to do that when you generate a random PWM using analogWrite https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/.

Then, you are trying to set the brightness again, presumably based on the ambient light value from the LDR AND it is set for the **combined** output of the 3 LEDs which are likely at different intensity values, since intensity was randomly chosen. The problem is, how can you scale the values perfectly so that you get the same color but at a lower intensity? I think that is much more difficult than you might believe...for a bunch of reasons.

I would suggest you try something along these lines, but keep some low expectations....

1. Use a variable called maxb, which changes the **maximum possible** value used in the analogWrite() values so that it it not always 255. You can adjust that value based on reading the LDR. You will have to do some experimenting and don't expect a huge range of values. Now, your color will still be picked at random, but with an adjustment for intensity.

2. You *"should"* try to use resistors on each of the RGB LEDs that will produce something close to equivalent brightness. This will vary somewhat between RGB LEDs. Below is a graph of where I looked at this for a color fader project many years ago. I used an old BH1750 ambient light sensor to get the lux values. That dashed line is for the equivalent brightness of the individual LEDs by resistor value (ohms) used [220-Red, 750-Green, 470-Blue]. This is not an ideal way, but it is easy.

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

3. That might get you near where you want to be, but for "extra credit", note that brightness scaling is not an equal interval scale. So, a PWM value of 250 is NOT 10 times brighter than a PWM value of 25. Brightness is, more or less, on an exponential scale except for very dim values, which are, again, more-or-less, linear. Look into the CIE 1931 perceived lightness formula and Weber and Stevens and so on. Since this is not a psychophysics lab, let me cut to the chase. The array below represents an intensity scale as I have described and includes values of 0 and 255 as per an 8 bit width (which is what analogWrite uses). You could use a minimum value of 4 or 8 instead of 0 if you wanted to guarantee a visible output every time. Test that out, but for the sake of discussion, let's assume you are using all values in the array.

A[13]{0,1,2,4,8,17,32,51,75,106,145,194,255};

You would scale your LDR range to 13 possible values (0-12) and then get your maximum value for analogWrite from the array. Then, you would pick a random value for 0 to maxb for each of your analogWrites to the RGB.

4. I don't know how brightness is represented by your LDR and you should consider that when you are determining your ambient light intensity values - ideally, you would want 13 equal intensity values from your LDR - right?. I suppose something about that is probably in the data sheet.

That is how I would do it anyways :)

  [1]: https://i.stack.imgur.com/hQOLq.jpg


message:
Can the Arduino Uno use a negative supply voltage (0V & -5V)

I acquired a bread-making machine. See control board image.
I want to use the machine for other purposes and control the buttons, paddle, heater & 7-segment display with an Uno.
As it stands, the machine provides 0V, -5V & -11V to the control board.

Is it possible to connect 0V to Uno VIN and -5V to Uno GND pins?

My initial idea was to replace the PENTALPHA-BV30K with an Uno and mapping the pins accordingly. I couldn't find any datasheet for the BV30K, however I'm reverse engineering the control board anyway.

Control board findings:
 - -11V is used to drive the A/B/C/D/E/F/G/DP segments of the LED display
 - BV30K only uses 0V & -5V

[![bread machine control board][1]][1]

I added an image of the transformer based power supply board so that I could check the supply there. The larger heatsink is for the 7905 IC and the smaller heatsink is for the BTA06 Triac.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/MmJ5c.jpg
  [2]: https://i.stack.imgur.com/wP2e9.jpg

body:
As you describe the system, you can connect the system's ground to 5V of the Uno, and the system's -5V to Uno's ground.

Please note that you cannot reverse-feed 5V through the pin with the same label, it is an output. You can use the USB connector. You might want to solder wires at its pins instead of cannibalizing an old USB cable. Alternatively you can try VIN, as there is a LDO, but measure the resulting voltage. The specification demands at least 7V there.

If you want to power the Uno during development by the USB connection, you can disconnect any of -5V or ground, but not both, because you need a reference connection.

In contrast, you cannot use the -11V supply and use VIN and GND of the Uno, because the Uno's voltage regulator uses the lower level as reference and will set Uno's "high" (5V) to about -6V with reference to the system's ground. See:

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

---

Concerning the separation of power-line and the controller: Well, I'm just worrying about your health.

If you are sure that all is done well, go ahead. With a working separation you can even dare to connect the development PC to your Uno while the power-line is connected.

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


message:
Setting pinmode() in header file

I am trying to have a header file to handle all my pin definitions and pinmodes.

This is the header:

    #ifndef __HEADER_TESTER__
    #define __HEADER_TESTER__

    #include <SoftwareSerial.h>
    const byte rxPin = 2;
    const byte txPin = 3;
    SoftwareSerial mySerial(rxPin, txPin);

    pinMode(LED_BUILTIN, OUTPUT);

    #endif

However, when I compile this, I get an error on the `pinMode(LED_BUILTIN, OUTPUT);` line:

    expected constructor, destructor, or type conversion before '(' token

body:
The `pinMode()` statement is executable code and can not be executed outside of a function - setup(), loop(), or some other function defined by you. One could imagine defining a function in your header (.h) file to set your pin modes but defining code in a header will cause a different kind of problem (multiple definitions) if you ever add another code module, a .cpp file, for instance, that also includes this same .h file.

Pin modes are usually set in the setup() function, once per execution of the sketch. There really isn't much value to having them in the .h file. If it is for documentation purposes, you could #define in the .h file, a symbol that expands to all of the pinMode() calls you need, then write that symbol at the appropriate place in your setup() function where it's expansion will be syntactically correct. This would accomplish the documentation, but at the cost of a reader of your code having to search for the definition of that symbol to find out what code is being executed there. That's pretty roundabout for what seems like little to no gain.