title: Is the LGT8F328P legal?

text:
# Question
Title: Is the LGT8F328P legal?
Since some months, everyone can buy a board with this IC.

It is compatible with the ATMega328 and has some features like 12bit ADC (instead of 10 bit), DAC, unique ID and also 32MHz.

But I can't find it in the "normal" shops. Also on the LCSC it is not available. Only in this shop: https://www.electrodragon.com/product/5pcs-logicgreen-lgt8f328p/
For 0.68$ compared to the 2$ for the atmega326P-AU of the other electronic parts shops (it is cheaper than the cheapest attiny with ADC!)

So the question. Is this chip just a clone for private use or can it be used as official alternative to the more expensive and original ATMega328?

# Answer
My understanding is that it is legal since it is just engineered to be (somewhat) compatible with ATmega328p but their difference are substantial if you deep dive.

It has a RISC core and its core instructions are quite different from ATmega328p. Most multi-cycle instructions are replaced by single-cycle instructions or less cycle instructions. And the core runs at 32Mhz from 1.8V-5.5V.

The peripheral registers are largely (backward) compatible with ATmega328. However, LGT has more or advanced peripherals.

* 2 16-bit timers, with capture and compare output
* ADC has 12 bits instead of 10.
* DAC, so you don't need PWM to emulate DAC.
* 9 high current PWM. 3 complementary PWM with dead band control.
* PGA 1x-32x differential amp. Which saved me 1 op-amp.
* 16 bit computing accelerator/Co-processor.
* High and adjustable current GPIO (so you can light up LEDs without current limiting resistors). These peripherals provide lots of additional registers for control and status reporting that don't exist on ATmega.

Development environment is also different. The best way for hobbyists to develop on this chip is either using LGT Arduino Core but not ATmega328 Arduino Core: https://github.com/dbuezas/lgt8fx (Arduino IDE) or https://community.platformio.org/t/how-to-add-lgt8fx-board/13294 (PlatformIO) Or you can use their official SDK for development which is very different from AVR's environment.

LGT8F328p also has SSOP20 and LFP48 package offering smaller or larger number of GPIOs, which are not so well known by DIY community since they are not similar to ATmega328p.

So in general LGT is a different, forward engineered chip and highly unlikely a direct silicon clone copied by reverse engineering.

In general having peripheral registers and pin compatibility are not illegal, unless the IP core of the peripherals are stolen from ATmega328p. And since CPU instructions (and clock trees) are quite different, if assembly language is used for development, developer would likely feel they are two distinct MCUs. It is just that a C compiler and Arduino framework can hide those details and make them similar.

However, the laws and regulations differ across countries and states so I am not sure if that applied to all markets. And there is natural murkiness in what is an IP and what is not. In software, API similarity could result in infringement but in the world of MCU pin compatibility would not, despite they are both "interface similarity" issues.
> 3 votes

# Answer
Legal or not, I DO NOT reccomend this clone. It is similar and compatible to some extend but it lacks features like an EEPROM. With fuses you can only reserve some FLASH to emulate an EEPROM. Thus have less space for your code.
Also the manual is only available in chinese. There are english translations but those are hard to read as the layout got screwed up.
It has some new features that sound great but I would not see them as replacement for the ATmega328P from Atmel/Microchip.

I bought an Arduino clone with LGT8F328P by accident. I find it barely usable as there are itches here and there which I don't want to deal with.
> 1 votes

# Answer
As legal as any other clone CPU / MCU. See

In short: if you copy the silicon design it's illegal. If you create it yourself from the ground up it's legal.

However, IANAL, so don't quote me on that.
> 0 votes

---
Tags: atmega328, hardware
---


# Question
Title: Serial port stops receiving data after random amount of time
EDIT: Things I have tried so far:

1. Increasing the baud rate, but this didn't make any difference as it still continued to stop receiving data after random amount of time.
2. I tried testing one sensor and reducing the sketch to something that only prints in a sketch. I can get the sketch to work up to 2 sensors where it prints the results continuously. 3 or 4 sensors and I get the issue mentioned.

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

Datasheets:

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

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

---

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

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

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

Thanks!

Here is my code below:

```
// Included libraries
#include <Arduino.h>
#include <Wire.h>

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

// Definitions
#define DEV_I2C Wire
#define SerialPort Serial

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

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

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


# Question
Title: Tools > Board settings: how are they captured?
In the Arduino IDE, the Tools menu can be used to make some board-specific settings like this:

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

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

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

# Answer
> 2 votes
The board settings from Tools menu are stored in the IDE preferences file.

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

---
Tags: arduino-ide
---


title: Strange Character In Tempurture Reading

text:
# Question
Title: Strange Character In Tempurture Reading
Can anyone identify this character?

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

The simplest solution might be to add

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

```

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

---
Tags: esp32
---


# Question
Title: Can not burn arduino pro mini 8 MHz bootloader with usbasp
I am using schematic of Arduino Pro mini 3.3v/8 MHz version. Please see below circuit diagram I built.

Power supply to circuit is 3.3V.

I have a USB ASP programmer which I used in previous version of same circuit running at 5V/16MHz. It was working fine. It is connected to board like this.

I want to burn bootloader in this controller so that I can use with arduino IDE. I have done following settings.

When I connect USBASP to PC (Windows 10), in device manager, I see the USBASP. Driver installed through Zadig.

When I click Tools --\> Burn Bootloader in arduino IDE , I get this error

avrdude: error: program enable: target doesn't answer. 1

avrdude: initialization failed, rc=-1

```
     Double check connections and try again, or use -F to override
     this check.

```

Error while burning bootloader.

What I have tried: 1 - Changed firmware of USBASP to official fishl.de website.

2 - Put JP3 on USBASP.

3 - Changed driver of USBASP from libusb-k to libusb-win32 from Zadig. Error changes to

Arduino: 1.8.15 (Windows 10), Board: "Arduino Pro or Pro Mini, ATmega328P (3.3V, 8 MHz)"

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: error: program enable: target doesn't answer. 1

avrdude: initialization failed, rc=-1

```
     Double check connections and try again, or use -F to override

     this check.

```

4 - Replaced microcontroller from some other board to this board.

5 - Checked voltage on 8 MHz crsytal pins of controller. 3.12V and 3.28V. Cant see wave on oscilloscope.

Nothing works. Same error. I was hopeful that maybe atemga328 is faulty but even after changing it, it doesnt work and I cant burn bootloader and get same error.

Can this be due to crystal capacitor values of 10 pF instead of 20pF? (I chose 10nF after reading datasheet carefully).

Any ideas why this problem?

# Answer
The problem was related to crystal. When I changed to another crystal (different part number), it worked.
> 1 votes

---
Tags: bootloader, arduino-mini, usbasp
---


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

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

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

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

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

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

Edit `line 45` containing by default `CONFIG_LOG_DEFAULT_LEVEL_ERROR=y` to one of the following lines depending on your desired log level:

```
CONFIG_LOG_DEFAULT_LEVEL_NONE=y # No output
CONFIG_LOG_DEFAULT_LEVEL_ERROR=y # Errors - default
CONFIG_LOG_DEFAULT_LEVEL_WARN=y # Warnings
CONFIG_LOG_DEFAULT_LEVEL_INFO=y # Info
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y # Debug
CONFIG_LOG_DEFAULT_LEVEL_VERBOSE=y # Verbose - All of the above

```

Then simply build the libs for all SoCs or one specific SoC. Note that building for all SoCs takes a lot of time, so if you work only with one specific SoC, build only for that one. If you have copied the defconfig file and the debug settings are in file `configs/defconfig.debug` add flag `debug` example : `./build.sh debug` Build all SoCs: `./build.sh` Build only selected SoC: `./build.sh -t <soc>` The exact text to choose the SoC:

