body:
I want to use snprintf() to format floats to a string.

I know the "normal" version of Arduino's avrlibc had all the float-formatting code removed to make it smaller.

I also know that at some point in the fairly recent past, it became possible to force gcc to use an alternate (forked?) larger Arduino avrlibc that had all the float-formatting functionality that was originally removed put back in.

However... I'm still trying to find an actual explanation of *how to **do** that* for an Arduino project using **PlatformIO**.

I found a clue someplace where someone said, "change linker rules in platform.txt file to enable floating point xxprintf()" (which hopefully enables floating point support in other float-to-string functions as well).

Problem #1: `platform.txt` appears to be global rather than local to this one project. There's no file named "platform.txt" anywhere in the project's directory.

Problem #2: I **do** have *several dozen* files on my computer named `platform.txt`... I don't know which one is the one that actually matters to PlatformIO, and I don't know enough about PlatformIO's internals to know how to figure out which `platform.txt` is the one that *matters*.

Problem #3: Even if I manage to figure out which `platform.txt` is the one I need to modify, I still don't know what exact modifications actually need to be *made*.

---

Update: I stumbled over a thread in Arduino's Issue discussion (["Sprintf for floats on Arduino Mega 293"][1]) that said to append the text quoted further down to boards.txt. The relevant line appears to be `mega.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt`

So... I'm guessing that what I need to put somewhere in `platform.txt` (once I figure out which `platform.txt` is the one that matters) is `-Wl,-u,vfprintf -lprintf_flt`

~~~
##############################################################

menu.printf=AVR printf Version
menu.scanf=AVR scanf Version

yun.menu.printf.default=Default printf
yun.menu.printf.default.avr_printf_flags=
yun.menu.printf.full=Full printf
yun.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
yun.menu.printf.minimal=Minimal printf
yun.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

yun.menu.scanf.default=Default scanf
yun.menu.scanf.default.avr_scanf_flags=
yun.menu.scanf.full=Full scanf
yun.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
yun.menu.scanf.minimal=Minimal scanf
yun.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

yun.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

uno.menu.printf.default=Default printf
uno.menu.printf.default.avr_printf_flags=
uno.menu.printf.full=Full printf
uno.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
uno.menu.printf.minimal=Minimal printf
uno.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

uno.menu.scanf.default=Default scanf
uno.menu.scanf.default.avr_scanf_flags=
uno.menu.scanf.full=Full scanf
uno.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
uno.menu.scanf.minimal=Minimal scanf
uno.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

uno.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

diecimila.menu.printf.default=Default printf
diecimila.menu.printf.default.avr_printf_flags=
diecimila.menu.printf.full=Full printf
diecimila.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
diecimila.menu.printf.minimal=Minimal printf
diecimila.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

diecimila.menu.scanf.default=Default scanf
diecimila.menu.scanf.default.avr_scanf_flags=
diecimila.menu.scanf.full=Full scanf
diecimila.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
diecimila.menu.scanf.minimal=Minimal scanf
diecimila.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

diecimila.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

nano.menu.printf.default=Default printf
nano.menu.printf.default.avr_printf_flags=
nano.menu.printf.full=Full printf
nano.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
nano.menu.printf.minimal=Minimal printf
nano.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

nano.menu.scanf.default=Default scanf
nano.menu.scanf.default.avr_scanf_flags=
nano.menu.scanf.full=Full scanf
nano.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
nano.menu.scanf.minimal=Minimal scanf
nano.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

nano.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

mega.menu.printf.default=Default printf
mega.menu.printf.default.avr_printf_flags=
mega.menu.printf.full=Full printf
mega.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
mega.menu.printf.minimal=Minimal printf
mega.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

mega.menu.scanf.default=Default scanf
mega.menu.scanf.default.avr_scanf_flags=
mega.menu.scanf.full=Full scanf
mega.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
mega.menu.scanf.minimal=Minimal scanf
mega.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

mega.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

megaADK.menu.printf.default=Default printf
megaADK.menu.printf.default.avr_printf_flags=
megaADK.menu.printf.full=Full printf
megaADK.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
megaADK.menu.printf.minimal=Minimal printf
megaADK.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

megaADK.menu.scanf.default=Default scanf
megaADK.menu.scanf.default.avr_scanf_flags=
megaADK.menu.scanf.full=Full scanf
megaADK.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
megaADK.menu.scanf.minimal=Minimal scanf
megaADK.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

megaADK.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

leonardo.menu.printf.default=Default printf
leonardo.menu.printf.default.avr_printf_flags=
leonardo.menu.printf.full=Full printf
leonardo.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
leonardo.menu.printf.minimal=Minimal printf
leonardo.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

leonardo.menu.scanf.default=Default scanf
leonardo.menu.scanf.default.avr_scanf_flags=
leonardo.menu.scanf.full=Full scanf
leonardo.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
leonardo.menu.scanf.minimal=Minimal scanf
leonardo.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

leonardo.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

micro.menu.printf.default=Default printf
micro.menu.printf.default.avr_printf_flags=
micro.menu.printf.full=Full printf
micro.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
micro.menu.printf.minimal=Minimal printf
micro.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

micro.menu.scanf.default=Default scanf
micro.menu.scanf.default.avr_scanf_flags=
micro.menu.scanf.full=Full scanf
micro.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
micro.menu.scanf.minimal=Minimal scanf
micro.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

micro.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

esplora.menu.printf.default=Default printf
esplora.menu.printf.default.avr_printf_flags=
esplora.menu.printf.full=Full printf
esplora.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
esplora.menu.printf.minimal=Minimal printf
esplora.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

esplora.menu.scanf.default=Default scanf
esplora.menu.scanf.default.avr_scanf_flags=
esplora.menu.scanf.full=Full scanf
esplora.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
esplora.menu.scanf.minimal=Minimal scanf
esplora.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

esplora.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

mini.menu.printf.default=Default printf
mini.menu.printf.default.avr_printf_flags=
mini.menu.printf.full=Full printf
mini.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
mini.menu.printf.minimal=Minimal printf
mini.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

mini.menu.scanf.default=Default scanf
mini.menu.scanf.default.avr_scanf_flags=
mini.menu.scanf.full=Full scanf
mini.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
mini.menu.scanf.minimal=Minimal scanf
mini.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

mini.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

ethernet.menu.printf.default=Default printf
ethernet.menu.printf.default.avr_printf_flags=
ethernet.menu.printf.full=Full printf
ethernet.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
ethernet.menu.printf.minimal=Minimal printf
ethernet.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

ethernet.menu.scanf.default=Default scanf
ethernet.menu.scanf.default.avr_scanf_flags=
ethernet.menu.scanf.full=Full scanf
ethernet.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
ethernet.menu.scanf.minimal=Minimal scanf
ethernet.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

ethernet.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

fio.menu.printf.default=Default printf
fio.menu.printf.default.avr_printf_flags=
fio.menu.printf.full=Full printf
fio.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
fio.menu.printf.minimal=Minimal printf
fio.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

fio.menu.scanf.default=Default scanf
fio.menu.scanf.default.avr_scanf_flags=
fio.menu.scanf.full=Full scanf
fio.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
fio.menu.scanf.minimal=Minimal scanf
fio.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

fio.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

bt.menu.printf.default=Default printf
bt.menu.printf.default.avr_printf_flags=
bt.menu.printf.full=Full printf
bt.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
bt.menu.printf.minimal=Minimal printf
bt.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

bt.menu.scanf.default=Default scanf
bt.menu.scanf.default.avr_scanf_flags=
bt.menu.scanf.full=Full scanf
bt.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
bt.menu.scanf.minimal=Minimal scanf
bt.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

bt.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

LilyPadUSB.menu.printf.default=Default printf
LilyPadUSB.menu.printf.default.avr_printf_flags=
LilyPadUSB.menu.printf.full=Full printf
LilyPadUSB.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
LilyPadUSB.menu.printf.minimal=Minimal printf
LilyPadUSB.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

LilyPadUSB.menu.scanf.default=Default scanf
LilyPadUSB.menu.scanf.default.avr_scanf_flags=
LilyPadUSB.menu.scanf.full=Full scanf
LilyPadUSB.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
LilyPadUSB.menu.scanf.minimal=Minimal scanf
LilyPadUSB.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

LilyPadUSB.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

lilypad.menu.printf.default=Default printf
lilypad.menu.printf.default.avr_printf_flags=
lilypad.menu.printf.full=Full printf
lilypad.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
lilypad.menu.printf.minimal=Minimal printf
lilypad.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

lilypad.menu.scanf.default=Default scanf
lilypad.menu.scanf.default.avr_scanf_flags=
lilypad.menu.scanf.full=Full scanf
lilypad.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
lilypad.menu.scanf.minimal=Minimal scanf
lilypad.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

lilypad.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

pro.menu.printf.default=Default printf
pro.menu.printf.default.avr_printf_flags=
pro.menu.printf.full=Full printf
pro.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
pro.menu.printf.minimal=Minimal printf
pro.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

pro.menu.scanf.default=Default scanf
pro.menu.scanf.default.avr_scanf_flags=
pro.menu.scanf.full=Full scanf
pro.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
pro.menu.scanf.minimal=Minimal scanf
pro.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

pro.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

atmegang.menu.printf.default=Default printf
atmegang.menu.printf.default.avr_printf_flags=
atmegang.menu.printf.full=Full printf
atmegang.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
atmegang.menu.printf.minimal=Minimal printf
atmegang.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

atmegang.menu.scanf.default=Default scanf
atmegang.menu.scanf.default.avr_scanf_flags=
atmegang.menu.scanf.full=Full scanf
atmegang.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
atmegang.menu.scanf.minimal=Minimal scanf
atmegang.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

atmegang.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

robotControl.menu.printf.default=Default printf
robotControl.menu.printf.default.avr_printf_flags=
robotControl.menu.printf.full=Full printf
robotControl.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
robotControl.menu.printf.minimal=Minimal printf
robotControl.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

robotControl.menu.scanf.default=Default scanf
robotControl.menu.scanf.default.avr_scanf_flags=
robotControl.menu.scanf.full=Full scanf
robotControl.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
robotControl.menu.scanf.minimal=Minimal scanf
robotControl.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

robotControl.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

robotMotor.menu.printf.default=Default printf
robotMotor.menu.printf.default.avr_printf_flags=
robotMotor.menu.printf.full=Full printf
robotMotor.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
robotMotor.menu.printf.minimal=Minimal printf
robotMotor.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

robotMotor.menu.scanf.default=Default scanf
robotMotor.menu.scanf.default.avr_scanf_flags=
robotMotor.menu.scanf.full=Full scanf
robotMotor.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
robotMotor.menu.scanf.minimal=Minimal scanf
robotMotor.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

robotMotor.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

