# Question
Title: Sketch uses 33218 bytes (102%) of program storage space. Maximum is 32256 bytes?
I need to upload code on atmega328 wihout bootloader
https://github.com/EasyOne2030/test but see Sketch uses 33218 bytes (102%) of program storage space. Maximum is 32256 bytes ?

# Answer
In the case where the size of the program (sketch) has become too large for the available program storage space (flash memory), there are a number of options. Note that this is not the same case as exceeding the amount of dynamic memory (RAM) which requires a different set of solutions.

**\_1. Microcontroller (MCU) upgrade.**

This can be a solution. The closer the architecture of the new MCU matches that that of the old MCU the easier this is likely to be. However, this approach can become complex, even when using a different MCU in the same series as the original, if low level configuration of (and access to) hardware peripherals such as timers, ports etc. has been used. Be aware that any libraries used may not be compatible with the new MCU so testing is important. In the worst case, there may be no supporting Arduino core available for the new MCU. Major incompatibilities can be tested with a simple compilation of a sketch for the new target MCU and this does not even require the new MCU to be present.

In the specific case of the ATmega328P, this is already the highest specified MCU in its series so a new MCU is required to increase resources such as Flash memory, RAM etc. An ATMega1284 may be a possible replacement within the AVR range. Also to consider is an ATmega4809 (newer megaAVR range) based board such as the Nano Every but here there are more significant architectural differences

**\_2. Optimising the use of flash memory.**

**\_2.1 Bootloader.**

Sometimes, changing the bootloader for a smaller one can help. For example, with some Arduino Nanos, this can free 1.5KB of flash memory by changing to the same bootloader which is used on the Arduino Uno (Optiboot). Dropping the bootloader altogether and using an ISP programmer (or an Arduino configured as one) to program the MCU can also save flash memory. Here it is important to select an Arduino core which supports a "No Bootloader" option to achieve the maximum benefits from this approach. The core "Minicore" https://github.com/MCUdude/MiniCore is such an example. Important to note is the the Arduino IDE (base 1.8.19) has a special upload procedure when using a programmer (Sketch--\> Upload using programmer). Note also that the target (AVR) MCU must have the fuses correctly set for "no bootloader" operation. That is the fuse BOOTRST must be unset. This is achieved by using the "burn bootloader" option supplied by the core. Despite its (inappropriate) name this has the effect of setting the fuses. Alternatively, the fuses can be set manually using the AVRDUDE command line.

**\_2.2 General.**

The compiler is quite good at optimising code however, it is important to be aware that the use of some program features can have a one time penalty when used. Examples are the String class, sprintf(), floating point handling etc. which force a large amount of code to be added to the compiled sketch. Some libraries can consume a large amount of program memory. Graphic libraries are notorious for this because often these include large font tables etc. Here the options are limited to looking for a lighter weight library or a hacking out unused parts of an existing library.
> 3 votes

# Answer
**Using Minicore to compile and load a program onto an ATmega328P without a bootloader. Screen shots and sample output.**

Resources used

1. CH340 ATmega328P Arduino Nano clone
2. A programmer (Nano based) running the Arduino ISP sketch
3. Minicore 2.1.3 https://github.com/MCUdude/MiniCore
4. Arduino IDE 1.8.19

```
/*
   Example sketch to use all flash memory of an ATmega328P
*/

const uint8_t bigArray[30121] PROGMEM = {0} ;

void setup() {
  Serial.begin( 115200 ) ;
  Serial.println("test-01" ) ;
  byte buffer = pgm_read_byte_near(bigArray+50); // stop compiler optimising the array away
  Serial.println(buffer ) ;
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

**Select Board**

**Select Programmer**

**Select No Bootloader**

**Verify**

**Burn Bootloader /set fuses**

Yes, even though you don't want a boot loader, you have to do this to correct the fuses (specifically, BOOTRST is unset by this procedure)

```
. . .
. . .
Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0f:
avrdude: load data lock data from input file 0x0f:
avrdude: input file 0x0f contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

avrdude done.  Thank you.

```

**Upload Using Programmer**

```
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\hardware -hardware C:\Users\6v6gt\Documents\ArduinoData\packages -hardware C:\Users\6v6gt\Documents\Arduino\hardware -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\tools-builder -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\hardware\tools\avr -tools C:\Users\6v6gt\Documents\ArduinoData\packages -built-in-libraries C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\libraries -libraries C:\Users\6v6gt\Documents\Arduino\libraries -fqbn=MiniCore:avr:328:bootloader=no_bootloader,eeprom=keep,variant=modelP,BOD=2v7,LTO=Os,clock=16MHz_external -vid-pid=1A86_7523 -ide-version=10819 -build-path C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964 -warnings=all -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino18 -prefs=runtime.tools.avrdude-6.3.0-arduino18.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino18 -prefs=runtime.tools.arduinoOTA.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.avr-gcc.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -verbose C:\Users\6v6gt\Documents\Arduino\big_flash_V0_01\big_flash_V0_01.ino
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\arduino-builder -compile -logger=machine -hardware C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\hardware -hardware C:\Users\6v6gt\Documents\ArduinoData\packages -hardware C:\Users\6v6gt\Documents\Arduino\hardware -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\tools-builder -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\hardware\tools\avr -tools C:\Users\6v6gt\Documents\ArduinoData\packages -built-in-libraries C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\libraries -libraries C:\Users\6v6gt\Documents\Arduino\libraries -fqbn=MiniCore:avr:328:bootloader=no_bootloader,eeprom=keep,variant=modelP,BOD=2v7,LTO=Os,clock=16MHz_external -vid-pid=1A86_7523 -ide-version=10819 -build-path C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964 -warnings=all -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino18 -prefs=runtime.tools.avrdude-6.3.0-arduino18.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino18 -prefs=runtime.tools.arduinoOTA.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.avr-gcc.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -verbose C:\Users\6v6gt\Documents\Arduino\big_flash_V0_01\big_flash_V0_01.ino
Using board '328' from platform in folder: C:\Users\6v6gt\Documents\ArduinoData\packages\MiniCore\hardware\avr\2.1.3
Using core 'MCUdude_corefiles' from platform in folder: C:\Users\6v6gt\Documents\ArduinoData\packages\MiniCore\hardware\avr\2.1.3
Detecting libraries used...
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++17 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_ATmega328 -DARDUINO_ARCH_AVR "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\cores\\MCUdude_corefiles" "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\variants\\standard" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\sketch\\big_flash_V0_01.ino.cpp" -o nul
Generating function prototypes...
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++17 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_ATmega328 -DARDUINO_ARCH_AVR "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\cores\\MCUdude_corefiles" "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\variants\\standard" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\sketch\\big_flash_V0_01.ino.cpp" -o "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\preproc\\ctags_target_for_gcc_minus_e.cpp"
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -Wall -Wextra -std=gnu++17 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_ATmega328 -DARDUINO_ARCH_AVR "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\cores\\MCUdude_corefiles" "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\variants\\standard" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\sketch\\big_flash_V0_01.ino.cpp" -o "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\sketch\\big_flash_V0_01.ino.cpp.o"
Compiling libraries...
Compiling core...
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -c -g -x assembler-with-cpp -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_ATmega328 -DARDUINO_ARCH_AVR "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\cores\\MCUdude_corefiles" "-IC:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\variants\\standard" "C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\MiniCore\\hardware\\avr\\2.1.3\\cores\\MCUdude_corefiles\\wiring_pulse.S" -o "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring_pulse.S.o"
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\hooks.c.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\WInterrupts.c.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\wiring.c.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\wiring_shift.c.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\wiring_digital.c.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\wiring_analog.c.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\wiring_pulse.c.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\CDC.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\HardwareSerial1.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\HardwareSerial2.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\HardwareSerial.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\IPAddress.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\PluggableUSB.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\HardwareSerial3.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\Stream.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\Print.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\HardwareSerial0.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\Tone.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\abi.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\USBCore.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\new.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\main.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\wiring_extras.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\WMath.cpp.o
Using previously compiled file: C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964\core\WString.cpp.o
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring_pulse.S.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\WInterrupts.c.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\hooks.c.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring.c.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring_analog.c.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring_digital.c.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring_pulse.c.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring_shift.c.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\CDC.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\HardwareSerial.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\HardwareSerial0.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\HardwareSerial1.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\HardwareSerial2.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\HardwareSerial3.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\IPAddress.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\PluggableUSB.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\Print.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\Stream.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\Tone.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\USBCore.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\WMath.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\WString.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\abi.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\main.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\new.cpp.o"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-ar" rcs "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\core.a" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\core\\wiring_extras.cpp.o"
Linking everything together...
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -Wall -Wextra -Os -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino.elf" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964\\sketch\\big_flash_V0_01.ino.cpp.o" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/core\\core.a" "-LC:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964" -lm
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino.elf" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino.eep"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino.elf" "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino.hex"
cmd /C "C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objdump" --disassemble --source --line-numbers --demangle --section=.text "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino.elf" > "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino_atmega328p_16000000L.lst"
"C:\\Users\\6v6gt\\Documents\\ArduinoData\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\6v6gt\\AppData\\Local\\Temp\\arduino_build_577964/big_flash_V0_01.ino.elf"
Sketch uses 32640 bytes (99%) of program storage space. Maximum is 32768 bytes.
Global variables use 196 bytes (9%) of dynamic memory, leaving 1852 bytes for local variables. Maximum is 2048 bytes.
C:\Users\6v6gt\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino18/bin/avrdude -CC:\Users\6v6gt\Documents\ArduinoData\packages\MiniCore\hardware\avr\2.1.3/avrdude.conf -v -patmega328p -cstk500v1 -PCOM6 -b19200 -Uflash:w:C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964/big_flash_V0_01.ino.with_bootloader.hex:i

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

         System wide configuration file is "C:\Users\6v6gt\Documents\ArduinoData\packages\MiniCore\hardware\avr\2.1.3/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         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  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 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 : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964/big_flash_V0_01.ino.with_bootloader.hex"
