body:
For a low power project, I need to power up the DFPlayer Mini module, let it say something, and power it down again using an Arduino Nano (w/o power regulator and LEDs). In the idle time, the Arduino will go to deep sleep. This is to be repeated regularly, e.g. on a daily basis. However, it seems I'm not able to power the module down in the right fashion. The module is connected to the Arduino via an n-channel logic-level MOSFET (IRLZ44N), such that the Player's VCC is permanently at ~5.3 V (4x1.3 V batteries), but no current can flow through the FET's drain to ground (source) if the MOSFET is not switched on via one of the Arduinos pins on its gate. I have a pull-down resistor on the gate to prevent a floating state and a 100uF capacitor from 5V to GND, otherwise turning on the MOSFET apparently causes a current spike which can reset the Arduino. The player's RX is protected by a 1k resistor as described in several tutorials. 5.3 V is not exactly within the specs of the player, but it doesn't seem to be the issue, as the following code works in the sense that the player does its job consistently fine in the first iteration of the loop but then fails every time afterwards.

```
#include <Arduino.h>
#include <LowPower.h>
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>

// MP3 module is powered through logic-level MOSFET
// 100uF capacitor is connected across 5V - GND to smoothen current spikes
static const int MP3Power = 2;
static const int MP3Tx    = 3;
static const int MP3Rx    = 4;
static const int MP3Baud  = 9600; // Default hardware baud rate

uint32_t loop_count = 50000; // large loop_count: start into working loop after reset
//unsigned long loop_max;

uint32_t loop_max   = 1;     // 8 sec * 1 ~ 8 sec

DFRobotDFPlayerMini player;
SoftwareSerial MP3serial(MP3Rx, MP3Tx); // RX, TX

void speak(int filenumber, int volume=20);

void setup() {
  // Set all pins connected to MOSFET gates as low outputs.
  pinMode(MP3Power, OUTPUT); digitalWrite(MP3Power, LOW);
}

void loop() {
  if (loop_count < loop_max) {
    // increase loop counter, then go to deep sleep for 8 sec.
    loop_count++;
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  } else {
    // reset loop count, speak
    loop_count = 0;
    speak(1);
  }
}

void speak(int filenumber, int volume) {
  // turn on power for mp3 module
  digitalWrite(MP3Power, HIGH);
  // wait for the module to cope with being powered up
  // it does light up its LED when powered up and doesn't seem to like
  // to be talked to right away.
  delay(1500);

  // initialise mp3 serial communication
  MP3serial.begin(MP3Baud);
  // sometimes I added another delay here, but it didn't really change to much.

  if (!player.begin(MP3serial)) {
    // MP3 Player can't start -- shut down everything and return early (but gracefully?)
    /*
     * This is where I end up after the first time worked. I can confirm this e.g. by blinking an
     * LED in here or reading the player's state, which returns a timeout error, whatever this means.
     */
    MP3serial.flush();
    MP3serial.end();
    digitalWrite(MP3Power, LOW);
    delay(100);
    return ;
  }

  player.setTimeOut(1000);
  player.EQ(DFPLAYER_EQ_POP);
  player.outputDevice(DFPLAYER_DEVICE_SD);

  player.volume(volume);
  player.playMp3Folder(filenumber);

  // enter this loop until playing is finished
  while (true) {
    delay(250); // give the player a little time before querying
    int i = player.readState();
    delay(250); // give the player a little more time, just in case
    if (i != 1) {
      // 1 means playing, break out when finished
      break;
    }
  }

  // close mp3 module
  MP3serial.flush();
  MP3serial.end();
  // wait a bit?
  delay(100);
  // turn off power
  digitalWrite(MP3Power, LOW);
  // wait until everything is turned off for good
  delay(100);

  // I also tried this, but it didn't really change anything
  //pinMode(MP3Tx,OUTPUT); digitalWrite(MP3Tx, HIGH);
  //pinMode(MP3Rx,OUTPUT); digitalWrite(MP3Rx, HIGH);
}
```
I also managed to obtain some delay settings via trial and error such that **sometimes** it would play another track, but this was very unstable. As you can see, I have a lot of delays, which makes me unhappy. I suspect that the error lies somewhere within the part which powers down the DFPlayer mini module. Can someone give me a hint what I'm doing wrong?

[![wiring][1]][1]
[![schematic][2]][2]

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

title: DFPlayer Mini does not boot reliably after being powered down

Answers: 0


body:
I am using Cactus Micro Rev2 and I'm trying to communicate with ESP via Mega32U4. I guess I have to update to espduino to be able to program the ESP side.

And I don't know current ESP firmware version. I tried firmware update (https://github.com/AprilBrother/espduino/tree/master/esp8266/release) via esptool but it gave connection error. And I can't erase flash it still gives an error. This time I tried via nodeMcu flasher:

> Screenshot:
[![enter image description here][2]][2]

It succeeds. But when I uploaded the basic serial communicate sketch to ESP and Mega32U4 side, I still don't get a response.

ESP side sketch:
```void setup()
{
Serial1.begin(115200);
}

void loop()
{
Serial1.println(“Hello”);
delay(1000);
}
```

MEGA32U4 side sketch:
```while(Serial1.available()) {
String character = Serial1.readString();
Serial.println(character);
}
```
Believe me, I don't know exactly where I went wrong. I wrote more descriptive, but I was asked to ask one question. In short, how exactly can I update to espduino via NodeMCU flasher?

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

title: Update the ESP to espduino via NodeMCU Flasher

Answers: 2

body:
[The Cactus Micro Rev2 board][1] has ATmega32u4 with LiliPad bootloader as main MCU and esp8266 as WiFi adapter.

The esp8266 UART is connected to 32u4 Serial1. The Serial on 32u4 is connected to computer over USB.

To bridge the esp8266 to computer you can use the SerialPassthrough sketch from Communication section of base Arduino IDE examples in File menu.

The manufacturer of the board made [a sketch][2] for the ATmega32u4 which sets the esp8266 to bootloader mode and bridges the esp8266 to USB.

The esp8266Programmer.ino sketch is basically a SerialPassthrough sketch with reset of the esp8266 to bootloader mode in setup().

Select "Arduino LiliPad USB" in Arduino IDE the upload the esp8266Programmer.ino sketch to the 32u4.

With the esp8266Programmer.ino in 32u4 you can upload to esp8266 with Arduino IDE or esptool.py.

If you want to communicate with the application (firmware or sketch) in esp8266, use the SerialPassthrough sketch from Arduino IDE examples (because the esp8266Programmer sketch always sets the esp8266 to bootloader mode).

For successful upload from IDE or esptool.py over the esp8266Programmer sketch, the reset before uploading must be suppressed. In IDE it is the "Reset method" option (select `no_dtr`), for esptool.py it is the `--before no_reset` option.

  [1]: https://wiki.aprbrother.com/en/Cactus_Micro_Rev2.html#description
  [2]: https://github.com/AprilBrother/cactus-micro-r2/blob/master/libraries/CactusMicro/examples/esp8266Programmer/esp8266Programmer.ino

body:
The board has an esp-03. First, we uploaded `esp8266programmer.ino` and then uploaded the esp sketch from IDE. Our esp settings must be like this:

> Flash Size: "1MB (none OTA)
Flash Mode: "DIO"
Reset method: "no dtr
> (aka ck)"

We uploaded our sketch. The Atmega sketch must have this two lines of code in the `setup()` function:

```cpp
digitalWrite(program_pin, HIGH); //Set GPIO to boot into programming mode
digitalWrite(enable_pin, HIGH); //Enable ESP-03 module
```

The serial baud rate must be less than 74880. This way, the problem will be solved. Thanks to @Juraj for the support.


body:
My Adafruit Feather M0 has two reset options I know of:
- single click restarts existing program
- double-click listens for an upload for a few seconds, then restarts existing program

Is there another option to have an existing program erased or replaced with something benign like a blinker, e.g.
- triple-click erases existing program and listens for upload indefinitely

If not, what is the level of difficulty to modify the standard bootloader to implement this option?

**NOTE**

The rationale for this option is to recover a bricked board, e.g. with USB port turned off by a low power mode, so the regular software upload doesn't work any longer, at least without some trickery.

title: Triple-click reset option to erase existing program

Answers: 2

body:
Now that we know the board type (Zero) — which took a couple of questions to elicit — it is possible to give a reasonable answer. Had it been a Uno I would have said that no, it doesn't do that, and it would take too much program space to implement it.

> Is there another option to have an existing program erased or replaced with something benign ...

No, not that I am aware of, unless the documentation for the Zero says otherwise.

> If not, what is the level of difficulty to modify the standard bootloader to implement this option?

Moderate, I would guess.

As for the Zero, with 256 KB of programmable memory it probably could be implemented by changing the bootloader. Any such change will, of course, reduce the amount of memory available for other tasks, but perhaps that isn't as big a deal if you start with 256 KB.

You would have to detect the triple-click somehow, for code running right after reset this could be tricky, but possibly achievable, as you say it has been for double-clicks.

Find the source code for the bootloader, see how it detects double-clicks, make it detect triple clicks, and have your "benign" program stored in the bootloader as a block of data ready to be copied into program memory.

There are a few alternatives you could consider:

* If you have a spare pin in your project, make it so that if (say) pin 13 is grounded at startup, do nothing (other than go into a tight loop). This could be done before anything that might make reprogramming hard, like going into low power mode.

* Reprogram it using SWD programming (rather than the bootloader). I don't know the exact details for the Zero, as I don't own one, but there must be a way, otherwise you wouldn't be able to put the bootloader onto it in the first place. Judging by what I read elsewhere the Atmel ICE is the device you need to reprogram it in that way.

* Judging by [what I read here](https://github.com/arduino/Arduino/issues/4291) you can access the bootloader by selecting Arduino Zero (programming port) as the board, and Atmel-EDBG as the programmer. Then you could tell the Atmel-EDBG to reprogram the board. My details here are hazy but you could look into that as an option.

body:
All Arduino bootloaders for boards with native USB support double reset as a way to activate the bootloader in case the sketch doesn't respond and fails to handle the USB. (The code linked from the Arduino core to your sketch handles the USB for MCU with native USB).

The M0 Arduino bootloader source code is [in Arduino SAMD boards support package][1]. Adafruit may use a modified version. The bootloader is strange because avrdude is used to upload over this bootloader and the board reports as ATmega to avrdude.

The M0 bootloader (and the ATmega 32u4 bootloader for Leonardo and Micro) have timeout after double reset. If no upload occurs some seconds after the double reset, they start the sketch.

You want to add a triple reset to replace the sketch which doesn't respond with a save sketch which will handle the USB and allow upload at any time. This would require to change the bootloader source, build the bootloader and use a SWD programmer to burn it (or create a sketch which replaces the bootloader).

Better option is what Arduino did for the Zero and MKR bootloader. The bootloader activated with double reset doesn't timeout with this bootloader and upload is possible anytime after double reset (until next reset or power-cycle).

The original M0 and Zero are almost the same board. One was sold by arduino.org other by arduino.cc. The most important difference is the bootloader.

It is possible to use M0 board as Zero with the Zero bootloader. By replacing the bootloader, you get the double reset without timeout. Other benefits are faster upload with bossac, the bootloader is half the size of the M0 bootloader and the Zero bootloader doesn't reset the internal RTC as the M0 bootloader does.

  [1]: https://github.com/arduino/ArduinoCore-samd/tree/master/bootloaders/mzero/Bootloader_D21/src


body:
I am trying to build an ACC device. when a button is pressed the changes should be made via android accessibility mode.
I am using arduino nano, and I don't know how to control android using arduino.

title: Is it possible to control android accessibility with arduino nano?

Answers: 0


body:
I am trying to use  ([NDIR CO2 sensor Mikroelectronika][1]) with Arduino Mega 2560 utilizing the Click shield.

Mikroelectronika provides libraries for their platform (likely proprietary), hence i have no idea how to manage to do this with arduino.

Here is the code I tried from the [library page][2].

    void application_init ( void )
    {
    log_cfg_t log_cfg;
    ndirco2_cfg_t cfg;

    //  Logger initialization.

    log_cfg.level = LOG_LEVEL_DEBUG;
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, "---- Application Init ----" );

    //  Click initialization.

    ndirco2_cfg_setup( &cfg );
    NDIRCO2_MAP_MIKROBUS( cfg, MIKROBUS_1 );
    ndirco2_init( &ndirco2, &cfg );

    Delay_ms( 300 );

    ndirco2_reset( &ndirco2 );
    ndirco2_write_register( &ndirco2, NDIRCO2_AVERAGING_COUNT_REG, 0x03 );
    ndirco2_set_mode( &ndirco2, NDIRCO2_CONTINUOUS_OP_MODE );
    log_printf( &logger, "NDIR CO2 is initialized \r\n" );
    Delay_ms( 200 );
    }

    void application_task ( )
    {
    uint16_t co2_data;

    ndirco2_read_co2( &ndirco2, NDIRCO2_CHECK_EACH_MEASURE, &co2_data );
    log_printf( &logger, "CO2 concentration is: %d ppm \r\n", co2_data );
    }

