text:
arduino nano with lora only runs once if connected to battery
this code works perfectly if connected with usb cable. but as soon as i connect my Arduino nano with battery (two 18650 batteries in series connected to VIN) it runs loop only once. it sends only 0 to another LoRa module (3.3v) and i assume it runs loop only once. blink works without a problem.
#include <SPI.h>
#include <LoRa.h>

int counter = 0;

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

  Serial.println("LoRa Sender");

  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
}

void loop() {
  Serial.print("Sending packet: ");
  Serial.println(counter);

  // send packet
  LoRa.beginPacket();
  LoRa.print(counter);
  LoRa.endPacket();
  counter ++;
  delay(3000);
}

Edit
battery pack voltage is 7.01v.
connections I've tried so far:

2x 18650 -> VIN = Does not work
2x 18650 + regulator -> 5v = Does not work
2x 18650 + regulator -> USB = Does work
USB -> USB = Of course works

when I say it works I mean it Arduino powers up and LoRa module sends data but only once and looks like loop is running only once.

it works if i connect usb cable with a power bank. but wont work if i power with regulated 5v on 5v pin

voltage on vin pin is 7.01v

A diagram of how you have all this wired together may be relevant.

are you powering the lora with the nano's 5v pin? iirc, Vin goes through an LDO, USB is fed directly.

no. i'm powering lora from 3v3 as vcc for lora is not 5v tolerant

If you measure the "5V" pin does the measured value read appear to be lower in the working scenarios and higher in the failing scenarios?

@timemage when in working condition 5v output reads 4.48 but when using regulator and its failing 5v pin is constantly at 5.05v

What exact Lora module do you have?

Again, it would be nice to looking at how you have it set up.  You didn't mention any proper signal level conversion, so I'm going to assume there isn't any.  My best guess is one of the signals being produced by the Lora module is near the edge of being correct on the ATMega328P.
In comments I asked:

If you measure the "5V" pin does the measured value read appear to be
lower in the working scenarios and higher in the failing scenarios?

The reason for the question is that the logic levels of the ATmega328P are dependent on its VCC, what we're nominally calling "5V".

when in working condition 5v output reads 4.48 but when using
regulator and its failing 5v pin is constantly at 5.05v