avrdude: writing flash (32640 bytes):

Writing | ################################################## | 100% 35.80s

avrdude: 32640 bytes of flash written
avrdude: verifying flash memory against C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964/big_flash_V0_01.ino.with_bootloader.hex:
avrdude: load data flash data from input file C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964/big_flash_V0_01.ino.with_bootloader.hex:
avrdude: input file C:\Users\6v6gt\AppData\Local\Temp\arduino_build_577964/big_flash_V0_01.ino.with_bootloader.hex contains 32640 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 19.57s

avrdude: verifying ...
avrdude: 32640 bytes of flash verified

avrdude done.  Thank you.

```
> 0 votes

---
Tags: atmega328
---


# Question
Title: Xbox 360 controller commands to Uno-compatible board via USB module
I am trying to receive commands on a third-party **Arduino-Uno-compatible board** from an **Xbox 360 controller** via an **M5Stack USB module** but I am not seeing the behavior I expect (see heading Expected Behavior).

To be clear, I am talking about reading commands from an Xbox controller using an Arduino, *not* emulating an Xbox controller using an Arduino.

# Hardware

* A Bluno Nano. (An Arduino-Uno-compatible board in a Nano-like form factor with program uploading and serial communication via a matching Bluetooth USB dongle. However, I am using a wired USB connection to my PC instead.) The board is recognized as an Uno by the Arduino IDE. The same board has worked as expected for other projects.
* An M5Stack USB module (with a MAX3421E chip), which is primarily meant to be compatible with an M5Stack microcontroller module. Either way, the USB module communicates using SPI.
* A *wireless* Xbox 360 controller, but I connected it to the USB module using a USB cable that plugs in to the controller with a seemingly proprietary connector. Should be in working order.

I am not using an Xbox 360 wireless receiver to connect to the Xbox controller, nor do I want to connect to it wirelessly.

## Wiring

* I connected the GND (#1/3/5), +5V (#28, VBUS), SCLK (#11, GPIO18), MISO (#9, GPIO19) and MOSI (#7, GPIO23) pins of the USB module to the corresponding pins of the Bluno Nano: GND, +5V, SCK (D13), MISO (D12), and MOSI (D11).
* I tried pulling the USB module's EN pin (#6) up to +5V in attempt to make sure it's enabled.
* I tried pulling the SS pin up/down. I have not tried connecting it to pins D10 or D8, both of which I have seen as SS pins on Arduino Nano pinout diagrams.
* I have not tried connecting the INT pin (#2, GPIO35) to anything.
* I believe these are the only useful pins on the USB module.

### USB module schematic

The useful pinout is in the bottom right corner.

## Attempts

* Unplugging and re-plugging the Bluno Nano's USB cable with my PC.
* Pressing the Bluno Nano's reset button.
* Unplugging and re-plugging the Xbox controller's USB cable with the USB module, or vice versa (that is, starting with it unplugged).
* Pressing or holding the center "X" button or other buttons on the controller, presumably to turn it on or hopefully enter some kind of connection-setup mode, maybe.
* Using a wired USB mouse instead of the Xbox controller.
* Trying various combinations of the above in different orders.

I have ensured that the USB module is receiving power (even though it seems to have no power indicator LED) by using it's additional 5V and GND pins to successfully drive a digital input pin on the Bluno Nano high or low.

I have ensured that the Xbox controller is receiving power because the center "X" button lights up upon being pressed.

# Software

* Windows 11
* Arduino IDE 2.0
* USB\_Host\_Shield\_2.0 version 1.6.2 (latest) installed through the library manager. Note that this library seems to be primarily designed for a particular USB host shield, but I see it being used with other USB host shields, including in my USB module's documentation. There is a library for Xbox 360 therein which works with a USB controller or a wireless controller, with example sketches for each.

Either example sketch uploads successfully without errors (although the programmer sometimes gets stuck not responding, whereupon I disconnect, let it error out, reconnect, and retry uploading).

In the Arduino IDE Serial Monitor, I set the baud rate to 115200 to match that specified in either example sketch.

## Expected behavior

To be printed in the Serial Monitor (`<...>` is how I indicate my comments):

```
XBOX USB Library Started  <instead of "OSC did not start" followed by unresponsiveness to controller button presses, etc.>
<Xbox controller commands upon controls/buttons being pressed, e.g., "LeftHatX: ...">

```

## Attempts

* The USB Host Shield 2.0 documentation says about use with an Xbox 360 controller: "To use it via USB use the XBOXUSB library or to use it wirelessly use the XBOXRECV library. Note that a Wireless controller can NOT be used via USB!". It is unclear to me if my wired USB connection to my wireless controller calls for the XBOXUSB or XBOXRECV library, so I tried both libraries (tried both accompanying example sketches) to no avail.
* I tried removing the following code snippets one-by-one and in some combinations, to no avail. The program uploads successfully in every case.

```
#include <SPI.h>

```

```
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif

```

```
XBOXUSB Xbox(&Usb);
<...along with the code in `loop()` that requires it to be defined.>

```

```
if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nXBOX USB Library Started"));

```

**The program failed here because `Usb.Init() == -1`.**
* I tried changing

```
if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nXBOX USB Library Started"));

```

to

```
while (Usb.Init() == -1);
Serial.print(F("\r\nXBOX USB Library Started"));

```

in attempt to keep trying to enable the connection (while I pressed the controller's "X" and other buttons) to no avail.
* I also tried changing the same snippet to

```
Usb.Init()

```

in attempt to ignore the `-1` return value (which I presume represents an error) and proceed anyway, to no avail.
* Using an older version of the USB Host Shield 2.0 library.
* Setting the following in the library's `settings.h`, with no apparent change in output.

```
/* Set this to 1 to activate serial debugging */
#define ENABLE_UHS_DEBUGGING 1

```
* Setting the following in `XBOXUSB.cpp` and `XBOXRECV.cpp`, with no apparent change in output.

```
#define EXTRADEBUG // Uncomment to get even more debugging data
#define PRINTREPORT // Uncomment to print the report send by the Xbox 360 Controller

```

For trying with a wired USB mouse instead of the Xbox controller, I used `USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino`, attempted additionally with some of the above modifications, to no avail in any case, leading me to believe that the problem is not specific to the Xbox controller or library for it.

I have also tried the example sketch from the M5Stack USB module documentation after removing parts that would be specific to an M5Stack microcontroller module and unecessary for testing purposes. This was no different.

---

I am completely lost on what else to try hardware- and software-wise. I have tried searching many questions. I suspect that I'm missing something simple and obvious, or that my setup can't work for whatever reason.

Thank you

---

# Update

After getting past the `Usb.Init()` problem by connecting the USB module's SS pin, the connection with the Xbox controller still wasn't being established and commands were not being received.

# Answer
I discovered that, upon plugging the USB cable into my PC rather than the USB module, the controller appears as "Xbox 360 Wireless Controller via Play & Charge Kit" under "Xbox 360 Peripherals" in the Device Manager.

Turns out, "Play & Charge Kit" refers to the controller's removable rechargeable battery and the USB cable.

According to this, "The play and charge kit only carries power. It does not carry the data required to connect a controller to a PC."
> 0 votes

---
Tags: usb, m5stack
---


# Question
Title: Arduino does not connect to MQTT local broker
I have an Arduino Mega with Ethernet connected to a router by cable. Also I have a PC connected to the router (by Wifi) where also the local MQTT broker is installed (mosquitto). Althought the Arduino Ethernet connection seems ok, the MQTT connection does not: I get the return code -2

This is the full code, there are several functions but the MQTT init is the one that fails:

```
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h> // Librería para MQTT

byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x3A, 0xC4 };
byte ip[] = { 192, 168, 1, 100 };
byte gateway[] = { 192, 168, 1, 2 };
byte subnet[] = { 255, 255, 255, 0 };

EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

const char *MQTT_BROKER_ADRESS = "192.168.1.101";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "mqttx_7c0a0ed3";

void SuscribeMqtt()
{
    mqttClient.subscribe("hello/world");
}

void OnMqttReceived(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Received on ");
    Serial.print(topic);
    Serial.print(": ");
    String content = "";
    for (size_t i = 0; i < length; i++)
    {
        content.concat((char)payload[i]);
    }
    Serial.print(content);
    Serial.println();
}

void InitMqtt()
{
    mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT);
    mqttClient.setCallback(OnMqttReceived);
}