* esp32
* esp32s2
* esp32c3
* esp32s3 Example: `./build.sh -t esp32` A wrong format or non-existing SoC will result in the error `sed: can't read sdkconfig: No such file or directory`

---
Tags: esp32, datalogging
---


# Question
Title: variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type
I have a problem with lcd, I have NUCLEO64 L746RG , I have Lcd Display and I2C connected to it. When I verify code it gives me and long error and I can not find the solution or cause of this error:

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

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

```

This is my code:

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

```

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

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

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

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

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

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

```

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

The top part is where the compiler proper is having issues with the macro expansion where it causes a more fundamental error, `error: expected identifier before '(' token` This is because it is trying to insert the macro definition directly into where it has found it resulting in this code effective after preprocessing:

```
class ((LCD_TypeDef *) LCD_BASE) : public Print

```

which is gibberish. It's pointing to the first open parenthesis there and saying `expected identifier`, the `identifier` being the class name it expected to see, not this cast and other stuff that follows. Whoever wrote your LiquidCrystal library did not expect `LCD` to already be defined as something via macro. This is one of a number of reasons why macros are hated.

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

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

```

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

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

---
Tags: arduino-nano, i2c, lcd, stm32
---


# Question
Title: What is the raw value & scale value functionality of analog read() of ESP32 ? (Provided for UNO for reference)
What is the difference between ESP32 Dev kit & Uno for **analogread() Function?**

As Uno -0 to 1023 As Esp 32 Dev Kit -0 to 4095

**So what will be the raw val & scale val ?**

**For UNO -**

```
int Rawval = analogRead(analogPin);
Serial.print("Rawvalue from Analog input =");
Serial.print(Rawval);
Scaleval = map(Rawval, 0, 675, 0, 20);
Serial.print(" Scaled Value =");

```

**What will be for ESP32 Dev Kit?**

**Ref UNO-** // For 3V3 input to read 100%, 3V3 of 5V ref = (3.3 / 5) * 1023 = 675

/// === RELAY code ===

```
// raw value 675 correspond to 20%, so for 5% we will get 169
  if ( Rawval < 169) digitalWrite(RELAY_pin, HIGH);
  else  digitalWrite(RELAY_pin, LOW);
}

```

**What will be for ESP32 Dev Kit?**

# Answer
Confusion! Here also, As you said that code for UNO was provided by someone expert.
> -1 votes

---
Tags: arduino-uno, esp32
---


# Question
Title: Need help figuring out how to organise a system to run a stepper motor at low speed without Steps-skipping
TL;DR : How to prevent step-skipping with a NEMA gearbox motor at low speed.

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

My system consists in:

This is the code I ended up with:

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

int mouvement=0;

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

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

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

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

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

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

```

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

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

My hypothesis of why steps are skipped:

* Too high a speed for the motor
* Not enough torque power supplied
* Not good enough electricity supply to the motor.

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

Especially this bit:

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

```

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

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

**My questions are:**

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

# Answer
> 0 votes
> How to calculate the best speed for such a system and how to implement it?

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

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

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

> Is there need for acceleration/ decceleration?

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

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

> Does microstepping makes sense when using a gearbox?

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

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

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

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

---
Tags: arduino-uno, motor, stepper, speed, a4988
---


# Question
Title: SIM800C developer board "SIM not inserted"
I bought this SIM800C development board (vendor unknow):

I conected it to an Arduino and put a brand new SIM card in it. This is the model of SIM I'm using:

Problem is, development board doesn't detect SIM card:

```
at+cfun=1,1
OK
at+cpin?
+CME ERROR: SIM not inserted
at+csmins?
+CSMINS: 0,0

```

This is the scenario:

* 6 pin SIM in a 6 pin SIM card holder.
* SIM works fine in a cel phone. Send/receive voice call/sms.
* Older, working SIM from various providers doesn't get detected either.
* Every other non-SIM related aspect works.
* No reboots, no flickering.
* Board takes care of regulating voltages and signal levels.

I put an oscilloscope probe on the SIM\_VDD pin (against board ground) and got this on every power-on:

Two 1.8v and two 3v pulses. That's all.

Please, note that I have no access to all SIM connexions (multi layer PCB).

How do I solve this problem?

# Answer
The print on the PCB and product description at sellers site states it is GSM/GPRS board. The module on the board comes from SIMCom. This particular SIM800 module seems to have following capabilities as per SIMCom:

* Compliant to GSM phase 2/2+
* GPRS multi-slot class 12/10
* Quad-band 850/900/1800/1900MHz

I think at the best you can only use a 2G SIM card on this board. Any 3G/4G SIM will not work.

Thanks for those images in the problem description, it gave me relevant keywords to search.
> 2 votes

# Answer
**This is a hardware problem.**

We have experience the same issue in the company I'm working for and after a short discussion with a SimCOM Engineer we conclude it was a soldering issue. The problem may lies in the PCB or inside the SimCOM module. In both cases some part/parts are not soldered or the solder contact is broken. If the problem is outside you may fix it by inspecting the parts. If it is inside the SimCOM module there are very little you can do with the usual tools.

Just to be clear I quote a little bit of the discussion

Original question to SimCOM:

```
A)We apply a zero pulse to PWR-key pin as you can see in the channel-1(yellow line)
and immediately the SIM800c module wakes up, the net and status led pins
become active (one led on the other blinks).

B) After a short time <1.5sec the SIM800c deploy a signal to SIM_VDD pin
(channel-2 - blue line)

Now in some boards the SIM_VDD pin goes to 1.8V as it appears in the
first of the 4 pulses and stay there. This situation is true if there is
a SIM card in the slot and the SIM800c is working properly. In that case
we can proceed and register to the network, send SMS etc...

In some boards though, as you can see in the screenshots, the SIM800
seams not to recognize the SIM card and tries again with 2 more pulses in
3V and one last one in 1.8V. The behavior is like there is no SIM-card in
the slot. Just to be clear. The SIM card is the same in all tests.
VBAT=3.9V, SIMVDD produced fine at 2.8V etc... The boards are identical
and no further code with AT commands is running.

```

Quite final answer from SimCOM:

```
It must be a soldering issue then. Did they followed recommended Solder
Reflow Profile?
https://www.elecrow.com/download/SIM800C_Hardware_Design_V1.02.pdf page 46

Please ask them where they measured signal from the scope pictures. From
the SIM card pins? If no, can they repeat that on them and send pictures.

```
> 0 votes

# Answer
This happened to me too with a SIM808 module on my own PCB. I would get those same 4 pulses on `SIM_VDD` and then nothing. I got the same `+CME ERROR: SIM not inserted` error with any AT command that had to do with the SIM card.

After futzing for wayyy too long, it turned out I had soldered the SIM slot on backwards! I am using the SIM8051-6-0-14-01-A holder and it has locating pins, but they're symmetrical. As a result, my SIM card was connected backwards and wasn't working.

Flipping it around fixed everything. Good luck!
> 0 votes

---
Tags: hardware
---


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

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

This is my code:

```
#include <Arduino.h>

#define AN_OUTPUT 15

int counter = 0;

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

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

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

```

And this is the corresponding signal:

# Answer
This link had the answer, you have to **remove** the `pinMode(PIN, OUTPUT)` line.
> 1 votes

---
Tags: analog
---


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

could anyone possibly help me?

EDIT: (this is the correct code sorry)

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

int inputval=0;
int outval =0;

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

}

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

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

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