gemma.menu.printf.default=Default printf
gemma.menu.printf.default.avr_printf_flags=
gemma.menu.printf.full=Full printf
gemma.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt
gemma.menu.printf.minimal=Minimal printf
gemma.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min

gemma.menu.scanf.default=Default scanf
gemma.menu.scanf.default.avr_scanf_flags=
gemma.menu.scanf.full=Full scanf
gemma.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt
gemma.menu.scanf.minimal=Minimal scanf
gemma.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min

gemma.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags}

##############################################################
~~~

### Update 2:
I found what appears to be the solution & posted it as my own answer, but I'm going to hold off for a day or two to test it thoroughly and make sure it actually works.

  [1]: https://github.com/arduino/ArduinoCore-avr/issues/293

title: Enable full float-capable snprintf() library with PlatformIO

Answers: 1

body:
I finally found the answer at https://github.com/sstaub/LCDi2c

When using PlatformIO, add the following line to `platformio.ini` to enable full support for floats to printf():

`build_flags = -Wl,-u,vfprintf -lprintf_flt -lm`

### Caution:

This solution increases the amount of required flash by at least 2k. If you're using a Mega2560, you probably have flash to burn and really don't care. If you're using an Uno, Leonardo, Nano, or some other smaller AVR-based variant... it might matter, and you might *have* to care.

Tip: if the Nano/Leonardo/Uno doesn't have enough flash or SRAM, but you don't have space for a full-blown Mega2560, consider the "Arduino Nano Every". It uses the ATMega4809, with 48k flash and 6k SRAM.


body:
I'm currently using a Sparkfun 4 Half-Bridge load sensor (50 Kg) with combinator and amplifier both are from the Sparkfun. Link:https://www.sparkfun.com/products/10245 (For Load Sensors)https://www.sparkfun.com/products/13878 (Combinator)
https://www.sparkfun.com/products/13879 (HX711)
Our application requires long-term use i.e 8 to 10 hours of load application and monitoring the weight change during this time. Is this possible to achieve the above requirement using these chips/amplifiers? As we have experienced a drift in the readings if a weight is placed for more than approx. 3 minutes.
We are using 4 half-bridge sensors, a combinator, and an amplifier.The issues I am tackling right now are,
1) Zero balance: Load sensor value exponentially increases or decreases after calibration(this is a cyclic thing and keeps happening). The error ranges usually from -20g to +40g.
2) Drift in reading: When the load is placed and kept for more than 3 minutes a drift is observed which increases with time and rises up to 50 to 60g.
Can you please assist in this matter?
have used different libraries. Results are the same.

title: Fluctuation in 4 half bridge load cell via combinator

Answers: 1

body:
Consider a change in temperature either the cause or partially the cause for weight drift.  [This supplier web page][1] talks about load cell temperature compensation.  There they consider a 2000lb load cell.  Their chart infers a 20 degree Fahrenheit change can cause an temperature uncompensated load cell to change about 1.5lb.

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

  [1]: https://www.interfaceforce.com/understanding-load-cell-temperature-compensation/
  [2]: https://i.stack.imgur.com/5PuRH.jpg


body:
I have esp32 cam. I want to send https request to azure function. I have exposed https port via ngrok.

    HTTPClient http;

    if (http.begin("https://4b21-31-183-241-151.eu.ngrok.io/", rootCACertificate)) { //Specify the URL and certificate
      int httpCode = http.GET();                                                  //Make the request

      if (httpCode > 0) { //Check for the returning code

          String payload = http.getString();
          Serial.println(httpCode);
          Serial.println(payload);
        }

      else {
        Serial.println("Error on HTTP request");
      }

      http.end(); //Free the resources
    } else {
      Serial.println("Cannot begin");
    }

I have generated cert as `openssl s_client -showcerts -connect 4b21-31-183-241-151.eu.ngrok.io `

http.begin returns 1, but http.GET() returns -1.

I want to do it with minimal effort. I saw that HttpClient allows https, so I don't need explicitly init WiFiClientSecure.

What I'm doing wrong?

title: Cannot make https request on esp32

Answers: 0


body:
I'm trying to connect 3 LEDs to a LoLin NodeMCU ESP8266. It seems that several or "all" of the digital pins have some special use that prevents me from using them.

 - If I connect the LEDs (and set pinmode to output) to D0, D1 and D2, then the blue bootloading LED will glow constantly, and the code does not seem to run at all (nothing in serial output).
 - D3 seems to constantly have high power, regardless what I code it to.
 - If I connect the LEDs (and set pinmode to output) to D1, D2 and D4, then the blue bootloading LED will glow constantly, and the serial output is garbled, but I guess the code is running.
 - If I connect the LEDs (and set pinmode to output) to D5, D6 and D7, then the blue bootloading LED will glow constantly, and the serial output is garbled, but I guess the code is running.

Yes, I have checked the baud rate, that's not the problem.

What's up with this?

title: NodeMCU ESP8266 - Which pins can I use?

Answers: 1

body:
This link at [projecthub][1] says:

> In order to use digital pins, you should select GPIO numbers. For example, the D7 pin is defined as GPIO13. So you should set up the pin number 13 whenever you want to use D7 in your program. Also, you can use pin D2(GPIO4) as SDA and pin D1(GPIO5) as SCL

  [1]: https://create.arduino.cc/projecthub/electropeak/getting-started-w-nodemcu-esp8266-on-arduino-ide-28184f


body:
I am trying to use an ultrasonic sensor to stop a tiny voice-controlled car but I can't get it to work. once the motor starts moving it doesn't stop I'm trying to make the car stop moving even though it is already in motion. I need help writing a proper if statement or while loop to make the motor stop when there is an obstacle in its path.

    #include <SoftwareSerial.h>

    SoftwareSerial BT(0, 1); //TX, RX respetively
    String readvoice;
    int IN1= 3;
    int IN2= 4;
    int IN3= 5;
    int IN4= 6;
    int trigpin= 12;
    int echopin= 11;
    int pingTraveltime;
    void setup() {
    BT.begin(9600);
    Serial.begin(9600);
    pinMode(IN1, OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(IN3, OUTPUT);
    pinMode(IN4, OUTPUT);
    pinMode(trigpin, OUTPUT);
    pinMode(trigpin, OUTPUT);

    }
    //-----------------------------------------------------------------------//
    void loop() {
    while (BT.available()){ //Check if there is an available byte to read
    delay(10); //Delay added to make thing stable
    char c = BT.read(); //Conduct a serial read
    readvoice += c; //build the string- "forward", "reverse", "left" and "right"
    digitalWrite(trigpin,LOW);
    delayMicroseconds(10);
    digitalWrite(trigpin,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigpin,LOW);
    pingTraveltime=pulseIn(echopin,HIGH);
    Serial.println(pingTraveltime);
    }
    if (readvoice.length() > 0) {
    Serial.println(readvoice);

    if(readvoice == "*forward#")
    {
    while(pingTraveltime>500){
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
    }
    }

    else if(readvoice == "*back#" )
    {
    digitalWrite(IN1, LOW);
    digitalWrite(IN3, LOW);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN4,HIGH);
    }

    else if (readvoice == "*left#")
    {
    digitalWrite (IN1,HIGH);
    digitalWrite (IN2,LOW);
    digitalWrite (IN3,LOW);
    digitalWrite (IN4,LOW);

    }

    else if ( readvoice == "*right#")
    {
    digitalWrite (IN1, LOW);
    digitalWrite (IN2, HIGH);
    digitalWrite (IN3, LOW);
    digitalWrite (IN4, LOW);

    }

    else if (readvoice == "*stop#")
    {
    digitalWrite (IN1, LOW);
    digitalWrite (IN2, LOW);
    digitalWrite (IN3, LOW);
    digitalWrite (IN4, LOW);
    }

    readvoice="";}} //Reset the variable

title: Controlling Bluetooth voice-controlled car with ultrasonic sensor

Answers: 0


body:
I am attempting to use radio modules to receive a value from a sensor, either 1 or 0, and complete an action. The only problem is that I would like the action to only complete once per state change, instead of every time (if it activates when the variable is 0, only activate again when the variable changes to 1.) Despite the != sign, the code inside the if statement will not activate even if the variables are reading 0 and 1.

```
// Keyboard - Version: Latest
#include <Keyboard.h>
#include <KeyboardLayout.h>
#include <Keyboard_da_DK.h>
#include <Keyboard_de_DE.h>
#include <Keyboard_es_ES.h>
#include <Keyboard_fr_FR.h>
#include <Keyboard_it_IT.h>
#include <Keyboard_sv_SE.h>
#include <SPI.h>
#include "RF24.h"

RF24 myRadio (7, 8);
int mag = 2;
int prevState = 1; // 0=open, 1=closed

byte addresses[][6] = {"0"};

void setup()
{
  Serial.begin(9600);
  Keyboard.begin();
  delay(1000);

  myRadio.begin();
  myRadio.setChannel(115);
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate( RF24_250KBPS ) ;
  myRadio.openReadingPipe(1, addresses[0]);
  myRadio.startListening();
}

struct package
{
  int val;
};

typedef struct package Package;
Package data;

void loop()
{
  if ( myRadio.available())
  {
    while (myRadio.available())
    {
      myRadio.read( &data, sizeof(data) );
    }
    // Serial.print("state: ");
    Serial.println(data.val);
    int state = digitalRead(data.val);
    // Serial.print("prevState: ");
    // Serial.println(prevState);
    // Serial.print("\n");

    if (state != prevState) {
      Keyboard.press(' ');
      delay(50);
      Keyboard.press(KEY_LEFT_GUI);
      delay(50);
      Keyboard.press('D');
      delay(50);
      Keyboard.releaseAll();
      Serial.println("Executed successfully.");

      prevState = state;
    }
  }
  delay(1000);
}
```

title: Read State from Variable

Answers: 0


body:
I have a bunch of pins given names in the header:

~~~
#define DIP5 53
#define DIP4 52
#define DIP3 51
#define DIP2 50
#define DIP1 49
#define DIP0 48
~~~

If it's not obvious, I have a bunch of DIP switches connected to digital pins 48..53 on an Arduino Mega2560

In setup(), I need to set them all to INPUT_PULLUP. I know it would probably be less total effort to just do a series of pinMode commands, like:

~~~
pinMode(DIP5, INPUT_PULLUP);
pinMode(DIP4, INPUT_PULLUP);
// ... and so on
~~~

... but I'm trying to enrich my C++ skills & be fancy, so I'm trying to figure out how to declare an anonymous array and foreach through it... something like:

~~~
for (int pin : {DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) {
    pinMode(pin, INPUT_PULLUP);
}
~~~

... which, presumably, the compiler will optimize away into 6 inline pinMode commands anyway, but let me feel good about having pretty source code ;-)

except... when I try it, I get the following error:

`error: deducing from brace-enclosed initializer list requires #include <initializer_list>`

... but when I add `#include <initializer_list>`, I get a different error:

`fatal error: initializer_list: No such file or directory`

**Any ideas what's wrong?**

also... *can* I safely assume that the compiler will just unroll the whole thing behind the scenes, or is there a real risk it will *actually* declare a *real* array in SRAM just to iterate through one time?

title: How to do 'for' loop over inline anonymous array

Answers: 2

body:
> I'm trying to enrich my C++ skills & be fancy

The Arduino Mega is probably not the right platform to learn fancy C++.
The development environment doesn't support all the modern C++ stuff. In
particular...

> `fatal error: initializer_list: No such file or directory`

...it rests on avr-libc, which is a C library with only limited support
for C++.

> _can_ I safely assume that the compiler will just unroll the whole
> thing behind the scenes

No, you can't. The Arduino IDE, by default, calls avr-gcc with the `-Os`
flag, which means “optimize for code size”. Loop unrolling is the kind
of space vs. speed trade-off the compiler is unlikely to do with this
optimization setting. You can disassemble the .elf file if you want to
know for sure.

> is there a real risk it will _actually_ declare a _real_ array in SRAM
> just to iterate through one time?

I suggest you follow jsotola's advice and declare the array yourself.
You can declare the array `PROGMEM` if you want to avoid wasting RAM.
But given that it need not take more than 6 bytes (as `uint8_t[]`),
I would personally not even bother.