By operating the 328P closer to 3.3V (when you're at 4.48), you're lowering the threshold voltage needed for the Lora's signals to reliably register as a HIGH on the Nano's pins.
You will likely need proper level conversion between the Nano and Lora module, but that will depend on the exact module.  Keep in mind that if your module says it has "5V tolerant" data pins, that doesn't mean it produces logic levels acceptable to a 5V Arduino Nano; it just means the module will accept 5V signals at its own inputs.

shouldn't according to datasheet, read ATmega328p operating at 5V everything above 3 V as HIGH?

In a roundabout way it does say that. I assume you're talking about the 0.6 * VCC for VIH low spec. I'm aware of that. I can't tell if you genuinely think this is relevant and not understood or you're just screwing with me. On the assumption that you're running at exactly 5V and you have a VIN(min) of 3V, you are still talking to a 3.3V device, nominal, which may not even be operated at exactly 3.3V. Taking the RFM95W as an example, VOH(min) is 0.9 * VCC, or 2.96V at 3.3V VCC.  Even if the figure were slightly above 3V, they are still operating with no margin to speak of.

yes it is possible


text:
DFPlayer Mini does not boot reliably after being powered down
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?

please add a schematic diagram of the circuit

I added two diagrams, are these ok?

On the breadboard, the top blue rail doesn't have a connection to the bottom blue rail. In the schematic, the GND pin on the DFPLAYER MINI is not connected to anything.

Well, there's no direct connection between the top and bottom blue rails as the point of the MOSFET is to disconnect them if it is switched off. They are connected to the MOSFET on its drain and source terminals, respectively. So this is intended. The DFPlayer Mini's pin 10 (GND) isn't connected to anything, but the same GND (pin 7) is actually connected to the top blue rail. I could connect pin 7 and 10, but it doesn't make any difference, since they are already connected internally.

It would be better to have a high-side MOSFET switch to control the power to the DFPLAYER and connect both GNDs to ground.

Unfortunately, I only have two logic-level MOSFET types available: IRLZ44N (the one I used so far) and IRL540N, both are N-channel enhancement mode MOSFETs. As written in the question, the first run does work completely fine, so the power setup seems to work (power is off initially!). The problem arises only after I power down the DFPlayer and power it up again. It actually does power up again, but communication doesn't seem to work properly, as I get these timeout errors. Hence, I actually assume this is rather a software issue due to turning the serial communication off and on again.

Try using a mechanical switch or wire link in place of a high-side MOSFET switch to see if you can depower and repower the DFPLAYER and continue successfully with the programme.

Following your suggestion, I removed the MOSFET completely from the breadboard and instead bridged the top blue rail with the bottom one (so actually there's no switch involved anymore). I left the sketch as above. The same thing happens: The player works the first time after powering up / resetting the Arduino, then starting with the second iteration, the player fails to play the file each time.

More information: With the bridged rails, the setup does work, if I comment out the lines containing MP3serial.flush(); and MP3serial.end();. However, taking the  bridge away again and plugging the MOSFET back in, same issue: works in the first iteration then fails, but sometimes it starts the audio and then stops.

With the bridged rails and no MOSFET, what happens when you depower and repower the DFPLAYER via a high-side wire link during the 8 second sleep? Does it then work during the subsequent iteration?

I removed the MOSFET and added a bride, s.th. both the 5V and GND rails are connected via bridges. This works if I comment out the flush and end commands. Then, if I pull either the 5V or the GND bridge and plug it back in place, it works (It actually works regardless of whether I plug it back in time or not, which seriously confuses me). That being said, if I plug out the 5V bridge, the Arduino draws more than 3 mA in deep sleep (due to serial left on!?), but w/o the GND bridge it draws only ~0.1 mA. The latter is what I'm aiming for, as it shall run for a year on a 1900mAh battery.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Update the ESP to espduino via NodeMCU Flasher
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:

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:
{
Serial1.begin(115200);
}

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

MEGA32U4 side sketch:
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?

The Cactus Micro Rev2 board 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 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.

Let us continue this discussion in chat.

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:
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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Triple-click reset option to erase existing program
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.

Isn't the bootloader open-sourced? Did you look for it?

Which Arduino? Single click of what exactly?

@NickGammon Tripple-click reset in the title, strongly suggest clicking the reset button. Arduinos with USB firmware upload capability.

You still haven't answered "which Arduino?" Is it a secret? In any Arduino the reset button resets it, there is no such thing as double-clicking reset. And certainly not triple-click. Resetting invokes the reset circuitry which makes the processor go through its reset code, clearing all registers and starting the code from the start.

@NickGammon Not a secret. I'm using clones of Zero, but I'm looking for something applicable to more than just a single model. there is no such thing as double-clicking reset - bootloader on my board responds to double-click on reset button differently, perhaps by saving state in NV memory.

how should erasing the old sketch help? double reset is the way to put a 'bricked' Zero in bootloader mode and upload a sketch. it stays in that mode. it doesn't time out.

@Juraj it stays in that mode. it doesn't time out. Mine was timing out in a few seconds. I was using Adafruit Feather M0.

M0 is not Zero. M0 bootloader times out. you can replace the bootloader to Zero bootloader if you have a SWD programmer

I was using Adafruit Feather M0 - you could have mentioned that at the start.

Next time, put that information in the question. That's where it belongs.

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 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.

I like the idea of using an extra pin for that purpose. Double-click works most of the time, but you have to synchronize your keystrokes and reset.

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. 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.


text:
Is it possible to control android accessibility with arduino nano?
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.

Not with a nano, unless you write some app for Android that responds to serial data.


text:
Using Arduino Click shield with NDIR Click CO2
I am trying to use  (NDIR CO2 sensor Mikroelectronika) 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.
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.


text:
Wireless programming of Arduino
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?

I use ESP32 and the built in ArduinoOTA library to update over WiFi. It's so much more convenient than the Arduino boards.

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.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
How can I check if my thermostat is on?
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.

If there are 3 relays, and you know that the relays control the 3 'systems', then you could wire up your 8266 through the "NC" (not connected) pin then you know that when voltage goes through the NC pin the relay is not on

The easiest way probably is to connect to the 28V signal and measure it. 28V is not high enough to be dangerous to humans, but it is dangerous to your ESP8266, but it's very simple to decrease the voltage to a level where your ESP8266 can safely detect it.

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.

heh i guess opto couplers are the way to go if you don't already have a bunch of op amps.  +1 to that

I used them because of the electronics in the HVAC system is AC and needed to stay isolated from the rest of the world. Thanks Able

Thank you! I’ll try this.

You are welcome, let us know how it works out.

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).

Sending a high voltage input to an op-amp powered by a lower voltage isn't necessarily safe for the op-amp. You'd have to check the datasheet for the specific op-amp. Better to use a voltage divider to reduce the voltage.

remember to check specs regardless of what components.  if you are using a voltage divider- figure out acceptable current losses and the wattage requirements for your resistors.


text:
Drum game controller - Problem with Piezo inputs
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 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);

  }
}