```

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

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

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

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

1. Use a variable called maxb, which changes the **maximum possible** value used in the analogWrite() values so that it it not always 255. You can adjust that value based on reading the LDR. You will have to do some experimenting and don't expect a huge range of values. Now, your color will still be picked at random, but with an adjustment for intensity.
2. You *"should"* try to use resistors on each of the RGB LEDs that will produce something close to equivalent brightness. This will vary somewhat between RGB LEDs. Below is a graph of where I looked at this for a color fader project many years ago. I used an old BH1750 ambient light sensor to get the lux values. That dashed line is for the equivalent brightness of the individual LEDs by resistor value (ohms) used \[220-Red, 750-Green, 470-Blue\]. This is not an ideal way, but it is easy.

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

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

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

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

That is how I would do it anyways :)

---
Tags: arduino-uno, programming, led, rgb-led, error
---


# Question
Title: Can the Arduino Uno use a negative supply voltage (0V & -5V)
I acquired a bread-making machine. See control board image. I want to use the machine for other purposes and control the buttons, paddle, heater & 7-segment display with an Uno. As it stands, the machine provides 0V, -5V & -11V to the control board.

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

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

Control board findings:

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

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

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

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

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

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

---

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

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

---
Tags: arduino-uno, voltage-level
---


title: Setting pinmode() in header file

text:
# Question
Title: Setting pinmode() in header file
I am trying to have a header file to handle all my pin definitions and pinmodes.

This is the header:

```
#ifndef __HEADER_TESTER__
#define __HEADER_TESTER__

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

pinMode(LED_BUILTIN, OUTPUT);

#endif

```

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

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

```

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

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

---
Tags: c++, header, pinmode
---


# Question
Title: How to connect Arduino Nano to Thermal Printer via serial connection
I have a generic Arduino Nano board that uses the old bootloader. I have the printer and the Arduino connected like so:

This is my code:

```
#include "Adafruit_Thermal.h"

// Here's the new syntax when using SoftwareSerial (e.g. Arduino Uno) ----
// If using hardware serial instead, comment out or remove these lines:

#include "SoftwareSerial.h"
#define TX_PIN 5 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define RX_PIN 6 // Arduino receive   GREEN WIRE   labeled TX on printer

SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor
// Then see setup() function regarding serial & printer begin() calls.

// Here's the syntax for hardware serial (e.g. Arduino Due) --------------
// Un-comment the following line if using hardware serial:

//Adafruit_Thermal printer(&Serial1);      // Or Serial2, Serial3, etc.

// -----------------------------------------------------------------------

void setup() {

  // This line is for compatibility with the Adafruit IotP project pack,
  // which uses pin 7 as a spare grounding point.  You only need this if
  // wired up the same way (w/3-pin header into pins 5/6/7):
  // pinMode(BUILTIN, OUTPUT); digitalWrite(7, LOW);

  // NOTE: SOME PRINTERS NEED 9600 BAUD instead of 19200, check test page.
  mySerial.begin(9600);  // Initialize SoftwareSerial
  //Serial1.begin(19200); // Use this instead if using hardware serial
  printer.begin();        // Init printer (same regardless of serial type)

  // The following calls are in setup(), but don't *need* to be.  Use them
  // anywhere!  They're just here so they run one time and are not printed
  // over and over (which would happen if they were in loop() instead).
  // Some functions will feed a line when called, this is normal.

  // Font options
  printer.setFont('B');
  printer.println("FontB");
  printer.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  printer.setFont('A');
  printer.println("FontA (default)");
  printer.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

  printer.sleep();      // Tell printer to sleep
  delay(3000L);         // Sleep for 3 seconds
  printer.wake();       // MUST wake() before printing again, even if reset
  printer.setDefault(); // Restore printer to defaults
}

void loop() {
}

```

When I run my code or reset no prints get sent to the print.

Here's what I've tried.

* Ensure power is on on both devices
* Try baud rate 19200
* Swop Tx and Rx cables around
* Tried D5 and D6 for Tx and Rx

Any help would me much appreciated.

# Answer
Your additional info about your printer tells me that it has a Bluetooth and a USB interface - but I can not see any other serial connection port.

So there is no way connecting this printer as-is to the arduino nano by some digital port pins.

You may decide to either buy the Thermal printer offered by Adafruit our search for a Thermal printer that clearly states that is has a "Serial Interface" or "Serial RS232 Interface" - no matter if that comes with "TTL" or not like the Adafruit printer.

The printer is intended to be connected to a USB host port (of an PC or RPi or so) or via Bluetooth (to an PC or Android phone).

It may offers a virtual serial interface over both USB and Bluetooth, but that is a speculation.

*It may be possible to hack your printer. I think the Adafruit printer was modded by Adafruit. They may have bought a stock-printer and added the connector for the TTL interface. This may also be possible with the printer you have, but that is not in the scope of your question and highly speculative.*
> 1 votes

---
Tags: arduino-nano
---


title: Why is the watchdog biting to quickly?

text:
# Question
Title: Why is the watchdog biting to quickly?
currently trying to implement a watchdog into my project. I am using the WDTZero library for controlling the watchdog on my MKR NB 1500. The program is trying to measure data, send it to a server, go to sleep, wake up, and repeat the process. Sometimes the code can hang if it can't connect to the NTP server or the server on which the data is being stored, I want the watchdog to reset the program in cases in which this happens.

A sketch of the program is below. The reason why the NB network is often after different connections is that the NB 1500 is not able to connect to another server if the GPRS connection is already open, so I always reset it before trying another connection.

```
void setup()
{
    setup_watchdog(); //Sets up the watchdog timer
    delay(1000);
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    request_NTP(); //Requests epoch1970 from the NTP server and then closes the connection
    timezone_adjustment(); //Adjusts the epoch time to my timezone (in Norway)
    set_RTC(); //Activates the SAMD21 RTC with this timezone adjusted time
    disconnect_NB(); //Disconnects from the NB network
    delay(2000);
    MyWatchDoggy.clear(); //Resets the watchdog timer
    }

void loop()
{
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    get_ENV_data(); //Takes measurements using the MKR NB ENV shield
    connect_to_server(); //Connects to the server in which the data will be stored
    write_to_server(); //Writes the data on the server
    disconnect_from_server(); //Disconnects from the server
    disconnect_NB(); //Disconnects from the NB network

    LowPower.deepSleep(300000); //Goes to deep sleep for 5 minutes
    delay(3000);
    MyWatchDoggy.clear(); //Resets the watchdog timer
}

```

All the functions above are written in other .cpp files and imported thru header files into the main file. Here is the code for activating and configuring the watchdog:

```
#include "watchdog.hpp"
#include "GPRS_NB_connection.hpp"

WDTZero MyWatchDoggy;

void setup_watchdog()
{
    MyWatchDoggy.attachShutdown(NVIC_SystemReset); //calls reset function
    MyWatchDoggy.setup(WDT_SOFTCYCLE8M); //8 minute watchdog timer
}

```

The program works fine in the way described at the top of the post when the watchdog is not included. But when including the watchdog, it bites after 30 seconds when the dog only should have bit after 8 minutes. I see this because data is being sent about every 25-30 seconds to the server. At first, I thought I had not activated the watchdog in the right way, so I wrote another program to test it:

```
#include <Arduino.h>
#include <WDTZero.h>
#include <RTCZero.h>

WDTZero MyWatchDoggy;
RTCZero rtc;

void set_RTC()
{
    rtc.begin();
    rtc.setYear(0);
    rtc.setMonth(0);
    rtc.setDay(0);
    rtc.setHours(0);
    rtc.setMinutes(0);
    rtc.setSeconds(0);
}

void shutdown()
{
    Serial.println("Shutting down");

}

void setup()
{
    Serial.begin(9600);
    while (!Serial)
    {

    }
    Serial.println("Starting up Arduino");
    MyWatchDoggy.attachShutdown(shutdown);
    MyWatchDoggy.setup(WDT_SOFTCYCLE8M);
    set_RTC();

}

void loop()
{
    Serial.print(rtc.getMinutes());
    Serial.print("/");
    Serial.print(rtc.getSeconds());
    Serial.println("");
    delay(1000);
}

```