void ConnectMqtt()
{
    Serial.print("Starting MQTT connection...");
    if (mqttClient.connect(MQTT_CLIENT_NAME))
    {
        SuscribeMqtt();
        mqttClient.publish("connected","hello/world");
    }
    else
    {
        Serial.print("Failed MQTT connection, rc=");
        Serial.print(mqttClient.state());
        Serial.println(" try again in 5 seconds");
        delay(5000);
    }
}

void HandleMqtt()
{
    if (!mqttClient.connected())
    {
        ConnectMqtt();
    }
    mqttClient.loop();
}

void CheckLinkStatus() {

  auto link = Ethernet.linkStatus();

  Serial.print("Link status: ");

  switch (link) {
    case Unknown:
      Serial.println("Unknown");
      break;
    case LinkON:
      Serial.println("ON");
      break;
    case LinkOFF:
      Serial.println("OFF");
      break;
  }
  delay(1000);
}

void setup() {

  // You can use Ethernet.init(pin) to configure the CS pin
  //Ethernet.init(10);  // Most Arduino shields

  Serial.begin(9600);

  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

  delay(1500);

  InitMqtt();

}

// put your main code here, to run repeatedly:
void loop() {

  CheckLinkStatus();

  HandleMqtt();

}

```

I have done ping from the PC IP (192.168.1.101) to the Arduino IP (192.168.1.100) and it is ok. What could be the issue?.

# Answer
The issue was coming from mosquitto local broker, which was being blocked by windows 10 firewall. When I executed mosquitto with the correct permissions on its folder (read and write for "all users") and with correct mosquitto configuration file, the following window popped up and I clicked on to allow both private and public connections:

I also use the following batch file to load mosquitto and it works all the time:

```
cd "C:\Program Files\mosquitto"
del mosquitto.log
mosquitto -v -c mosquitto.conf

```

This is the content of my mosquitto configuration file:

```
listener 1883
allow_anonymous true
log_type error
log_type warning
log_type notice
log_type information
connection_messages true
log_timestamp true
log_dest file C:\Program Files\mosquitto\mosquitto.log

```

Now I am able to use MQTT from Arduino connected to a router.
> 3 votes

# Answer
With a bit of research you can see that return code two is:

`2 Connection refused: client identifier not allowed by server.`

My guess is that you forgot to add the login details in the code, or the code fails because the client ID is not a c-string. Try something like this (replace with appropriate values):

`if (client.connect(clientId.c_str(), mqttUsername, mqttPassword)){`
> -1 votes

---
Tags: arduino-mega, ethernet, mqtt
---


# Question
Title: Best way to get JSON from struct vector class
I have a vector which consist of a struct, see below:

```
struct FileInformation
  {
    String name;
    size_t filesize;
  };

std::vector<FileInformation> FileInformations;

```

How do I get JSON out of it the easiest way?

# Answer
> 1 votes
Using ArduinoJson:

```
DynamicJsonDocument doc(2048);
for (const FileInformation& item : FileInformations) {
  JsonObject& obj = doc.createNestedObject();
  obj["name"] = item.name;
  obj["filesize"] = item.filesize;
}
serializeJson(doc, Serial);

```

This will produce a JSON document that looks like this:

```
[
  {"name": "command.com", "filesize": 1234},
  {"name": "config.sys", "filesize": 2345},
  {"name": "autoexec.bat", "filesize": 3456}
]

```

Please read the tutorial for more information.

---
Tags: json
---


title: Why 5V instead of 3V3?

text:
# Question
Title: Why 5V instead of 3V3?
I'm still quite new to electronics, so please forgive me if the answer is obvious.

I was wondering why virtually all the example circuits I find use the 5V power supply with resistors for all the components instead of the 3V3 power supply directly.

Even for the most simplistic "Blink" example, they use 5V pin and a 220 Ohm resistor to protect the LED instead of using the built-in 3.3V pin.

Yes, I know that in former times "everything" ran on 5V, but since we already have a lower voltage built-in, why not use it and reduce the number of components needed?

TIA for anyone who can solve this puzzle for me.
mav

# Answer
> 6 votes
First, even with 3.3V, an LED needs a resistor to limit the current through it. So, running with 3.3V doesn't solve that particular problem. Try Googling for "LED current limiting resistor".

Second, many Arduinos are designed to run using 5V. In many cases they have an input power jack which can accept a range of voltages and use a voltage regulator to convert it down to 5V,

Why not convert down to 3.3V you might ask? Well, the higher the voltage, the faster the processor can run, within its design limits. For example, the Atmega328P (which is in the Arduino Uno, and others) could only run at 13 MHz at 3.3V rather than 16 MHz.

> ... instead of using the built-in 3.3V pin

But that pin is only provided for convenience. You can't turn it on or off by a program.

The higher voltage (5V vs 3.3V) can be more convenient in some situations, for example switching motors on and off, or with other devices designed to work with 5V.

Motors or other high-power devices are typically turned on with MOSFET transistors. To be efficient, they need to fully turn on (have a low resistance between Source and Drain) and even so-called "logic level" MOSFETs typically require 5V to fully turn them on, rather than 3.3V. If you tried to control a motor with a 3.3V based board you would probably need extra components to turn the MOSFET on properly, so lowering the voltage could potentially add components, not reduce them.

On the other hand, many components these days are designed to work with 3.3V (or lower) so the choice of 5V is a bit of a compromise.

---
Tags: voltage
---


# Question
Title: How to read analog sensor data with different timers in arduino
I have three analog sensors like voltage, temperature and pressure. I need to measure the voltage and temperature every 10 ms and I need to measure the pressure alone every 30 ms by using the timers in an Arduino.

How can I do this?

# Answer
> 1 votes
May this help as starting point! Not tested

```
void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
}

unsigned long previousMillis1;
unsigned long previousMillis2;

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis1 >= 10) {
    int val1 = analogRead(A0);
    int val2 = analogRead(A1);
    Serial.print("Values from A0 and A1: ");
    Serial.print(val1);
    Serial.print(" ");
    Serial.println(val2);
    previousMillis1 = currentMillis;
  }

  if (currentMillis - previousMillis2 >= 30) {
    int val3 = analogRead(A2);
    Serial.print("Value from A2: ");
    Serial.println(val3);
    previousMillis2 = currentMillis;
  }
}

```

---
Tags: arduino-uno, sensors, timers
---


# Question
Title: How do I control the rotation of my servo?
```
#include <Servo.h> // servo library
Servo servo;
int trigPin = 5;
int echoPin = 6;
int servoPin = 7;
int led= 10;
long duration, dist, average;
long aver[3];   //array for average

void setup() {
  Serial.begin(9600);
  servo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  servo.write(0); // close cap on power on
  delay(100);
  servo.detach();
}

void measure() {
  digitalWrite(10,HIGH);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(15);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  dist = (duration/2) / 29.1; // obtain distance
}

void loop() {
  for (int i=0; i<=2; i++) {
  // average distance
  measure();
  aver[i] = dist;
  delay(10); // delay between measurements
  }

  dist = (aver[0]+aver[1]+aver[2])/3;

  if (dist < 50) { // Change distance as per your need
    servo.attach(servoPin);
    delay(1);
    servo.write(0);
    delay(3000);
    servo.write(150);
    delay(1000);
    servo.detach();
  }

  Serial.print(dist);
}

```

This is my first time in robotics. The servo is a Tower Pro SG90. It rotates over 360° and ony spins in one direction, but I want it to rotate for just about 90° and to rotate back to its original place after. This is the code I used. I'm making a trash bin where the lid automatically opens.

# Answer
You should buy a normal servo, not a servo with continuous rotation. The Tower Pro SG5010, for example, should basically meet your needs. But depending on the size of the bin and the mechanical control of the lid, you may want to choose a servo with greater actuating force.
> 0 votes

# Answer
A continuous rotation servo cannot be set to specific angles, only specific speeds. That's the point for continuous rotation servos.

So for your trash bin you should buy a normal servo (not continuous rotation). Such servo can be moved to specific angles between 0 and 180°.
> -1 votes

---
Tags: servo
---


# Question
Title: Arduino nano 33 BLE serial port not working with C# app
I use an Arduino Nano with some sensors and send data to a PC using the serial port. I just got a new Arduino Nano 33 BLE and tried the same code but its not working. So for testing I just wrote some simple test code on the Arduino Nano 33 BLE side:

```
void setup()
{
  Serial.begin(57600);
}

void loop()
{
  if (Serial.available())
  {
    char c = Serial.read();
    Serial.write(c);
  }
}

```

This just sends back whatever arrives through the COM port. Using the Arduino IDE Serial Monitor this works very well with the Arduino Nano 33 BLE. I also made this very simple C# test code (Windows Forms app):

```
SerialPort serialPort = new SerialPort("COM17", 57600);
serialPort.ReadTimeout = 4000;
serialPort.WriteTimeout = 4000;
serialPort.Encoding = Encoding.ASCII;
serialPort.DataReceived += SerialPort_DataReceived;
serialPort.Open();
if (serialPort.IsOpen)
{
    Debug.Print("COM port open");
}