@Juraj I can use both, but not at the same time.

they don't activate at the same time. they activate one after another. here is a video that shows it. https://imgur.com/a/a6quH5d

I think, from your description, that your problem is with your methodology and what you think your code can achieve. Code executes strictly sequentially. If you have simple "if this then that" constructs then yes, things will happen separately, no matter how close you think they are in time. It sounds like you need to introduce the concept of "time slices" and "events" into your design. If these two events happen both within this predefined period of time then activate both buttons.

An alternative is to separate out the pressing of the buttons from the releasing of the buttons. When the drum is struck press the button, and set a timer running (store a timestamp). When that timer expires (millis() - drum1Time >= 100, for example) then release the button. That way you can have one button being pressed, followed by a second button being pressed, and eventually both buttons being released.

For that it may be useful to encapsulate all the logic and variables for one drum in a class, then simply instantiate multiple instances with different parameters for each drum pad and joystick button.

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:
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:
Drum drum1(A0, 0);
Drum drum2(A1, 1);

Then in your loop simply:
void loop() {
    drum1.process();
    drum2.process();
}

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


text:
Why won't this work as a delay?
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,
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!

I really do not agree that this code is “simpler and cleaner”. The 1st solution is what you would call “spaghetti code” and does nothing more than “busy waiting” i.e. it will not allow you to do anything else while the delay is happening (just like a normal “delay()” would). The 2nd solution is also “busy waiting” but a bit cleaner code. The reason solutions like “blink without delay” exist, is because they allow your code to delay some things (for ex. turning on an LED in a specific rythm) while continuing with others (for ex. Checking for a button or handling I/O). Your code cannot do that.

TBH, you first solution looks ugly, both in terms of control flow logic and indentation. And as StarCat says, there is no difference between a busy waiting loop and using delay(). Your second solution does not work, mainly because Test1 is not changed in the loop. -- Anyway, there is no need to call digitalWrite() repeatedly with the same arguments.

Try to avoid the use of goto, it is said to be a bad practice

Fun fact: (Here in Greece [i don't know if anywhere else too]) we call goto as the "black sheep" of programming

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;
    }
  }
}

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.


text:
the buzzer stops sounding after a few seconds
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;

  }

There is no light or 2-second-interval in your code and it won't behave like you want at all. Please post a full minimal example so we have something to work with.

still fail does not describe what happens ... please edit your post with a description of observed behavior

If there is even one sensorValue > 25 it will stop beeping and is armed again for the next beep if it goes <= 25 -- you might want to average sensor values to protect against outliers. Did you put in some Serial.println() statements to see all sensorValue values that it processes?

You need to study https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay as that gives you a way to run two timer events simultaneously. One can blink your LED, the other can sound your buzzer for two seconds.

At least give us a circuitry showing what you're doing or what you want to do.


text:
Interrupt takes longer than expected
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.
#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.

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:
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.

Sorry for the maybe trivial question but I always thought that PIND=1 loads the bit 0b00000001 to register PIND , why does it toggle?

That's just how the AVR GPIO registers are designed.  It allows for a single write to flip a bit rather than doing a set of read, modify, and write instructions.  PIND's naming in in the spirit of reading from the port.

Is this true for every GPIO register?

I think yes, if I understand what you're asking.  For the other GPIO ports on the ATMege328P, writng a  1 in a PINx bit index causes the bit at that same index to toggle in the associated PORTx register.  Many (not all) other AVR parts follow this same scheme for their ports.

See Page 60 in the ATMega328P datasheet.


text:
Multi turn potentiometer are a pain should I use a incremental encoder instead?
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?