But in this program the watchdog bites after about 8 minutes as it should.

I have not included the code for the functions described in the first code since I know they work without the watchdog and the code itself is very long. But if you think the problem could be caused by these functions for some reason, I will edit the post and include all the function codes.

# Answer
> 1 votes
In the WDTZero library the long watchdog times are achieved by restarting the watchdog timer in watchdog interrupt until the required time is reached.

This doesn't work if the MCU sleeps.

---
Tags: watchdog, arduino-mkr
---


# Question
Title: I got a missignatured ATmega328-PU. How can I fix that?
Sometime in the past, I was burning bootloaders on a fresh batch of four **ATmega328-PU** using the Arduino IDE (notice there's no **P** after 328 - it's the slightly cheaper non-picopower version of the MCU, not to be confused with the **ATmega328P-PU** with a **P**), and was surprised with the following message from avrdude:

```
avrdude: Device signature = 0x1e950F
avrdude: Expected signature for ATMEGA328 is 1E 95 14
Double check chip, or use -F to override this check.

```

That means avrdude thought the chip was not what its label said. Then I changed the chip type on my Arduino IDE to **ATmega328P-PU** and avrdude burned the bootloader without complaints. What that means is that the chip was labelled as one MCU and internally it responded as another, slightly different.

What I would like to know is:

* ~~How rare is this event? Has anyone had a similar experience?~~ (*Original question, off-topic*)
* Is it possible to fix this? How can I fix the signature so that avrdude recognize the chip correctly?

This is a cross-post from EE.SE. I posted this question there but didn't attract much attention, so I wanted to see if anyone from our community had a similar experience.

# Answer
> 4 votes
While browsing sparkfun, i have found several news posts that show their struggle with mislabeled chips. Here are a few:

Sparkfun had received a questionable shipment if ICs from a new seller in china. They decided to test them before sending them into production, and none of their test boards worked. Using nitric acid, they were able to remove the case of the ICs and fould a hunk of metal that looked like copper.

In another article, they dissected some suspicious ICs from Atmel, and found an ON semiconductor silicon wafer inside. The chips were not functional ATmegas, but they did have silicon, unlike the other ones.

# Answer
> 3 votes
Not the preferred way to fix things and certainly not the first solution to consider, but you can consider programming the signature bytes. Before attempting this be absolutely sure you really want to do this and you have investigated what is involved to undo this. This may involve changing configuration files on your computer ...

Anyways the way to set the controller's signature bytes is as follows (untested, I don't have a spare AVR lying around):

```
avrdude -p atmega328 -c arduino -P /dev/ttyUSB003 -b 19200 -v -U signature:w:0x1E,0x95,0x14:m

```

# Answer
> 1 votes
There are several different flavors of ATMega328. The most commonly found in Arduinos Uno (et al) is the ATMega328P, which is Atmel's "picopower" version; this one has the 0x1E950F signature that AVRDude expects when it's tasked with programming an Arduino Uno. Gee, figure that.

Less common is the base model ATMega328 (no suffix) and the ATMega328PU, both of which yield a 0x1e9514 signature instead of the expected 0x1E950F.

As to commonality... that depends upon the crowd with which you run. If you are Arduino through-and-through, never use any boards that aren't teal-colored, then it's extremely uncommon for you to find a non-ATMega328P. If, on the other hand, you run in my gang and build all manner of cool stuff on funny-colored boards that don't have staggered header pin spacing in one spot... then it's very common to get non-p '328s.

There are workarounds. There was for a while a variant ArduinoISP\_Multi that would translate a 0x1e9514 signature to a 0x1E950F signature, permitting you to gleefully program your breadboarded or otherwise non-teal '328 boards exactly as if they were genuine Arduino Unos. For whatever reason that "sketch" can no longer be found.

You can also edit avrdude.conf (with backup, please!) such that it (AVRDude) expects the signature that your '328 coughs up. The backup is particularly important because you may want someday to program "real teal". The avrdude.conf file can be found in your Arduino installation at ...\hardware\tools\avr\etc.

OR... wait! There's MORE! All for one money! You can also write your own hardware profile for non-P '328s and put it in your Arduino "sketchbook"'s hardware directory, then draw from that as a custom board definition. Aw, shucks... it ain't that hard! Really! I've written several of those for my own board designs.

---
Tags: atmega328
---


# Question
Title: How to configure watchdog for the arduino Nano 33 BLE Sense board?
For the arduino Nano 33 BLE Sense board, the standard `avr/wdt.h` is not available. And it seems that no standard library provides it. How to use the watchdog system for this board ? I found no full information about it.

I've found the page https://www.mysensors.org/apidocs/group\__avr\__watchdog.html which allow to configure the reboot mode. And it works. But no way to configure the interruption mode with `ISR()` function. Moreover, there's no explanation about the manipulation of used register/variables for any fine configuration.

Simple code example with regular asynchronous stuff using the watchdog ISR() mechanism. It which works well with ATmega328 (e.g.UNO). But I do not find equivalent configuration for the Nano 33 BLE using the nRF52840.

```
# include <avr/wdt.h>

volatile byte led;
int k;

ISR(WDT_vect) {
  Serial.println("Asynchronous stuff in ISR() function");
  digitalWrite(LED_BUILTIN,led);
  led=!led;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  WDTCSR = ( 1 << WDE ) | ( 1 << WDCE );
  WDTCSR = ( 1 << WDP2 ) | ( 1 << WDP0 ) | ( 1 << WDIE ) ; // Interruption and timeout  1/2 s
}

void loop() {
  Serial.print("Loop #");
  Serial.println(k);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}

```

Thks.

# Answer
> 0 votes
In fact, for the RF52940, I'm not sure that the watchdog can provide the needed interruption mechanism despite it exists the INTENSET bit for interruption according to the chipset doc https://content.arduino.cc/assets/Nano\_BLE\_MCU-nRF52840\_PS\_v1.1.pdf). But the good way is for sure the use of timers (and one can use more than just one, quite good).