body:
Edgar Bonet [answers](https://arduino.stackexchange.com/a/89904/70020) why `for (int pin : {DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) {` isn't working. What you would get (where supported) with this syntax is an `initializer_list` which itself is not an *array type*, although it is *backed* by an array.

If you really did want to do something *like* that with an AVR-based Arduino you could do:

```c++
for (int pin : (const int []){DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) {
    pinMode(pin, INPUT_PULLUP);
}
```

This is technically not standard C++. It is the use of something called a [compound-literal](https://en.cppreference.com/w/c/language/compound_literal), which is being used to make an array typed value. This is a feature of C language feature (from C99 onward), not C++. However, the compiler and its configuration for Arduino allows its use as a language extension.

Should you do this? *Perhaps* not, for the reasons that Edgar, 6v6gt, and jsotola point out.  However, this much *can* be done if you really wanted. With respect to what it's doing efficiency-wise, you should test it.


body: I want to learn assembly, but would like to learn by doing, is it possible to learn and make something useful with arduino hardware? I dont know where or how to start something like this.

title: Is it possible to use assembly with arduino?

Answers: 1

body:
I suggest the [ARV libC](https://www.nongnu.org/avr-libc/user-manual/assembler.html) project as a starting point to HOW to get assmbler code running. And the [AVR Instruction Set Manual](https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-Instruction-Set-Manual-DS40002198A.pdf) to get hold of the actual assembler mnemonics.

Maybe also my own [AVR Assembly Project](https://kwasi-ich.de/blog/2019/11/15/pwm_rider/) might be a helpful starting point with its code available on GitHub.


body:
So Im using this sensor:
https://wiki.dfrobot.com/Serial_6_Axis_Accelerometer_SKU_SEN0386 with this library https://github.com/DFRobotdl/DFRobot_WT61PC

Im using 2 sensors but got poor frequency on Arduino Uno and decicded to switch to Mega since it supports multiple communications at once.

This code works perfectly fine on Uno, but doesnt on Mega. Of course I tried using this method: https://docs.arduino.cc/built-in-examples/communication/MultiSerialMega and I know I shouldnt be using Software Serial on Mega but **this library has been written using Software Serial and I cant use a different method** (or at least thats how I understand it).

Here is the reason.
```c++
SoftwareSerial mySerial(10, 11);
DFRobot_WT61PC sensor(&mySerial);
```
So I tried multiple variations of pins (ones supporting UART, pcint, TX/RX) https://docs.arduino.cc/learn/built-in-libraries/software-serial and nothing seems to we working. Also tried removing the SD card reader, tried the original example code. I also tried Hardware Serial as it should be but again, it doesnt support this sensor and ends up resulting in errors(or vice versa). Nothing.

Here is the working Uno code:
```c++
#include <DFRobot_WT61PC.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

#define FILE_BASE_NAME "Pomiar"
#define VCC2 7

const uint8_t CS_PIN = 4;

SoftwareSerial mySerial(2, 3);
SoftwareSerial mySerial2(5, 6);
DFRobot_WT61PC sensor(&mySerial);
DFRobot_WT61PC sensor2(&mySerial2);

File myFile;
File file;

const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[] = FILE_BASE_NAME "00.txt";

void setup()
{

  pinMode(VCC2,OUTPUT);
  digitalWrite(VCC2,HIGH);

  //Use Serial as debugging serial port
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }

  //Use software serial port mySerial as communication seiral port
  mySerial.begin(9600);
  mySerial2.begin(9600);
  //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz,
  //                        FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz,
  //                        FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz.
  sensor.modifyFrequency(FREQUENCY_10HZ);
  sensor2.modifyFrequency(FREQUENCY_10HZ);
}

void loop()
{

  long timestamp = millis();

  float acc1;
  float acc2 ;
  float acc3 ;
  float gyro1 ;
  float gyro2 ;
  float gyro3;
  float angle1;
  float angle2;
  float angle3;

  float acc12 ;
  float acc22 ;
  float acc32 ;
  float gyro12;
  float gyro22 ;
  float gyro32 ;
  float angle12 ;
  float angle22;
  float angle32;

  mySerial.listen();
  if (sensor.available()) {

    acc1 = sensor.Acc.X;
    acc2 = sensor.Acc.Y;
    acc3 = sensor.Acc.Z;
    gyro1 = sensor.Gyro.X;
    gyro2 = sensor.Gyro.Y;
    gyro3 = sensor.Gyro.Z;
    angle1 = sensor.Angle.X;
    angle2 = sensor.Angle.Y;
    angle3 = sensor.Angle.Z;

  }

  mySerial2.listen();
  if (sensor2.available()) {

    acc12 = sensor2.Acc.X;
    acc22 = sensor2.Acc.Y;
    acc32 = sensor2.Acc.Z;
    gyro12 = sensor2.Gyro.X;
    gyro22 = sensor2.Gyro.Y;
    gyro32 = sensor2.Gyro.Z;
    angle12 = sensor2.Angle.X;
    angle22 = sensor2.Angle.Y;
    angle32 = sensor2.Angle.Z;

  }

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc1);
    myFile.print("|");
    myFile.print(acc2);
    myFile.print("|");
    myFile.print(acc3);
    myFile.print("|");
    myFile.print(gyro1);
    myFile.print("|");
    myFile.print(gyro2);
    myFile.print("|");
    myFile.print(gyro3);
    myFile.print("|");
    myFile.print(angle1);
    myFile.print("|");
    myFile.print(angle2);
    myFile.print("|");
    myFile.print(angle3);
    myFile.println("");

    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc12);
    myFile.print("|");
    myFile.print(acc22);
    myFile.print("|");
    myFile.print(acc32);
    myFile.print("|");
    myFile.print(gyro12);
    myFile.print("|");
    myFile.print(gyro22);
    myFile.print("|");
    myFile.print(gyro32);
    myFile.print("|");
    myFile.print(angle12);
    myFile.print("|");
    myFile.print(angle22);
    myFile.print("|");
    myFile.print(angle32);
    myFile.println("");

    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
}
```
I also found this question: https://arduino.stackexchange.com/questions/37333/arduino-mega-2560-softwareserial-not-working.
The guy has exact problem as I do but nooone found a solution to it.
I also want to note that the manufacturer states that this library and sensor works fine on Mega. Really need your help.

cheers

@edit
So I did some tests and the only code that actually shows something in monitor is:
```c++
#include <DFRobot_WT61PC.h>

DFRobot_WT61PC sensor(&Serial);

void setup()
{
  //Use Serial as debugging serial port

  //Use software serial port mySerial as communication seiral port
  Serial.begin(9600);
  sensor.modifyFrequency(FREQUENCY_10HZ);
}

void loop()
{
  if (sensor.available()) {
    Serial.print("Acc\t"); Serial.print(sensor.Acc.X); Serial.print("\t"); Serial.print(sensor.Acc.Y); Serial.print("\t"); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro\t"); Serial.print(sensor.Gyro.X); Serial.print("\t"); Serial.print(sensor.Gyro.Y); Serial.print("\t"); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle\t"); Serial.print(sensor.Angle.X); Serial.print("\t"); Serial.print(sensor.Angle.Y); Serial.print("\t"); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }
}
```

[![monitor][1]][1]
But as you see the output is corrupted.

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

title: Using Software Serial on Arduino Mega

Answers: 2

body:
There are three fairly major issues in your code:

* The Mega does not support SoftwareSerial on pins 2, 3, 5, 6 because those pins do not support change interrupts. Thus it simply can't work on those pins. This itself is a show-stopper.

* Your code to read data is flawed. You test if a single byte is available (sensor.available()) and then proceed to read 9 bytes. There is no guarantee that 8 of them are actually there.

* I'm confused about what you are doing in your second block of code. You are telling the sensor library to get its data from Serial, which is where you type stuff. All that would do is echo what you type, bearing in mind my point directly above.

body:
It's quick and dirty but you can make it Mega compatible by deleting the line `#include <SoftwareSerial.h>`, and replacing the lines

    SoftwareSerial mySerial(2, 3);
    SoftwareSerial mySerial2(5, 6);
with

    #define mySerial Serial1
    #define mySerial Serial2
replacing `Serial1` and `Serial2` with whichever of the Mega's serial ports you wish to use for mySerial and mySerial2, and connecting your DFRobot sensor signals to the correct pins for your chosen hardware serial ports.


body:
I am trying to adapt a [alarm clock sketch][1] that used external buttons, but I would like to utilize a LCD Keypad Shield.  The data sheet says all the buttons are on pin A0, so every button is "set time" in the original sketch.

After reading [this post][2]

I found the values when I press each button, :
```
Right    0
Up     100
Down   257
Left   410
Select 640
```
and have tried to define them by modifying the existing code:

    LiquidCrystal lcd(2, 3, 4, 5, 6, 7); //Arduino pins to lcd
    #define bt_time   A0
    #define bt_up     A1
    #define bt_down   A2
    #define bt_alarm  A3

With:

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Arduino pins to lcd
    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define bt_time   0
    #define bt_up     1
    #define bt_down   2
    #define bt_alarm  3

    #define buzzer 10

    int read_LCD_buttons()
    {
     adc_key_in = analogRead(0);      // read the value from the sensor
     // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
     // we add approx 50 to those values and check to see if we are close
     if (adc_key_in < 50)   return bt_time;
     if (adc_key_in < 150)  return bt_up;
     if (adc_key_in < 307)  return bt_down;
     if (adc_key_in < 690)  return bt_alarm;

    }

I got this from [here][3]

 It doesn't work.... when you press the buttons nothing happens.

It up loads with no errors, but the buttons don't do anything.

Please help, your my only hope.

Edit:
The linked "Real_Time_Clock_With_Alarm.ino" is the source file, all I have changed is the above code.  It works except I can't interact with it...  because no buttons....  I have also tested the hardware with other sketch and it works as expected.

  [1]: https://github.com/embeddedlab786/Real_Time_Clock_With_Alarm/blob/master/Real_Time_Clock_With_Alarm.ino
  [2]: https://arduino.stackexchange.com/questions/48587/how-do-i-control-the-buttons-on-an-arduino-lcd-keypad-shield
  [3]: https://www.elecrow.com/wiki/index.php?title=LCD_Keypad_Shield

title: Code question: LCD keypad Shield. How do I define the buttons?

Answers: 0


body:
I tried to experiment with the `tone()` function that comes with the arduino library.

I played around with the standard code example located here:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody

This is the code:

    #include "pitches.h"

    int melody[] =
    {
      NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
    };

    int noteDurations[] =
    {
      4, 8, 8, 4, 4, 4, 4, 4
    };

    void setup()
    {
       for (int thisNote = 0; thisNote < 8; thisNote++)
       {
          int noteDuration = 1000 / noteDurations[thisNote];
          tone(8, melody[thisNote], noteDuration);

          // to distinguish the notes, set a minimum time between them.
          // the note's duration + 30% seems to work well:
          int pauseBetweenNotes = noteDuration * 1.30;
          delay(pauseBetweenNotes);

          // stop the tone playing:
          noTone(8);

       }
    }

    void loop()
    {
      // no need to repeat the melody.
    }

However, the problem is that there is always a pause between notes.
In musical terms, this is called `staccato`.
I want to be able to play short melodies where there are no delays between the notes, and one note progresses to the next naturally. By the way, this is called `legato` in music theory.

Now, in this example, the delay between the notes sounds good because this "music piece" is supposed to be played this way. But in every other song that i experimented with, there were always some pauses between notes.

This is what this song sounds like: https://soundcloud.com/nikowow-1/normal

Naturally, my mind went to the `delay(pauseBetweenNotes)` function. So i thought this is what causes the delay between the notes. So i set it up to `0.5`. This is what it sounds like: https://soundcloud.com/nikowow-1/05a

As you can hear, it just speeds up the whole song. The delay between the notes remain, but the whole song is sped up (in a higher tempo, so to speak).

In order to better hear the delay between the notes, please take a listen at the song when i selected a value of `3` - causing a smaller tempo, so that the delay between the notes can be more easily audible: https://soundcloud.com/nikowow-1/3a-1

I want to create some melodies where there are no delays between the notes and i am stuck.

EDIT: If you remove the delay line alltogether, the song is played so quickly that only a click sound is heard.

title: Tone() function pauses between notes

Answers: 1

body:
there is
```
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
```

so the *1.30 creates the pause.

if you change it to
```
   int pauseBetweenNotes = noteDuration;
```
there will be no pause between notes.

The tone length is specified with the last parameter of the tone() function (`noteDuration` here).


body:
I have purchased a couple of different types of DigiSpark Attiny85 clones (couldn't find originals available) and they have worked great except some devices (so far, just laptops) don't see the device AT ALL.

It's not that they don't recognise it and so is a driver issue - there is nothing to apply the driver to, no indication that the thing is even plugged in other than the light comes on (so I know it has power).

More frustratingly, if I plug the Digisparks in to any problematic device via a docking station, USB hub, etc. everything works as expected (confirming the drivers are ok) and I can write scripts to the digispark.

I've tried updating the Nucleous bootloader but the problem persists.  I get this problem on three modern laptops (HP & 2 Dells) but my older Lenovo laptops have no problems.  Not sure if here is an issue with modern USB controllers?

UPDATE: Everything points towards it just being an issue with Digispark's and some USB 3.0 controllers.  The clock is correctly set at 16.5Mhz so not sure what else to do other than write these-off as a reliable device.

Anyone had any experience of this or have any suggestions?

Thanks!

title: Anyone had Digispark Attiny85 not SEEN by some USB controllers but seen via HUB or DOCK on same device?

Answers: 2

body: It appears the problem is down to issues around Attiny85 timing with USB 3.0 chipsets and so isn't something that can be solved.

body:
The four USB traces on the digistump board are NOT to perfect specification and don't work with 4/5 conductor USB3 ports.  Use a dremel or band saw and cut about 2/3 of the end off the digistump Printed Circuit Board USB plug. Leave enough of the original four traces to solder to.  Cut off the plug end from an older USB cord. After carefully cutting away and cleaning off the plastic and old wires on the actual USB plug, it fits perfectly to line up to the old (now shorter) traces on the digistump. Be sure trace sides are the same direction on old and new plug and solder all four connections.  Add some superglue and/or silicone for strength and it should work every time with any USB port.

WZ


body:
I am looking to use SAM4S series microcontroller by Atmel/Microchip and trying to program it using Arduino IDE.

 1. Can I use the bootloader provided by Adafruit for [Feather M4 Express](https://www.adafruit.com/product/3857) [uses SAMD51]  or  [Feather M4 Can Express](https://www.adafruit.com/product/4759) [uses SAME51] both of which are ARM Cortex M4 based just like the SAM4S series?

If yes, how do I work around few different features such as different FLASH memory and RAM of my SAM4S16B IC compared to that of SAMD51 or SAME51?

2. Could you suggest any other ways for using SAM4S with Arduino IDE? I, personally, did not find any direct resources for the same.

3. Is it even possible to use SAM4S with Arduino IDE provided that I don't have to write my own bootloader or API's etc?

Appreciate your help in the matter.
Thank you.

title: Using SAM4 series microcontroller with Arduino IDE

Answers: 0


body:
I am currently usinga BNO055 sensor fitted on the Arduino Nine-axis motion shield to measure ocean wave heights and periods. To do this, I'd like to use the quaternions provided, however I have a slight issue. A quaternion should be <cos(theta/2), X*sin(theta/2), Y*sin(theta/2), Z*sin(theta/2)>, with X, Y and Z the coordinates of a unit vector and theta the angle of rotation around that vector. Therefore, I expect all three to be inferior to one.

However, when I run a simple code to see the raw data, the W given by my sensor when on the table is 16 375, and X, Y and Z values are in the high hundreds range...

This gives me a wave height of hundreds of thousands of kilometers :slightly_smiling_face:

Does anyone know why this happens? Do I need to divide the quaternion by it's norm to get the correct result? Or maybe I am misunderstanding the use of a quaternion?

Oh, and I have calibrated the sensor beforehand

Thanks in advance for your help

title: Quaternion values from Arduino 9-axis motion shield seem very wrong

Answers: 1

body:
I am not familiar with this sensor, so I am just guessing.

The sensor is likely giving you [fixed-point][] numbers. Judging from
the real part, there are most likely 14 bits right of the implicit
radix point. If that is the case, the actual quaternion can be computed
as:

```c
float w = raw_w / 16384.0;
float x = raw_x / 16384.0;
float y = raw_y / 16384.0;
float z = raw_z / 16384.0;
```

You can check whether this is reasonable by computing the norm, which
should be very close to one.

[fixed-point]: https://en.wikipedia.org/wiki/Fixed-point_arithmetic


body:
I am following this guide to produce tones with the arduino:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody

This uses the `tone()` builtin function. The connections is that one pin of the speaker got to one digital pin of the arduino, while the other goes to ground.

Is there a way to perform volume control (perhaps with a potentiometer) on this setup?
What worries me is that this is digital information (PWM) that goes to the speaker, and not an analog signal that can be adjusted.

title: Perform Volume Control on arduino speaker

Answers: 2

body:
The `tone()` function generates a 50% duty cycle square wave using a timer and interrupts. 50% duty cycle is basically full volume.

It's possible to reduce the volume by reducing the duty cycle, but the `tone()` function does not support it. It is of course possible to change the software PWM generation to change the duty cycle (I wouldn't know how, so don't ask me), but I'll leave that as an academic exersize for you to experiment with should you wish.

An alternative is to do it in hardware. You can use an op-amp as buffer (or speaker driver) and a couple of resistors (or a potentiometer) as an "attenuator" before it to change the voltate of the signal going to the op-amp.

You need the op-amp as a buffer because the speaker will mess with the potentiometer otherwise.

body:
There is a [library][1] from LixieLabs that implements an audio-based PWM at super high frequencies that allows you to change the tone volume without additional hardware.

  [1]: https://hackaday.io/project/11957-10-bit-component-less-volume-control-for-arduino


body:
I made a 3.3V board and I've put both atmega328p (that I pulled off of a 3.3V pro mini), and an atmega168 that I bootloaded (using USBtinyISP whilst selecting board "Arduino Pro or Pro Mini" and "atmega168 (3.3V, 8MHz") .

Everything works perfectly with the atmega328 - code works and interrupts do as well - which function to pull the Arduino out of sleep when INT0 rises.

However on the Atmega168, the interrupt doesn't seem to work. All the normal code works as expected (communications, instructions etc), just not the interrupt. After the Arduino goes to sleep, I can't wake it since the interrupt isn't working.

Basic code below:

    #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes

    byte interruptPin = 2; //Turn board on/off
    unsigned long shutDownTimer = 0; // Timer for shutdown

    void setup() {
      Serial.begin(57600);
      pinMode(interruptPin, INPUT); //Set pin d2 to input using the buildin pullup resistor
      Serial.println("Starting");

    }

    void loop() {
      Serial.println("Awake");
      delay(1000);

      // Shutdown control
      if (digitalRead(interruptPin) == LOW ) {
        Serial.println("Shutdown detected");
        shutDownTimer = millis();
        while (digitalRead(interruptPin) == LOW ) {
          if (millis() - shutDownTimer > 1000) {
            Serial.println("sleep mode triggered");
            Going_To_Sleep();
          }
        }
      }
    }

    void Going_To_Sleep() {
      sleep_enable();//Enabling sleep mode
      delay(1000);
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
      delay(1000); //wait a second to allow the led to be turned off before going to sleep
      attachInterrupt(0, wakeUp, RISING);//attaching a interrupt to pin d2

      Serial.println("Interrrupt attached");//Print message to serial monitor
      sleep_cpu();//activating sleep mode
      Serial.println("just woke up!");//next line of code executed after the interrupt

    }

    void wakeUp() {
      sleep_disable();//Disable sleep mode
      detachInterrupt(0); //Removes the interrupt from pin 2;
      Serial.println("Interrrupt Fired - wakeup");//Print message to serial monitor

    }

Instead of using "attachInterrupt(0, wakeUp, RISING);" Ive also tried the following which also don't work:

    attachInterrupt(INT0, wakeUp, RISING);
    attachInterrupt(digitalPinToInterrupt(interruptPin), wakeUp, RISING);
    attachInterrupt(32, wakeUp, RISING);  //since its the pin of the chip? Hail Mary
    attachInterrupt(2, wakeUp, RISING);  //obviously this won't work, Hail Mary 2

I have no idea why the interrupts aren't working. I have an inkling it might be due to something fuse related within the boot loader, but I don't really understand things at that level (Though I'm happy to dive in with some guidance). Any guidance will be appreciated!

title: External Interrupt not working on 3.3V atmega168

Answers: 2

body:
According to the [datasheet for the Atmega168](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-9365-Automotive-Microcontrollers-ATmega88-ATmega168_Datasheet.pdf):

> Note that recognition of falling or rising
edge interrupts on INT0 or INT1 requires the presence of an I/O clock, described in
Section 6.1 “Clock Systems and their Distribution” on page 23. Low level interrupt on INT0 and INT1 is detected
asynchronously. This implies that this interrupt can be used for waking the part also from sleep modes other than idle mode.
The I/O clock is halted in all sleep modes except idle mode

In other words, only the LOW interrupt wakes it from sleep.

Having said that, the Atmega328P does wake from sleep with a rising or falling interrupt, as I have previously had confirmed by Atmel, however I can't say for sure that this enhancement (over what is stated in the datasheet) applies to the 168.

You could try doing a bit of testing to confirm that. Maybe rejig so that the interrupt occurs when the signal goes low rather than high, and then use a LOW interrupt and not a RISING one.

Also, don't do serial prints inside an ISR. The modern versions of the library handles that better than in the past, but this may still be an issue. As suggested in a comment, try flashing an LED rather than printing something. Or don't print anything, after all you print something when it wakes up. Why print something extra inside the ISR? That is just asking for trouble.

body:
Depending on what signal you are using to wake the Arduino, you may also find pin change interrupts an alternative to the edge triggered interrupts you are currently using.
These are usually more predictable in behaviour and less subject to nuanced interpretations of the data sheets.
See https://playground.arduino.cc/Main/PinChangeInterrupt/ for examples of how to use these.


body:
I'm using `PubSubClient` to pub/sub MQTT messages using ESP8266.

As far as I know "Keep-alive" detects when a client went off-line after a period of time.

I'm using library's example `mqtt_ESP8266` with 2 minor adjusments (noted "<----- 1/2"), to use keepAlive.

1. Timeout was set to 45 sec (`client.setKeepAlive(45);`), in order to be "far enough" from reboot.
2. Pressing on-board Reset button.
3. Although Wifi+MQTT connection establish after 10 sec, and mqtt sends messages as shown `loop`, a "DEAD" publish is sent to designated topic after roughly 45 seconds from (2) , whuch makes no sense since MQTT was reconnected 35 seconds before.

Appreciate assistance,
Guy

    /*
      Basic ESP8266 MQTT example
      This sketch demonstrates the capabilities of the pubsub library in combination
      with the ESP8266 board/library.
      It connects to an MQTT server then:
      - publishes "hello world" to the topic "outTopic" every two seconds
      - subscribes to the topic "inTopic", printing out any messages
        it receives. NB - it assumes the received payloads are strings not binary
      - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
        else switch it off
      It will reconnect to the server if the connection is lost using a blocking
      reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
      achieve the same result without blocking the main loop.
      To install the ESP8266 board, (using Arduino 1.6.4+):
      - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
           http://arduino.esp8266.com/stable/package_esp8266com_index.json
      - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
      - Select your ESP8266 in "Tools -> Board"
    */

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>

    // Update these with values suitable for your network.

    const char* ssid = "Wifi";
    const char* password = "Password";
    const char* mqtt_server = "192.168.2.100";

    WiFiClient espClient;
    PubSubClient client(espClient);
    unsigned long lastMsg = 0;
    #define MSG_BUFFER_SIZE (50)
    char msg[MSG_BUFFER_SIZE];
    int value = 0;

    void setup_wifi() {

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

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

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

      randomSeed(micros());

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

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived [");
      Serial.print(topic);
      Serial.print("] ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();

      // Switch on the LED if an 1 was received as first character
      if ((char)payload[0] == '1') {
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is active low on the ESP-01)
      } else {
        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
      }

    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        // Attempt to connect
        client.setKeepAlive(45);  \\ <--------- Line 1
        if (client.connect(clientId.c_str(), "guy", "kupelu9e", "myHome/log", 0, true, \\ < "DEAD")) { \\ <---- Line 2
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish("outTopic", "hello world");
          // ... and resubscribe
          client.subscribe("inTopic");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

    void setup() {
      pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
      Serial.begin(115200);
      setup_wifi();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);
    }

    void loop() {

      if (!client.connected()) {
        reconnect();
      }
      client.loop();

      unsigned long now = millis();
      if (now - lastMsg > 2000) {
        lastMsg = now;
        ++value;
        snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
        Serial.print("Publish message: ");
        Serial.println(msg);
        client.publish("myHome/debug", msg);
      }
    }

title: PubSub'a - KeepAlive function not as expected

Answers: 1

body:
This is the correct behavior.

The “last will” message is sent by the broker when it detects that the client has gone away.

When you reset the ESP8266, the original connection to the broker is destroyed. When it restarts, it creates a new, second connection, it does not resume the original connection. So the broker correctly transmits the last will message when the original connection times out.


body:
I am having a ridiculously hard time trying to make a passive buzzer work correctly on my Seeeduino XIAO.

Here is the buzzer module :
[![enter image description here][1]][1]

Here is how I believe it works, assuming the SOT23 smd is a PNP transistor? :
[![enter image description here][2]][2]

I plugged VCC to a +5V rail, GND to the ground rail, and I/O pin to my Seeeduino XIAO's pin 2 (aka "A2 / D2" :
[![enter image description here][3]][3]

When I write ```DigitalWrite(2, LOW)```, I can mesure about 0.4V on pin 2, while ```DigitalWrite(2, HIGH)``` reads about 3.3V (I assume the 5V rail feeding my Seeeduino XIAO's VCC gets converted to 3v3 through an internal regulator)

I understand I have to oscillate the signal to make this module buzz (remember it is a passive buzzer, or a transducer, whatever it is called), or simply use the ```tone()``` method, and I eventually managed to make this beep on and off every 1 second successfully during 10 seconds, but what bothers me is that I can NOT turn this module OFF after 10 seconds as a test in my sketch. It stops beeping after 10 sec as expected (```ìf (millis() < 10000) { doBeep(); }``` , but it still draws massive current and gets hot after that delay. It's like the PNP transistor never turns off? I tried both digitalWrite HIGH and LOW but no success.

This is driving me crazy. What am I doing wrong?

  [1]: https://i.stack.imgur.com/KTWnE.png
  [2]: https://i.stack.imgur.com/ZFGoT.png
  [3]: https://i.stack.imgur.com/yf5Fj.jpg

title: passive buzzer is drawing 500mA

Answers: 1

body:
You're right that it's a PNP transistor - the SS8550 to be precise.

And therein lies the problem.

When running at 5V to "make no current flow" through the base the voltage at the base has to be higher than 4.4V (5v - 0.6v), and since you're controlling it from a 3.3V microcontroller that can never happen. So you are right in thinking it never turns off - it never does.

Even when you're "beeping" it it's not turning fully off, so the beep sounds you make will be reduced accordingly.

You should power the board from 3.3V instead of 5V so the PNP can turn off fully. If that is not possible then switching the GPIO pin to INPUT mode will prevent it from driving the PNP thus allowing it to turn itself off.


body:
I have an Arduino project where the file structure looks like this

```
myProject/
    myProject.ino
    ImportantClass1.hpp
    ImportantClass1.cpp
    ImportantClass2.hpp
    ImportantClass2.cpp
    Etc….

```

It compiles and runs fine. No problem pulling the cpp and hpp files into the ino program. However to really make sure of reliability I want to make additional ino files for unit testing of importantClass1 & etc. I have made files ``` importantClass1UnitTest.ino ``` & ``` importantClass2UnitTest.ino ``` however these can’t be in the same dir as the respective source files as the arduino compiler requires the ino file and the dir to have the same name.

The tests run when I move the files around. But I am not happy with that, I want to be able to run the tests at any time with the standard arduino compiler without having to script filecopy commands.

If I put the unit test in its own dir separate to the class source and ```#include``` using the full path it also works. However this solutions is not portable, when I (or any collaborator) pull the project from git hub on any other computer the paths are wrong and it doesn’t work.

Where am I going wrong? How can I do this so as to avoid moving/copying files and also avoid using full paths?

title: Where should unit tests go in the Arduino IDE

Answers: 1

body:
One way to do it is to use preprocessor conditionals. Name your project file and unit-test files with `.cpp` extensions and put them in a subfolder (called "sources" in my example). Then your `.ino` file would only be used to instruct the preprocessor which of the several "main" file to start compiling with:

myProject.ino:

    /*
     * myProject.ino
     * define which "main" CPP file to compile:
     */

    #define PRODUCTION
    // #define UNITTEST1
    // #define UNITTEST2
    // #define UNITTEST3

    // The compilation starts here with the requested "main" file:
    #if defined PRODUCTION
    #include "sources/myProject.cpp"

    #elif defined UNITTEST1
    #include "sources/unitTest1.cpp"

    #elif defined UNITTEST2
    #include "sources/unitTest2.cpp"

    #elif defined UNITTEST3
    #include "sources/unitTest3.cpp"

    #else
    // If nothing defined, compile for production
    #include "sources/myProject.cpp"
    #endif

    /* END */

Only the .ino file would need to be edited to compile one of the unit tests, and only one project file would be needed.

Update:
"did you try it? "

Yes, and it does work. The only caveat I'd add is: don't name your subfolder "src" - that seems to be a magic-name to the IDE, and you'll get complaints of compilation errors (multiple definitions) if you use it. And further, if you try it, you can't get back simply by changing the folder's name (on disk and in the code); you'll have to restart the IDE as well.
<br>I tested it with v1.8.19 of the IDE.


body:
I am using [ADXL373Z][1] accelerometer with Arduino Uno for a project.

When I run the code, I am getting incorrect values which are probably not even acceleration data. I am thinking it might be a wiring problem, I attached circuit diagram below. This is my first Arduino project, and I couldn't find any other applications with the sensor I am using so any help would be much appreciated. Thanks in advance.

Datasheet for sensor : https://www.analog.com/media/en/technical-documentation/data-sheets/adxl373.pdf

Code ( for x-axis data only) :

    // ADXL373 Accelerometer Test

    #include <Wire.h>

    /* -------- REGISTERS -------- */
    #define ADDRESS_ADXL373 0x53 // sensor adress (assumes MISO pin high)
    #define ADDRESS_POWER_CTL 0x3F // power control
    #define ADDRESS_MEASURE 0x0E // measurement control
    #define ADDRESS_TIMING 0x3D // output data rate and extarnal timing triggers
    #define ADDRESS_XDATA_H 0x08 // x-axis acceleration data [11:4]
    #define ADDRESS_XDATA_L 0x09 // x-axis acceleration data [3:0]
    #define ADDRESS_YDATA_H 0x0A // y-axis acceleration data [11:4]
    #define ADDRESS_YDATA_L 0x0B // y-axis acceleration data [3:0]
    #define ADDRESS_ZDATA_H 0x0C // z-axis acceleration data [11:4]
    #define ADDRESS_ZDATA_L 0x0D // z-axis acceleration data [3:0]
    /* -------- REGISTERS -------- */

    #define SCALE_FACTOR 0.2f // 200 mg per LSB scaling factor
    #define GRAVITY_EARTH 9.80665f // gravity of earth in m/s^2

    void setup() {
      Serial.begin(115200);
      while(!Serial);
      Serial.println("ADXL373 Accelerometer Test");
      Wire.begin();
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_POWER_CTL);
      Wire.write(0x03); // activate full bandwith measurement mode
      Wire.endTransmission(true);
      delay(50);
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_MEASURE);
      Wire.write(0x04); // set output signal bandwith to 2560 Hz
      Wire.endTransmission(true);
      delay(50);
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_TIMING);
      Wire.write(0x80); // set output data rate to 5120 Hz
      Wire.endTransmission(true);
      delay(50);
    }

    void loop() {
      byte xAxisH, xAxisL;
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_XDATA_H);
      Wire.endTransmission(false);
      Wire.requestFrom(ADDRESS_ADXL373, 1, true);
      xAxisH = Wire.read();
      Wire.beginTransmission(ADDRESS_ADXL373);
      Wire.write(ADDRESS_XDATA_L);
      Wire.endTransmission(false);
      Wire.requestFrom(ADDRESS_ADXL373, 1, true);
      xAxisL = Wire.read();
      int16_t xAxisFinal;
      xAxisFinal = (uint16_t) xAxisH << 8 | xAxisL; // bit shift and combine two components
      xAxisFinal = xAxisFinal >> 4; // 12-bit resolution
      float xAccel;
      xAccel = xAxisFinal * SCALE_FACTOR * GRAVITY_EARTH;
      Serial.print("Xa = "); Serial.println(xAccel);
      delay(200);
    }

Circuit Diagram :

[![Circuit Diagram][2]][2]

Results from Serial Monitor (in m/s^2) :

[![Serial Monitor][3]][3]

  [1]: https://eu.mouser.com/ProductDetail/Analog-Devices/EVAL-ADXL373Z?qs=QNEnbhJQKva6ENie%2BWXLsQ==
  [2]: https://i.stack.imgur.com/qFgje.png
  [3]: https://i.stack.imgur.com/Gnn1p.png

title: Help with reading data from ADXL373 Accelerometer (I2C)

Answers: 1

body:
According to the datasheet, the 12 bits of the X acceleration are stored
into the registers `XDATA_H` and `XDATA_L` as follows:

```text
XDATA_H:   b₁₁b₁₀b₉ b₈ b₇ b₆ b₅ b₄
XDATA_L:   b₃ b₂ b₁ b₀ x  x  x  x
```

where `x` means “reserved”.

Now, there are two issues with this code:

```c++
xAxisFinal = xAxisH << 4 | xAxisL; // bit shift 12-bit output data
```

The first issue is that, by shifting `xAxisH` by four places, the bits
b₇–b₄ end up in the same positions as the bits b₃–b₀ in `xAxisL`. Then,
when those values are combined with `|`, the bit b₇ gets mixed with b₃,
b₆ with b₂, etc. If you really want to shift `xAxisH` left by four
places, you should also shift `xAxisL` right by four places.

The second issue is that the x data is a signed number represented as
two's complement, and the sign bit (b₁₁) ends up in the wrong place. For
example, if the measured value is −16 (XDATA\_H:XDATA\_L = 0xff:0x00),
you end up reading 4980 (0x0ff0). In order to avoid this issue you could
[sign extend][] the 12-bit number to 16 bits.

I would suggest, though, a completely different approach. The number is
left justified in the sensor registers, so just keep it like this:

```c++
xAxisFinal = (uint16_t) xAxisH << 8 | xAxisL;
```

The intermediate cast to `uint16_t` is here to avoid an undefined
behavior, the final result is signed. If there is some risk that the
reserved bits are non-zero (the datasheet is not very clear in this
respect), you could

```c++
xAxisFinal &= 0xfff0;  // clear last 4 bits
```

Note that now the unit of the acceleration is 1/16 of the resolution of
the sensor, and all values you get are multiples of 16. I don't expect
this to be an issue. If you really want to use the sensor resolution as
your unit, you could now shift `xAxisFinal` four places to the right,
which would automatically perform the sign extension.

[sign extend]: https://en.wikipedia.org/wiki/Sign_extension

------------------------------------------------------------------------

**Edit**: Addressing the edited code from the OP:

> I modified the code according to your suggestions. But I am still
> getting incorrect values from serial monitor.

What I see in your post is very small values, around ±3 LSBs of the
sensor. This could very well be sensor noise. But then, there is the
occasional larger value. Interestingly, those larger values seem to be
very close to ±16 LSBs, hinting at some kind of communication
problem.

I guess the answer is in this warning from the sensor's datasheet:

> Always read acceleration data using multibyte transfers to ensure that
> a concurrent and complete set of x, y, and z acceleration data is
> read.

Imagine the sensor is outputting only noise, and the noise fluctuates
between −1 and +1 LSB. What you expect then is:

    value  XDATA_H   XDATA_L
      −1   11111111  11110000
      +1   00000000  00010000

If you read `XDATA_H` and `XDATA_L` in two different transactions, you
may well read 0b11111111 for `XDATA_H` (as the sensor is reading  −1),
then read `00010000` for `XDATA_L` (as it is getting +1). When you
combine these two readings together, you get

    value  XDATA_H   XDATA_L
     −15   11111111  00010000

I suggest you follow the recommendation from the datasheet and read both
registers in one go:

```c++
Wire.beginTransmission(ADDRESS_ADXL373);
Wire.write(ADDRESS_XDATA_H);
Wire.endTransmission(false);
Wire.requestFrom(ADDRESS_ADXL373, 2, true);
xAxisH = Wire.read();
xAxisL = Wire.read();
```


body:
What happen when a  voltage measured by analogRead() is higher than AREF voltage?

Example: AREF = 2.5V AO = 3.2V

What is the maximum voltage ?

title: Measured voltage higher than AREF

Answers: 1

body: You will be reading the maximum ADC value. If you were sampling a waveform the top of it would be clipped off at 2.5v.


body:
I am working on a hobby project: creating an rc-(radio controlled)-toy car.

I'm working with a **Wemos D1 Mini** (esp8266) microcontroller, **L298N** H-bridge (for controlling the motor) and I'm using the **Arduino IDE** to program it all.

The project is quite simple: make the car drive around via an virtual joystick on an app. The project is quite fun and a nice learning experience for me. The project is going pretty well until this point.

I can move the car forwards and backwards with a constant speed, but I'm not able to change the speed via a **PWM** signal. Actually, I'm not even sure if it is even possible to create a PWM signal on the Wemos D1 Mini, I have never done it before on this specific controller. I'm not an electrical engineer, so I'm not really familiar with very specific details about the controller itself.

Can somebody help me create a PWM signal to control the speed of the car?

This is what I have got now, very basic stuff:

```c
void setup() {
  pinMode(D2, OUTPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, OUTPUT);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);
}

void forward() {
  digitalWrite(D5, LOW);
  digitalWrite(D6, HIGH);
}

void backward() {
  digitalWrite(D5, HIGH);
  digitalWrite(D6, LOW);
}

void setVelocity(int value){
  analogWrite(D2, value);
}

void loop() {
  setVelocity(1023);
  forward();
}
```

Thanks in advance!

Sincerly,

Stefan

title: PWM on Wemos D1 Mini (esp8266 chip) does not work

Answers: 1

body:
At one point `analogWrite` as it was implemented in the esp8266-core had defaulted to a 10-bit range. This is [no longer the case](https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output). It defaults to 8-bit range now.

In any case `analogWrite` is implemented to [clamp](https://github.com/esp8266/Arduino/blob/f2d83ba/cores/esp8266/core_esp8266_wiring_pwm.cpp#L57,L59) the given value to be within the range.

If you were not experimenting in the bottom quarter of the velocity range with your code as written then you would have seen full velocity.

You can change to working with the 8-bit range or use `analogWriteRange(new_range)` or `analogWriteResolution(bits)` as [this](https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output) mentions.

Your code as is will produce a 50% duty cycle 1Khz signal on D2 if setVelocity is given 128 with the current core.


body:
I found the following code within an example for performing very fast changes on a PWM-output. It works, however I'm wondering about some details.

TIMER2 was set up in setup() as follows:

    TCCR2A = 0;               // We need no options in control register A
    TCCR2B = (1 << CS21);     // Set prescaller to divide by 8
    TIMSK2 = (1 << OCIE2A);   // Set timer to call ISR when TCNT2 = OCRA2
    OCR2A = 32;               // sets the frequency of the generated wave
    sei();                    // Enable interrupts to generate waveform!

If I understand that correctly, the timer will run until overflow and generate interrupts any time in between as defined by OCR2A.

    ISR(TIMER2_COMPA_vect) {  // Called each time TCNT2 == OCR2A
      static byte index=0;    // Points to successive entries in the wavetable
      OCR1AL = wave[index++]; // Update the PWM output
      asm("NOP;NOP");         // Fine tuning
      TCNT2 = 6;              // Timing to compensate for time spent in ISR
    }

TIMER2 is used to call this routine in equidistant points in time.
To adapt the timespan between two calls of the ISR the author sets OCR2A and within the ISR resets TCNT2. As the timer is reset at the end of the ISR there's some time "already gone" written into the start value of the timer. However there are two things I don't understand.

 1. Why isn't CTC mode used by setting WGM21 in TCCR2A? This should call the ISR in precise intervals.

 2. If not using CTC mode the counter has to be reset by the ISR. But why isn't that done directly at the beginning of the ISR? Everytime the ISR gets some minor changes the correction value written into TCNT2 has to be changed.

Am I missing some vital detail? Or is my idea of using CTC better?

For sake of completeness, the only other things done in setup() are configurations on timer1:

    pinMode(9, OUTPUT);       // Make timer's PWM pin an output
    TCCR1B  = (1 << CS10);    // Set prescaler to full 16MHz
    TCCR1A |= (1 << COM1A1);  // PWM pin to go low when TCNT1=OCR1A
    TCCR1A |= (1 << WGM10);   // Put timer into 8-bit fast PWM mode
    TCCR1B |= (1 << WGM12);

loop() is empty.

title: ISR for very fast processes, strange code found. Has ISR effect on timer behaviour?

Answers: 1

body:
> Why isn't CTC mode used by setting WGM21 in TCCR2A?

As we cannot read the author's mind, we cannot say for sure. That being
said, to me, the most likely reason is that either the author was not
aware of CTC mode, or they just didn't think about it.

You are right that CTC is the most straightforward way to get precise
intervals. You are also right that the resetting the timer at the end of
the ISR makes the code somewhat fragile. If, for some reason, I needed
to avoid CTC in a code like this, I would

```c++
OCR2A += 32;
```

rather than resetting `TCNT2`.


body:
I'm trying to effectively allocate a doc's size, based on the size of the file saved in flash of ESP8266. Is there a way?

For example: `file.size()` X 1.5

title: Determining ArduinoJSON document size based on file size

Answers: 1

body:
There is unfortunately no way to predict the size of the [`JsonDocument`](https://arduinojson.org/v6/api/jsondocument/) from the file size alone.

As a workaround, I suggest that you allocate a very large memory pool and shrink  it after deserialization; like so:

```c++
DynamicJsonDocument doc(ESP.getMaxAllocHeap());
deserializeJson(doc, file);
doc.shrinkToFit();
```

Indeed, this program consumes more memory than strictly required, but only for a fraction of a second.

See also:

* [How to determine the capacity of the JsonDocument?](https://arduinojson.org/v6/how-to/determine-the-capacity-of-the-jsondocument/)
* [BasicJsonDocument<T>::shrinkToFit()](https://arduinojson.org/v6/api/basicjsondocument/shrinktofit/)


body:
I'm currently working on connecting a Funduino version of usb host shield onto an arduino mega board. But the serial output shows "osc did not start", which means the board can't find the shield. However the reset button works, so I estimate insufficient power being supplied.

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

I'm aware of the bridging solution for the regular arduino module for the 3.3v and 5v ([example][2]). But how can this solution be applied to the Funduino model.

Update: I've changed the SPI lines on the shield to the 6 ISCP pins on the Mega, but still no change in results.

I performed a second test using board_qc, which returned:

Circuits At Home 2011

USB Host Shield Quality Control Routine

Reading REVISION register... Die revision invalid. Value returned: 00

Unrecoverable error - test halted!!

0x55 pattern is transmitted via SPI

Press RESET to restart test

  [1]: https://i.stack.imgur.com/2KNVC.jpg
  [2]: http://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html

title: Funduino USB Host Shield problems

Answers: 1

body:
That shield communicates over SPI. However the SPI pins it uses are the "old" style (10-13) for the Arduino UNO.

The Mega doesn't use those pins, which is why the "new" style 6-pin SPI/ICSP header was added to boards.

You will have to manually jumper the right pins to the SPI pins of the Mega using wires.


body:
I want to connect two HC-05 modules, one master and one slave. So to that I need to access 'AT Commands'.

Theoretically, I just needed to upload an empty code, and then connect the module to the arduino in command mode (I use a Nano) TX and RX pins and then go to the Serial Monitor at 38400 baudrate and sent the AT commands. In the past this worked for me, but now this ain't working anymore.

So I went for some code online and aparently AT commands started working. I configured master and slave, and binded the address of the slave to the master.

I connected the modules to an input voltage and I was expecting a connection between them but they are not pairing. On youtube videos they say to connect with two different arduinos, but doesnt make any sense to me because they should connect by themselves just for being ON.

I don't know what to do, I need these working for a project and I'm just wasting time searching on the internet, because nothing works for me. I just didnt tried using them with 2 arduinos with code on them, but I dont think thats the issue AND IF IT IS, please tell me what's the correlation.

title: Can't pair two HC-05 (Master - Slave)

Answers: 0


body: I tried to do a simple program using the ATmega16 microcontroller, the program is to toggle two LEDs the first one by using timer0 interrupt and the other using timer2 interrupt.

title: Can we use more than one timer when programming an Atmega32/16?

Answers: 2

body:
Yes, we can.

(stackexchange wants the body of the answer to be at least 30 characters, so I have to add some filler. Truth is, for answering the question _as asked_, there is nothing more to say.)

body:
Yes, you can. However there is one thing to note:

**Only one ISR can run at once.**

That means that if one LED wants to toggle while the other one is in the process of toggling it will have to wait until that first ISR is finished before it can toggle.

For simple LED toggling that won't be noticeable, but it's something you need to bear in mind if you are doing multiple things that require precise timing.


body:
Is there any way to change the TCP send buffer size (TCP_SND_BUF) on this module ?

Now it is equal to `TCP_SND_BUF = 2 * TCP_MSS = 2 * 1460 = 2920`.

Editing `lwipopts.h` doesn't make any difference.

The same question applies to `ΤCP_MSS`, `TCP_WND` etc.

I am using v2 Higher Bandwidth variant. Platform is Microchip Studio with vMicro Arduino addon.

title: ESP8266 Wemos D1 min pro - how to change TCP_SND_BUF?

Answers: 2

body:
No, you can't.

The macro you are trying to tweak is for reference only and does not control the size of the buffer.

On the ESP8266 the IP stack (and much of the rest of the system) is precompiled as `.a` libraries. Changing things like the `TCP_SND_BUF` macro will never change what has been compiled into those libraries. Instead all it will do is cause problems of buffer overruns and corrupted data as other code is then given incorrect information about the size of the buffer.

body:
I finally figured it out the hard way :

https://github.com/esp8266/Arduino/discussions/8616

--------------------------------------------

Install **Git** for windows (https://git-scm.com/download/win)

Install **MinGW** for windows (https://sourceforge.net/projects/mingw)

In **MinGW** installation manager, enable:

- mingw-developer-toolkit
- mingw32-base
- mingw32-gcc-g++
- msys-base

_(not sure if all are necessary but just in case)_

put _C:\MinGW\bin_ in Windows PATH (check this https://www.rapidee.com)

**reboot PC**
--------------------

rename **C:\MinGW\bin\mingw32-make.exe** to **C:\MinGW\bin\make.exe**

open **bash** terminal (just type bash in run)

_(from now on assume that hardware files are in \Documents\Arduino\hardware\esp8266com\esp8266)_

go to _\tools\sdk\lwip2_

optional: change **lwip options** in _\tools\sdk\lwip2\builder\glue-lwip\arduino\lwipopts.h_

(caution : **NOT** _\tools\sdk\lwip2\include\lwipopts.h_, this will be overwritten !)

type in bash: **make install** to build libraries in _\esp8266com\esp8266\tools\sdk\lwip2\builder_

type in bash: **make clean** to clean _\esp8266com\esp8266\tools\sdk\lwip2\builder_

finally copy new libraries to _\esp8266com\esp8266\tools\sdk\lib_


body:
I'm not entirely sure about the proper C++ terminology, so I'll just illustrate what I'm trying to achieve by giving a Java example since it should be pretty obvious:

~~~
public class LcdDecorator {
    private HD44780Lcd lcd;

    public LcdDecorator(int rows, int cols, int i2cAddress) {
        this.lcd = new HD44780Lcd(rows, cols, i2cAddress);
    }
}
~~~

or... alternatively...

~~~
public class LcdDecorator {
    private HD44780Lcd lcd;

    public LcdDecorator(HD44780Lcd lcd) {
        this.lcd = lcd;
    }
}
~~~

For what it's worth, there's no real concern about scope... LcdDecorator is a Singleton that gets created in setup(), then lives forever and gets used by loop() until the power gets shut off.

#### Here's what I've attempted so far:

`LcdFacade.h`:
~~~
#ifndef CORECONTROLLER_LCDFACADE_H
#define CORECONTROLLER_LCDACADE_H

#include <stdint.h>
#include "../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h"

class LcdFacade {

public:
    LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) ;
};

#endif //CORECONTROLLER_LCDFACADE_H
~~~

`LcdFacade.cpp`:
~~~
#include "LcdFacade.h"
#include "../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h"

HD44780LCD lcd;

LcdFacade::LcdFacade (uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd{rows, cols, i2cAddress} {
    // ... the rest of the constructor goes here ...
}
~~~

note: I also tried using parentheses instead of braces for lcd's constructor:
~~~
LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd(rows, cols, i2cAddress) {
~~~

In CLion, the 'lcd{rows, cols, i2caddress}' portion of the constructor in LcdFacade.cpp is red-underlined, and reports `member initializer 'lcd' does not name a non-static data member or base class`

Meanwhile, gcc(?) reports `error: no matching function for call to 'HD44780LCD::HD44780LCD()` on line 4 of LcdFacade.cpp.

Any ideas?

title: Create member object using constructor arguments, or pass reference to object via constructor

Answers: 1

body:
When you define

```c++
HD44780LCD lcd;
```

at global scope, you are creating a global variable that is initialized
before `main()` is called. In this case, it is initialized with the
default constructor `HD44780LCD::HD44780LCD()`, which does not exist,
hence the error. You could avoid this error by calling a suitable
constructor in the initialization, e.g.

```c++
HD44780LCD lcd(4, 20, 0x23);
```

but this may be inconvenient to you.

If you want to initialize `lcd` in the constructor of `LcdFacade`, then
it must be a non-static member of the class:

```c++
// In LcdFacade.h:
class LcdFacade {
public:
    LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress);
private:
    HD44780LCD lcd;  // <- non-static member
};

// In LcdFacade.cpp:
LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress)
: lcd(rows, cols, i2cAddress) {
    ...
}
```


body:
    #include <Arduino.h>
    #include <WiFi.h>
    #include "WiFiManager.H"
    #include <HTTPClient.H>
    #include "ESPAsyncWebServer.h"
    #include <AsyncTCP.h>

    float version = 1.9;

    uint32_t chipId = 0;
    String chipId2 = "";
    int i;

    String serverName = "http://d";

    // WiFiManager
    // Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;

    // Create AsyncWebServer object on port 80
    AsyncWebServer server2(80);
    WiFiServer server(80);

    // variables to count the pulses of the meters.
    int count1=0;
    float prior_count1=0;
    int count2=0;
    float prior_count2=0;
    int count3=0;
    float prior_count3=0;
    int count4=0;
    float prior_count4=0;
    int countgas=0;
    float prior_countgas=0;
    int countwater=0;
    float prior_countwater=0;

    String payloadpulse = "0";

    unsigned long lastTime = 0;
    unsigned long timerDelay = 6000;

    String guifactor1 = "1000";
    String guifactor2 = "1000";
    String guifactor3 = "1000";
    String guifactor4 = "1000";
    String guifactorgas = "1000";
    String guifactorwater = "1000";

    String counter1 = "1";
    String counter2 = "1";
    String counter3 = "1";
    String counter4 = "1";
    String counter5 = "1";
    String counter6 = "1";

    // function to increment the meters value by 1.
    void pulse1() {
      if (counter1.toInt() == 1) {
        count1 = count1 + 1;
      }

      if (counter1.toInt() == 2) {
        count1 = count1 - 1;
      }
    }

    void pulse2() {
      if (counter2.toInt() == 1) {
        count2 = count2 + 1;
      }

      if (counter2.toInt() == 2) {
        count2 = count2 - 1;
      }
    }

    void pulse3() {
      if (counter3.toInt() == 1) {
        count3 = count3 + 1;
      }

      if (counter3.toInt() == 2) {
        count3 = count3 - 1;
      }
    }

    void pulse4() {
      if (counter4.toInt() == 1) {
        count4 = count4 + 1;
      }

      if (counter4.toInt() == 2) {
        count4 = count4 - 1;
      }
    }

    void pulsegas() {
      if (counter5.toInt() == 1) {
        countgas = countgas + 1;
      }

      if (counter5.toInt() == 2) {
        countgas = countgas - 1;
      }
    }

    void pulsewater() {
      if (counter6.toInt() == 1) {
        countwater = countwater + 1;
      }

      if (counter6.toInt() == 2) {
        countwater = countwater - 1;
      }
    }

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

      wifiManager.autoConnect("ss", "ss");

      pinMode(25, INPUT_PULLDOWN); // Set GPIO25 as digital output pin
      attachInterrupt(digitalPinToInterrupt(25), pulse1, RISING);

      pinMode(19, INPUT_PULLDOWN); // Set GPIO19 as digital output pin
      attachInterrupt(digitalPinToInterrupt(19), pulse2, RISING);

      pinMode(23, INPUT_PULLDOWN); // Set GPIO22 as digital output pin
      attachInterrupt(digitalPinToInterrupt(23), pulse3, RISING);

      pinMode(18, INPUT_PULLDOWN);// Set GPIO18 as digital output pin
      attachInterrupt(digitalPinToInterrupt(18), pulse4, RISING);

      pinMode(21, INPUT_PULLDOWN); // Set GPIO22 as digital output pin
      attachInterrupt(digitalPinToInterrupt(21), pulsegas, RISING);

      pinMode(5, INPUT_PULLDOWN); // Set GPIO5 as digital output pin
      attachInterrupt(digitalPinToInterrupt(5), pulsewater, RISING);
    }

    //--------------------------------------------------------------------
    void loop() {
      float new_count1  = static_cast<float> (count1) / guifactor1.toInt();
      float new_count2 = static_cast<float> (count2) / guifactor2.toInt();
      float new_count3 = static_cast<float> (count3) / guifactor3.toInt();
      float new_count4 = static_cast<float> (count4) / guifactor4.toInt();
      float new_countgas = static_cast<float> (countgas) / guifactorgas.toInt();
      float new_countwater = static_cast<float> (countwater) / guifactorwater.toInt();

      // keeps track of the amount of pulses of pulse meters
      if (new_count1 != prior_count1 ||
       new_count2 != prior_count2 ||
        new_count3 != prior_count3 ||
         new_count4 != prior_count4 ||
          new_countgas != prior_countgas ||
           new_countwater != prior_countwater) {
         Serial.println(new_count1, 4);
         Serial.println(new_count2, 4);
         Serial.println(new_count3, 4);
         Serial.println(new_count4, 4);
         Serial.println(new_countgas, 4);
         Serial.println(new_countwater, 4);
         prior_count1 = new_count1;
         prior_count2 = new_count2;
         prior_count3 = new_count3;
         prior_count4 = new_count4;
         prior_countgas = new_countgas;
         prior_countwater = new_countwater;
      }
      // sends an update to the web
      if ((new_count1 > 0 && ((millis() - lastTime) > timerDelay)) ||
       (new_count2 > 0 && ((millis() - lastTime) > timerDelay)) ||
        (new_count3 > 0 && ((millis() - lastTime) > timerDelay)) ||
         (new_count4 > 0 && ((millis() - lastTime) > timerDelay)) ||
          (new_countgas > 0 && ((millis() - lastTime) > timerDelay)) ||
           (new_countwater > 0 && ((millis() - lastTime) > timerDelay))) {
      {
          // checks if wifi is connected.
          if (WiFi.status()== WL_CONNECTED) {
            HTTPClient http;
            // preparation HTTP GET request.
             String serverPath = serverName + "?chip_id=" + chipId + "&count1=" + new_count1 + "&count2=" + new_count2 + "&count3=" +
             new_count3 + "&count4=" + new_count4 + "&countgas=" + new_countgas + "&countwater=" + new_countwater;
            // Your Domain name with URL path or IP address  with path.
            http.begin(serverPath.c_str());
            // Send HTTP GET request.
            int httpResponseCode = http.GET();
            // confirms the arrival of a response from the server or sends an error.
            if (httpResponseCode>0) {
              count1 = 0;
              count2 = 0;
              count3 = 0;
              count4 = 0;
              countgas = 0;
              countwater = 0;
              payloadpulse = http.getString();
              Serial.println(payloadpulse);
             }
             else {
              Serial.print("Error code: ");
              Serial.println(httpResponseCode);
             }
            // closes the HTTP connection.
            http.end();
          }
          else {
           Serial.println("WiFi Disconnected");
          }
        }
      }

      //reset timer when done sending data
      if (((millis() - lastTime) > timerDelay)) {
        lastTime = millis();
      }
    }

The program is a pulse counter which should add 0.001 pulse everytime it detects one. I expect it to send 0.006 to the server, but instead it sends 0.01. How do I make sure it doesn't send rounded data?

title: Why does the data I send to the server get rounded off and how do I send the entire float instead?

Answers: 1

body:
The constructor for the String object from float is this:

    String(double, unsigned char decimalPlaces=2);

So if you don't want to have 2 decimal digits, you have to use `String(someFloat, 3)`.

Also you have to remember there are limits for the floating point numbers, but in this case it shouldn't be the case.

And as Edgar mentioned, String objects are bit dangerous if they are overused, particularly building that serverPath is the worst way how to do it (every single level of it creates new temp object to be copied into next bigger one and released).

It would be cheaper to do it like:

    String serverPath;
    serverPath.reserve(100); // reserve space so it doesn't have to resize; should be proper estimate
    serverPath += serverName;
    serverPath += "?chip_id=";  // on AVR it should be F()
    serverPath += chipId;
    serverPath += "&count1=";
    serverPath += new_count1;
    serverPath += "&count2=";
    serverPath += new_count2;
    serverPath += "&count3=";
    serverPath += new_count3;
    serverPath += "&count4=";
    serverPath += new_count4;
    serverPath += "&countgas=";
    serverPath += new_countgas;
    serverPath += "&countwater=";
    serverPath += new_countwater;

or you can use some c++ magic:

    template <class T> inline String & operator<<(String & out, T const & what) {
        out += what;
        return out;
    }

    String serverPath;
    serverPath.reserve(100); // reserve space so it doesn't have to resize

    serverPath << serverName << "?chip_id=" << chipId << "&count1="
               << new_count1 << "&count2=" << new_count2 << "&count3="
               << new_count3 << "&count4=" << new_count4 << "&countgas="
               << new_countgas << "&countwater=" << new_countwater;

this code takes `serverPath << serverName` adds serverName into serverPath and the result is serverPath again, and then it continues as `serverPath << "?chip_id="` and so on


body:
I installed arduino 1.8.19 (64-bit) on a Fedora Linux 35 Workstation Edition system. When I started the IDE, and selected the "Open" menu icon, the menu item list appeared, but there was no text displayed with the items. I could open sub-menu items, but there was still no text. It looked like:

[![The "Open" menu with no text][1]][1]

I tried several other 1.8.x versions, but with the same result. I haven't found any discussion about this on the Web. so I suspect that it is problem with my configuration. Nevertheless, any suggestions will be most welcome. I have not tried to install the IDE on Windows 10, but that is an option.

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

title: No text in the IDE menu items

Answers: 1

body:
There is a incompatibility between Arduino 1.8.19 and Fedora 35. On another PC, where I was running an older version of Arduino, I upgraded to Fedora 36 and the upgrade warned me of the incompatibility with the older Arduino and Fedora 36 and said it was deleting Arduino. After the Fedora upgrade completed, I installed Arduino 1.8.19 and it worked as expected. When I upgraded the original PC, the one with the no text in the menus, to Fedora 36, the menus also worked as expected. Hallelujah!! So, all is well and I have my answer. Thanks for your replies.

[![Arduino 1.8.19 and Fedora 36 are working as expected][1]][1]

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


body: I use a homemade board that hosts a PIC16F1829 and an ATmega328P on the same board.  We use the ATmega328P with the Arduino IDE and the PIC with the MPLABX IDE for about 100 EE students a semester at UTSA.  I have 100 pic chips but no ATmega328P chips, I can re-spin the board and adapt it to the ATmega8-U2, since right now I can by 250 ATmega8-U2 chips that are in stock but there are no ATmega328P chips available anywhere and I need 100 at least. I am currently using a different UART to TTL adapter, the CP2102 to connect the ATmega328P to the Arduino IDE.  I have the 2 chips talk via a shared I2C line. How difficult will it be to use the Arduino IDE with the ATmega8-U2?  (Again, not as the UART to USB interface but as the main processor.  Thanks,

title: Will the atmega8-U2 work with Arduino IDE

Answers: 1

body:
I never tried, but it seems to me it should work without issues.

In the Arduino IDE, Menu Tools → Board, you can select “Arduino NG or
older”. You then have a menu Tools → Processor where you can select
either “ATmega168” or “ATmega8”. These options don't require you to
install any extra board support package: they come with the default
“classic” AVR core, which does support the ATmega8.


body:
I wanted to control my servo with a Bluetooth module.

I gave certain values for rotating it. When I press those values the servo rotates, but then retains its original position and the PC also makes the sound of the Arduino board disconnecting because I powered the board with my PC (tried with powerbank also). Even my Bluetooth disconnects.

This is my code:

    #include <Servo.h>

    Servo myservo;
    int pos = 0;
    char data = 0;

    void setup() {
      myservo.attach(9);
      Serial.begin(9600);
    }

    void loop() {
      if (Serial.available() > 0) {
        data = Serial.read();
        if (data == 'F') {
          // for (pos = 0; pos <= 180; pos += 1)
          myservo.write(180);
          delay(1);
        }
      }
      else if (data == 'B') {
        // for (pos = 180; pos >= 0; pos -= 1)
        myservo.write(0);
        delay(1);
      }
    }

Connections:

Servo:
```
red wire -- 5 V (not working at 3.3 V)
orange wire -- pin9
brown wire -- gnd
```
Bluetooth (hc05):
```
5 V -- 5 V
gnd -- gnd
rx -- tx
tx -- rx
```

title: Servo retaining its position every time I send some value

Answers: 1

body: I tried changing the USB B cable with a better quality one and it worked.