Please show your circuitry. Any potentiometer can be operated in a way that it does not burn, you might have an error here. However, the number of revolutions is limited. -- No, an incremental encoder does not remember its value, aside the current quadrant. That's why it's called "incremental". You might want to save the current value in EEPROM, time after time or at power loss. The latter needs some prerequisites. -- There are "absolute rotational sensors", at least I was involved in the development of one more than 20 years ago. However, they are expensive.

I kind of thought about it so I also ordered a sd card module to store the values and retrieving on resets. At first I thought about saving the values in EEPROm of the arduino but I figured out it has 100,000 write/read cycles

@Juraj the reason why I need to remember the position is because I do no want my system resetting every time the power takes a turn. And continue where it left.
Thats just a technique to make a dependable system.
I know about limiting switches and in a device which has 6 degree of freedom its kind of a pain to use them.

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).

I kind of thought about it so I also ordered a sd card module to store the values and retrieving on resets.
At first I thought about saving the values in EEPROm of the arduino but I figured out it has 100,000 write/read cycles.


text:
How does while(analogRead(A0)) function in this code?
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 ^_^.
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;
}

print the value of analogRead(A0) ... that will tell you when it exits the while loop

Can you fix the indentation of the code?

Re "A sine wave is being fed to A0": What is its amplitude and DC offset? What is the output impedance of the signal generator (what kind of signal generator is it)? How is it coupled? AC coupled?

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.

I think I get this now, this line just works as some sort of delay. Without while(analogRead(A0)), just after the first threshold is crossed (say val is now 202), state becomes +1 and the program loops to "val=analogRead(A0)" again. The val is now 210, so state will get incremented again.........and until state>5, val probably reaches upto 250. This will certainly give the wrong time period. On the other hand while(analogRead(A0)) keeps looping until false (0), gives enough time for val to cross threshold and then become less than threshold, so that the crossing can be detected again. Thanks!

@Nawaz Not a delay, rather a “keep checking the value until it’s what I’m looking for”. It has nothing to do with time, but value.

Yes, but analogRead() may never return identical 0 (an offset of 20 mV would prevent it). Or only occasionally due to random noise. This is the equivalent to comparing floats with fixed values. Perhaps address that in your answer?

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

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.
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:
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:
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;
    }
}

Re "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.". Indeed. And perhaps add a more general statement about comparing for equality (with fixed values) for such ADC output (noise, rate of change of the input signal, etc.)?

@PeterMortensen: This is generally quite relevant. However, the reasons why one should normally not compare an ADC value for equality do not quite apply to the special case of comparing to zero.


text:
How do I connect my ESP32 cam to my old modem without using Wi-Fi?
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.

please draw a diagram of how you want everything connected ... right now, all we know is that the computer and modem are connected together by some type of cable

You want to connect the ESP32 to the "modem" over the modem's wireless, then the modem to the computer over an Ethernet cable? Then you need to configure the "modem" appropriately. We can't help you with that.

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.


text:
800l v1 Baud rate is not fixing at 115200, How fix it for 115200 for lifelong
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

From a quick scan of its AT command manual, 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.

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.


text:
How can I play sound on Arduino with an SD card?(I have a problem with the sound)
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");
  }
}

A) Please add a link to the shield. B) Have you tried using a sample sketch that comes with the library to ensure everything works as expected?

I bought the shield while we were living in China, so it is a Chinese website. https://i-item.jd.com/59763201006.html. Yes  I tried using a sample sketch, everything works, but the sound is just two long static sounds

When I change the name of the file, then the speaker does nothing, but when I use the real name of the file, the speaker makes squeaky sounds

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 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;.

Hi, thanks for the help! I did change it like you said, but it still makes that static sound... I also tried an example TMRpcm code, but my speaker still just makes a static sound? Do you think that could be related to the code or the file? Because I did try it with two other speakers and they did the same...

@RenierJr. I've looked again at the library and found, that you cannot freely choose the used pin. It has to be PWM capable and belong to the used Timer (defaults to Timer1). I added a paragraph about that in my answer

Thanks chrisl!! I did try the example code and it used pin 9, now it works, but there is a lot of static playing with the music. I will try to change the sampling rate to see if that works... Thanks again for the time you spent to help me!


text:
Read bytes from PROGMEM array
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 which lets me store much more data. So I write something along the lines of:
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:
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:

In the official documentation of PROGMEM, it states that you have to get the variables back into memory. However, none of the methods they provided worked for me.
In a similar question on ASE, both answer and comments state that nested arrays aren't supported, but my knowledge of C++ isn't good enough to understand the answer.