For a similar behaviour as the code given for the UNO before, here is the code one can write for the Nano BLE using a timer interrupt (see https://github.com/khoih-prog/NRF52\_MBED\_TimerInterrupt for full and usefull doc).

```
#include "NRF52_MBED_TimerInterrupt.h"

volatile byte led;
volatile uint32_t count=0;
NRF52_MBED_Timer myTimer(NRF_TIMER_1);
unsigned k=0;

void myHandler() {
  digitalWrite(LED_BUILTIN,led);
  led=!led;
  count++;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  if (myTimer.attachInterruptInterval(500*1000, myHandler)) // each 1/2 second
    Serial.println("myTimer launched");
  else
    Serial.println("Can not set the timer");
}

void loop() {
  Serial.print("Loop #");
  Serial.print(k);
  Serial.print(" and nb times in Handler : ");
  Serial.println(count);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}

```

# Answer
> -1 votes
You do not want to update your watchdog in an ISR. It is possible to get stuck but the ISR is continually triggered. I have seen this happen many times especially when a bad transient hits it. I normally use an external one so it will force a reset on the whole package. I do this by power cycling everything. Not all watchdog timers in processors will do an external reset.

---
Tags: arduino-nano, arduino-nano-ble, watchdog
---


# Question
Title: How do i fix the "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header"
I have an AI Thinker ESP32-CAM and I've had issues uploading the CameraWebServer sketch, every time I hit upload it says "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header" and I've tried everything that I can think of, I disconnected and reconnected all the connections on my FTDI board and I've done all sorts of button presses during the connection, I've switched the voltage and I've bought a whole new board and I don't know what the issue is or how to fix it.

# Answer
**ESP32 only works with 3.3 V serial do not switch the FTDI voltage to 5 V**

**Watch out for the serial connections too**

U0R--\>TX

U0T--\>RX

**If you mixed it up it won't work!**

First of all you need to connect two pins only when uploading It is all ready fixed for you need to press the rest button when uploading and seeing these dots as below image.

* ESP32-CAM on-board RST button **Press and hold until you see uploading**

After a few seconds, the code should be successfully uploaded to your board.

I hope this helped for you!

You can reffer to this link for more info

https://randomnerdtutorials.com/esp32-cam-take-photo-display-web-server/
> 2 votes

# Answer
I have had the same problem / error message with a different board. I did not realise that during upload you **must** make sure that any GPIO pins that the board uses to talk to the flash chip **are NOT connected to other devices**. The upload process should be:

1. Disconnect any GPIO pin connectors.
2. Upload your code.
3. Reconnect any GPIO pin connectors.

(In your question, you say "I disconnected and reconnected all the connections" but **you do not say** whether all your connections were disconnected while you were trying to upload your code.)

I found this information here (the text in that post says "This message normally means that the ESP32 can't talk to its attached flash chip (the flash chip may be in the module). Check the GPIO pins 6,7,8,9,10 & 11 (which are shared with the flash chip) are not connected to anything external or shorted together, etc.")

HTH.
> 1 votes

---
Tags: esp32
---


# Question
Title: How can i separate values from the full string, incoming string always changes its positions?
```
String str = {"timestamp": "2023-02-08 16-37-31" ,"cpcb_device": [{"Station" : "832","Para": [{"tag_name": "COD","tag_value": "35.5","tag_unit": "mg/l"},{"tag_name": "BOD","tag_value": "13.7","tag_unit": "mg/l"},{"tag_name": "TSS","tag_value": "24.8","tag_unit": "mg/l"},{"tag_name": "pH","tag_value": "6.5","tag_unit": "pH"}]}]}

```

# Answer
You can use substring() and indexOf() to get parts of the string at certain positions. for example:

```
String test = "timestamp: 123 value: test";

int val = test.indexOf("timestamp:"); //gives you the index for the beginning of "timestamp:"
int start = test.indexOf(" ", val)+1; //get index of the space starting at our 'val' index
int end = test.indexOf(" ", start); //get index of the next space, we added 1 to the previous value so it doesn't pick up the first space
timestamp = test.substring(start, end); //get the characters between these two index values

```

Try it out and see how it works for you, obviously getting the index of separating characters that make more sense, such as a comma or colon rather than a space.
Also you could do it like this:

```
String search = "timestamp:";
int start = test.indexOf(search)+search.length();
//etc...

```
> 0 votes

---
Tags: esp32, string
---


# Question
Title: delayMIcroseconds and micros execution time not explainable
i just experimented with the timing accuracy of my Arduino Uno R3 using this code:

```
unsigned long beginTime;
unsigned long endTime;

void setup() {
  Serial.begin(9600); // open a serial port
}

void loop() {
  beginTime = micros();
  delayMicroseconds(200);
  endTime = micros();
  delay(500);
  Serial.println(endTime-beginTime);
  delay(500);
}

```

The results I got are (just an excerpt):

```
200
204
200
200
204
204
204
200
212
208
212
204
204

```

I tried to understand this behavior, read this link Can I make delayMicroseconds more accurate?.

Due to the timing of `micros` (4 µs) I would understand values between 200 and 208. **But why do I get occasional values of 212 microseconds?** I'm kinda curious, since I bought the Arduino because of bare-metal programming and bounded execution times.

# Answer
> 2 votes
The Arduino core uses hardware Timer0 with its ISR (Interrupt Service Routine) for timekeeping. While `delayMicroseconds()` directly uses the value of the hardware timer, `delay()` and `millis()` are handled by the ISR. It will be called regularly.

If the ISR is getting executed during your measurement, then the execution time of the ISR will add to the execution time of your measured code. Thus you get a higher count occasionally.

To prevent this you can either deactivate all interrupts (via `noInterrupts()`) or deactivate this specific interrupt, either by stopping Timer0:

```
TCCR0B &= ~( (1 << CS02) | (1 << CS01) | (1 << CS00) );

```

or by letting the timer run, but deactivating its interrupts:

```
TIMSK0 = 0;

```

For details about this have a look at the datasheet of the Atmega328p, which is the microcontroller on the Arduino Uno.

---
Tags: timing
---


# Question
Title: an lcd with I2C is not recognized by esp32
I have a NodeMCU esp32-s board and I'm trying to connect My 16x2 lcd with PCF8574T I2C bus to the esp32 , the problem is that the lcd doesn't show anything and the WireScan sketch can't recognize the lcd too,but when I use arduion uno ,it's recognized and work perfectly ,I hope somebody can help me,the schematic for the connection is :

the schematic for the connection of the lcd with the bus is below with the bus module part number :

# Answer
> 1 votes
You can run the PCF8574 on 5V and the EXP on 3V3 just be sure the I2C is pulled up to the 3V3 and NOT the 5V. I do this a lot and have never had a problem. The reason it works is the bus is driven by open collector/drain drivers which do not source any voltage.

---
Tags: arduino-uno, arduino-ide, esp32, lcd
---


# Question
Title: How can I connect 2 Arduinos using ESP8266 transiver: ESP01
I have: 2 arduinos UNO, 2 ESP01 transivers. But if that's not enough, I'm ready to buy something else I need to use one of Arduinos as a wifi hot spot, and the second as a modem. They should just be connected to each other :) P.S. This is for my school project! Subsequently, I will put some obstacles between the Arduinos to see how much the signal strength degrades.

# Answer
Here is the ESP8266 WiFi library:
https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi

In there You'll find an example for a WiFi access point:
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino

And an example for WiFi client:
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino

That should provide enough information for you to build your project.

To get the signal strength without connecting, you can use WiFiScan:
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino
> 0 votes

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


# Question
Title: adc arduino using reference voltage to read stable/constant lithium battery voltage
I want to read my lithium battery voltage.

1. I WANT TO CREATE A FUNCTION TO READ MY 3.7~4.2V,1200mAH BATTERY VOLTAGE THROUGH A MICROCONTROLLER (ARDUINO OR ATTINY44).
2. THEN I WANT TO CALL THE CREATED BATTERY FUNCTION IN THE FORMULA TO READ PRECISE SENSOR VALUE

```
 int voltage = ((CALLING BATTERY FUNCTION) * (READ SENSOR VALUE)) / 1023;

```
3. I AM USING INTERNAL REFERENCE VOLTAGE 1.1V. NOTE: I want the whole system to run on lithium battery ( I am just creating a prototype on Arduino, if it works, ill be editing the code for my attiny44 using 8mhz external crystal).

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

 void loop() {
   //REFS1 AND REFS0 to 1 1 -> internal 1.1V refference
   ADMUX |= B11000000;
   //We read A1 (MUX0)
   ADMUX |= B00000001;
   // Start AD conversion
   ADCSRA |= B11000000;
   // Detect end-of-conversion
   while (bit_is_set(ADCSRA,ADSC));
   float val = ADCL | (ADCH << 8);
   val = val * 5.7; //Multiply by the inverse of the divider
   Serial.println(val);
 }