**The example for arduino is [available here][3].**

  [1]: https://www.mikroe.com/ndir-co2-click
  [2]: https://libstock.mikroe.com/projects/view/3625/ndir-co2-click
  [3]: https://www.mikroe.com/arduino-uno-click-shield

title: Using Arduino Click shield with NDIR Click CO2

Answers: 0


body: I'm trying to find a convenient way to program my Arduino remotely (by Bluetooth or Wi-Fi) because it will be packed and placed outside of my working place. Found a few ways (Arduino Cloud and Blynk) but most of them are about IoT and this is not an IoT project. Maybe you already faced such a problem. If so, then how have you dealt with this?

title: Wireless programming of Arduino

Answers: 1

body:
My ArduinoOTA library, which is based on Arduino's WiFi101OTA library, was created for upload from IDE. But in some scenarios as for example deployed sleeping battery powered devices it is better to have the update available for download by the device.

In advanced section of examples of the ArduinoOTA library you can find examples of sketch update over download from a http server. The OTASketchDownloadWifi shows update over the InternalStorage object of the ArduinoOTA library with download over the WiFiNINA library.


body:
I'm working on a project to better understand how my home cooling system behaves. I'd like to produce graphs of temperature in various areas, overlaid with when my existing thermostat turns the A/C compressor and fan on.

Connecting up a few ESP8266's with temperature sensors reporting over WiFi is straightforward enough; I'm comfortable doing that. But I'm struggling with how to detect when my thermostat is calling for A/C cooling.

My (battery-powered) thermostat has red, white, yellow, and green wires:

 - Red has ~28Vac
 - White enables the heating system
 - Green enables the fan
 - Yellow enables the A/C compressor

With a multimeter, I easily determined that the thermostat simply closes a relay (I can hear it; that was a dead giveaway) and there's no resistance. So if A/C is called for, it closes relays connected Red to Yellow (and Green).

I don't really want to mess with drawing power from the 28Vac; it's easy enough to power an 8266 with 5V from a wall wart and that's sufficient for this project. Ugly, but acceptable.

I want to detect when the thermostat relay is closed and turning on the air conditioner. Clearly I'm not an EE by trade, and I'm struggling with the right search terms to communicate "detect whether two outside pins are electrically connected". I think something that emulates a multimeter's continuity function would work.

I did find references to the LM*39 series, but (1) I'm not sure it would like being exposed to AC power, and (2) the 'offset voltage' is usually measured in mV, which suggests to me that I'm barking up the wrong tree.

title: How can I check if my thermostat is on?

Answers: 2

body:
Welcome! I used bidirectional optocouplers. The input has a resistor I believe 27K and the output is a NPN transistor with a pull up to +5. The emitter goes to electronic ground. I connected these across the relay coils. They have not given me any problems since installed about 15 years ago. Nice thing they are not polarity sensitive.

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

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

body:
Most straight forward method should be to slap an op amp on the leg of the wire that the relay activates and deactivates by connecting to it.  The key is to power the op amp with low voltage so your esp gets that as input.  The signal legs can handle whatever the relay gives, and the ac, fan, and heater will handle the pull signal for the not connected state.

That only goes so far as to protect the esp by having the op amp take the high voltage and output low.  To turn a potentially AC low voltage signal into a nice dc one, use a diode, capacitor, and resistor (trim pot).  Remember that this is going to be discharging that cap through your resistor so figure out a minimum and check the pot before powering the device (or add a regular resistor in series).


body:
I currently try to build some Drums for the game Clone Hero. The problem that I have is that I can't use both of my Piezo inputs that I have hooked up at the same time.
I have a Arduino Pro Micro and use [this][1] Library. This is my code that I have so far. I'm pretty new to this Arduino stuff, so I don't understand a ton yet.

Anyway, thanks in Advance. :)

```
#include <Joystick.h>

const int drum1 = A0;
const int drum2 = A1;
const int drum3 = A2;
const int drum4 = A3;

const int threshold = 100;

int sensorReading = 0;

Joystick_ Joystick;

void setup() {

  // Initialize Joystick Library
  Joystick.begin();
}

// Last state of the button
int lastButtonState = 0;

void loop() {

  sensorReading = analogRead(drum1);

  if (sensorReading >= threshold)
  {
    Joystick.pressButton(0);
    Joystick.releaseButton(0);
  }

  sensorReading = analogRead(drum2);

  if (sensorReading >= threshold)
  {
    Joystick.pressButton(1);
    Joystick.releaseButton(1);

  }
}

```

  [1]: https://github.com/MHeironimus/ArduinoJoystickLibrary

title: Drum game controller - Problem with Piezo inputs

Answers: 1

body:
From my interpretation of your problem it seems like you want to be able to press two (or more) joystick buttons at once by striking multiple drum pads.  As it stands your code will never be able to do that since you press, then immediately release, each button sequentially.

The simplest way around this is to only press the button when you strike the drum, then release the button at a later time, which gives a chance for another button to be pressed in the meantime.  What that "later time" is would be for you to decide.