@Juraj It's downloadable through the IDE. It's called Gamer.h.

@Juraj In the "Arrays of strings" it tells me to do something like this: strcpy_P(buffer, (char *)pgm_read_word(&(frames[1])));   arduino.printImage(buffer);
However, it just tells me that 'buffer' was not declared in this scope

On the question you are referencing, 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():
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);
}

I tried your approach and it sadly still just displays arbitrary patterns. Do I need to do anything else except for inserting your printProgmemFrame-function and replacing the loop function?

@gurkensaas: In principle you need nothing else. I cannot test this, as I do not have the hardware. It works for me, however, with a mock of the arduino object.

The code compiles fine, it uploads fine, but the problems of the arbitrary patterns stay the same.

I think you are returning ramFrame which is allocated on the stack when you call printProgmemFrame. Try again adding static to the variable declaration:
static byte ramFrame[8];

@EugenioPace It generated another random pattern.

Shouldn't there be something extra in the declaration of printProgmemFrame()? Something like void printProgmemFrame(const byte flashFrame[8] PROGMEM)?

@PeterMortensen: Alas, no. Unlike the __flash keyword, which works like a type qualifier (like volatile or const), PROGMEM is really only a kludge to get the compiler allocate the variable in a specific program section. This works only when the variable is actually declared: it makes no sense for a pointer to be declared as “pointer to PROGMEM data”. It's a pity __flash is only supported in C mode (not in C++).


text:
What is the overhead of a saturated serial connection at 256k baud?
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?

A lot depends on your software. I have no information on the part you are using, can you post a link showing technical information not sales information.

@Gil the technical isn’t really relevant. Just treat it that everything sent by any Arduino hardware serial on the link is received by every other Arduino via hardware serial

@Gil as for the software. It doesn’t really matter. Let’s assume loop is just a busy loop doing simple mathematical operations and counting how many times it goes round the loop in 10 seconds.

@Simm Count the clock cycles used by the ISR in different situations (buffer usage percentage - empty, half full, overflow, etc). Calculate the number of clock cycles that would pass during one byte's transmission period. Do some math. There's your answer.

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);
        }
    }
}

code would tell us what the test really meant in greater detail than the note.  would also make the test results easier to repeat and verify


text:
Cannot enable watchdog timer when using Arduino 8mhz bootloader
I am running my Arduino projects like this:

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?

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.

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.


text:
Battery supply vs laptop supply
Setup:
I have wired up the arduino, motor and battery as shown.

(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)

Please no code as image. You can copy and paste the code as text into the question and format it as code by selecting it and clicking the {} button or pressing control+K

your battery does not last very long ... what does that tell you about the battery?

Does it tell me that the battery does not have enough current? I tried to test this out and I used a series of AA batteries which (although there were 6 of them) output only 7V due to their usage in the past. These batteries made my motor spin faster and for way longer than my 9V duracell battery.  So i think it might be because of current.

@Sanchez2009 that is correct ... the 9 V battery contains six AAAA cells, same as when you created a 9 V battery from six AA cells, but with very small capacity to provide current ... try using larger cells, like size C or D


text:
ESP32 SerialBluetooth disconnects within a second after connecting but not BLEDevice/BLEServer
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):
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

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

void loop() {
}

Minimal code with stable BT connection (from BLE_notify example):
#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.

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.


text:
Program ATTiny85 running at 16 KILOhertz
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.