```

**This code is working but it is reading from analog Pin. Is there any possibility to do it without using AnalogPin because I dont have any spare pin on my attiny.**

# Answer
> 1 votes
> I want the whole system to run on lithium battery

If you power the Arduino from the battery, then you can indirectly read the battery voltage by reading the internal voltage reference. This requires no pins - just connect the battery across the Arduino ground and the 5V pin. Here is more explanation on why this works...

https://wp.josh.com/2014/11/06/battery-fuel-guage-with-zero-parts-and-zero-pins-on-avr/

Note: Do not connect more than 5 volts or less than 0 volts to the `5V` Arduino pin. This pin is connected directly to the AVR without any overvoltage or reverse polarity protection. Your 3.7~4.2V battery should be fine.

---
Tags: arduino-uno, attiny, voltage-level, voltage-divider, analogreference
---


# Question
Title: Cannot compile MFRC522 minimal I2C example
On ESP32 I'm trying to build the Minimal I2C example of the MFRC522 library: But I get errors on the first declarations:

```
TwoWire i2cBus = TwoWire(0);
MFRC522_I2C dev = MFRC522_I2C(RST_PIN, 0x28, i2cBus);
MFRC522 mfrc522 = MFRC522(dev); // <--- error

```

Here the build output:

```
src/rfid.cpp:6:30: error: no matching function for call to 'MFRC522::MFRC522(MFRC522_I2C&)'
 MFRC522 mfrc522 = MFRC522(dev);
                              ^