```

This C# code works perfect with my good old Arduino Nano but it doesn't work with the Arduino Nano 33 BLE. I have the **COM port open** message so the port exists and it is open, but then nothing else, no timeout, nothing. I already lost one day trying out all sorts of combinations but it just doesn't work, my C# app can't communicate with the Arduino Nano 33 BLE. It looks like a serial port issue so I think I'll put it on hold for now...

EDIT: The rest of my test code, for reference:

```
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        Debug.Print(serialPort.ReadExisting());
    }
    catch (Exception exception)
    {
        Debug.Print(exception.Message);
    }
}

private void buttonSend_Click(object sender, EventArgs e)
{
    try
    {
        serialPort.WriteLine("HELLO");
    }
    catch (Exception exception)
    {
        Debug.Print(exception.Message);
    }
}

```

# Answer
> 4 votes
I noticed that a lot of line discipline and flow control settings were not made explicit in your C# code, so it made me wonder what they were by default.

In particular `DtrEnable` appears to be false by default and `Handshake` is None by default (which seems to be irrelevant). The other default amount to 8N1. The first part I found interesting because it seems more typical in serial APIs for DTR to be automatically asserted when a port is opened when you're not explicitly asking it to. If I'm reading the .NET documentation correctly, it isn't for your application. The original Nano doesn't much care about DTR apart from a falling edge triggering reset. The board is happy to communicate with it solidly either asserted or not. The original Nano's DTR is only capacitively coupled to reset; there's not a way for the code running on the AVR to respond to DTR (unless you count resetting). That lead to a question about to what extent a Nano 33 BLE would care about DTR.

As it turns out the Nano BLE does care. If I deassert DTR in test with pyserial the board stops sending traffic back. I can write while it's deasserted and after asserting again some queued data arrives. *A test environment with pyserial is just more immediately available to me; if needed and I get a chance I'll set up a .net/C# test and confirm with that, but I suspect that won't be necessary.* Seeing that result, I searched and found this Arduino Forum post with a somewhat similar problem description. The OP replies in answer to their own post saying:

> Problem sorted out. Arduino nano BLE requires DTR and RTS signals to be On. Then it works like FDTI.

Disabling RTS had no effect during my tests with pyserial. I'm not sure why it would. Perhaps they just asserted it preemptively. Being entirely a virtual port RTS doesn't really make sense for flow control. DTR might arguably still makes more sense in this context; at the level of serial signals it normally tells you something is paying attention on the other side of the connection. I'm not really surprised, either way, that the BLE sense would react to DTR being disabled by not sending data to the host; there's a lot of latitude in how these signals can be handled. That it's not automatically used when the port is opened (or until specifically requested) seems *mostly* a C# thing. But it looks like the different handling of DTR between the two boards that is making your code work with one but not the other.

So it would seem necessary and sufficient to add

```
serialPort.DtrEnable = true;

```

amongst your other settings following the opening of the port.

If there's truth to what the Arduino Forum poster said about RTS, then you would also need

```
serialPort.RtsEnable = true;

```

but this is not indicated by the tests I've done (though again with pyserial).

---
Tags: serial, arduino-nano, arduino-nano-ble
---


# Question
Title: How to fix the scambled output of the emojis in Arduino IDE 2?
I have relatively simple code printing some emojis:

```
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Hello world ❤♀♂✔");
}

```

Just in case it doesn't render very well, here's an image on how it looks like in Arduino IDE 2.0.3:

However, the Serial Monitor sometimes displays emojis and sometimes not. It varies from line to line like so:

```
Hello world �����������������♀�������♂✔����
Hello world ���������������♀♂✔
Hello world ��❤���������������������������������♂���✔
Hello world ❤��������������������
Hello world �������♀��������������✔����
Hello world ��������������♀�������������������
Hello world ��❤���������������������♂�������✔���

```

Again, there's how it looks like on my Windows 10 machine:

I verified that it's not a mistake in the baud rate. Both, Arduino and PC are set to 9600.

In Arduino IDE 1, the output is not colorful and some emojis are not rendered at all, but the result is much more consistent:

How to fix the scrambled output in Arduino IDE 2?

# Answer
> 2 votes
This is an issue of Arduino IDE 2.0.3. It was reported as issue 589 and issue 1405.

It was fixed on 9th of December 2022 \[PR\] and I can confirm it is fixed in nightly build 2.0.4-221229.

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


# Question
Title: How to get rid of the second tab in Arduino IDE 2?
For a reason unknown to me, Arduino IDE 2.0.3 opens two tabs with the same name for this sketch. I'm not able to reproduce how to get into this situation.

Changes in one tab immediately changes the other tab as well.

How can I get rid of the second tab?

Things I tried:

* File / Close (Ctrl+W) closes the whole sketch, i.e. Arduino IDE exists.
* The usual key combination to close tabs (Ctrl+F4) does not work either.
* I deleted all `%AppData%\Local\Temp\.arduinoIDE-unsaved*.gfv2` folders
* I deleted all `%AppData%\Local\Temp\arduino-sketch-*` folders
* I deleted all `%AppData%\Local\Temp\arduino-language-server*` folders
* I deleted all `%AppData%\Local\Temp\arduino-ide2-*` folders
* I used Streams to check the INO file for alternate data streams
* I deleted the folder `%UserProfile%\.arduinoIDE`

Maybe interesting: when I rename the sketch to HelloWorld2.ino, it opens only one tab. If I rename it back, I have two tabs again.

When I change the preferences to show the files in Sketchbook view, I only see one file:

The other sketches have been created when trying to reproduce the problem. They are not affected

The tooltip which shows the full file name is identical on both files:

The Registry does not contain suspicious information. I found only one occurrence of HelloWorld in

```
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths

```

# Answer
> How can I get rid of the second tab?

* Press `F1`,
* Type: `View: Reset Workbench Layout` into the *Command Palette*,
* Press `Enter`,
* IDE reloads.

If it does not help, get the layout data from the logs.

* Open the DevTools with `Ctrl/⌘`+`Alt`+`I` built-in command,
* Open the *Console* if it's not opened with `Esc`,
* Right-click in the console and `Save as...`,
* Share the data with the devs.

For example:

```
{"version":5,"mainPanel":{"main":{"type":"tab-area","widgets":[{"constructionOptions":{"factoryId":"code-editor-opener","options":{"counter":0,"kind":"navigatable","uri": ...

```
> 5 votes

---
Tags: arduino-ide-2
---


# Question
Title: How do I reset the recently used commands in Arduino IDE 2?
I am recording videos on Arduino IDE version 2. In one of the videos I want to explain how to enable a specific setting via the advanced properties. This requires using `Ctrl`+`Shift`+`P` (command palette).

However, my Arduino IDE now shows some commands I have used recently (sorry, screenshot is in German).

That's not the default. If someone has just installed Arduino IDE, he would need to scroll until he finds the entry. How do I reset the recently used items, so that I can record a proper video which requires scrolling?

Resetting the workbench layout does not help.

# Answer
1. open the command palette
2. search and choose Preferences: Open Settings (UI)
3. in the preferences window, search for the setting `workbench.commandPalette.history`
4. set that value to 0 and it will not save the recent commands
> 2 votes

---
Tags: arduino-ide-2
---


# Question
Title: Stoplight Simulator - White LED not turning on with button press
I am working on a relatively simple stoplight simulator that uses four LEDs - red, green, yellow, and white - in addition to a button. The 3 colored stoplight LEDs cycle as a real stoplight would. If the button is pressed while the green LED is on, the white light should turn on while the green light is still on (this can only be allowed to happen once). Previously, the stoplight cycle didn't work, but now the white light isn't turning on with the button press (see below)

Edit: The stoplight cycle now works, thanks to all your input, but the white light still doesn't come on when I press the button. This could be an issue using delay instead of millis(), but I'm not sure the easiest way to implement a fix. Any tips? My code is below. Thank you!

```
const int g_led = 3;
const int y_led = 4;
const int r_led = 5;
const int w_led = 6;
const int g_delay = 4000; //adjust test timings to reqs
const int y_delay = 2000;
const int r_delay = 3000;

int g_ledState;
int buttonState;
bool counter = false;

const int buttonPin = 2;

//green led function with conditional for white led
void green_light(){
  digitalWrite(g_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState = 1;
  buttonState = digitalRead(buttonPin);
if (buttonState == HIGH && g_ledState == 1 && counter == false){
  digitalWrite(w_led, HIGH);
    counter = true;
  }
  else{
    digitalWrite(w_led, LOW);
    counter = true;
  }
}

void yellow_light(){
  digitalWrite(y_led, HIGH);
  digitalWrite(g_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void red_light(){
  digitalWrite(r_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(g_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(g_led, OUTPUT);
  pinMode(y_led, OUTPUT);
  pinMode(r_led, OUTPUT);
  pinMode(w_led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
//main stoplight cycle
  green_light();
  delay(g_delay);
  yellow_light();
  delay(y_delay);
  red_light();
  delay(r_delay);
}

```

# Answer
> 0 votes
You need to try it this way

```
allowed to happen once). My code compiles, but none of the lights turn on when I run it. I'm pretty sure I set the circuit correctly, so I want to see if I'm missing any issues in my code (below). Thank you!

//variables
const int g_led = 3;
const int y_led = 4;
const int r_led = 5;
const int w_led = 6;
const int g_delay = 1000;
const int y_delay = 500;
const int r_delay = 1000;
int g_ledState;
int buttonState;

const int buttonPin = 2;

//LED functions
void green_light(){

  int counter=0;

// conditional to let button turn on the white LED IF green LED is on and the white LED cycle hasn't already been run
if (buttonState == HIGH && g_ledState == 1 && counter == 0){
  digitalWrite(w_led, HIGH);
    counter =1;
  }
  else{
    digitalWrite(w_led, LOW);
    counter=0;
  }

  digitalWrite(g_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=1;
  button state=digitalRead(buttonPin);

}

void yellow_light(){
  digitalWrite(y_led, HIGH);
  digitalWrite(g_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void red_light(){
  digitalWrite(r_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(g_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(g_led, OUTPUT);
  pinMode(y_led, OUTPUT);
  pinMode(r_led, OUTPUT);
  pinMode(w_led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

//main stoplight cycle
  green_light();
  delay(g_delay);
  yellow_light();
  delay(y_delay);
  red_light();
  delay(r_delay);

}

```

Note that using delay is not that advisable but this way might help.

Here is another method using millis(), note that it hasn't been tested with arduino. If the compiling gives an error try modifying some things

```
//variables
const int g_led = 3;
const int y_led = 4;
const int r_led = 5;
const int w_led = 6;
const int g_delay;
const int y_delay;
const int r_delay;
int g_ledState;
int buttonState;
int oldbuttonState;
const int buttonPin = 2;

/* you can remove this one
Switch (white){
case 1:
//do nothing
break;

case 2 :
   buttonState=digitalRead(buttonPin);

   // conditional to let button turn on the white LED IF green LED is on and the white LED cycle hasn't already been run
if (buttonState == HIGH && counter == 0){
  digitalWrite(w_led, HIGH);
    counter =1;
  }
  else{
    digitalWrite(w_led, LOW);

  }
counter=buttonState;
//switch to case 3
 white=3;
break;

case 3 :
//switch back to case two and continue reading the button
white=2;
break;
*/

}
//LED functions
void green_light(){

  digitalWrite(g_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);

// start reading the button
  // I added this for better performance
int rep=millis;
while((millis-rep) < 3000){
digitalRead(buttonpin);
if (buttonState == HIGH && counter == 0){
  digitalWrite(w_led, HIGH);
    counter =1;
  }
  else{
    digitalWrite(w_led, LOW);

  }
counter=buttonState;

}
  g_delay=Millis();

}

void yellow_light(){
//stop button reading
  white=1;
  digitalWrite(y_led, HIGH);
  digitalWrite(g_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  y_delay=millis();

}

void red_light(){
 //stop button reading
  white=1
  digitalWrite(r_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(g_led, LOW);
  digitalWrite(w_led, LOW);
  r_delay=millis();
}

Switch (cases){
//main stoplight cycle
case 1 :
  green_light();
  /// wait for 3 seconds
  if (millis() - g_delay >=3000){
     yellow_light();
}
 cases=2;
 break;

case 2 :
  /// wait 2 seconds
  if (millis() - y_delay >=2000){
     red_light();
}
cases=3;
break;

 case 3 :
 // wait 5 seconds
  if (millis() - r_delay >=5000){
      cases=1;
}
cases=1;
break;

}

void setup() {
  // put your setup code here, to run once:
  pinMode(g_led, OUTPUT);
  pinMode(y_led, OUTPUT);
  pinMode(r_led, OUTPUT);
  pinMode(w_led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
cases=1;

}

```

It haven't been tested but just try it out

# Answer
> 0 votes
You don't have any circuit details... SO...

Where most indicator LEDs need 2 to 2.2 volts and 8 to 25mA, white LEDs typically need 3.1V and 25mA minimum to turn on.

Also micro processors have limits to the current a pin can deliver If you are using a 3.3v micro not all the voltage will make it to the LED.

look up the spec sheets on the micro and white LED. I have a feeling you are going to find either the micro pin or the supply an issue.

Try switching out a colored LED for testing the code. If the LED works then try going to some driver circuit to power the white LED.

---
Tags: arduino-uno, arduino-ide, sketch, code-review
---


title: TFT and SD don't work together

text:
# Question
Title: TFT and SD don't work together
I use a 2.8" TFT Touch Shield v1 and I want to read some data that were stred in sd and plot them with the tft.

When the following code is ordered, to access the data. TFT freezes.... but the code's execution is continued...

```
    pinMode(SS, OUTPUT);
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
       Serial.println("Card failed, or not present");
    // don't do anything more:
       while (1) ;
    }

    Tempfile = SD.open("DATALOG.TXT",FILE_READ);
    if (! Tempfile) {
       Serial.println("error opening datalog.txt");
    // Wait forever since we cant write data
       while (1) ;}

```

I tested the code on the example of the tft graphics test... and the result was a freezed tft...

I tried also to run the example: tftbmp but the tft remains black. Once again the code is executed in the loop as i receive results from the Serial monitor but tft is black...

I use an Arduino Uno R3.

Any tip is welcomed

# Answer
The solution to getting data from SD to TFT may depend on the type of data stored. See examples included in software for your TFT. Also it might be possible to solve this issue with 2 Arduinos using Software Serial, which, I believe, is included in the Arduino IDE. Assume you have stored analog data from a sensor on an SD. During the recording, you were able to visualize incoming data on your serial plotter and your sketch also allowed you to see the live data on your TFT. You now wish to visualize the data recorded on your SD on the TFT once more. To accomplish this with Software Serial, the SD card could be mounted on one Arduino and the TFT on another. The Tx and Rx pins of the 2 Arduinos must be connected as described in the Arduino Software Serial guide. This technique should allow user to "fool" the Arduino with TFT into thinking it is receiving live analog data from a sensor. Since the user has already written the sketch to visualize data from a sensor on TFT , the modifications should be easy.
> 1 votes

# Answer
old topic, but since I'm having the same issues I'll share what I found.

chipSelect is usually 10 for arduino uno, some exemples have other pin setted.

also I found a guy claiming he fixed his issues setting after

pinMode(SS, OUTPUT); digitalWrite(SS, HIGH);
> 0 votes

---
Tags: arduino-uno, shields, sd-card
---


# Question
Title: Can I configure the highlighting for escaped characters in a string?
Given a simple mistake like

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

void loop() {
  Serial.println("\");     // note: " is escaped, so this won't compile
}

```

This is rendered in Arduino IDE 2.0.3 as

and the problem is hard to spot.

The Jetbrains IDEs have special highlighting for escaped characters like

which makes the problem more obvious because the two quotation marks have different color.

Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?

Because it was asked in the comments: no, the syntax highlighting does not highlight the escaped character when the string is complete. The backslash and quotation mark are both still green.

# Answer
> Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?

Yes. You'll need to enable the Arduino language features provided by the language server. They're disabled by default.

* Press `F1`,
* Type `Preferences: Open Settings (JSON)`,
* Press `Enter`,
* The `settings.json` file opens.

Add the following to the JSON and save it if you do not have auto-save enabled:

```
{
  "arduino.language.realTimeDiagnostics": true
}

```

My `settings.json` with the Arduino language features enabled.

Select a board. You can ignore the port selection if you like. The language feature should start, and you will see the error in the editor.

More details on the *Advanced Settings* are here.
> 1 votes

---
Tags: arduino-ide-2
---


# Question
Title: List of supported boards in Arduino IDE 2.0
Where can I find the list of supported boards in Arduino IDE 2.0 without installing the IDE? Googling it was not fruitful. Specifically, I'm looking for ESP32-S3 support.

# Answer
> 2 votes
The 2.X IDE makes use of arduino-cli:

> The backend operations such as compilation and uploading are offloaded to an arduino-cli instance running in daemon mode.

which has roughly the same internals as arduino-builder

> The arduino-builder is now just a wrapper of arduino-cli

which is what the 1.X IDE uses to launch the build process. Roughly speaking, they support the same boards.

About the only difference I've noticed is that the 2.X IDE does not *yet* support `disableRTS` and `disableRTS` board properties, so some ESP32 board that require these settings will not (yet) work in with the 2.X IDE's serial monitor. The ESP32-CAM-MB together with ESP32CAM is one combination where the Serial Monitor won't work. You can still upload with it though.

So, the IDE should compile and upload for your ESP32-S3 just fine. If you want to know whether or not the Serial Monitor will work, it's down to looking at the specific board schematic to see whether or not the EN/RESET and GPIO0 signals are connected to the serial transceiver using only diodes. The official boards don't do this. So if you have one of the Expressif devkits (or a clone) the 2.0 IDE Serial Monitor will work fine with it.

# Answer
> 1 votes
> Where can I find the list of supported boards in Arduino IDE 2.0 Specifically, I'm looking for ESP32-S3 support.

Without knowing what you want to do, the short answer is: check this JSON's `"boards"` properties: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package\_esp32\_index.json.

The Arduino IDE is just a user interface on top of the `arduino-cli`. It provides a way to change the `board_manager#additional_urls` property of the CLI configuration. Once a new 3rd party platform URL is specified in the IDE, the CLI will see the available boards of the platform. You'll need to install the platform to verify and upload your sketches. After installing the platform, the `"boards.txt"` will be available on your filesystem for the CLI. For this example, this is https://github.com/espressif/arduino-esp32/blob/master/boards.txt.

---
Tags: esp32, arduino-ide-2
---


# Question
Title: AD8232 - Measuring heart rate only if USB connector is touched. Grounding issue?
### TL;DR

I can read out my heart rate but I have to physically touch GND of the Arduino or else the signal is just noise.

### Description

So I've started to play around with an Arduino and wanted to try out a heartrate sensor module (AD8232).

The following is the code I am using for this:

```
const int CONNECTED_LED = 13;

const int LO_MINUS = 10;
const int LO_PLUS = 11;

bool disconnected = true;

enum State {
  CONNECTED,
  DISCONNECTED,
  LO_MINUS_DISCONNECTED,
  LO_PLUS_DISCONNECTED
};

enum State currentState = DISCONNECTED;

void setup() {
  Serial.begin(9600);
  pinMode(LO_MINUS, INPUT); // Setup for leads off detection LO +
  pinMode(LO_PLUS, INPUT); // Setup for leads off detection LO -
}

void loop() {
  State nextState = getState();

  if (nextState != currentState) {
    // Store the current state
    currentState = nextState;
    switch (nextState) {
      case DISCONNECTED:
        break;
      case LO_MINUS_DISCONNECTED:
        break;
      case LO_PLUS_DISCONNECTED:
        break;
    }
  }

  if (currentState == CONNECTED) {
    digitalWrite(CONNECTED_LED, HIGH);
    Serial.println(analogRead(A0));
  } else {
    digitalWrite(CONNECTED_LED, LOW);
    // Serial.println(-1);
  }

  delay(1);
}

State getState() {
  if (digitalRead(LO_MINUS) == 1 && digitalRead(LO_PLUS) == 1) {
    return DISCONNECTED;
  } else if (digitalRead(LO_PLUS) == 1) {
    return LO_PLUS_DISCONNECTED;
  } else if (digitalRead(LO_MINUS) == 1) {
    return LO_MINUS_DISCONNECTED;
  }
  return CONNECTED;
}

```

This is how I am connecting the boards (I double checked already twice)

```
AD8232  | Arduino UNO R3
------------------------
GND     |  GND
3.3v    |  3.3V
OUTPUT  |  A0
LD-     |  ~10
LD+     |  ~11
SDN     |  <not used>

```

I've followed this diagram for connecting the electrodes:

However, the result is a random signal *unless* I am touching the USB-connector or GND of the Arduino.

Below you can see the random signal and the moment I touched the connector. I noticed this by accident after hitting the reset button after wondering why on earth I only get this random signal:

So.. what's going on here? I have all three electrodes connected.

I've even tried to different modules (I bought the AD8232 two times) but I see the same issues with both modules.

If I touch something else e.g. a radiator (heater) then the signal becomes another kind of random. It only works touching the connector.

Since this appears like a grounding issue I checked for continuity from the GND pin of the AR8232 to the USB connector and continuity is given.

I'm not expert enough (yet) to see the problem. Anybody?

# Answer
One of your three ECG leads is equivalent to (human)body ground, and it's not making contact. I spent too long making this image to explain it, which should help you a lot more than it will me. I mean, I don't have the board in my hands, so I cannot see which lead goes to which pin. You can, easily, with a multimeter testing for continuity between the: RIGHT ARM, RIGHT LEG, LEFT ARM (RA, RL, LA) solder spots, and the tip, ring, barrel of the jack. Something to keep in mind though is the headphone jack switch. When the plug is physically inserted, this switch opens. Again, I'm not there to guide your multimeter, so this image is the best I can do for you. One of your leads is going to be a grounding lead. It may be the "black" one, it may be the (traditionally) "RL" one, it may be another one, i can't tell.

When you touch USB ground you are effectively replacing the body contact of the missing ground lead. I made these images for you to better understand it. You should be able to fault find this in a few minutes via you MM and continuity testing.
> 1 votes

---
Tags: sensors, analog
---


title: is there Raw RTC output?

text:
# Question
Title: is there Raw RTC output?
I have an I2C Real Time Clock, DS3231 RTC module , and I just want something like Unix Time. I'm using the uRTCLib, looking at the class methods but dont see anything like that. I'm thinking there must be a raw read that would return all the digits. Is there an easy way to do that?

# Answer
> 3 votes
The DS3231 doesn't report the Unix time. It reports the current time in broken-down form (year, month... second). If you need Unix time, you have to compute it.

I suggest using Adafruit's RTClib. This library implements the computation of Unix time, e.g.

```
uint32_t unix_time = rtc.now().unixtime();

```

---
Tags: programming, rtc
---


# Question
Title: Detecting an approximate angle/location of a light source using phototransistors
**Note: \[I am approximately two weeks into learning Arduino and hence have little experience with utilizing Phototransistors.\]**

My plan revolves around placing four identical Phototransisors which are spread approximately 10cm apart on a breadboard in a V configuration. Each Phototransistor is connected to one of the "analog In" pins respectively (I am using the Arduino Uno), with the long leg attached to 5V while the short leg is connected to ground via a 220-ohm resistor. In the center of this setup, I plan to place a servo that will face the direction of the light beam emitted from a flashlight.

(I want this project to be allocated in a dark room with any external lighting calibrated),The idea is to identify the phototransistor which has the highest analog value (closest to the light source). With this information, I want to be able to compute an approximate angle of the light source to then write it on my servo.

You can find the attached datasheets below (All the components are from the Arduino starter kit :) ).

\[Datasheet for the Phototransistor\]

\[Datasheet for the Servo motor\]

\[Datasheet for the 220 ohm Resistor\]

Here is what I have so far for the code:

```
#include <Servo.h>
Servo myServo;
const int transistorPin1 = A0;
const int transistorPin2 = A1;
const int transistorPin3 = A2;
const int transistorPin4 = A3;
void setup() {
  myServo.attach (10);
  Serial.begin (9600);
}
void loop() {
 int reading1 = analogRead (transistorPin1);
 int reading2 = analogRead (transistorPin2);
 int reading3 = analogRead (transistorPin3);
 int reading4 = analogRead (transistorPin4);
 int reading [] = {reading1, reading2, reading3, reading4}; //This is an array for the values:
 int maxReading = reading [0], maxSensor = 1; // I am setting the maximum reading and the Phototransistor that corresponds to it:
   for (int i = 1; i <= 3; i++){ //Setting this for the other three phototransistors:
     if (reading[i] > maxReading){
     maxReading = reading[i];
     maxSensor = i + 1;
     }
   }
}

```

So my question is: What is the most efficient way to compute the angle of the lighsource? And is my method even relevant for this application?

Thank you for taking you time to read this! Your support will be very much appreciated!

**Edit 1:**

Explanation of my hardware setup:

This project is allocated on two connected breadboards which means that there are no moving parts. The only moving component is the one single servo that is fixed in position.

The phototransistors, (as mentioned above), are placed in a V configuration which too are stationary. The servo is allocated behind the phototransistors and can only rotate 180 degrees. (You can see the attached illustrations below, I apologize in advance for any technical errors or my horrible drawings.)

As you can visualize on the first image, I do not plan on a complete 360 degree rotation which probably complicates the issue further. Any suggestions on how I can code this would be greatly appreciated! Once again thank you for your time.

# Answer
In principle, you only need two phototransistors, a left and a right one. The quotient of the values from the ad-convertor (Vleft/Vright) will tell you where to find the light source. If the quotient \> 1 then the light source is at the left side, if the quotient \< 1 then the light source is at the right side. Most likely there is no lineair relationship between the quotient and the angular position of the light source. This relationship depends on the housing and the positioning of the diodes in their housings. One possibility is to do a calibration beforehand and use a lookup table during operation. The calibration could be done by placing the breadboard with photodiodes on a rotating platform with the light source in front and then record Vleft and Vright at various angles (in 1 degree steps?) of the platform in relation to the light source. If two photoresistors don't give you the required precision and/or range, you can use more photoresistors and use the pair which is best 'looking' in the direction of the light source.
> 1 votes

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


# Question
Title: Temperature is not updated on OLED screen - Grove components
I am using 2 grove components in order to display a temperature. I use an I2C High Accuracy Temperature Sensor - MCP9808 and an OLED Screen using this script:

```
#include <U8g2lib.h>
#include <SPI.h>
#include <Wire.h>
#include "Seeed_MCP9808.h"

MCP9808 sensor;
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/SCL, /* data=*/SDA, /* reset=*/U8X8_PIN_NONE);  //Software I2C

char strTemp\[16\];
float temp;

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

  if (sensor.init()) {
    Serial.println("sensor init failed!!");
  }
  sensor.set_config(SET_CONFIG_ADDR, 0x0008);
  Serial.println("sensor init!!");
}

void loop() {
  sensor.get_temp(&temp);
  Serial.print("temperature value is: ");
  Serial.println(temp);
  delay(1000);

  dtostrf(temp, 7, 2, strTemp);

  u8g2.clearBuffer();                   // clear the internal memory
  u8g2.setFont(u8g2_font_luBIS08_tf);   // choose a suitable font
  u8g2.drawStr(0, 10, "Hello Seeed!");  // write something to the internal memory
  u8g2.drawStr(0, 30, "Temp. value:");  // write something to the internal memory
  u8g2.drawStr(0, 50, strTemp);         // write something to the internal memory
  u8g2.sendBuffer();                    // transfer internal memory to the display
}

```

The temperature output is not updated on the screen and I think it might be related to I2C addresses. Is it possible?

I run an I2C scanner and I think that the OLED address is 0x3C and the temp. sensor is 0x18. How can I assign them correctly. I never done something like that so any help is welcome.

Thanks a lot.

# Answer
You mix software I2C with hardware I2C on the hardware I2C pins.

To use hw I2C with the display use the U8G2\_SSD1306\_128X64\_NONAME\_F\_**HW**\_I2C constructor.

```
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

```

Or use a different pair of pins for the software I2C display control.
> 1 votes

---
Tags: temperature-sensor, arduino-zero, oled
---


# Question
Title: GCRduino shows up briefly in the IDE and then disappears
I have two UNO boards from a few years ago. They look the same as far as chip placement goes.

I can plug both in and get flashing lights on them, and when I hit the reset (2x the on-off) button, they both make the same LED "noises". Since the LEDs on the non-detected board flash the same start-up sequence as a board that is detected, I assume both boards are working.

One of them has "UNO" printed on the circuit board and the other has "GCRduino Rev 1.0" printed on the circuit board. (edited according the comments for clarification)

I'm using Linux Mint 21 and Arduino IDE 2.0.3.

On hardinfo (the linux program), both of them are listed in Devices-\>USB Devices as "QinHeng Electronics CH340 serial converter."

The one that has UNO printed on the board is detected and I can load software onto it. The one that say GCRduino is not detected by the IDE and no new entry shows up in /dev.

The GCRduino is detected for a split second and then disappears again. check this video: http://100wires.com/arduino.mp4

# Answer
I found the problem with dmesg. When I insert the card and it shows up very briefly, it gets kicked by another device:

```
[  167.032321] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input25
[  172.660038] usb 3-3: new full-speed USB device number 9 using xhci_hcd
[  172.809032] usb 3-3: New USB device found, idVendor=1a86, idProduct=7523, bcdDevice= 2.62
[  172.809038] usb 3-3: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[  172.809041] usb 3-3: Product: USB2.0-Serial
[  172.810938] ch341 3-3:1.0: ch341-uart converter detected
[  172.811372] usb 3-3: ch341-uart converter now attached to ttyUSB0
[  173.349731] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input26
[  173.655257] usb 3-3: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1
[  173.656203] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
[  173.656275] ch341 3-3:1.0: device disconnected

```

I can see the device on lsusb:

Bus 003 Device 008: ID 1a86:7523 QinHeng Electronics CH340 serial converter

That same device serial number is listed in

```
grep 1a86 /usr/lib/udev/rules.d/85-brltty.rules
ENV{PRODUCT}=="1a86/7523/*", ENV{BRLTTY_BRAILLE_DRIVER}="bm", GOTO="brltty_usb_run"

```

So when it connects, it gets kicked off by it being detected as another device.

So I just comment out that line in /usr/lib/udev/rules.d/85-brltty.rules, restart, and the board can now be detected.
> 1 votes

---
Tags: hardware
---


# Question
Title: Arduino code giving error while compiling
I am a beginner, and I'm trying to make code to control a servo using two ultrasonic sensors. I've tried to make the code, but when I tried to compile it using my simulation app, it gives this error:

```
sketch.ino: In function 'void value2()':
sketch.ino:123:19: error: expected ')' before '!' token
 if((L < R)>=6 & L !> normal){
                   ^
sketch.ino: In function 'void value3()':
sketch.ino:131:19: error: expected ')' before '!' token
 if ((R< L)>=6 & R !> normal){
                   ^

Error during build: exit status 1

```

How do I go about fixing this? I'm using the Wokwi simulator website, and here is the link to the simulation.

Here is where the problem is in my code:

```
void value2() {
  /* I'm using L !> normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */
  if ((L < R) >= 6 & L !> normal) {
    servo.write(120);
    //goto
    loop();
  }
}

void value3() {
  /* I'm using R !> normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */
  if ((R < L) >= 6 & R !> normal) {
    servo.write(60);
    //goto
    loop();
  }
}

```

And here is my complete code:

```
#include <Servo.h>
#include <Stepper.h>
#define STEPS 100 // stepper steps
#define speed 30 // stepper speed
#define Lechopin 10 // ultrasonic sound sensor left
#define Ltrigpin 11 // ultrasonic sound sensor left
#define Rechopin 12 // ultrasonic sound sensor right
#define Rtrigpin 13 // ultrasonic sound sensor right
long Lduration;
long Ldistance;
long Rduration;
long Rdistance;
int  L;
int  R;
int dt1 = 100; //delay
int dt2 = 1;   //delay
int dt3 = 2;   //delay
int dt4 = 10;  //delay
int serv = 9;  //servo pin
Servo servo;
Stepper stepper(STEPS, 5, 6, 7, 8);
/* Assuming distance of 4 feet measured by sensor is between 100 to 1000, let's set 750 as the normal distance between
sensor and object in which will be anything in 4feet upward far
away from sensor won't be detected by the code. you can edit it with real time measurement, I just assume this */
int normal=750;
int minn=250;

void setup() {
  Serial.begin(9600);
  stepper.setSpeed(speed);
  servo.attach(serv);
  pinMode(Lechopin,INPUT);
  pinMode(Ltrigpin,OUTPUT);
  pinMode(Rechopin,INPUT);
  pinMode(Rtrigpin,OUTPUT);
}

void loop() {
  get_L_dist();
  L = get_L_dist();
  get_R_dist();
  R = get_R_dist();

  normalp();
  value1();
  value2();
  value3();

  //bailout;
}

//print sensors
/*
Serial.print("L is:");
Serial.println(L);
Serial.print("R is:");
Serial.println(R);
*/

/* read left sensor and calculate the distance */
long get_L_dist() {
  digitalWrite(Ltrigpin, LOW);
  delayMicroseconds(dt3);
  digitalWrite(Ltrigpin, HIGH);
  delayMicroseconds(dt4);
  digitalWrite(Ltrigpin, LOW);
  Lduration=pulseIn(Lechopin, HIGH);
  Ldistance=Lduration / 58.2;
  return Ldistance;
}

/* read right sensor and calculate the distance */
long get_R_dist() {
  digitalWrite(Rtrigpin, LOW);
  delayMicroseconds(dt3);
  digitalWrite(Rtrigpin, HIGH);
  delayMicroseconds(dt4);
  digitalWrite(Rtrigpin, LOW);
  Rduration=pulseIn(Rechopin, HIGH);
  Rdistance=Rduration / 58.2;
  return Rdistance;
}

//normal position of servo
void normalp() {
  if (L >= normal & R >= normal) {
    servo.write(90);
    //goto
    loop();
  }
}

void value1() {
  if ((L < minn) >= 2 & (R < minn) >= 2) {
    int ran = random(2);
    if (ran == 0) {
      servo.write(30);
      //goto
      loop();
    }
    if (ran == 1) {
      servo.write(150);
      //goto
      loop();
    }
  }
}

void value2() {
  /* I'm using L !> normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */
  if ((L < R) >= 6 & L !> normal) {
    servo.write(120);
    //goto
    loop();
  }
}

void value3() {
  /* I'm using R !> normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */
  if ((R < L) >= 6 & R !> normal) {
    servo.write(60);
    //goto
    loop();
  }
}

```

# Answer
> 0 votes
Use `<=` instead of `!>`; the latter is not proper C++ syntax.

Also, `if (L < R) >= 6` doesn't do what you may think: `(L < R)` evaluates to `true` or `false`, so the whole expression will always evaluate to `false`. Did you mean `if (L - R) >= 6` maybe?

Also, you use `&` as an "and" in your `if` statements, which should be `&&`.

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


title: how to transfer json to string?

text:
# Question
Title: how to transfer json to string?
I am getting a json object from aws iot MQTT. Assuming that json from aws is {status:opened}. Here is my code.

```
#include <ArduinoJson.h>
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  StaticJsonDocument<32> doc;
  deserializeJson(doc, payload);
  const char *status = doc["status"];
  Serial.println(status);//opened
  if (status == "opened")
  {
    Serial.println("door is opened");//not excute
  }
  else if (status == "closed")
  {
    Serial.println("door is closed");
  }
}

```

Why the if condition is not being excute?

# Answer
That's one of the peculiarities of the C language: the `==` operator compares the string addresses, not their content. It makes sense when you think of them as pointers, but it can be confusing for beginners.

To fix this, you can use `strcmp()` like so:

`if (strcmp(status,"opened") == 0)`

Alternatively, you can change the type of `status` to `JsonVariant`, like so:

`JsonVariant status = doc["status"]`

It works with `JsonVariant` because I overloaded the `==` operator to support string comparison.
> 6 votes

---
Tags: c++, iot, json, mqtt
---


title: esp_now.h: No such file or directory

text:
# Question
Title: esp_now.h: No such file or directory
```
Arduino: 1.8.19 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 4M (1M SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
esp_now_testing:3:21: fatal error: esp_now.h: No such file or directory
 #include <esp_now.h>
                     ^
compilation terminated.
exit status 1
esp_now.h: No such file or directory
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

Couldnt compile for a node mcu esp8266 board. Have installed esp8266 library from boards manager

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

// Variables for test data
int int_value;
float float_value;
bool bool_value = true;

// MAC Address of responder - edit as required
uint8_t broadcastAddress[] = {0x24, 0x6F, 0x28, 0x7A, 0xAE, 0x7C};

// Define a data structure
typedef struct struct_message {
 char a[32];
 int b;
 float c;
 bool d;
} struct_message;

// Create a structured object
struct_message myData;

// Peer info
esp_now_peer_info_t peerInfo;

// Callback function called when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
 Serial.print("\r\nLast Packet Send Status:\t");
 Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

void setup() {

 // Set up Serial Monitor
 Serial.begin(115200);

 // Set ESP32 as a Wi-Fi Station
 WiFi.mode(WIFI_STA);

 // Initilize ESP-NOW
 if (esp_now_init() != ESP_OK) {
   Serial.println("Error initializing ESP-NOW");
   return;
 }

 // Register the send callback
 esp_now_register_send_cb(OnDataSent);

 // Register peer
 memcpy(peerInfo.peer_addr, broadcastAddress, 6);
 peerInfo.channel = 0;
 peerInfo.encrypt = false;

 // Add peer
 if (esp_now_add_peer(&peerInfo) != ESP_OK){
   Serial.println("Failed to add peer");
   return;
 }
}

void loop() {

 // Create test data

 // Generate a random integer
 int_value = random(1,20);

 // Use integer to make a new float
 float_value = 1.3 * int_value;

 // Invert the boolean value
 bool_value = !bool_value;

 // Format structured data
 strcpy(myData.a, "Welcome");
 myData.b = int_value;
 myData.c = float_value;
 myData.d = bool_value;

 // Send message via ESP-NOW
 esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

 if (result == ESP_OK) {
   Serial.println("Sending confirmed");
 }
 else {
   Serial.println("Sending error");
 }
 delay(2000);
}

```

# Answer
> 0 votes
To use ESP-NOW with ESP8266 and Arduino IDE, you must use the "espnow.h" header file. In this case, the error codes change and only need to use int values for success(0). esp\_now\_peer\_info\_t is not required to add peers. Here is the code:

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

// Variables for test data
int int_value;
float float_value;
bool bool_value = true;

// MAC Address of responder - edit as required
uint8_t broadcastAddress[] = {0x24, 0x6F, 0x28, 0x7A, 0xAE, 0x7C};

// Define a data structure
typedef struct struct_message {
 char a[32];
 int b;
 float c;
 bool d;
} struct_message;

// Create a structured object
struct_message myData;

// Callback function called when data is sent
void OnDataSent(uint8_t *mac_addr, uint8_t status) {
 Serial.print("\r\nLast Packet Send Status:\t");
 Serial.println(status == 0 ? "Delivery Success" : "Delivery Fail");
}

void setup() {

 // Set up Serial Monitor
 Serial.begin(115200);

 // Set ESP32 as a Wi-Fi Station
 WiFi.mode(WIFI_STA);

 // Initilize ESP-NOW
 if (esp_now_init() != 0) {
   Serial.println("Error initializing ESP-NOW");
   return;
 }

 // Register the send callback
 esp_now_register_send_cb(OnDataSent);

 // Add peer
 if (esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 0, NULL, 0) != 0){
   Serial.println("Failed to add peer");
   return;
 }
}

void loop() {

 // Create test data

 // Generate a random integer
 int_value = random(1,20);

 // Use integer to make a new float
 float_value = 1.3 * int_value;

 // Invert the boolean value
 bool_value = !bool_value;

 // Format structured data
 strcpy(myData.a, "Welcome");
 myData.b = int_value;
 myData.c = float_value;
 myData.d = bool_value;

 // Send message via ESP-NOW
 int result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

 if (result == 0) {
   Serial.println("Sending confirmed");
 }
 else {
   Serial.println("Sending error");
 }
 delay(2000);
}

```

---
Tags: esp8266, nodemcu, esp
---


# Question
Title: How to abort compilation based on a "wrong" value in a variable
I looking for some code that can generate a compile time error when a variable contains a wrong value.

I once started with this code in a c program:

```
#define FIFO_BUFFER_SIZE 8

#define FIFO_BUFFER_MASK ( FIFO_BUFFER_SIZE - 1 )

#if ( FIFO_BUFFER_SIZE & FIFO_BUFFER_MASK )
#error Fifo buffer size is not a power of 2
#endif

```

Rewrote that in C++ for a PC console application:

```
MovingAVG::MovingAVG( const unsigned long element_count ) {
    ptr = 0;
    siz = element_count;
    buf = new long[siz];
    msk = siz - 1;
    if( siz & msk ) {
        //std::cerr << "Buffer size is not a power of 2" << std::endl;
        //exit( -1 );
    }
}

```

Now I want to use something similar in an Arduino sketch. Because there is not always a terminal connected to the serial port and exit() is useless in a microcontroller, I am looking for a way to abort compilation based on a value in a variable. I don't give myself much chance to find anything but to be absolutely sure that there is really no way, I am dropping the question here.

I want to abort compiling (preferably with a message) when the parameter of a class-constructor contains an invalid value. Is that possible at all?

Actually I want to see a message before I start programming the device. I have posted a possible solution below, that will throw a message during linking, but that only works when I declare the class with a constant parameter:

```
class MovingAVG avg( 32 );

```

# Answer
> 3 votes
As suggested by timemage, I think `static_assert()` is the right solution to your problem: it is the clearest and most semantically correct. The problem is, you cannot plug `static_assert()` directly into your code, as the expression you are testing is not a compile-time constant.

I suggest you turn the argument of the constructor into a template argument. This will guarantee it is a compile-time constant. As a bonus, you will be able to use a statically-allocated buffer, which is nicer on the RAM than dynamic allocation:

```
template <int siz> class MovingAVG {
    static const int msk = siz - 1;
    long buf[siz];
    int ptr = 0;
public:
    MovingAVG()
    {
        static_assert((siz & msk) == 0,
                "Element count should be a power of two.");
    }
};

```

This works:

```
MovingAVG<32> filter;

```

but this fails with “error: static assertion failed: Element count should be a power of two.”:

```
MovingAVG<33> filter;

```

# Answer
> 1 votes
Because `element_count` is a method's parameter, it is by definition *variable*. Therefore, its value is generally **not known** at compile time.

Since the value of `element_count` is not known at compile time, you cannot get a compile time error for a wrong value.

---

Only if you use the method (here: a constructor) in the *same translation unit* as its definition, and if the arguments of all calls are known to the compiler (they are *constants*), the compiler will be able to evaluate `siz & msk` as a constant. Please note that some compilers need to receive optimization options for this.

Then you can use any approach that triggers a compiler diagnostic, for example like this one in C.

# Answer
> 1 votes
This will do the trick, a very dirty trick but it will generate an error before I program/test the device. That might save a few program cycles of the device, but more important it will not waste my time.

```
extern void ElementCountShouldBeAPowerOfTwo(void);

MovingAVG::MovingAVG( const unsigned long element_count ) {
    ptr = 0;
    siz = element_count;
    buf = new long[siz];
    msk = siz - 1;
    if( siz & msk ) {
        // This function will be removed by the optimiser
        // when the buffer size is a power of 2
        ElementCountShouldBeAPowerOfTwo();
    }
}

```

The compiler will not complain about the function "ElementCountShouldBeAPowerOfTwo" because it is marked as external. The linker will throw an error when the optimizer leaves the call in place.

In case the linker throws an error it will show:

```
undefined reference to `ElementCountShouldBeAPowerOfTwo()'

```

@chrisl I've used both code in C and in C++ and I don't want to rewrite the C++ part. You and @the\_busybee were both right when you wrote that the error will not be shown at compile time.

I should have asked my question differently, I want to see a warning before I program the device :-)

I do not mark an answer because I expect this to fail in the future when the compiler is updated. For the moment, with Arduino 1.8.19, it does what I want.

---
Tags: c++
---


# Question
Title: Alternate full speed usb library for ATTINY85?
I'm currently working on a project using the ATTINY85 for USB communication. After some research, it turns out that the V-USB library only supports usb 1.1, which only supports a 125hz polling rate. I would like to be able to have a polling rate of 1000hz, or close to it, which requires usb 2.0 or faster. I was hoping that someone could help point me to a library which supports usb 2.0, or suggest an alternative. Any help would be greatly appreciated, thanks in advance!

# Answer
Since an ATtiny85 has no built-in USB hardware module, you use a software solution like V-USB. Unfortunately bit-banging software cannot be as fast as hardware, so you are out of luck here. (Reading the documentation of V-USB is enlightened and explains the difficulties and limits of such a solution.)

You cannot have USB 2.0 with an ATtiny85 alone.

Possible solutions:

* an external USB module
* another microcontroller
> 1 votes

---
Tags: usb, attiny, attiny85
---