I suggest you pick whichever core is your favourite and then open a github (or wherever it's hosted) issue to add the relevent clock speed settings.

@Majenko Thank you for the suggestion. I hope there is already one providing this clock speed and someone will point it out here, but if not I will do as you say.

For the ATTinyCore, you can change in the boards.txt setting for the variant you're using  (https://github.com/SpenceKonde/ATTinyCore/blob/master/avr/boards.txt#L409-L412). Modify f_cpu foremost. I don't know about clocksource = 3 though, look that up in the code. The boards.txt should locally be in C:\Users\<user>\AppData\Local\Arduino15\packages\ATTinyCore\hardware\avr\1.5.2

It should just be a matter of adjusting the boards.txt file for the core, but there may be some technical reason (calculations that fail) at that clock speed for why it's not implemented already.

@MaximilianGerhardt I modified the f_cpu and the low_fuses values to my values (16000L and 0x24) and it works ! Thank you ! I didn't modify the clocksource=3 as I don't know what it means.

https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

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
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 (+VSCode) instead of the Arduino IDE. A getting started page is here. 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.
[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

Thank you for all the informations ! A lot to read, a lot to learn, a lot to try ! :p


text:
Signal clipping in Arduino Serial Plotter
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:

Schematic:

LM358 is not rail-to-rail IO. You will never be able to get anything even close to 3.3V out of it.

So this is an opamp issue correct?? When 5V was supplied, clipping occurred at 600. Might have to change the opamp then, or decrease the gain of my signal??

Yep. Choose something that was designed sometime in the last 30 years.

The OPA342 or one of its derivatives might do what you want. You should read the data sheet to be sure it will do what you want.


text:
Programming ATMega4809 via Atmel-ICE with Hex File from Arduino IDE - why doesn't the code loop / work?
Background
I am programming a 40-pin ATMega4809 (datasheet)  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.

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

I've tried increasing the delay value to see if internal crystal is
set different and the timing is different or something.
I've set the internal crystal to different values (ranging from 1Mhz
to 20Mhz) and haven't seen any difference.
I've considered that it could just be not looping, so I've tried
various things to see if that were true or not.
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.
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.

for what board do you compile in Arduino IDE? why do you think pin 6 is PA6?

I was trying not to get to deep into the weeds, but I downloaded special boards from https://github.com/MCUdude/MegaCoreX These support the 4809.  Also, that's a good question about PA6.  I just noticed that when I used pin 7 (in IDE) I could turn on PA7 and when I used pin 6 I could turn on PA7.  But, you're right, I need to look closer at that.  Do you see something different somewhere?  If so let me know. thanks. Also, if I build the HEX for the Nano Every (which uses the 4809) it does not turn on PA6 / PA7 using 6, 7.

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:

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).

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 (youtube).


text:
Bug in code of Self-Balancing Bot
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);*/
}

It might be something with " Wire.read()<<8|Wire.read()". If you șhift a byte 8 bits you get 0. Read the Wire.read() to a long first.


text:
Run esp32 without freeRTOS in order to execute something faster
I am currently running Arduino with this configuration (using atmega328p chip):

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.

With your current Arduino setup, you're externally waking it up (applying power) every two seconds? Or are you having a sketch that delays for two seconds?

The above picture doesn't seem to be related to your question at all. It's just the basic schema how to wire up an AtMega chip.

You could run the 328p at 8 MHz and with 2 AA batteries as well. The Arduino-Core for an ESP32 is based on freeRTOS.  Your question is OT in Arduino.SE

I have a watchdog timer to wake up every 2 seconds @PMF.

If you have a 32, why not use the ULP to make those decisions without even waking up? Then your battery will likely last a lot longer than a year.

What I am looking for is "Deep Sleep Wake Stubs"
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.


text:
False interrupt triggering Arduino Mega
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

volatile is necessary to be sure changes made are observable between the ISR and non-ISR contexts.  That said, it doesn't seem like it would completely account for what you're seeing.  You should make them volatile an let us know what the behaviour in that case is though.

why do you believe that it is a programming problem?

@timemage, changing to volatile is not helping.

In that case, it's probably a good idea to just make the variables volatile in your code  and remove the part where ask about doing that, to remove the distraction from the primary question.

This has nothing to do with your question as such, but your Serial stream concatenates things for you as a matter of course.  All of your assignments and appends to String a are an inefficient and bug-prone alternative to a series of print/println calls.

You have the right idea to atomically obtain a copy of the data that is updated by the interrupt:
  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:
  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.

Thanks Tim , from oscilloscope I understood its an issue of INPUT_PULLUP, I will do external PULLUPs.

used 1K resistor and its working. Is there any issue with using external pull-up  along with INPUT_PULLUP.?


text:
Serial to USD (HID keyboard device) converter
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 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. I am using the board's native USB port to connect to the barcode scanner. The USBHost library 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.

you could use a scanner which has SPI or Serial interface and let the USB free for keypad emulation

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

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 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
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.

Thank you so much for your response. I will try with Attiny85 and 32U4 Micro boards and see how it goes. Unfortunately, i have to work with USB barcode scanners and I am using the arduino board's native USB to get the data from the barcode scanner.

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.