In file included from include/rfid.h:5,
                 from src/rfid.cpp:1:
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:348:2: note: candidate: 'MFRC522::MFRC522(byte, byte)'
  MFRC522(byte chipSelectPin, byte resetPowerDownPin);
  ^~~~~~~
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:348:2: note:   candidate expects 2 arguments, 1 provided
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:347:2: note: candidate: 'MFRC522::MFRC522(byte)'
  MFRC522(byte resetPowerDownPin);
  ^~~~~~~
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:347:2: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'byte' {aka 'unsigned char'}
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:346:2: note: candidate: 'MFRC522::MFRC522()'
  MFRC522() DEPRECATED_MSG("use MFRC522(MFRC522_BUS_DEVICE bus_device)");
  ^~~~~~~
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:346:2: note:   candidate expects 0 arguments, 1 provided
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:343:2: note: candidate: 'MFRC522::MFRC522(MFRC522_BUS_DEVICE*)'
  MFRC522(MFRC522_BUS_DEVICE * dev);
  ^~~~~~~
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:343:2: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'MFRC522_BUS_DEVICE*'
In file included from include/rfid.h:5,
                 from src/rfid.cpp:1:
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note: candidate: 'constexpr MFRC522::MFRC522(const MFRC522&)'
 class MFRC522 {
       ^~~~~~~
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'const MFRC522&'
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note: candidate: 'constexpr MFRC522::MFRC522(MFRC522&&)'
.pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'MFRC522&&'

```

Unfortunately there is no way to open an issue on the repository. Why the official example does not work?

## UPDATE

Here the compatibility declaration for ESP32:

# Answer
> -1 votes
if you look, it says, "Candidate expects 2 inputs, one provided."

so in the arduino IDE hover over the function and see what it expects.

(What your putting in `MFRC522(byte resetPowerDownPin);` what it expects: `MFRC522(byte resetPowerDownPin, Something else);`)

---
Tags: esp32, rfid
---


title: Button Matrix / Wiring Schematics

text:
# Question
Title: Button Matrix / Wiring Schematics
I am just beginning my journey into the Arduino world - plenty of development experience, but basically nothing with electronics outside of building computers.

The question I have involves wiring schematics - specifically for a button matrix, but it does apply more broadly. Using this diagram and Fritzing mapping, I see numerous buttons connected to each other - presumably via soldering:

My question is, can you use wire nuts (or, more specifically multi-slot lever connectors) such as these to simplify the connection process?

I apologize in advance if this seems obvious, but I get lost trying to understand how to connect this stuff because I'm so new to it all.

Thanks in advance!

# Answer
Assuming that "multi-slot lever connectors" is shorting the inserted wires together I see no reason why you could not use them.

If you are adverse to soldering consider using switches and cables commonly found in arcade machines instead.

Previously crimped cables ...

And arcade style micro switches ...

Can be combined / connected to form the switch matrix your designed above.
> 1 votes

---
Tags: arduino-uno, button, wires
---


# Question
Title: How to use reset pin as I/O pin with ATtiny44
I am using the Arduino IDE as an ISP programmer to program my ATtiny44 IC. Unfortunately, I ran out of pins, so I want to use the reset pin as I/O. I read several articles online that says it is possible and even the datasheet says so.

I have a high voltage programmer as well. I wrote the code in the Arduino IDE and then used its hex file to program it using the high voltage programmer (TNM PROGRAMMER).

After I program, the IC stops working.

////////////////////////////////////EDIT/////////////////////////////////////

```
const int led = 0;
const int reset_led = 11; //physical pin 4 on attiny

// the setup function runs once when you press reset or power the board
void setup() {
    // initialize digital pin LED_BUILTIN as an output.
    pinMode(led, OUTPUT);
    pinMode(reset_led, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
    digitalWrite(reset_led, HIGH);  // turn the LED on (HIGH is the voltage level)
    digitalWrite (led, HIGH);
    delay(1000);                    // wait for a second
    digitalWrite(reset_led, LOW);   // turn the LED off by making the voltage LOW
    digitalWrite(led, LOW);         // turn the LED off by making the voltage LOW
    delay(1000);                    // wait for a second
}

```

New fuse bit setup:

////////////////////////EDIT 2 /////////////////////////////////////////

Now, the led on reset has turned off completely while the another still blinks. Powering my attiny44 with 5v.Code is same as before

////////////////////////////////EDIT 3////////////////////////////////////

```
#include <avr/io.h>
const int led = 0;
#define ledd PB3
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(led, OUTPUT);

DDRB |= (uint8_t)(1<<PB3);
pinMode (ledd, OUTPUT);

}

// the loop function runs over and over again forever
void loop() {

PORTB |= (uint8_t)(1<< PB3);

 digitalWrite (led, HIGH);
  digitalWrite (ledd, HIGH);

 delay(1000);                       // wait for a second

PORTB &= ~((uint8_t)(1 << PB3)); // set PB3 to "low"

 digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
 delay(1000);                       // wait for a second
}

```

This code worked miraculously for me, Thanks to @thebusybee.

/////////////////////////////EDIT 3/////////////////////////////////////////

The PB3 pin is pin11 in arduino.

# Answer
The data sheet gives insights:

Chapter 1.1.4 states:

> The reset pin can also be used as a (weak) I/O pin.

"*Weak*" means here, that the output function cannot deliver as much current as the other outputs, according to figures 21-24 to 21-27 beginning at page 198 roughly 2 to 3 mA. This is commonly not enough for LEDs, except you use a high-efficiency LED.

And on page 66 is this relevant table (I cut the irrelevant column for PB2):

> **Table 10-8.** Overriding Signals for Alternate Functions in PB\[3:2\]
>
> | Signal Name | PB3/RESET/dW/PCINT11 |
> | --- | --- |
> | PUOE | RSTDISBL(1) \+ DEBUGWIRE\_ENABLE(2) |
> | PUOV | 1 |
> | DDOE | RSTDISBL(1) \+ DEBUGWIRE\_ENABLE(2) |
> | DDOV | DEBUGWIRE\_ENABLE(2) • debugWire Transmit |
> | PVOE | RSTDISBL(1) \+ DEBUGWIRE\_ENABLE(2) |
> | PVOV | 0 |
> | PTOE | 0 |
> | DIEOE | RSTDISBL(1) \+ DEBUGWIRE\_ENABLE(2) \+ PCINT11 • PCIE1 |
> | DIEOV | DEBUGWIRE\_ENABLE(2) \+ (RSTDISBL(1) • PCINT11 • PCIE1) |
> | DI | dW/PCINT11 Input |
> | AIO |  |
>
> Note:
>
> 1. RSTDISBL is 1 when the Fuse is “0” (Programmed).
> 2. DebugWIRE is enabled when DWEN Fuse is programmed and Lock bits are unprogrammed.

Since you have `DebugWIRE` enabled, this seems to be the cause. The alternate function `RESET` is still active.

Please be aware that according to note 1 below table 19-4 on page 160:

> After programming the RSTDISBL fuse, high-voltage serial programming must be used to change fuses and allow further programming.

This means that your circuit at PB3 needs to withstand the high voltage, and that the voltage source needs to provide enough current, which the circuit additionally draws at the high voltage.

---

Now to your code.

You use the pin number "0" and hope to have PB3. Well, according to this shamelessly linked pinout this is not correct:

Pin "0" is PA0.

PB3 has no number assigned.

Your next step could be to look up the sources of the Arduino library and check, if PB3 has a number assigned at all. I'm afraid this is not the case. If you're lucky and it has, use it. You will want to tell us about your finding then.

You can directly access the data direction control register and the port register. Grab your data sheet and other documentation, read, and implement.

This is untested:

```
// in setup():
    DDRB |= (uint8_t)(1U << 3);

// in loop():
    PORTB |= (uint8_t)(1U << 3);    // set PB3 to "high"
    PORTB &= ~((uint8_t)(1U << 3)); // set PB3 to "low"

```
> 1 votes

---
Tags: input, reset, programmer, arduinoisp
---


# Question
Title: Using MFRC522 along with other inputs (Bluetooth, keypad)
I'm making a little parking lot, which includes mostly opening a servo motor using either keypad, Bluetooth (hc-05) and freshly added, RFID (RC522).

I can't get inputs from other sources if I want to get the UID from the RFID meaning when I added the only piece of code that I found that returns the UID it seems to block all the `void loop()` hence all the other inputs/code don't work. Here's the full code:

```
#include <LiquidCrystal.h>  //Lcd functions library
#include <Servo.h>          //Servo Motor
#include <SoftwareSerial.h>//Bluetooth functions library:HC05 IS SUPERIOR!
#include "TM1637.h"        //4 digit display functions library
#include <SPI.h>
#include <MFRC522.h>
//Credit to Baroryan

//copyright (c)*/
const int rs = 38, en = 39, d4 = 36 ,d5 = 37, d6 = 41, d7 = 40;//Defining LCD PINS
const int DA=31, D0=30,D1=33,D2=32,D3=35;//Defining KEYPAD data PINS
const int servoPin=43,buzzer=42,rx=53,tx=52;//Defining(By order): servo pin, buzzer pin, 4DD pins, and bluetooth pins(rx tx)
//buzzer pin is 36!
//,CLK=34,DIO=35

#define SS_PIN 45
#define RST_PIN 44
int count = 0;
int cnt=0;//this cnt is used later on to make sure all 5 chars are equal.
int cnt2=0;//used for switch case to count how many chars were already received
int cnt3=0;
char c=0;//this is where we place the char received from the user

char password[5] = {'8', '5', '2', '0', '#'};
char keysPressed[5] = "";
char keys[5]="";

byte customChar2[] = {
  B00000,
  B00000,
  B01010,
  B00000,
  B10001,
  B01110,
  B00000,
  B00000
};

byte customChar[] = {//Custom Char for lcd screen, in this case; a heart.
  0x00,
  0x00,
  0x0A,
  0x1F,
  0x1F,
  0x0E,
  0x04,
  0x00
};
//  #define DA 25 Used to define Keypad pins and other misc using #Define which talks to the processor->
//  #define D0 24  ->decided to use const int instead.
//  #define D1 27
//  #define D2 26
//  #define D3 29
//  #define servoPin 37
//  #define buzzer 36
//  #define CLK 34
//  #define DIO 35
void lcdSetup();
void gateOpenSequence();
void returnKey(int key);
void wrongPassword();
void Beep();
SoftwareSerial Bluetooth(rx,tx);//intialize bluetooth to pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);//intialize LCD to pins
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
Servo servo;//intialize servo
byte nuidPICC[4];

void printHex(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

void setup()
{
  Serial.begin(9600);
  Bluetooth.begin(9600);
  SPI.begin();      // Initiate  SPI bus
  pinMode(DA ,INPUT);
  pinMode(D0 ,INPUT);
  pinMode(D1 ,INPUT);
  pinMode(D2,INPUT);
  pinMode(D3,INPUT);
  mfrc522.PCD_Init();   // Initiate MFRC522
  lcd.begin(20,4);
  lcdSetup();//Self Created function that turns lcd to our preffered default screen "Home screen"
  servo.attach(servoPin);
  servo.write(5);
  pinMode(buzzer,OUTPUT);
  digitalWrite(buzzer, HIGH);
  delay(200);
  digitalWrite(buzzer, LOW);
  Bluetooth.print("Enter 1 to open the gate!");//Write to user bluetooth terminal instructions
  lcd.createChar(2, customChar2);
  lcd.createChar(1, customChar);
}

void loop()
{

  if (!mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  //Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "17 27 C7 A6" || "BA FA 21 28") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    delay(3000);
  }

 else   {
    Serial.println(" Access denied");
    delay(3000);
  }

  char Data=Bluetooth.read();//Recieves Data from bluetooth and places it in variable 'Data'
  if(Data=='1'){//if data from bluetooth equals to 1(1 recieved from bluetooth IS NOT an integer, it is a char.)
    gateOpenSequence();//Self created function that executes all actions when Gate need to be opened.
  }
  while(digitalRead(DA)==1){         //While recieving characters from keypad.
    int key =digitalRead(D3)*8 + digitalRead(D2)*4 +digitalRead(D1)*2 + digitalRead(D0);//Certain formula used to decipher what key has been pressed
    returnKey(key);//Self created function that translates key deciphered to keypad layout. puts key pressed into variable 'c'
    Serial.print(c);
    if(c!='D') keys[cnt3]=c;

    switch(cnt2){
      case 0:
        if(c!='D'){
          lcd.clear();
          lcd.setCursor(9, 0);
          lcd.print(keys[cnt3]);
          ++cnt3;
          ++cnt2;
          Beep();
          break;
        }
        else break;
      case 1:
        if(c!='D'){
          lcd.setCursor(8,0);
          lcd.print("*");
          lcd.print(keys[cnt3]);
          ++cnt3;
          ++cnt2;
          Beep();
          break;
        }
        else{
          lcd.clear();
          --cnt3;
          --cnt2;
          break;
        }

      case 2:
        if(c!='D'){
          lcd.setCursor(8, 0);
          lcd.print("**");
          lcd.print(keys[cnt3]);
          ++cnt2;
          ++cnt3;
          Beep();
          break;
        }
        else{
          lcd.clear();
          lcd.setCursor(9,0);
          cnt3--;
          cnt2--;
          lcd.print(keys[cnt3-1]);

          break;
        }

      case 3:
        if(c!='D'){
          lcd.setCursor(8, 0);
          lcd.print("***");
          lcd.print(keys[cnt3]);
          ++cnt2;
          ++cnt3;
          Beep();
          break;
        }
        else{
          lcd.clear();
          lcd.setCursor(9,0);
          lcd.print("*");
          cnt3--;
          cnt2--;
          lcd.print(keys[cnt3-1]);
          break;
        }
      case 4:
        if(c!='D'){
          cnt2=0;
          cnt3=0;
        }
        else{
          lcd.clear();
          lcd.setCursor(9, 0);
          lcd.print("**");
          cnt2--;
          cnt3--;
          lcd.print(keys[cnt3-1]);
        }
      break;
    }
    while(digitalRead(DA)==1);//Making sure we wont get double input from one press, forcing the loop to stay there as long as a key is pressed
    if(c!='D'){
      keysPressed[count] = c;//Placing key pressed into an array
      count++;//raising array index
    }
    else{
      keysPressed[count]="";
      count--;
     }
    if (count == 5)//when count reaches 5, meaning array is full check if array 'password' is equal to the 5 keys the user just entered.
    {
      for (int i = 0; i < 5; i++)
      {
        if (password[i] == keysPressed[i])//if keys are the same add one to cnt, if cnt equals to 5, it means all keys were the same
        {
          cnt++;
        }
      }
        if(cnt==5){
          gateOpenSequence();
          cnt=0;
        }
        else{
          wrongPassword();
          cnt=0;
        }
        }
      }
  }

void returnKey(int key)
{
  char arrkey[16]={ '1','2','3','A','4','5','6','B','7','8','9','C','*','0','#','D' };
  c=arrkey[key];

}

void lcdSetup(){
  lcd.setCursor(0,0);
  lcd.write(2);
  lcd.setCursor(1, 0);
  lcd.write(1);
  lcd.setCursor(18,0);
  lcd.write(1);
  lcd.setCursor(19,0);
  lcd.write(2);
  lcd.setCursor(2,0);
  lcd.print("----Welcome-----");
  lcd.setCursor(0,1);
  lcd.print("|  Enter password  |");
  lcd.setCursor(0,2);
  lcd.print("|and then press '#'|");
  lcd.setCursor(0, 3);
  lcd.print("|------------------|");
}
void gateOpenSequence(){
  int start = 0;
  int desired = 105;
  lcd.clear();
  lcd.setCursor(6,0);
  lcd.print("Welcome");
  lcd.setCursor(8,1);
  lcd.print("Home");
  count = 0;
  digitalWrite(buzzer,HIGH);
  while(start<desired){
  servo.write(++start);
  delay(10);
  }
  delay(1000);
  digitalWrite(buzzer,LOW);
  lcdSetup();
  while(start>5){
  servo.write(--start);
  delay(10);
  }

}
void wrongPassword(){
  lcd.clear();
  lcd.setCursor(7,0);
  lcd.print("Wrong");
  lcd.setCursor(6,1);
  lcd.print("Password");
  lcd.setCursor(4, 2);
  lcd.print("Achalta ota");
  count = 0;
  for(int jj=0;jj<3;jj++){
    Beep();
  }
  delay(2000);
  lcdSetup();

}

void Beep(){
  digitalWrite(buzzer,HIGH);
  delay(200);
  digitalWrite(buzzer,LOW);
  delay(200);
}

```

I will really appreciate help as I can't seem to find any explanations about these two functions:

```
if (!mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  //Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

```

# Answer
```
mfrc522.PICC_IsNewCardPresent()

```

will check, if a new RFID card/tag was presented to the reader. So if this returns `true`, you can read the card.

```
mfrc522.PICC_ReadCardSerial()

```

will actually read the data from the card/tag, so that the UUID is then available via `mfrc522.uid`.

---

Your problem stems from how you are using these functions. Lets have a look at that exact code snippet:

```
if (!mfrc522.PICC_IsNewCardPresent())
{
    return;
}
//Select one of the cards
if (!mfrc522.PICC_ReadCardSerial())
{
    return;
}

```

When we translate the first if statement into english we get:

```
 If no new card is present restart the function `loop()`.

```

This code snippet is at the start of the function. This means, that you will only read the code below that, if a new card is present and could be read. This logic only works good, if the RFID code is the only thing done in that function, which is not the case for you.

Instead you can restructure your RFID code a bit:

```
if(mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()){
    // Handling all RFID code in here
    //Show UID on serial monitor
    Serial.print("UID tag :");
    String content= "";
    byte letter;

    for (byte i = 0; i < mfrc522.uid.size; i++)
    {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
        content.concat(String(mfrc522.uid.uidByte[i], HEX));
    }
    Serial.println();
    Serial.print("Message : ");
    content.toUpperCase();
    if (content.substring(1) == "17 27 C7 A6" || "BA FA 21 28") //change here the UID of the card/cards that you want to give access
    {
        Serial.println("Authorized access");
        Serial.println();
        delay(3000);
    } else {
        Serial.println(" Access denied");
        delay(3000);
    }
}

```

This will execute the RFID code, if a new card could be read. Otherwise it will just continue with the rest of the code.

Note, that due to the `delay(3000)` call your code won't react to anything for 3 seconds after a card was presented to the reader. You might wanna ditch that delay in favor of a better responsiveness.
> 0 votes

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


# Question
Title: Wemos D1 mini won't connect to WiFi: status code 6
So I have a Wemos D1 mini which I want to connect to my WiFI in order to let is push sensor data to my server. But I cannot connect it with my WiFi as I get a code 6.

```
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

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

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

```

The `Serial.print(WiFi.status());` prints 6 which is WL\_CONNECT\_FAILED if I'm right.

I checked the router and it uses WPA/WPA2, the ssid and password are correct. The router is using 2.4 GHz with WiFi 802.11b and 802.11g.

I used the board to scan, with the example code provided by the esp8266 board manager library thing, and it found my SSID with the ones of my neighbors.

Can somebody tell me what is going wrong?

I already checked solutions like: This one , github answers, etc.

Edit: It can connect to a mobile phone hotspot. It gives code 6 1 time and then it connects. Any one an idea how I connect to the WiFi the router is providing ?

# Answer
Apparently, something went wrong with connecting to the router. The router was casting 802.11 g + n, which for some reason, made the esp8266 give a code 6. I have tried 802.11 b, 802.11 b+g+n, 802.11 n, which work all fine.

So I updated the settings that the router now uses 802.11n and the esp8266 can now connect to the internet!
> 1 votes

# Answer
For me, the solution was manually setting the mode to 802.11g as explained here: https://github.com/esp8266/Arduino/issues/8412

Add the following code before connecting the WiFi:

```
WiFi.setPhyMode(WIFI_PHY_MODE_11G);

```
> 0 votes

---
Tags: esp8266, wifi
---


title: Using timer0 on Arduino Uno

text:
# Question
Title: Using timer0 on Arduino Uno
I am trying to find a simple timer0 interrupt example, but none of those work. Neither this code which I tried to run:

```
boolean toggle0 =0;

void setup() {
pinMode(8, OUTPUT);
  cli();

  // Set timer1 interrupt at 1 Hz
  TCCR1A = 0; // Set entire TCCR1A register to 0
  TCCR1B = 0; // Same for TCCR1B
  TCNT1  = 0; // Initialize counter value to 0

  // Set compare match register for 1 Hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)

  // Turn on CTC mode
  TCCR1B |= (1 << WGM12);

  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);

  // Enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER0_COMPA_vect){  // Change the 0 to 1 for timer1 and 2 for timer2
  if (toggle0){
    digitalWrite(8,HIGH);
    toggle0 = 0;
  }
  else{
    digitalWrite(8,LOW);
    toggle0 = 1;
  }
}

void loop() {

}

```

What am I doing wrong?

# Answer
The main problem is you are using the wrong interrupt handler. You are setting up Timer1, but the interrupt handler is for Timer0:

```
boolean toggle0 = 0;

void setup() {
pinMode(8, OUTPUT);
  cli();
//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER1_COMPA_vect){  //change the 0 to 1 for timer1 and 2 for timer2
  toggle0 = !toggle0;
  digitalWrite(8, toggle0);
}

void loop() {

}

```
> 1 votes

# Answer
Arduino timers are reserved for buid-in functions:

Timer0 is reserved fire a millisecond interrupt for the millisecond counter Timer1 is reserved for measuring time passed since the last reboot Timer2 is reserved for pwm timing

So, using these timers is not a good suggestion if you plan to use above options. For me, Timer0 seems a good choice, as microsecond timing is a bit of an overkill.

Here you may find your solution: https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers
> 0 votes

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