The simplest thing to do is maintain a "this drum has been struck" flag along with a "this drum was struck at" timestamp (it's possible to combine the two), both of which are set at the moment of striking the drum. Then later in your code you check that timestamp and flag and release the button (and disable the flag) if the required time has expired.

To prevent duplicate code it can be good to encapsulate the logic and state variables for a single drum into a `class` and then instantiate multiple instances, one for each drum pad. For example, here's some untested code that may or may not work:

```c++
class Drum {
    private:
        uint32_t _timestamp;
        uint8_t _button;
        uint8_t _channel;
        int16_t _threshold;

    public:
        Drum(uint8_t channel, uint8_t button, int16_t threshold = 100) {
            _channel = channel;
            _button = button;
            _threshold = threshold;
            _timestamp = 0;
        }

        void process() {
            if (_timestamp > 0) { // Has been struck
                if (millis() - _timestamp >= 100) { // 100ms window - adjust as needed
                    Joystick.releaseButton(_button); // Release the button
                    _timestamp = 0; // Set it as not struck
                }
            }

            if (analogRead(_channel) > _threshold) {
                _timestamp = millis(); // Set it as struck now
                Joystick.pressButton(_button); // Press the button
            }
        }
};
```

Then you can instantiate multiple drums:

```c++
Drum drum1(A0, 0);
Drum drum2(A1, 1);
```

Then in your loop simply:

```c++
void loop() {
    drum1.process();
    drum2.process();
}
```

Again I reiterate: this code is untested, I don't even know if it compiles.


body:
I'll start off by saying I'm very very new to coding, so please bare with me.

I'm doing an assignment where the task is to create a traffic light system, but blocking delays aren't allowed. I have looked into "blink without delay", but it seems that option would require me to create far too confusing and long code than is needed. So instead I used for, else and goto functions together since it was a lot simpler and cleaner, but I have heard goto isn't a preferred option,

```c++
for(int i = 0; i < 20; i = i + 1)
{
    break0:
    digitalWrite(Traffic_R, HIGH);
    long int CurrentMillis1 = millis();

    break1:
    if (millis() - CurrentMillis1 <= 250){
        digitalWrite(Pedestrian_R, HIGH);
        goto break1;
    }else{
        long int CurrentMillis2 = millis();

        break2:
        if (millis() - CurrentMillis2 <= 250){
            digitalWrite(Pedestrian_R, LOW);
            goto break2;
        }
    }
}
```

Then I made another way without goto function,

```
for(int Test1 = millis(); Test1 < 7500; Test1 + millis())
{
  digitalWrite(LED, HIGH);
}
```

**TLDR**
So my question is, are either of these methods a "blocking method", like delay is? Also what are the pros and cons of each method? Also I can upload the code for the first method if needed. Thanks heaps in advance!

title: Why won't this work as a delay?

Answers: 2

body:
Here I have a simple example of cycling over 3 LEDs with the same 'delay' for every LED.
```
void loop() {

  static unsigned long previousMillis;
  static uint8_t cycleCounter;

  if (millis() - previousMillis > 100) {
    previousMillis = millis();
    digitalWrite(LEDS_CENTRAL_PIN, cycleCounter == 0);
    digitalWrite(LEDS_LEFT_PIN, cycleCounter == 1);
    digitalWrite(LEDS_RIGHT_PIN, cycleCounter == 2);
    cycleCounter++;
    if (cycleCounter == 3) {
      cycleCounter = 0;
    }
  }
}
```

body:
    break1:
    if (something)
      goto break1;

is basically a while loop - just more confusing to read.

---

> Also I can upload the code for the first method if needed.

You can upload it, of course. Personally I would mark you down for using `goto`.

---

> are either of these methods a "blocking method", like delay is?

Neither method literally blocks. The `delay` function blocks because it doesn't return until the time is up. Your loops don't block because you could conceivably do something else in the loop.

---

> I have heard goto isn't a preferred option

For a good reason. Do you think that, if you looked at your code again in a year, you would easily understand it? I have been coding for years and would have to carefully follow all the ways that the `goto` could jump around in unexpected ways.

At least with a `while` loop you have a well-defined start and end of the loop.


body:
Sorry, I'm not fluent in English.
I beg your help
I made an arduino uno project where the buzzer only turns on for 2 seconds after the light turns on. Even though the light is still on I want the buzzer to turn off after 2 seconds. I have tried several methods but I still fail.I use sensor ldr here.
can you guys help me?

        if( sensorValue <= 25 && lastBuzzer == 0)
       {
        lastBuzzer = millis();
       }
       if(sensorValue <= 25)
      {
        if (millis() - lastBuzzer < 1000L)
        {
        digitalWrite(buzzer, HIGH);
        delay(100);
        digitalWrite(buzzer, LOW);
        delay(100);

      }
      }
      else
      {
        digitalWrite(relayPin, LOW);
        lastBuzzer = 0;

      }

title: the buzzer stops sounding after a few seconds

Answers: 0


body:
I am trying to write a delay function in C, which should take 0.5 seonds then carry on. I am aware that there are libraries for this purpouse, I want to make it myself.

```C
#include <avr/interrupt.h>
#include <avr/io.h>
#define bitset(var,bitno) ((var) |= (1 << (bitno)))

int volatile time_unit;

ISR(TIMER0_COMPA_vect) {

  time_unit += 1;
}

void wait_func(){
  TCNT0 = 0;
  time_unit = 0;
  while (time_unit < 31);
}

int main(void){
  DDRD = 1;
   cli();
  bitset(TCCR0A, WGM01);
  bitset(TCCR0B, CS00);
  bitset(TCCR0B, CS02);
  OCR0A = 0xFF;
  bitset(TIMSK0, OCIE0A);
  sei();

  while(1){
    PIND = 0;
    wait_func();
    PIND = 1;
    wait_func();
  };
}
```
The timer is in CTC- Mode 1024 prescaler, counting 31*255 (OCR0A = 0xFF) times should give about 0.5 seconds at a base clockrate of 16MHz of the Arduino Atmega328p. The code works, but it turns the LED on and of at a rate of 1 second, (1 sec on 1 sec off). I do not understand why.

title: Interrupt takes longer than expected

Answers: 1

body:
* `PIND = 1;` toggles the state of bit 0 of `PORTD`.
* `PIND = 0;` does nothing at all; no toggling of any pins.

So you're simply just not toggling as often as you think.  Your delay itself is otherwise fine.  Change `PIND = 0;` to  `PIND = 1;` and it will work as expected.  Having done that you can get rid of one set of `PIND = 1;` and `wait_func();` call.

Alternately, if you want to follow the current form of the code, set and clear the bit on `PORTD` directly:

```c
while(1){
  PORTD &= ~1; // or &= 0xFE
  wait_func();
  PORTD |=  1;
  wait_func();
}
```

For what it's worth:
* The semicolon after your while loop does nothing.
* The `time_unit` should probably be an `unsigned char` / `uint8_t`.
* Unless you're running really tight on code space, it's probably best not to rely on the prior state of the timer hardware registers.


body:
I built a robotic arm, the problem is I want to rotate the base more than once in order to complete a job, so I figured out I could use multi turn potentiometer.
The problem I am facing is the potentiometer is burning without any reason.
I have a ton of burnt ones with me.
Sometimes it is caused by soldering and sometimes the shaft testing rotates the potentiometer beyond its limits.
While I could get the values precisely.
I am trying to avoid the pain of buying more.

My question is if I can use incremental encoder, the electricity in my country is not that stable and I don't want to lose the values accumulated by the arduino.
So does the encoder remembers the values or rotation or it starts afresh?

title: Multi turn potentiometer are a pain should I use a incremental encoder instead?

Answers: 1

body: Yes, you can use a rotary encoder. However, there are two kinds of rotoary encoder: absolute, and relative. Relative encoders are the small common ones you find being used for things like volume controls. They only give you "It moved clockwise x steps" kind of information, which is not ideal for your usage. What you need is an *absolute* rotary encoder. This is a far more complex device and is often used on the shaft of motors to give the current angle the motor is at. These usually use a *Gray code* to represent an absolute angle at a specific resolution (choose the resolution to meet your requirements) and will tell you (within that level of resolution) the exact angle your robot arm is at. You can rotate it as many times as you like and it will always give you the current angle (note: it can't tell you how many revolutions it's made, that is down to you to count, should you actually need to).


body:
A sine wave is being fed to `A0` and I would like to calculate the frequency. If a certain threshold is crossed, start the timer.....count 5 such crossings.....then stop the timer. The code is attached. Even though I understand `while()` with logical operators such as `while(State<5)` (shown in code), I do not understand the use of `while(analogRead(A0))`. I would like to know how it functions in relation the code? The program runs fine as it is. Tested this in Tinkercad, and got erroneous readings when `while(analogRead(A0))` was commented. Thank you so much for reading my question ^_^.
```cpp
void loop()
{

  while(State<5)
  {
    val=analogRead(A0);
    if(val>200)
    {
      Serial.println("Threshold Crossed");
      if(State==0)
      {
        Start_Time=millis();
      }
      State++;
      while(analogRead(A0)); //I DON'T UNDERSTAND THIS
    }
  }

End_Time=millis();

Period=(Start_Time-End_Time)/5;
Frequency=1000/(Start_Time-End_Time)
Serial.println(Frequency);

State=0;
}
```

title: How does while(analogRead(A0)) function in this code?

Answers: 2

body: As you correctly note, `while` typically takes a bool as argument. However, mainly for historical reasons, C/C++ don't really differentiate between int and bool, and therefore conditions can be of integer type. Any condition, be it in a `while` or an `if`, can be of int type. The condition evaluates to true if it is not zero. So the condition `while(analogRead(A0));` loops (doing nothing) until `analogRead` returns 0.

body:
What you have implemented, perhaps unknowingly, is called
[hysteresis][]. Your program spends most of its time in either of these
two states:

1. It is continually running the outer `while` loop, and the value read
   is ≤ 200. It gets out of this state as soon as it reads a value
   larger than 200.
2. It is continually running the inner `while` loop, and the value read
   is > 0. It gets out of this state only when `analogRead()`
   returns zero.

Hysteresis is a good way to reject noise when you want to detect a
signal crossing a threshold. I would, however, recommend you use it in a
more controlled manner. Specifically, the second threshold should
probably be greater than zero, otherwise it won't be crossed unless the
signal goes all the way down to ground level. At a minimum, you can
replace the inner `while` loop with something like:

```c++
while (analogRead(A0) >= 100)
    /* wait until the signal gets low enough */;
```

For the record, this logic can be implemented in a _non-blocking_
fashion, which would let the program do other things, like responding to
button presses, while waiting for the transitions. For this, you need a
variable to record the current state of the signal (say, `LOW` or
`HIGH`) and record the state changes when the corresponding thresholds
are crossed.

The sketch below implements this non-blocking technique in `loop()`,
whereas `setup()` does block while waiting for the first `LOW` → `HIGH`
transition:

```c++
const int LOW_THRESHOLD  = 100;
const int HIGH_THRESHOLD = 200;

uint8_t state;      // either LOW or HIGH
uint8_t count = 0;  // count the LOW -> HIGH transitions
uint32_t start_time;

void setup() {
    // Wait for the first LOW -> HIGH transition.
    while (analogRead(A0) >= LOW_THRESHOLD)
        /* Wait for the LOW state. */;
    while (analogRead(A0) < HIGH_THRESHOLD)
        /* Wait for the HIGH state. */;
    state = HIGH;

    // Record transition time.
    start_time = millis();
}

void loop() {
    // Record transitions.
    uint8_t val = analogRead(A0);
    if (state == HIGH && val < LOW_THRESHOLD) {
        state = LOW;
    } else if (state == LOW && val >= HIGH_THRESHOLD) {
        state = HIGH;
        ++count;
    }

    if (count >= 5) {
        // Report measured frequency.
        uint32_t end_time = millis();
        int frequency = 1000 * count / (end_time - start_time);
        Serial.println(frequency);

        // Prepare for the next round.
        start_time = end_time;
        count = 0;
    }
}
```

[hysteresis]: https://en.wikipedia.org/wiki/Hysteresis


body: I have an Arduino ESP32 cam that I want to use as a bird cam. I want to use my old Orcon wireless modem to connect with this cam. I will connect with cable from my computer to this modem. As my existing Wi-Fi is running on 5Ghz, I cannot connect to it with this cam. So I need some pointers on how to do. Thanks.

title: How do I connect my ESP32 cam to my old modem without using Wi-Fi?

Answers: 1

body:
Use an FTDI programmer and communicate with a serial protocol like UART.
The connection schematic can be found here.
https://randomnerdtutorials.com/program-upload-code-esp32-cam/
However you would have to do some extra research work on making the serial communication with the ESP32.

So a nice way would be to buy a wifi module for your old computer and use it to connect to the wifi and program the ESP32 accordingly.


body:
I am trying t change the baud rate of sim800l v1. But not successfully happening, every power cycle again going to AT+IPR= 0. I am using the following AT commands for changing the baud rate.

1.AT
2.AT+IPR?
3.AT+IPR=115200
4.AT&W

after power rebooting of sim800L going it is going AT+IPR=0.

Thank you

title: 800l v1 Baud rate is not fixing at 115200, How fix it for 115200 for lifelong

Answers: 2

body:
From a quick scan of its [AT command manual][1], I think you want to look at section 1.7.1, "Parameter Saving Mode". There are several modes, and while the description isn't quite clear, it looks like one command causes all subsequent parameter changes to be saved into NVRAM (so they will survive over a power-down), while another one causes the most recently changed parameter into NVRAM. I'm not sure which mode would best serve your needs, but the latter one would appear to answer your immediate need, retaining the baud rate.

  [1]: https://www.elecrow.com/wiki/images/2/20/SIM800_Series_AT_Command_Manual_V1.09.pdf

body: Your mistake is using AT&W to save the parameter, for some reason you have to add the profile number which is only 0 and use AT&W0 on a sim800l a sim800c with newer firmware accepts AT&W. I've learnt this the hard way.


body:
I am working on a "personal assistant" with Arduino and I am having trouble playing sound from an SD card... I am using a shield called "Easy Shield UNO" by Simkeim, and it has an SD card reader on it. It does work because I tested it through the Serial monitor, but when I try to play sound, nothing happens. (The speaker does work) Can someone please help me check my code or something to see what is wrong?

Here is the code I found online, I only changed it a bit...

    #include "SD.h"
    #define SD_ChipSelectPin 10
    #include "TMRpcm.h"
    #include "SPI.h"

    TMRpcm tmrpcm;

    void setup(){
     tmrpcm.speakerPin = 7;
     Serial.begin(9600);

     tmrpcm.setVolume(255);
    }
    void loop() {
      if(!SD.begin(SD_ChipSelectPin)) {
        Serial.println("SD card not found");
        return;
    }
      else{
        Serial.println("SD card reading sucess");
        tmrpcm.play("test1.wav");
      }
    }

title: How can I play sound on Arduino with an SD card?(I have a problem with the sound)

Answers: 1

body:
I see three problems with your code:

- It doesn't make much sense to begin the SD card again and again in `loop()`. Please move that part to `setup()` or somewhere, where it isn't called on every loop iteration.
- You shouldn't call `tmrpcm.play()` in every `loop()` iteration. It doesn't wait for the song to be finished. It just starts the playing (which is controlled by a timer interrupt) and exits. And every call of it will start the file again at its start. So by calling it again and again in fast succession you don't leave enough time for the file to actually be played, until you play again from start. To prevent that you can use an if statement to only start, if there isn't a file playing currently:

        if(!tmrpcm.isPlaying()){
            tmrpcm.play("test1.wav");
        }

- You are choosing pin 7 as output pin, but you cannot choose the pin freely, because it has to be connected to the used Timer and thus being PWM capable. Thats not the case for pin 7. In the [wiki of the TMRpcm library][1] you can find the following line under "Functions":

        audio.speakerPin = 11;     set to 5,6,11 or 46 for Mega, 9 for Uno, Nano, etc.

    So please connect your speaker to pin 9 and use `tmrpcm.speakerPin = 9;`.

  [1]: https://github.com/TMRh20/TMRpcm/wiki


body:
**Disclaimer:** I just started using C++ and I'm a bit of a beginner. Keep that in mind as your answering.

So I recently bought my first Arduino. It's a customized one and it has an 8x8 display attached to it. To display something on the display, the company I bought it from recommends storing the instructions for the display in a two-dimensional byte array.

I now have a longer animation I want it to play, so I researched and found [PROGMEM](https://www.arduino.cc/reference/en/language/variables/utilities/progmem/) which lets me store much more data. So I write something along the lines of:
```c
const byte frames[2][8] PROGMEM {
  {
    B10000100,
    B10000100,
    B10000100,
    B10000100,
    B10000100,
    B10000100,
    B10000100,
    B10000100,
  },
  {
    B10010100,
    B10010100,
    B10010100,
    B10010100,
    B10010100,
    B10010100,
    B10010100,
    B10010100,
  }
};

void setup() {
  arduino.begin();
}

void loop() {
  arduino.printImage(frames[0]);
  delay(1000);
  arduino.printImage(frames[1]);
  delay(1000);
}
```
After compiling, it throws a few errors at me:
```c
warning: invalid conversion from 'const byte* {aka const unsigned char*}' to 'byte* {aka unsigned char*}' [-fpermissive]
   arduino.printImage(frames[0]);
                      ~~~~~~~~^
```
This did not worry me as much and I just ignored those. After uploading, however, the display just showed arbitrary patterns instead of the lines I told it to draw.

After I removed the PROGMEM, it worked flawlessly, however, the memory wasn't big enough to store the array (not the one I provided as an example).

I could think of two reasons:

1. In the [official documentation of PROGMEM](https://www.arduino.cc/reference/en/language/variables/utilities/progmem/), it states that you have to get the variables back into memory. However, none of the methods they provided worked for me.
2. In a [similar question on ASE](https://arduino.stackexchange.com/questions/63178/read-nested-array-item-from-progmem), both answer and comments state that nested arrays aren't supported, but my knowledge of C++ isn't good enough to understand the answer.

title: Read bytes from PROGMEM array

Answers: 1

body:
On [the question you are referencing][q], the accepted answer suggests
to modify the library. This could be the most efficient option. A less
invasive solution, however, would be to copy the data from the flash
memory to RAM, and use the `printImage()` function as is.

Obviously, copying everything to RAM defeats the purpose of PROGMEM. But
you only need to copy one frame at a time, and only hold it in memory
for little more than the duration of the call to `printImage()`:

```c++
void printProgmemFrame(const byte flashFrame[8]) {
  byte ramFrame[8];
  memcpy_P(ramFrame, flashFrame, 8);
  arduino.printImage(ramFrame);
}

void loop() {
  printProgmemFrame(frames[0]);
  delay(1000);
  printProgmemFrame(frames[1]);
  delay(1000);
}
```

[q]: https://arduino.stackexchange.com/questions/63178


body:
I have am putting together multiple arduinos on a RS485 network (connected to Rx/Tx on the arduino and using Serial - connection via one of these https://www.ebay.co.uk/itm/272929871278) - RS485 because it is spread over quite a distance - total linear wiring approx 200m.

My question is: If I have Master, Slave1 and Slave2 on the bus, and the link is running at full speed in comms between Master and Slave1 - then what is the expected interrupt handler overhead on Slave2 in putting the incoming traffic into the ring buffer? (since as it is RS485 all devices not sending see all the traffic)

My "finger in the air" estimate is around 5%-15% at 256k baud and would scale fairly linearly with baud rate.

Does anyone have a definitive answer on this or can point to any profiling done on this?

title: What is the overhead of a saturated serial connection at 256k baud?

Answers: 1

body:
So I decided a little empirical testing was in order. This is using a nano (328P)

Using a simple for loop in loop() (calculating the squares of 0 to 255) over 10 seconds with and without there being serial traffic and at different speeds.

Note: this is without any inspection of the ring buffer on incoming data - just measuring the overhead of there being traffic on the wire. The traffic on the wire was the maximum an arduino mega was able to send at that baud rate.

    No load: 2600462 iterations
    256k: 2381219 iterations
    2M: 1349142 iterations

    256k takes 8.5% of the runtime
    2M takes 48% of the runtime

Code block as requested for the unit doing the timing (it includes calls to the libraries I am using for my environment, but I am sure you can abstract those away to something else and should not be significant to the stats)

    uint32_t start_time;
    void setup() {
        init_serial();
        start_time = millis();
    }

    uint32_t count = 0;
    uint16_t foo;
    void loop() {
        byte buff[MESSAGE_BUFFER_SIZE];
        if (millis() - start_time < 10000){
            for(int i = 0; i<256; i++) {
                foo = i * i;
            }
            count++;
        }
        else {
            if (getMessage(buff)) {
                char msg[30];
                sprintf(msg, "Count: %lu ---", count);
                send_debug_message(msg);
            }
        }
    }


body:
I am running my Arduino projects like this:
[![enter image description here][1]][1]

**My goal is to have this project run at 8mhz so that (1) battery last longer and (2) so that I am following the specs.** I was able to burn a 8mhz bootloader to my Atmega328 chip thanks to this video: https://www.youtube.com/watch?v=fzZ2TR_mwgs

After following the video I am able to run sketches at 8mhz and they consume less current. But my original project crashes to the point where I have to burn a bootloader again. Even if I press the reset button it will not become responsive. I have discovered that this line of code is the one that makes my atmega328 chip unresponsive:

    wdt_enable(WDTO_4S);  // #include <avr/wdt.h>

I find out about that because removing that line made my project work. That line enables waking up after 4 seconds. So I basically perform some work and go to sleep for 4 seconds. I then repeat the same steps forever in order to save battery.  So before going to sleep I execute this:

    // wake up from sleep after 4 seconds
    wdt_enable(WDTO_4S);

    // go to deep sleep
    if (true)
    {
        // BIG difference when in sleep
        // Diable ADC (analog to digital converter)
        ADCSRA &= ~(1 << 7);

        SMCR |= (1 << 2); // power down mode
        SMCR |= 1;        // enable sleep;

        // BOD DISABLE (big difference when in sleep only)
        MCUCR |= (3 << 5);                      // set both BODS and BODSE at the same time
        MCUCR = (MCUCR & ~(1 << 5)) | (1 << 6); // then set the BODS bit and clear the BOSE bit at the same time

        __asm__ __volatile__("sleep");
    }

    // this line will not execute....

**Anyways how could I solve this problem? Should I keep the original project and just replace the crystal to  8mhz?** I will then have to keep in mind that all delays will be half the speed correct?

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

title: Cannot enable watchdog timer when using Arduino 8mhz bootloader

Answers: 2

body: Your delays are probably what is killing you. If you have delays longer than the WDT time that will cause a WDT timeout. Remember the Delay function does nothing but burn time, nothing else is processed. Go to the Millis or something like that as recommended many times in the Arduino forums.

body:
Try power cycling the UNO when the boards stops responding. That should reset the watchdog settings. Just pressing reset doesn't disable the watchdog, as far as I know.

The bootloader doesn't know you enabled the watchdog, and if it takes more that 4 seconds, you get stuck in an infinite loop. You could try using the optiboot bootloader instead. That one resets the watchdog when it runs.

Thirdly, you could enable the watchdog interrupt. If you do that the MCU will still wake up after 4 seconds of sleep, but it will resume you code, instead of doing a reset. Doing this will make it so the bootloader only runs once.


body:
**Setup:**
I have wired up the arduino, motor and battery as shown.
[![enter image description here][1]][1]
(12 and 5 of L293D are not connected to anything)
D11,D10...D6 means that those pins on the L293D are connected to digital pins 11-6 on the nano.

**Problem:**
The motors spin for a while but then they slow down to a stop. If I unplug the battery, wait for 5 mins or so and then reattach the battery then the motors start spinning but after a while they stop again. Now if I keep the setup the same except I unplug the battery and connect the arduino to my laptop then the laptop manages to power not only my arduino but also my motors (although they spin a little bit less faster than with the battery). And when I do it with the laptop the motors don't stop spinning.
Because of this I thought my battery might be faulty so I attached a fresh 9V energiser battery. Then the same thing happens. The motors spin for a while then stop and after I plug in the battery after a while they spin again.
I tried this yet again with a fresh battery and the same thing happened.

**Question**
What could be causing this?
Why are all of my batteries incapable of powering the motor steadily and why is my laptop capable of doing this?

CODE:
(all this does is make both motors spin)
[![enter image description here][2]][2]

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

title: Battery supply vs laptop supply

Answers: 0


body:
Code using BluetoothSerial api disconnects immediately after establishing connection with my laptop running Ubuntu 18.04. If instead of BluetoothSerial BLEDevice api is used, the connection stays connected. See minimal examples below.
Another peculiar observation is that connection with my Android phone is stable when running BluetoothSerial example below.

How to make BT connect properly with both the phone and laptop?
The chip running the code is esp32-wroom-32d.

Minimal code with BT disconnecting from laptop Ubuntu 18.04 after roughly a second (from [SerialToSerialBT example](https://github.com/espressif/arduino-esp32/blob/master/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino)):

    #include "BluetoothSerial.h"

    BluetoothSerial SerialBT;

    void setup() {
      SerialBT.begin("ESP32 SerialBT");
    }

    void loop() {
    }

Minimal code with stable BT connection (from [BLE_notify example](https://github.com/espressif/arduino-esp32/blob/master/libraries/BLE/examples/BLE_notify/BLE_notify.ino)):

    #include <BLEDevice.h>
    #include <BLEServer.h>

    BLEServer* pServer = NULL;

    void setup() {
      BLEDevice::init("ESP32");

      pServer = BLEDevice::createServer();
      pServer->setCallbacks(new BLEServerCallbacks());

      BLEDevice::startAdvertising();
    }

    void loop() {
    }

UPDATE:
- Updating Ubuntu to 20.04 did not help.

title: ESP32 SerialBluetooth disconnects within a second after connecting but not BLEDevice/BLEServer

Answers: 1

body:
I know this is old but I had the same issue using bluetoothserial.h.  But by using rfcomm

    rfcomm bind 0 <bluetooth MAC ADDRESS>
and then my example command sent to serialBT

    echo -ne ">LOOOCR" > /dev/rfcomm0

/dev/rfcomm0 being the device created with the bind. It even still shows as disconnected in the Ubunutu 20.04 bluetooth GUI.  For what it's worth I think it is the same on all devices.  Until you connect to the BT serial port it is only Paired.  But someone with greater knowledge than myself can explain.


body:
I set the fuses of my attiny85 so it uses the internal 128khz clock, prescaled so it is 16kHz.
I set the CKOUT fuse too so I can check the clock using an oscilloscope on pin 3 and yes it is 16kHz.

Now my problem is I have no option in the Arduino IDE to compile my code for 16kHz clock speed.
The slowest I have is 128khz, which causes the "blink" sketch to run for 8 seconds up, 8 seconds low on my attiny instead of 1 second.

I tried with "attiny" from David A. Mellis using https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json (Slowest : 1Mhz) and "ATTinyCore" from Spence Konde using http://drazzy.com/package_drazzy.com_index.json (Slowest : 128khz).

Does someone know how I can set my Arduino IDE to compile the code for an attiny85 using the 16khz internal clock ?

(Please, no question "why use a 16khz clock ?". The point is, this chip may be set to 16khz clock, so it should be possible to program it to use such clock speed)

Thank you.

title: Program ATTiny85 running at 16 KILOhertz

Answers: 1

body:
The Arduino core you've referenced (and pretty much all other AVR Arduino cores too) specify the clock frequency that a particular selected board is running at in the `boards.txt` file. The `platform.txt` file then retrieves that value and creates the `F_CPU` macro with the clock frequency in hertz as a value.

For the ATTinyCore by Spence Konde, the ATTiny85 board definition is the `attinyx5` section. There, you can either add a new clock selection menu item or modify the settings of an existing one, e.g.

https://github.com/SpenceKonde/ATTinyCore/blob/f5eabc8fb97e8fd72f1782a5e97345729e42ec47/avr/boards.txt#L409-L412

```ini
attinyx5.menu.clock.128internal=128 kHz (internal WDT)
attinyx5.menu.clock.128internal.bootloader.low_fuses=0xC4
attinyx5.menu.clock.128internal.build.f_cpu=128000L
attinyx5.menu.clock.128internal.build.clocksource=3
```

The file is locally under `C:\Users\<user>\AppData\Local\Arduino15\packages\ATTinyCore\hardware\avr\1.5.2`.

There, `f_cpu` should be modified to `16000L` for 16KHz, the `low_fuses` (lfuse) setting should be set to `0x24` and the text "128 kHz" should be adapted too. This is working per the comment on the question.

On a final note, you should create an issue at the core's repo to have a 16kHz added by default.

Also, you might find it easier to work with [PlatformIO](platformio.org/) (+VSCode) instead of the Arduino IDE. A getting started page is [here](https://docs.platformio.org/en/latest/integration/ide/vscode.html#installation). In PlatformIO, instead of having to modify the internal `boards.txt` file, you can create a project configuration file (`platformio.ini`) in which you specify the same thing setting.

```ini
[env:attiny85]
platform = atmelavr
board = attiny85
framework = arduino
board_build.f_cpu = 16000L
; for upload settings, see
; https://docs.platformio.org/en/latest/platforms/atmelavr.html#upload-using-programmer
```


body:
I would like to understand why did Arduino clipped the input signal as shown in the attached diagram? As far as I know, Arduinos are able to read analogue voltages up to **5v**, that is **1023**. But for some reason my signal got clipped at **390** which is about **1.90V**. What may be the reason behind this? The schematic is also attached. The low voltage input signal **(mV range)** is passed through a Band pass filter with a gain of **143**. The signal is then DC shifted by +3.3/2=**1.65V** by using a capacitor coupled voltage divider offset. The opamp **LM358 (not LT1215 shown in the schematic)** and everything else is powered from Arduino's built in **3.3V** regulator. One reason might be that the opamp can't spit out anything more than its supply voltage, that is **3.3V**, but even then the clipping should take place at **675 (1023*3.3/5), not 390**. Am I missing something??

Thank you for reading my question. Any help is highly appreciated ^_^.

**Serial Plotter:**
[![enter image description here][1]][1]

**Schematic:**
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/j8Efn.png
  [2]: https://i.stack.imgur.com/35LSB.png

title: Signal clipping in Arduino Serial Plotter

Answers: 0


body:
**Background**

I am programming a 40-pin ATMega4809 ([datasheet][1])  using ATMEL-ICE programmer.
I'm simply using the Atmel Studio to upload a HEX file to the chip.
I generate the HEX file using the Arduino IDE.

I'm using the very simple blink sample sketch with a slight modification which uses a different output pin for the LED.

    const byte LED = 6;

    void setup() {
      // initialize digital pin LED as an output.
      pinMode(LED, OUTPUT);
    }

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

I have a LED (with resistor) connected to PA6 on the ATMega4809.

**Code Result**

I use the Export compiled binary choice in the Arduino IDE to generate the HEX file.

[![export compiled binary][2]][2]

I then use Atmel Studio to upload the HEX file to the ATMega4809.

When I do, the program runs and the LED turns on.

However, I never see the LED turn off (blink).

Do you know why this might be true?

**Things I've Tried**

 1. I've tried increasing the delay value to see if internal crystal is
    set different and the timing is different or something.
 2. I've set the internal crystal to different values (ranging from 1Mhz
    to 20Mhz) and haven't seen any difference.
 3. I've considered that it could just be not looping, so I've tried
    various things to see if that were true or not.
 4. I've placed all of the code in the `setup()` function to see if it
    would working differently -- it didn't, it still just turned the LED
    on but never off.
 5. I've tried turning LED **on** in `setup()` & **off** in `loop()` to
    insure both are at least running once and they are.

**NOTE**: I know the HEX file is being properly uploaded because when I alter the program and upload different ones (turn on/turn off led) then the code does seem to either turn the LED on or off.
I've also verified the code using Atmel Studio -- reading the chip's memory out to a file and doing diff.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega4809-40-Pin-40002104B.pdf
  [2]: https://i.stack.imgur.com/iCRWg.png

title: Programming ATMega4809 via Atmel-ICE with Hex File from Arduino IDE - why doesn't the code loop / work?

Answers: 1

body:
Because of the great question asked by @Juraj I thought about how pins are mapped (and that I was probably thinking wrong about that mapping).

I searched for and found the following diagram:

[![nano every pin map][1]][1]

Notice that D7 is mapped to PA1

I switched the code to use Digital Pin 7 (`const byte LED = 7;`)
I then switched the LED in the circuit to be connected (with appropriate resistor) to PA1 which is actually PIN 34 (on my ATMega4809 40 pin).

Back in the Arduino IDE I switched the board to Nano Every (which also uses the ATMega4809).

[![Arduino IDE - Nano Every board][2]][2]

I compiled the code.
Then I exported the HEX file and uploaded it to the 40 pin ATMega4809 using Atmel Studio.

**With Bootloader Or Without**

**Didn't Work: With Bootloader**

The first time I tried it i selected the HEX file which contains the bootloader and it didn't work.  The LED didn't flash.

**Did Work: Without Bootloader**

I then tried uploading the HEX file which does not contain the bootloader and the LED began flashing as expected.

Solved!  All because of the great question which got me thinking better.
Thanks,
Here's a very fast [video of it in action][3] (youtube).

  [1]: https://i.stack.imgur.com/M29jD.png
  [2]: https://i.stack.imgur.com/38ZDs.png
  [3]: https://www.youtube.com/watch?v=BR4ZSOv2R6Q


body:
1)The values drifts to the extreme every time I run this , I guess this is due to my mistake in the calculation of angles or in the filter that I have applied which I have been trying to but can't find it. 2)I have tried to  calibrate MPU many times but failed as the x-axis value is showing 0 only when I tilt the bot to 12-14 degrees on x-axis(data from only accelometer),(if you can just tell me the variable to modify)

    #include <Wire.h>
    long accelX, accelY, accelZ;
    float gForceX, gForceY, gForceZ,elapsedTime;
    long gyroX, gyroY, gyroZ;
    float rotX, rotY, rotZ;
    double x,y,z,dx,dy,dz,ex,ey,ez,desx=0,desy=0,desz=0;
    float PID, PWM, error, previous_error,timePrev,time1;
    float pid_p;
    float pid_i;
    float pid_d;
    float rad_to_deg = 180/3.141592654;
    /////////////////PID CONSTANTS/////////////////
    double kp=2;
    double ki=0;
    double kd=0;
    int motor1pin1 = 2;
    int motor1pin2 = 3;
    int led = 9;           // the PWM pin the LED is attached to
    int brightness = 0;    // how bright the LED is
    int fadeAmount = 5;

    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      pinMode(motor1pin1, OUTPUT);
      pinMode(motor1pin2, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(13, OUTPUT);
      setupMPU();
      delay(500);
    }

    void loop()
    {
        timePrev = time1;  // the previous time is stored before the actual time read
        time1 = millis();  // actual time read/
        elapsedTime = (time1 - timePrev) / 1000;
        recordAccelRegisters();
        recordGyroRegisters();
       processangle();
        Apply_PID();
        printData();
        delay(100);
    }
    void right(int PWM)
    {
       analogWrite(9, PWM);
      digitalWrite(motor1pin1, HIGH);
      digitalWrite(motor1pin2, LOW);
      digitalWrite(13, HIGH);
      Serial.println("RIGHT");
    }
    void left(int PWM)
    {
       analogWrite(9, PWM);
      digitalWrite(motor1pin1, LOW);
      digitalWrite(motor1pin2, HIGH);
       Serial.println("LEFT");
    }
    void stopper()
    {
       analogWrite(9, PWM);
      digitalWrite(motor1pin1, LOW);
      digitalWrite(motor1pin2, HIGH);
       Serial.println("STOPPED");
      }
    void setupMPU()
    {
      Wire.beginTransmission(0b1101000); //This is the I2C address of the MPU (b1101000/b1101001 for AC0 low/high datasheet sec. 9.2)
      Wire.write(0x6B); //Accessing the register 6B - Power Management (Sec. 4.28)
      Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9)
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x1B); //Accessing the register 1B - Gyroscope Configuration (Sec. 4.4)
      Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x1C); //Accessing the register 1C - Acccelerometer Configuration (Sec. 4.5)
      Wire.write(0b00000000); //Setting the accel to +/- 2g
      Wire.endTransmission();
    }

    void recordAccelRegisters()
    {
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x3B); //Starting register for Accel Readings
      Wire.endTransmission();
      Wire.requestFrom(0b1101000,6); //Request Accel Registers (3B - 40)
      while(Wire.available() < 6);
      accelX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
      accelY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
      accelZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
      processAccelData();
    }

    void processAccelData()
    {
      gForceX = accelX / 16384.0;
      gForceY = accelY / 16384.0;
      gForceZ = accelZ / 16384.0;
      x= (RAD_TO_DEG * (atan2(-gForceY, -gForceZ)+PI));
      y= RAD_TO_DEG * (atan2(-gForceX, -gForceZ)+PI);
      z= RAD_TO_DEG * (atan(sqrt(square(-gForceY) + square(-gForceX)) / -gForceZ));
     /* x=map(x,340,11,-90,90);*/

        Serial.print(" AccelX=");
      Serial.print(x);

    }

    void recordGyroRegisters()
    {
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x43); //Starting register for Gyro Readings
      Wire.endTransmission();
      Wire.requestFrom(0b1101000,6); //Request Gyro Registers (43 - 48)
      while(Wire.available() < 6);
      gyroX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
      gyroY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
      gyroZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
      processGyroData();
    }

    void processGyroData()
    {
      rotX = (gyroX / 131.0);
      rotY = gyroY / 131.0;
      rotZ = gyroZ / 131.0;
      Serial.print(" GyroX=");
      Serial.println(rotX*elapsedTime);
    }
    void processangle()
    {
      dx=0.98 *(dx + rotX*elapsedTime) + 0.02*x;
      dy=0.98 *(dy + rotY*elapsedTime) + 0.02*y;
      dz=0.98 *(dz + rotZ*elapsedTime) + 0.02*z;
      ex=dx-desx;
      ey=dy-desy;
      ez=dz-desz;
      Serial.print("After Filter Angle");
      Serial.println(ex);
    }
    void Apply_PID()
    {
      float l=(float)ex;
      pid_p=kp*l;
      pid_i = pid_i+(ki*l);
    pid_d = kd *((l - previous_error)/elapsedTime);
    PID = pid_p + pid_i + pid_d;
    /*Serial.print("I=");
    Serial.println(pid_d);
    Serial.print("p=");
    Serial.println(pid_p);*/
    Serial.print("PID");
    Serial.println(PID);

    if(l>5.5 || l<5.5)
      {
        if(l<0)
        right(PID);
        else
        left(PID);
      }
      else
      {
        stopper();
        }
    previous_error = l;
    }

    void printData()
    {
      /*Serial.print("Gyro (deg)");
      Serial.print(" X=");
      Serial.print(rotX);
      Serial.print(" Y=");
      Serial.print(rotY);
      Serial.print(" Z=");
      Serial.print(rotZ);
      Serial.print(" Accel (g)");
      Serial.print(" X=");
      Serial.print(gForceX);
      Serial.print(" Y=");
      Serial.print(gForceY);
      Serial.print(" Z=");
      Serial.println(gForceZ);*/
     /* Serial.print(" PWM");
      Serial.println(PID);*/
    }

title: Bug in code of Self-Balancing Bot

Answers: 0


body:
I am currently running Arduino with this configuration (using atmega328p chip):

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

Basically, my program wakes up every 2 seconds for 10ms each time. If during those 10ms it finds and event of interest it will perform some actions. Because it only takes 10ms to check for those events the battery lasts for over a year even though it wakes up every 2 seconds.

Anyways now I want to migrate that same project to an esp32. I am not able to do so because the esp32 takes about 40ms to run the startup function plus the 10ms it takes to check for events it will be 50ms. **Waking up for 50ms every 2 seconds will drain my battery to fast!** Is there a way I can run some code before the setup function? I believe the reason it takes 40ms is because it uses freeRTOS. Is there a way I can run the esp32 without freeRTOS just like the atmega328P? I don't mind losing WiFi/bluetooth functionality. Moreover, the esp32 chip is able to run at lower voltages than the atmega328p and this makes it very convenient when using batteries. For example now I would be able to use 2 AA batteries instead of 3 that I need now.

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

title: Run esp32 without freeRTOS in order to execute something faster

Answers: 1

body:
What I am looking for is ["Deep Sleep Wake Stubs"][1]

Here is an example that works that I found from the internet:

```
#include <Arduino.h>

#include "driver/rtc_io.h"
#include "rom/ets_sys.h"
#include "rom/rtc.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "soc/rtc.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/rtc_io_reg.h"
#include "soc/timer_group_reg.h"
#include "soc/uart_reg.h"
#include <stdio.h>
#include <string.h>

RTC_IRAM_ATTR void deepsleep_for_us(uint64_t duration_us);

#define S_TO_NS 1000000ULL
// Boot counter value, stored in RTC_SLOW_MEM
static size_t RTC_DATA_ATTR boots;
static size_t RTC_DATA_ATTR max_boots;

// Function which runs after exit from deep sleep
static void RTC_IRAM_ATTR wake_stub();
void setup(){

}
void loop(void) {
  if (rtc_get_reset_reason(0) == DEEPSLEEP_RESET) {
    printf("I'm back! Wake up from (extended) deep sleep. Should be 60s elapsed.\n");
    printf("Boot count=%d\n", boots);
    while (1) {
      ;
    }
  } else {
    printf("Not a deep sleep wake up\n");
  }

  printf("Going to deep sleep for 5x12=60s second\n");
  boots = 0;
  max_boots = 12;
  // hold high during deep sleep
  esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);

  // Set the wake stub function
  esp_set_deep_sleep_wake_stub(&wake_stub);

  esp_sleep_enable_timer_wakeup(5 * S_TO_NS);
  esp_deep_sleep_start();
}

static const char RTC_RODATA_ATTR wake_fmt_str[] = "count=%d\n";
static const char RTC_RODATA_ATTR sleep_fmt_str[] = "sleeping\n";

static void RTC_IRAM_ATTR wake_stub() {
  // Increment the Boot counter
  boots++;
  // and print the Boot counter value:
  ets_printf(wake_fmt_str, boots);

  if (boots >= max_boots) {
    // On revision 0 of ESP32, this function must be called:
    esp_default_wake_deep_sleep();
    // Return from the wake stub function to continue
    // booting the firmware.
    return;
  }

  // Print status
  ets_printf(sleep_fmt_str);
  // Wait for UART to end transmitting.
  // feed the watchdog
  REG_WRITE(TIMG_WDTFEED_REG(0), 1);
  while (REG_GET_FIELD(UART_STATUS_REG(0), UART_ST_UTX_OUT)) {

  }
  deepsleep_for_us(5 * S_TO_NS);

  // Set the pointer of the wake stub function.
  REG_WRITE(RTC_ENTRY_ADDR_REG, (uint32_t)&wake_stub);
  // Go to sleep.
  CLEAR_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
  SET_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
  // A few CPU cycles may be necessary for the sleep to start...
  while (true) {
    ;
  }
  // never reaches here.
}

// Comment out this line if you're using the internal RTC RC (150KHz) oscillator.
//#define USE_EXTERNAL_RTC_CRYSTAL
#ifdef USE_EXTERNAL_RTC_CRYSTAL
#define DEEP_SLEEP_TIME_OVERHEAD_US (650 + 100 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
#else
#define DEEP_SLEEP_TIME_OVERHEAD_US (250 + 100 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
#endif // USE_EXTERNAL_RTC_CRYSTAL

RTC_IRAM_ATTR void deepsleep_for_us(uint64_t duration_us) {
  // Feed watchdog
  REG_WRITE(TIMG_WDTFEED_REG(0), 1);
  // Get RTC calibration
  uint32_t period = REG_READ(RTC_SLOW_CLK_CAL_REG);
  // Calculate sleep duration in microseconds
  int64_t sleep_duration = (int64_t)duration_us - (int64_t)DEEP_SLEEP_TIME_OVERHEAD_US;
  if (sleep_duration < 0) {
    sleep_duration = 0;
  }
  // Convert microseconds to RTC clock cycles
  int64_t rtc_count_delta = (sleep_duration << RTC_CLK_CAL_FRACT) / period;
  // Feed watchdog
  REG_WRITE(TIMG_WDTFEED_REG(0), 1);
  // Get current RTC time
  SET_PERI_REG_MASK(RTC_CNTL_TIME_UPDATE_REG, RTC_CNTL_TIME_UPDATE);
  while (GET_PERI_REG_MASK(RTC_CNTL_TIME_UPDATE_REG, RTC_CNTL_TIME_VALID) == 0) {
    ets_delay_us(1);
  }
  SET_PERI_REG_MASK(RTC_CNTL_INT_CLR_REG, RTC_CNTL_TIME_VALID_INT_CLR);
  uint64_t now = READ_PERI_REG(RTC_CNTL_TIME0_REG);
  now |= ((uint64_t)READ_PERI_REG(RTC_CNTL_TIME1_REG)) << 32;
  // Set wakeup time
  uint64_t future = now + rtc_count_delta;
  WRITE_PERI_REG(RTC_CNTL_SLP_TIMER0_REG, future & UINT32_MAX);
  WRITE_PERI_REG(RTC_CNTL_SLP_TIMER1_REG, future >> 32);
  // Start RTC deepsleep timer
  REG_SET_FIELD(RTC_CNTL_WAKEUP_STATE_REG, RTC_CNTL_WAKEUP_ENA, RTC_TIMER_TRIG_EN); // Wake up on timer
  WRITE_PERI_REG(RTC_CNTL_SLP_REJECT_CONF_REG, 0);                                  // Clear sleep rejection cause
  // Go to sleep
  CLEAR_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
  SET_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
}

```

I will try to see how hard is to run my code that checks for events on the `wake_stub` that runs before anything else.

  [1]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/deep-sleep-stub.html


body:
I am using Arduino mega with 4 interrupts to find the rotation speed of 4 motors . For this I have used INT2, INT3, INT4, INT5 and the code for the same is given below

```
struct Pulse {
  uint32_t last_toggle;
  uint32_t width;
  bool stateHigh;
  uint32_t get_width() {
    noInterrupts();
    uint32_t width_copy = width;
    interrupts();
    return width_copy;
  }
};

Pulse ch1, ch2, ch3, ch4;

void pin_initialization() {
  // Four engine configuration
  pinMode(19, INPUT_PULLUP);
  pinMode(18, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

}

volatile uint32_t ovfCount = 0;
ISR(TIMER3_OVF_vect) {
  ovfCount++;
}

void timer3_initialization() {
  TCCR3A = 0x00;

  TCNT3 = 0x1FF; // from datasheet
  TIFR3 = _BV(TOV3);
  TIMSK3 = _BV(TOIE3); // overflow enable
  TCCR3B = B00000011; // 64 prescaling
}

void pulseWidthCalculator(Pulse *channel){
  unsigned char sreg;
  sreg = SREG;
  cli();
  uint16_t tcnt3 = TCNT3;
  SREG = sreg;
  uint32_t ovf_count = ovfCount;

  if (bit_is_set(TIFR3, TOV3) && tcnt3 < 32768) {
    ovf_count++;
  }

  uint32_t time = ovf_count << 16 | tcnt3;

  if (!channel->stateHigh) {  // first high
    channel->stateHigh = true;
  } else if ( channel->stateHigh) {  // second High
    channel->width = time - channel->last_toggle;
    channel->stateHigh = false;
  }
  channel->last_toggle = time;
}

ISR(INT2_vect) {
  pulseWidthCalculator(&ch1);
}

ISR(INT3_vect) {
  pulseWidthCalculator(&ch2);
}

ISR(INT4_vect) {
  pulseWidthCalculator(&ch3);
}

ISR(INT5_vect) {
  pulseWidthCalculator(&ch4);
}

void externalInterrputInitialization() {
  EIFR = _BV(INTF2) | _BV(INTF3) | _BV(INTF4) | _BV(INTF5);
  EICRA = 0; EICRB = 0;
  EICRA = B10100000;
  EICRB = B00001010;
  EIMSK = B00111100;
}

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

  pin_initialization();
  delayMicroseconds(10);

  externalInterrputInitialization();
  delayMicroseconds(10);

  timer3_initialization();
  delayMicroseconds(10);

}

void loop() {
  String a = String(15e6/ch1.get_width());
  a += " ";
  a += String(15e6/ch2.get_width());
  a += " ";
  a += String(15e6/ch3.get_width());
  a += " ";
  a += String(15e6/ch4.get_width());

  Serial.println(a);

}

```

The issue I am facing is , whenever I give a signal to INT2, INT3 is also getting triggered, same with INT4, INT5 also getting triggered without signal .

What I am I missing here, ?

Should I make my channels ch1, ch2 , ch3, ch4 to volatile or not.? like
```volatile Pulse ch1, ch2, ch3, ch4```

- Any thing wrong with ```OUTPUT_PULLUP```

title: False interrupt triggering Arduino Mega

Answers: 1

body:
You have the right idea to atomically obtain a copy of the data that is updated by the interrupt:

```cpp
  unsigned char sreg;
  sreg = SREG;
  cli();
  uint16_t tcnt3 = TCNT3;
  SREG = sreg;
  uint32_t ovf_count = ovfCount;
```

...but the last two lines should be swapped to keep the copying operation within the non-interrupt section:

```cpp
  unsigned char sreg;
  sreg = SREG;                    // Save interrupt state.
  cli();                          // Disable interrupts.
  uint16_t tcnt3 = TCNT3;         // Atomic operations.
  uint32_t ovf_count = ovfCount;
  SREG = sreg;                    // Restore interrupt state.
```

Though I notice you are calling that code from within an interrupt service routine so interrupts should already be disabled unless you are intending to use nested interrupts.

The false interrupt could be caused by crosstalk between INT2 and INT3. You could confirm this by using an oscilloscope. Keep the signal wires separate to avoid crosstalk.

You could also try stronger external pull-ups such as 10K or 1K. The Arduino internal pull-ups are weaker at about 20-50K Ohms.


body:
I am working on a project to collect data from a barcode scanner using an Arduino, which in turn is connected to a POS/laptop. So far I am able to collect the data from the barcode scanner by using the Arduino as a host, and in order to send the scanner data from the Arduino to the laptop, I am using a [basic FTDI board][1] that converts serial data from the arduino to USB.

However, it shows up as a COM port in my computer and I need an additional serial monitor to see the data transferred from the Arduino.

Is there a device that converts serial data from the arduino to "HID keyboard Device" similar to the FTDI board?

Please let me know if I have not made myself clear or if you need more information.

Edit: I forgot to add that I am using an [Arduino MKR NB 1500][2]. I am using the board's native USB port to connect to the barcode scanner. [The USBHost library][3] gives the board the ability to act as a USB host and connect to the barcode scanner and get the scanned data from the barcode scanner.

I am using the FTDI board (serial to USB converter) and arduino's serial1 to send the scanned data to my laptop.

We are trying to build a portable device that connects to the barcode scanner and the POS. We are using the Arduino to update our database (I can use the MKR board to send a POST request with the barcode data to update our database) and in addition to this the Arduino should be able to send the scanned data to POS.
As of now I am connecting the Arduino's RX and TX pins to the FTDI board, which converts UART to USB. I would like to replace this FTDI board with an interface that converts UART to "USB HID keyboard". Please let me know if more information is needed.

  [1]: https://www.sparkfun.com/products/9716
  [2]: https://store.arduino.cc/arduino-mkr-nb-1500-1413
  [3]: https://github.com/arduino-libraries/USBHost

title: Serial to USD (HID keyboard device) converter

Answers: 2

body:
>  **I would like to replace this FTDI board with an interface that converts UART to "USB HID keyboard".**

[![FTDI Friend and ATmega32u4 board][1]][1]

On the left is an "FTDI Friend" that converts serial to USB. It is similar to the Sparkfun product you are using.

On the right is a similar sized, similar priced, board that can read serial and can act as a USB keyboard (Implementing the appropriate HID). It's a [Pololu A*Star micro](https://www.pololu.com/product/3101) but it's just one example of many similar devices. I used this one to implement a physical keyboard using mechanical switches but the input could have as easily come from it's serial interface.

Any ATmega32u4 or SAMD based board can act as a USB HID keyboard using the standard [Arduino keyboard library](https://www.arduino.cc/reference/en/language/functions/usb/keyboard/)

Admittedly you'll have to write and upload a sketch but that ought to be relatively straightforward.

There are also smaller, potentially cheaper, boards such as the Digispark and clones that have a separate software library to implement USB HID Keyboard functionality on a very simple microcontroller like the ATtiny85.

---

> **We are trying to build a portable device that connects to the barcode scanner and the POS.**

As Juraj's comment suggests, many barcode readers started out as serial devices and only later had USB-serial capability added. If you use a Barcode scanner with serial output, you probably don't need any extra hardware and can use the MKR NB 1500's USB interface to act as a keyboard device instead of as a host for the scanner.

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

body: use CH9329 chip it's cheap and could act as Keyboard and mouse at the same time. interface is a little bit hard as it's Chinese but it's cost 1 USD only.


body:
**EDIT1** - This phenomena occurs only after reboot using button or `ESP.reboot()`

I'll try to make my question more focused:

1) I have library that saved log events to SPIFFS.

2) From 3rd entry (in the following example - epoch clock entries), it saves wrongly somehow (jump to **Take-4** below).

3) Following code is an example using only relevant functions from that library.

Quick explanation:

`T` is holding epoch clock, that stores it right after boot.

`write(const char *message, bool NOW)` function - gets a message to store, and a boolean `NOW` if it has to be saved immediately rather than delayed save (delayed saved is implemented only in library, while here it gets saved instantly.)

`void _write2file()` writes the buffer to SPIFFS.

`int getnumlines()` returns number of entries saved (seeking for `_EOL` chars). In code below it acts as information only that serves displaying the problem, while when used in real library code, it limits the number of entries of the log.

`void rawPrintfile()` prints in human readable manner log's contents.

And last, the only function which does not belong to the library, `void insert_log_entry()`, simply enter a log entry (always the same one, after reboot).

**Take 1**-After uploading the sketch, you get this result on:

    19:58:00.125 -> add buffer #0: 1234567890

    19:58:00.191 -> total Lines before: 0
    19:58:00.191 -> entries in buffer: 1
    19:58:00.257 -> ~~~ Saved in /logfile.txt ~~~
    19:58:00.257 -> row #0 {1234567890}
    19:58:00.257 -> ~~~ EOF ~~~

Explanation: there was 1 entry to buffer, no- entries before, and a printout of file contents. So far- OK!

**Take 2** - Pressing reboot button, and results are:

    19:58:07.747 -> Start!
    19:58:07.814 -> add buffer #0: 1234567890

    19:58:07.814 -> total Lines before: 1
    19:58:07.814 -> entries in buffer: 1
    19:58:07.814 -> ~~~ Saved in /logfile.txt ~~~
    19:58:07.814 -> row #0 {1234567890}
    19:58:07.814 -> row #1 {1234567890}
    19:58:07.814 -> ~~~ EOF ~~~

Explanation:again 1 entry in buffer, 1 entry in log, and a printout of 2 entries.

**Take 3**
Pressing reboot button again, and results are:

    19:58:10.167 -> Start!
    19:58:10.200 -> add buffer #0: 1234567890

    19:58:10.200 -> total Lines before: 2
    19:58:10.233 -> entries in buffer: 1
    19:58:10.233 -> ~~~ Saved in /logfile.txt ~~~
    19:58:10.233 -> row #0 {1234567890}
    19:58:10.233 -> row #1 {1234567890}
    19:58:10.233 -> row #2 {1234567890}
    19:58:10.233 -> ~~~ EOF ~~~

Explanation: same, but now 3 entries are saved.

**Take 4!!!**

    19:58:11.194 -> Start!
    19:58:11.227 -> add buffer #0: 1234567890

    19:58:11.227 -> total Lines before: 2
    19:58:11.260 -> entries in buffer: 1
    19:58:11.260 -> ~~~ Saved in /logfile.txt ~~~
    19:58:11.260 -> row #0 {1234567890}
    19:58:11.260 -> row #1 {1234567890}
    19:58:11.260 -> row #2 {12345678⸮⸮⸮1234567890}
    19:58:11.260 -> ~~~ EOF ~~~

Explanation: Now here is the unsolved error- 4th entry gets mixed up with 3rd, causing it to count only 2 entries (where it had to be 3), and row #2 is now mixed.

In purpose - I simplified the code to focus on the problem itself, which I can't find it root cause for this error (rather that showing entire library , consisting delayed save and delete line function, when log gets full).

`

    #include <FS.h>
    unsigned long T = 1234567890;

    char *_logfilename = "/logfile.txt";
    int _buff_i = 0;
    #define TEMP_LOG_SIZE 10
    #define TEMP_LOG_LEN 150
    int _logSize = TEMP_LOG_SIZE;                 // entries
    int _logLength = TEMP_LOG_LEN;                // chars in each entry
    char _logBuffer[TEMP_LOG_SIZE][TEMP_LOG_LEN]; // Temp buffer for delayed write
    const char _EOL = '\r';
    unsigned long lastUpdate = 0;

    void insert_log_entry()
    {
      char a[25];
      sprintf(a, "%d", T);
      write(a, true);
    }
    void rawPrintfile()
    {
      int row_counter = 0;
      bool new_line = true;

      File file = SPIFFS.open(_logfilename, "r");
      if (!file)
      {

        Serial.println("Failed to open file for reading");
      }
      Serial.print("~~~ Saved in ");
      Serial.print(_logfilename);
      Serial.println(" ~~~");
      while (file.available())
      {
        if (new_line)
        {
          Serial.print("row #");
          Serial.print(row_counter++);
          Serial.print(" {");
          new_line = false;
        }
        char tt = file.read();
        if (tt == _EOL)
        {
          new_line = true;
          Serial.println("}");
        }
        else
        {
          Serial.print(tt);
        }
      }
      file.close();
      Serial.println("~~~ EOF ~~~");
    }
    int getnumlines()
    {
      int row_counter = 0;

      File file = SPIFFS.open(_logfilename, "r");
      if (file)
      {
        while (file.available())
        {
          char tt = file.read();
          if (tt == _EOL)
          {
            row_counter++;
          }
        }
      }
      file.close();
      return row_counter;
    }
    void write(const char *message, bool NOW)
    {
      sprintf(_logBuffer[_buff_i], "%s%c", message, _EOL);

      Serial.print("add buffer #");
      Serial.print(_buff_i);
      Serial.print(": ");
      Serial.println(_logBuffer[_buff_i]);
      _buff_i++;
      lastUpdate = millis();

      if (NOW == true)
      {
        _write2file();
      }
    }
    void _write2file()
    {
      int num_lines = getnumlines();
      Serial.print("total Lines before: ");
      Serial.println(num_lines);
      Serial.print("entries in buffer: ");
      Serial.println(_buff_i);

      File file1 = SPIFFS.open(_logfilename, "a");
      if (!file1)
      {
        Serial.println("Failed to open file for appending");
      }
      else
      {
        for (int x = 0; x < _buff_i; x++)
        {
          file1.print(_logBuffer[x]);
        }
        _buff_i = 0;
        lastUpdate = 0;
      }
      file1.close();
    }

    void setup()
    {
      Serial.begin(115200);
      Serial.println("\n\nStart!");
      SPIFFS.begin();
      insert_log_entry();
      rawPrintfile();
    }

    void loop()
    {
      delay(50);
    }

title: Error saving SPIFFS on ESP8266 - only after 3rd entry

Answers: 1

body:
Well , getting to answer was complicated.

1) It happens only after reboot ( button, or `ESP.reset()` ), somehow after 2nd attempt, every time - getting this ( see `THIS`):

>     19:58:11.194 -> Start!
>     19:58:11.227 -> add buffer #0: 1234567890
>
>     19:58:11.227 -> total Lines before: 2
>     19:58:11.260 -> entries in buffer: 1
>     19:58:11.260 -> ~~~ Saved in /logfile.txt ~~~
>     19:58:11.260 -> row #0 {1234567890}
>     19:58:11.260 -> row #1 {1234567890}
>     19:58:11.260 -> row #2 {12345678⸮⸮⸮1234567890}   <----- THIS ----
>     19:58:11.260 -> ~~~ EOF ~~~

2) @Peter, in comments referred for [github issue][1] , that pointed out that there is a known problem regarding reboots and validity of data stored. Issue was solved by using `file.flush()` - but this solution **did not solve the problem**

3) When searching ESP8266 core, it pointed out an erros [SPIFFS][2]- regarding data saved and it validity

4) only after updating `LittleFS` for all instances in code (somehow when checked as part of Peter's suggestion, only few instances were changed from `SPIFFS` ), solved that problem. no `file.flush()` or `delay()` is required.

  [1]: https://github.com/esp8266/Arduino/issues/2853
  [2]: https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html?highlight=SPIFFS


body:
I wonder if someone could help me with figuring out how to control XL6009 Boost converter via Arduino. I have [this][1] popular board, and it has potentiometer to adjust the output voltage. However, I want to adjust output voltage based on sensor reading so I need to do it "non-mechanically".

I tried with PWM voltage to the resistor network, but I didn't get wanted results. Any ideas (except digipot)?

Best regards

  [1]: https://www.amazon.com/HiLetgo-Adjustable-DC3-0-30V-DC5-35V-Converter/dp/B00LP2LZ4M

title: Control output of XL6009 Boost converter with Arduino

Answers: 0


body:
Before starting working, I am just researching around how can I achieve OTA over MQTT in ESP32 in using Arduino IDE.
The process I understand the esp listen to MQTT messages and then received that file over MQTT(not fully at once may be in chunks). And then stored that in flash at specific address. And then change boot loader configuration for executing new firmware.

Here I am confused how can I change boot loader configuration settings to execute the new firmware memory address ??
Any help is appreciated.

is there any out of box library available for this work? Please share reference. I can take reference from there.

Thanks

title: OTA over MQTT for ESP32

Answers: 1

body:
I am not familiar with OTA for ESP32 but with SAMD21 using [ArduinoOTA library][1] and there the download is not done over MQTT but HTTPS.

Link to download is sent over MQTT but that's where it ends, download over HTTPS, verification of received data using checksum and bytes count and once InternalStorage.apply() executed it swaps the program downloaded with the older version and reboot.

**EDIT:**

As per Juraj request, I am adding the code as a guide you can use to get ideas. You can't run it as is, you would need to add variable declaration and wrap it in a function.

As updating wrong file will most likely brick your board, I would just add that before running this code I check the filename to make sure it is the correct BIN for the board downloading it, I am using constants like WIFI, GSM, and board name and expect to see them in the filename.

I also send the file length from the server as part of the MQTT update request and check it against my own bytes count and I am not relying on TCP to provide an error on corrupted data and do a my own checksum test.

    #include <ArduinoOTA.h>  // https://github.com/jandrassy/ArduinoOTA

    // Access the file
    HttpClient client(*transport, upgradeServer, upgradePort);
    client.get(upgradePath);

    int statusCode = client.responseStatusCode();
      /*
       0   HTTP_SUCCESS
      -1  HTTP_ERROR_CONNECTION_FAILED  The end of the headers has been reached.  This consumes the '\n' Could not connect to the server
      -2  HTTP_ERROR_API                This call was made when the HttpClient class wasn't expecting it to be called.
                                        Usually indicates your code is using the class incorrectly
      -3  HTTP_ERROR_TIMED_OUT          Spent too long waiting for a reply
      -4  HTTP_ERROR_INVALID_RESPONSE   The response from the server is invalid, is it definitely an HTTP server?
      */

    if (statusCode != 200) {
      client.stop();
      // here you can do something with statusCode like notifying over MQTT
    }

    long length = client.contentLength();
    if (length == HttpClient::kNoContentLengthHeader) {
      client.stop();
      //Server didn't provide Content-length header, abort.
      return;
    }

    if (!InternalStorage.open(length)) {
      client.stop();
      // Not enough space to store the file, abort.
      return;
    }

    // Start update, length holds the file size in bytes

    client.setTimeout(5000);
    byte b;
    bool ok;
    long fileLength = length;
    unsigned long otaStartMillis = millis();
    int localChecksum = 0;

    while (length > 0) {

      ok = client.readBytes(&b, 1);
      if (!ok) {
       // Abort, stopped after ((millis() - otaStartMillis)/1000) Sec
        return;
      }

      InternalStorage.write(b);
      int bValue = (int)b;
      localChecksum = localChecksum + bValue;

      length--;
    }

    InternalStorage.close();
    client.stop();

    if (localChecksum != remoteCkecksum) {
     // Checksum mismatch, abort.
      return;
    }

    if (length > 0) {
      // Timeout at byte length, abort.
      return;
    }

    InternalStorage.apply(); // this doesn't return, board should restart

    Serial.println("Update failed"); //shown only if update failed

Another opportunity to thank Jurak for this library!

  [1]: https://github.com/jandrassy/ArduinoOTA


body:
I am in a situation close to:
https://arduino.stackexchange.com/questions/14243/hi-speed-external-adc

But with 100,000 ~ 500,000 samples per second, I don't need more.

I only want to detect changes in 2 sensors, so each loop is only an "analogread" and a couple of conditionals, so I have the 16MHz almost intact to store data from an external ADC.

What is the fastest thing you can aspire to with an arduino and an external ADC?

title: Fastest external High Speed ADC?

Answers: 0


body:
Hi (Sorry for the long post).
The other day I finally found a code that worked on my standard 2.8" TFT LCD by Simkeim, but then I pressed the bottom left corner too hard and the screen went white. The code is a calculator code and it worked because the screen showed the numbers and the screen saver, but when I pressed the screen nothing happened. After the screen went white, I "opened" it and saw no damage to the screen. I have tried a bunch of example sketches and now the touch functions work, but nothing is displayed on the screen. The LCD does not have any wires, it just plugs in the board. When I upload a sketch, the backlight changes brightness a bit, and there is a slight line on the left side of the screen, when the code uses dark colors, I can press two parts of the screen and the screen goes dark (except for a small part of the left side).

Could the screen be damaged by pressure?

This is what the LCD looks like:

![LCD Screen Module](https://lh3.googleusercontent.com/proxy/cf7NsNHkpP5PpROraBhgiHMchAe7BjDPhCXzNSWKvOcmhSz-D2tn2da7zKtTIbzioazb8D4Zz6wF7BAyn9hfr7QuYLU2lB_suU60sX6Y2KUiuck0-5SiaWEs0u_DOntu7xs)

![](https://s2.bukalapak.com/img/24439445462/s-250-250/data.jpeg)

title: 2.4" TFT LCD is only showing white screen, but the touch functions still work

Answers: 0


body:
I am using Arduino MKR1500 with adafruit 1.3 inch display(https://www.adafruit.com/product/4313) and I want to rotate the font on the screen by 90 degree. I tried setRotation() and added an angle in the brackets. but that did not help.

Can someone please let me know what command do I need to use to do that?

title: Adafruit TFT 1.3 inch display with arduino-rotate the font

Answers: 0


body:
I have tried debugging for a couple days with no luck, so this question is a cry for help.

I am trying to configure an external ADC ([MCP3464 datasheet][1]). The ADC uses SPI communication and I am getting a response from it when I set the delay to 1000ms. If I lower this below 100ms, the ADC does not update and prints the last value stored in the ADC register.

Here is the relevant part of the code, although I have attached the whole file in case you would like to check command bytes etc.

    void adcSimple(){

        unsigned char convStatus;
        uint16_t adcData;
        // chip Select pin LOW to read/write to ADC
        digitalWrite(adcChipSelectPin,LOW);
        convStatus = SPI.transfer(readConversionData);
        // extracts remaing bytes and append to adcData 16 bit integer (15bits plus sign)
        adcData = SPI.transfer(0);
        adcData <<= 8;
        adcData |= SPI.transfer(0);
        // chip select pin hgih to stop read/write to ADC
        digitalWrite(adcChipSelectPin, HIGH);

        // start next conversion
        writeData(&startConversionFastCmd, 1);

        Serial.println(adcData);
    }

    void setup(){
      Serial.begin(115200);
      while (! Serial);
      spiInit();
      adcInit();
      // set ADC Multiplexer to channel 0
      writeData(&muxRegisters[0][0], 2);
      delay(1000);
    }

    void loop(){
      adcSimple();
      delay(1000);
    }

The adcSimple() function reads the ADC register address and appends it to the 16 bit adcData variable.

    writeData(&startConversionFastCmd, 1);

The line above then restarts the ADC conversion (not the whole device) which is required to update the ADC register. For some reason this does not update the ADC register when there is insufficient delay in the loop.

      // Check the data ready bit
      if ((convStatus & 0x04) == 0x04)
      {
         Serial.println("ADC not ready!!!");

      }

I have run a test on convStatus, and this shows the ADC is not ready when the delay is short (around 100ms). I just don't understand why it takes so long (1000ms is equivalent to light years when running on 6MHz clock!)

Any suggestions would be greatly appreciated. Maybe someone has had a similar problem before?
Thanks,
Will

  [1]: https://www.mouser.co.uk/datasheet/2/268/20006180C_MCP3461_2_4_Two_Four_Eight_Channel_LowNo-2297874.pdf

title: ADC stops working at small delays (MCP3464)

Answers: 0


body:
My Arduino Nano Every runs at 16Mhz (but the 4809 can support internal 20Mhz).
I know it may be possible to alter the boards.txt file and set it to build for 20Mhz.
However, I can't find the boards.txt for these new boards (MegaAVR).
Where is the boards.txt located?

title: Where is the Arduino IDE boards.txt file for Nano Every located?

Answers: 2

body:
I found the boards.txt file at: `~/.arduino15/packages/arduino/hardware/megaavr/1.8.7`

The Nano Every portion of the [boards.txt][1] looks like the following:

    ##############################################################

    nona4809.name=Arduino Nano Every

    nona4809.vid.0=0x2341
    nona4809.pid.0=0x0058

    nona4809.upload.tool=avrdude
    nona4809.upload.protocol=jtag2updi
    nona4809.upload.maximum_size=49152
    nona4809.upload.maximum_data_size=6144
    nona4809.upload.speed=115200
    nona4809.upload.use_1200bps_touch=true
    nona4809.upload.extra_params=-P{serial.port}

    nona4809.build.mcu=atmega4809
    nona4809.build.f_cpu=16000000L
    nona4809.build.board=AVR_NANO_EVERY
    nona4809.build.core=arduino
    nona4809.build.variant=nona4809
    nona4809.build.text_section_start=.text=0x0
    nona4809.build.extra_flags={build.328emulation} -DMILLIS_USE_TIMERB3 -DNO_EXTERNAL_I2C_PULLUP
    #nona4809.build.extra_flags=-B{runtime.tools.atpack.path}/gcc/dev/{build.mcu}

    nona4809.bootloader.tool=avrdude
    nona4809.bootloader.file=atmega4809_uart_bl.hex
    nona4809.bootloader.SYSCFG0=0xC9
    nona4809.bootloader.BOOTEND=0x00
    nona4809.bootloader.OSCCFG=0x01
    nona4809.fuses.file=fuses_4809.bin

    menu.mode=Registers emulation
    nona4809.menu.mode.on=ATMEGA328
    nona4809.menu.mode.on.build.328emulation=-DAVR_NANO_4809_328MODE
    nona4809.menu.mode.off=None (ATMEGA4809)
    nona4809.menu.mode.off.build.328emulation=

    ##############################################################

If you change the following line from:

    nona4809.build.f_cpu=16000000L

to:

    nona4809.build.f_cpu=20000000L

Then go in and turn on verbose when you build in the Arduino IDE you will see that avrdude will pass in the following when it builds your sketch:

    DF_CPU=20000000L

Will this push the CPU to 20Mhz?  Not sure, but at least you know where this is now.

**UPDATE**

**FYI** - Do not set your board to 20Mhz.  Especially if you have Serial Communication going on.  I have software serial set up to communicate with an attached bluetooth device and when you set the CPU to 20Mhz other things are not set properly and the Serial communication fails.

  [1]: https://github.com/arduino/ArduinoCore-megaavr/blob/master/boards.txt

body:
In addition to set the

    nona4809.build.f_cpu=20000000L

you will have to set the corresponding fuse byte to

    nona4809.bootloader.OSCCFG=0x02

this enables the 20 MHz clock.