text:
Modify duty cycle of tone on AVR
I'm writing a MIDI - to square wave converter designed to interface between a MIDI instrument and a musical Tesla coil. Essentially, this should act like a monophonic MIDI synthesiser, but the requirements are slightly different to most projects:

I only want to generate (audible frequency) square waves.
It is essential that the pulse on time not exceed a configurable constant value, e.g. 160 microseconds.
I'd like to map the 'velocity' of a given note to the duty cycle, scaled appropriately.
Ideally, I'd like to generate envelopes for the pulse width with configurable attack, decay, sustain, release parameters.
I'd like to write the audio generation code "from scratch" for the sake of my own understanding of how timing registers work.

The gist of what I want is this (untested) sketch, but it obviously doesn't allow for control of the on time.
#include <MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();
const static int out_pin = 9;

void handleNoteOn(byte channel, byte pitch, byte velocity)
{
    tone(out_pin, pitch);
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
}

void handleNoteOff(byte channel, byte pitch, byte velocity)
{
    noTone(out_pin);
    digitalWrite(13, LOW);   // turn the LED off
}

void setup() {
  MIDI.setHandleNoteOn(handleNoteOn);
  MIDI.setHandleNoteOff(handleNoteOff);

  MIDI.begin(MIDI_CHANNEL_OMNI);
}

void loop() {
  // put your main code here, to run repeatedly:
  MIDI.read();
}

My question is essentially, what the best way to achieve this kind of musical pulse-width control is. The ideas I had were either
a) A large number of manual register-sets to bit-bang the required signal out at the highest frequency I can get, probably in the kHz
b) Create each pulse using a custom pulseOut function, using timer0 for microsecond delays
I'd also be open to using external analog circuitry, e.g. a voltage controlled pulse shortener.
The load here is an LED, so no special allowances need to be made for its behavior.

What Arduino board are you using?

did you see the arduino-toneac library?

An Arduino nano.
I didn't see the toneaclibrary - though not exactly capable of what I need out of the box, it's very helpful to read!

I would recommend using a hardware PWM signal generated by Timer 1, or
another 16-bit timer if you have more than one (like on the Mega). The
16 bits provide both a decent frequency range and a good time
resolution. This should provide jitter-free timings, unlike any
software-based method. This will also avoid unduly loading the CPU.
The first thing to do would be to choose the prescaler and the operating
mode. These choices will impact both the lowest available frequency and
the time resolution. The latter affects the accuracy of the
highest-pitched notes. Assuming your Arduino is clocked at 16 MHz,
some sensible choices are:

prescaler = 64, normal PWM
prescaler = 8, phase correct PWM
prescaler = 8, normal PWM

prescaler
PWM mode
time resolution
lowest freq.
lowest note

64
normal
4 µs
3.81 Hz
C−1 (MIDI 0)

8
phase correct
1 µs
15.26 Hz
B0 (MIDI 11)

8
normal
0.5 µs
30.52 Hz
B1 (MIDI 23)

For the sake of having accurate notes, I would go for the lowest time
resolution that is compatible with the music you want to play.
Once this is configured, you can control the music by writing to three
registers:

TCCR1A turns the PWM on and off
the register holding TOP (OCR1A or ICR1, depending on the mode)
controls the frequency (the pitch)
a compare match register (OCR1A or OCR1B, depending on the channel)
controls the duration of the pulses

Your program would then need to set the frequency as a function of the
requested note, then continuously adjust the pulse duration in order to
create the desired envelope while obeying the requested velocity and
ensuring the value of 160 µs is never exceeded.
The main code does not even need to be synchronized with the timer: the
PWM modes guarantee glitch-free PWM even when you change the duty cycle.
Be careful though when changing the frequency: you may get huge glitches
when increasing the frequency. It is safer to stop, clear and restart
the timer when changing notes.


text:
Grove - Mech Keycap counter
I am using Grove - Mech Keycap as a counter but if I continue pressing the keycap the counter continues to run. Any idea how to program it to increase counter by one only after releasing and pressing again?
#define BUTTON_PIN   8

bool oldState = LOW;
long timecheck;
int i = 1;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop()
{

  // Get current button state.
  bool newState = digitalRead(BUTTON_PIN);

  // Check if state changed from low to high (button press).
  if (newState == HIGH && oldState == LOW) {
    timecheck = millis();
    // Short delay to debounce button.
    delay(200);
    // Check if button is still low after debounce.
    newState = digitalRead(BUTTON_PIN);

    if (newState == HIGH) {
      Serial.println("HIGH");
      Serial.println(i);
      i = i + 1;
    }
  }
}

use the Bounce2 library (or set oldState )

You never change oldState...?

how & to what shell I change the oldState?

when you determine that the state changed ... how else would you remember the state of the system?

Change oldstate to equal newstate when oldstate and newstate differ. That way you can know when oldstate and newstate differ....

source: Stack Exchange

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

sort: votes


text:
How to distinguish identical Arduinos from Linux?
I have two identical (but with different software) Arduinos connected to Linux box. Their serals are identical
# udevadm info -a -n /dev/ttyUSB1 | grep '{serial}'
    ATTRS{serial}=="0000:00:1d.0"

# udevadm info -a -n /dev/ttyUSB0 | grep '{serial}'
    ATTRS{serial}=="0000:00:1d.0"

Can I make these Arduinos to differ somehow programmatically?

What Arduinos do you have?

request some info over Serial

If you want the same firmware for both Arduinos, you could make a simple hardware solution: use a jumper and connect and input pin to select a 0V or 5V value as input.

You can't change the USB information programmatically. The fact that you're referencing /dev/ttyUSB* means you have hardware USB interface chips (CH340, PL2302, FT232, etc) which you can't change from your sketch (some can be adjusted using tools provided by the chip manufacturer though, so you may be able to tweak it using that).
Instead your only option is to have some kind of "fingerprint" that software on your computer can request from your firmware. If you stick to a common serial protocol for all your firmwares you can implement a standard "Firmware Version" command which will respond with what code and version you have installed.
It's up to you to decide how best to implement such a system, of course.

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


text:
arduino 28BYJ-48 stepper only whining, not rotating
Edit, this question has been answered in the comments by chrisl, and also after retesting the code with delay() which showed I forgot to update my lastupdate variable(eerst), I have answered it in the comments and chrisl possibly also will post their findings in a answer
TLDR- 28BYJ-48 unipolar 5v not working only whining. run using transistors and code in the bottom of the post. transistors connected to 5V and resistors ranging from 100ohm to 1000ohm tried from Arduino to the transistors Trigger/Gate. - END TLDR
More Detailed
I have some 5v and 12v 28BYJ-48 unipolar stepper motors,(I only connect one to the Arduino at a time) the common(tested with resistance meter) is connected to +, and I the other pins are connected to one BC336 transistor per pin so 4 in total. these transistors should handle 0.8A a piece and I measured the maximum amperage used by the coils to be 0.2+-0.02A for the 5v version at 5v, and 0.045 +- 0.001A for the 12v version at 5v. it makes sense if the 12v version doesn't work at 5v, I just wanted to test it to have an ultra-low-power stepper motor. however the 5v version should work, My setup allows a higher voltage drop in the coils in the motor and can handle a higher amperage than a normal driver however this is limited by the motors resistance ofcource.
I drive it according to the steps in the datasheet with the standard method. and simplified my code to leave out all extra things and even hardcoding the values but still it only whiles and doesn't run the motor. I use the Arduino 5v to run the stepper motor but according to the datasheet and my measurements, you could drive more than one stepper motor on the 5v pin, even when running from USB power. I also set it really slow so that it should work(based on datasheet). I want to get this working like this because I am working on a custom budget stepper driver for Arduino which allows much simpler control, and which is much cheaper than the current drivers as well as that it by default can run higher voltage stepper motors as well, and one very specific functionality which almost everyone who has ever used one stepper motor or more has hoped that their stepper motor driver had.
I used pin 8 9 10 and 11
Broken Code:
unsigned long eerst=0;
unsigned long nu=0;
int state=0;
byte vals[8]={0b00000001,0b00000011,0b00000010,0b00000110,0b00000100,0b00001100,0b00001000,0b00001001};//made hardcoderd aray to make sure fault wasn't in the cyclic bitshifting

void setup() {
  //0b76543210 portD <-- direction right is low num left is high num, keep confusing this since it differs on some platforms and not having used arduino for a while
  DDRB=DDRB | 0b00001111;//only set 8,9,10, 11 as output do not change resst.
  PORTB=0b00000000;//simplified from only turning of 8,9,10,11 to turning of all of portb
  delay(1000);
  eerst=millis();
}

void loop()
{
  nu=millis();
  if(nu-20>=eerst)
  {

//forgot to update here
PORTB=vals[state];
state++;
if(state>7)//resets state
{
state=0;
}
}
}
Working Code (might be changed for the long overflow stabilizing), changed variable names to make it clearer for others to read:
unsigned long TimeOfLastStep=0;
unsigned long CurrentTime=0;
int step=0;
byte vals[8]={0b00000001,0b00000011,0b00000010,0b00000110,0b00000100,0b00001100,0b00001000,0b00001001};//made hardcoderd aray to make sure fault wasn't in the cyclic bitshifting

void setup() {
  DDRB=DDRB | 0b00001111;//only set 8,9,10, 11 as output do not change resst.
  PORTB=0b00000000;
  CurrentTime=millis();
}

void loop()
{
  CurrentTime=millis();
  if(CurrentTime-2>=TimeOfLastStep)//increased speed from 20ms delay to 2 ms
  {
    TimeOfLastStep=CurrentTime;//forgot this
    PORTB=vals[state];
    state++;
    if(state>7)//resets state
      {
        state=0;
      }
  }
}

I guess eerst should be the timestamp variable. You need to set this inside the if statement. Currently you are running as fast as the Arduino can, probably too fast for the motor. Also you should handle the if statement line in the BlinkWithoutDelay example if(nu - eerst >= 20). Then inside the if statement do eerst += 20;. Please test this. I will write an answer if that solves it

yes you are right, not long after posting it I saw the problem as well, and my timings were of since I assumed 100 steps per rotation, so a movement would be very slow if it did something. So I know now what I failed, it was one of those typical cases where you think something and think of typing it but then forget you didn't actually type it yet.

@chrisl You mean to edit it directly in the if statement just like you do in a for loop?
or do you mean that thing about the order of how to put the variables for non blocking code to prevent the code from hanging or misbehaving/skipping when the unsigned long flips(passed it's maximum value). if so, then that would be very helpful and why/what value order to use it for infinite amounts without needing a restart to prevent possible problems.

@chrisl the thing you mean in the second thing is  if(nu-eerst>=2), instead of if(nu-2>=eerst). right? I checked it with some mathematics and my precious code indeed was not rollover proof(weird behavior when you go beyond the max value of a unsigned variable and get back to the lowest one.

I found the problem(s) in my design, everything was right but I forgot to add eerst=nu;(first=now;, used a different language because now is used by the arduino ide).
Also I didn't read the datasheet properly and so assume 100step/revolution causing me to use delays which where to large, and so even if it worked the movement would be super slow and possibly missed.
New working code:
unsigned long eerst=0;
unsigned long nu=0;
int state=0;
byte vals[8]={0b00000001,0b00000011,0b00000010,0b00000110,0b00000100,0b00001100,0b00001000,0b00001001};//made hardcoderd aray to make sure fault wasn't in the cyclic bitshifting.
//in PortB you have the pins 8,9,10,11,12,13. you start at the back of the byte, so if 0b00000001 then only pin 8 is on. if 0b00000010, then only pin 9 is on, if 0b00000011 then pin 8 and 9 are on. PortB has 8 bits, but only 6 settable pins, so do not change the first 2 bits. you can do it more secure this should be done when using port D since that one is connected to serial. however for simplicity I did not add that code here, you can ask for it and I will probably respond with it.

void setup() { since it differs on some platforms and not having used arduino for a while
  DDRB=DDRB | 0b00001111;//only set 8,9,10, 11 as output do not change resst.
  PORTB=0b00000000; // disabling all port B outputs
  eerst=millis();//eerstm means first, set first to milis to have delay without pausing the code.
}

void loop()
{
  nu=millis();//nu is now, store this lets the code know for how long the arduino ran in milliseconds, needed for non blocking delay, only one now/nu is needed.
  if(nu-2>=eerst)// if 2 milliseconds have passed(have been waited), execute the following code.
  {
    eerst=nu;//reset the non blocking delay timer
    PORTB=vals[state];//Hardcoded values in the array above, this turns on and off pins and is much faster than digital write, selects item at number [state] of aray.
    state++;//go to next state/step
    if(state>7)//resets state
      {
        state=0;//resets state/back to state 0(1 of 8)
      }
  }
}

edit: solution was also referenced to in the comments below the post. it was really a problem about having it in mind but forgetting to type something down. anyway I will probably soon start to test with that custom driver don't know how to publish it, but will probably link it back here if I remember it. will be open source probably if I find the proper methods.

I have my new driver working, currently my current design costs around 15 cents to make yourself as a hobbyist, and it allows much more than a traditional driver as well as that it can control 2 stepper motors separately and doesn't require as much pins. however I still have to do some tests and improve things a bit to increase the efficiency and such, especially when you replace parts with custom parts. currently it is around as powerful per motor as the normal driver, but in tests I found that I could reach a much greater efficiency than the original one.

with my current setup I could make a working lithography mashine for €1,65(excluding the arduino) In this design I do use scrap parts for things like the frame and lens, the precision of the uv beam can only be changed manually in this design, I calculated it using the prices I paid for the parts, this excludes shipping and I got parts in bigger quantities, however I also included parts in this price which you probably already have laying around like resistors, transistors, a capacitor to stabilize the power,etc. I asumed one to have cables. I will probably publish how to make this thing.


text:
Will the arduino uno still work if I replace the onboard 16Mhz crystal with a 12Mhz crystal?
I have recently bought an arduino uno R3 (the type where the atmega328 is surface mount and not removable on a mainly blue PCB); the board has two crystals on it one for the clock for the USB serial and the other for the atmega328 clock. Suppose I have built a fully completed circuit using the arduino (this means the arduino needs not to be further connected to a PC).  Will my arduino uno based circuit still work if I  simply replace (desolder) the 16Mhz (for the atmega328)  crystal with a 12Mhz crystal (soldered in its place)? The circuit doesn't use the serial ports or the the crystal for USB serial. Actually the circuit is simply the blink LED example built into the IDE.  I am guessing it will still work but blink slower-but I don't know the answer for sure.

look at page 2 ... https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

Per the @jsotola link, the datasheet says the chip will do 0-16MHz.  https://forum.arduino.cc/t/arduino-with-internal-oscillator-on-1mhz/24547/4 suggests that it would mess with the bootloader, and gives guidance for compiling for lower speed operation.

Sure the device will work, but all time related peripherals won't behave. The USART will run at the wrong baud rate, the millisecond timer's intervals will be too long, and so on.

Assembling an answer from the comments. Ever-terse @jsotola points the OP to page two of the data sheet which @Dave X summarizes as saying that yes, the chip will operate at 0 to 16 MHz. There is a caveat though, discussions on the Arduino forum suggest that the reduction in clock speed proposed by OP might interfere with the boot loader. The same discussion provides guidance for compiling for lower speed operation.


text:
Arduino Nano and ESP32 Read Different Values over Serial
I am trying to use the Neato xv11 lidar with an ESP32. This should output packets of 22 bytes with the starting byte 0xFA. The communication is 8N1 and the baud rate is 115200.
When I connect the Lidar TX to the ESP32 RX2 pin, I get data that does not make sense as I get the start byte every 9 (and sometimes 8) bytes. However, when I run the same code on an Arduino Nano, I get the correct 22 byte packages. I even connected both at once and logged the results in Putty. This is the data I got.
// Arduino Nano Code
void setup() {
  Serial.begin(115200);
  Serial1.begin(115200);
}
void loop() {
  while (Serial1.available()) {
    Serial.println(Serial1.read(),HEX);
  }
}

// ESP32 Code
void setup() {
  Serial.begin(115200);
  Serial2.begin(115200, SERIAL_8N1, 16, 17);
}

void loop() {
  while (Serial2.available()) {
    Serial.println(Serial2.read(),HEX);
  }
}

ESP32
FA
A8
0
35
6D
11
17
71
3D
FA
A9
0
3D
12
97
12
10
D1
41
FA
AA
0
E1
E
14
12
E7
1F
FA
AB

Arduino Nano
FA
D8
74
35
6B
3
3D
1
7B
3
3B
1
8C
3
2B
1
9F
3
1C
1
A
1D
FA
D9
74
35
B2
3

try running Serial at a higher baud rate ... also try using if, instead of while

did you check the voltage of the communication?

I checked the voltage and tried voltage converters. The ESP32 still gets strange data. I also tried to use an if statement instead of while and that did not fix it. It is very strange behaviour.


text:
Space taken by Global Variables
Using Nano's for small programmes I get compilation reports about the amount of space taken by global variables.
On a typical progamme it says something like Sketch uses 16316 bytes (53%) of program storage space. Maximum is 30720 bytes. Global variables use 1798 bytes (87%) of dynamic memory, leaving 250 bytes for local variables. Maximum is 2048 bytes. Low memory available, stability problems may occur.
If I count up the number of bytes taken by the declared global variables it is 126 bytes, depending on how bool's take up memory ( one bit or one byte ).
Can I get the compiler to give me a dump of what it is actually assigning as global variable space to reconcile the difference between 126 bytes and 1798 bytes.  Then I could change the programme to get round the memory problem and keep using the Nano's.
Thanks in advance for any useful insights.
Thanks to those who commented for the help.
Checking the memory requirement for the global variables, includes and begins still only used 34% so I realised that something in the main loop was using extra memory.  Then the penny dropped, I had print messages left over from tracing problems and these become stored constants when compiled.  Moved these to a conditional compile section so they are only compiled during tracing for bugs. Problem solved. Once again thanks for the helpful hints.

Start with an empty sketch and see its RAM requirements. Then add Serial.begin(9600); and notice the difference. Your 1798 bytes are certainly used by some library. And yes, there`s a tool avrdump , but not that easy to use.

If you dive into command line levels, you can ask the linker to generate a map file. However, this is not trivial for the beginner.

Here's a hint for future use: this form (note the 'F' macro) Serial.print(F("Your message here.\n")); will store the message text in flash instead of RAM. That will work for any object that uses Print library. Though your concern wasn't (yet) running out of RAM, in a larger program, adding text messages can cause various kinds of out-of-RAM crashes.

Please do not answer questions in the comments. There is a nice big box underneath where answers go. @Harry - if you find the answer yourself (as you did it seems) feel free to make an answer yourself.

RAM is precious on a microcontroller, PROGMEM (program memory) not quite as much so. On the Arduino Uno and the Nano (using an Atmega328P) you have:

1 kB of EEPROM
2 kB of RAM
32 kB of PROGMEM

Clearly, there is a lot more program memory than RAM.
Variables are copied into RAM at program startup
The problem with constants in general (including string constants like "hello") is that the compiler generates code to copy them into RAM at program startup, because most C functions do not expect to find data in PROGMEM. (It has to generate different instructions to access PROGMEM).
Benchmark memory use
To test memory use, I'll start off with a sketch that simply returns how much memory is free, without doing anything else. Tested on IDE 1.0.6, Arduino Uno, on Ubuntu.
#include "memdebug.h"

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("Free memory = "));
  Serial.println (getFreeMemory ());
  }  // end of setup

void loop () { }

Output:
Free memory = 1702

Since we started with 2048 bytes of RAM, already we have used 2048 - 1702 = 346 bytes. These are used as follows:
34 bytes for the HardwareSerial instance (Serial)
64 bytes for the Serial transmit buffer
64 bytes for the Serial receive buffer
4 bytes for the Serial transmit buffer head and tail pointers
4 bytes for the Serial receive buffer head and tail pointers
9 bytes for keeping track of millis / micros
4 bytes for memory allocation (__malloc_heap_start, __malloc_margin)
128 bytes for the heap safety margin
6 bytes for a few nested function calls (main -> setup -> getFreeMemory)
16 bytes for the compiler vtable for HardwareSerial
4 bytes for variables __brkval and __flp (used in memdebug)
2 bytes pushed onto the stack in main (to save registers)
2 bytes pushed onto the stack in setup (to save registers)
4 bytes pushed onto the stack in getFreeMemory (to save registers)
1 byte because the stack pointer starts at 0x8FF rather than 0x900

(That's 346 bytes accounted for)
Tips
The stack starts at the highest possible address and grows downwards. Each function call would add 2 bytes to the stack (the return address) plus any local (auto) variables would be allocated there.
The heap safety margin is a buffer between the top of the heap and the bottom of the stack. Without it, if you did a "malloc" and got all available memory, there would be no memory left for function calls and local variables in functions.
The vtable is used by the compiler to generate late bindings for virtual functions used by classes.
The compiler generates code to push registers onto the stack when you call a function (the registers used inside that function) so that if the same register was used by the calling function, it would not be corrupted.
Printing constants
Let's print a constant by adding this line:
  Serial.println ("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo");

Output is now:
Free memory = 1630
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo

So the free RAM has gone down by 72 bytes, which happens to be be how long that string is (allowing one byte for the 0x00 terminator at the end).
Why? Because the string was copied from PROGMEM, where it must be when the Arduino is turned off, into RAM.
The first thing we can do is use the F() macro, which cunningly expands out to print directly from PROGMEM, thus saving RAM. So we change the line above to read:
  Serial.println (F("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo"));

Output:
Free memory = 1702
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo

Back to 1702 bytes of free memory. So, lesson #1 is to use the F() macro as illustrated above whenever printing constants.
More information
I have more information on my page about RAM usage which discusses putting arrays of constants into PROGMEM as well as what I mention above.


text:
Multiple Arduinos, same name - Windows 10 Game Controllers
I am making some SimPit panels and SimRacing devices, and I've run into an annoying issue. I have  multiple Arduinos (Leonardos and ProMicros) that show up as the same "Controller Names" (See Image)
EDIT: In the Game Controllers (joy.cpl) windows of Windows 10, where does the name "Arduino Leonardo" come from?, so that I can rename each, so they show up listed as something different like: Leonardo 1, Leonardo 2, Leonardo 3?
I imagine this is a change to the boot-loader and nothing to do with anything via Arduino IDE?
Thank you for your time, and let me know if more info/explanation is needed.

Thank you, edited, where does the name "Arduino Leonardo" come from?

https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L387

That didn't work, it changed the name in "Bus Reported device description" in device manager (https://i.imgur.com/TgIgXBR.png), but not in the joy.cpl "Game Controllers" window
also I purged all USB Serial devices to be sure there was no lingering windows drivers overwriting the changes

Then it may be in the .inf file for the driver in Windows.

So, if that's true, then it'll likely change all the devices using that driver together to the same name?
Not 3 devices using the same inf to 3 unique names?
I'll test ASAP

If it is the case then you'll need to make three distinct devices with unique VID/PID combinations and have three separate drivers for them.

it appears that windows is able to distinguish more than VID/PID of a USB device ... there is mention of VID/PID/REV in the inf files ... REV is the device revision number which is the bcdDevice field in the USB device descriptor ... the bcdDevice field would have to be different in each Leonardo ... the inf file would have to be edited to create a different device name for each REV version

start on the windows side of the problem ... write arduino code that sets the bcdDevice field to some number, such as 4 .... edit the inf file to match VID/PID/REV ... choose REV = 4 ... windows should hopefully detect Leonardo ... next, change REV to 5 ... if windows detects an unknown device, then you have a way to distinguish Leonardos

Thank you both I'm going to try this new path ASAP, I will update when I can

@jsotola why are these comments, instead of an actual answer? This is detailed enough to absolutely justify being its own step by step answer, which can then also be found by searching (both on-site and through google).

Windows is likely assigning the inbox driver to use based on the VID/PID of the USB device.  Take care changing those values, as you may not be able to easily reprogram the devices.
There is a Device Firmware Update (DFU) technique where if a pin is low at startup / USB init, the VID/PID are returned as different values

Meaning I should setup a "board" with the changed VID/PID in arduino IDE?
DFU if you mean the vulgar acronym, I can do that ... I am that ;)

Certainly not the vulgar term. I was referring to Device Firmware Update (DFU).  If you setup the board(s) to use a VID/PID that the inbox joy stick driver recognized, then Windows will recognize the devices as such. The key to this is being able to make sure that you can still get the Arduino IDE to recognize the board as well.  I don't have any leonardo boards, but I have done this with one of the other Arduino boards... though it was some time ago.

Correction:  The project I was thinking of emulated a keyboard not a joy stick

Haha lol DFU is permanently ruined for acronyms, ill never see beyond the vulgar one now.. Thanks for all the info


text:
Multiple Arduinos connected to one display
I have one display screen, and 5 Arduino Nanos. They are checking to see if passwords in a text file hash to a specific hash, then display it on the screen when found.
Since they aren't all sending signals to the screen, is it possible to wire it so that all of them are connected to one screen, and then have the one that finds the correct password send the signal to the screen, and how would I go about doing this?

What type of screen is it? What protocol are you using to communicate with it?

I'd have a coordinator that listens to the nanos and gets the password to display. I'd also not use nanos.

in theory yes.  one can make a multiplexer for just about any type of circuit.  just need to make sure you have some exclusionary mechanism that ensures only one can talk (usually first one gets it until it sends a signal saying it is done)

k thanks, I will work with the coordinator idea, also I know nanos aren't the best option but for what I'm doing they are certainly very cheap and I already have around 6, the project involves clustering them so if I were to use unos or something else the price would increase drastically

Why do you think you need 5 Arduino Nanos? Why not just one? And why do they all need to be connected to a display? The display has some kind of display driver IC (this highly depends on your display: 7-Seg, LCD, OLED,...) and this ONE controller has some kind of interface that you can just connect ONE master to. That should totally be enough.

well the idea is that it is a cluster, I am splitting up the work between them, one arduino can test one at a time, 5 can test five at a time, the idea is every nano has one fifth of a password list(stored on an sd card), that they are checking constantly, then when one of them finds it, it will display it on the screen

It should be possible to connect all nanos to the display, just like you would if there was only one nano as long as there is only one nano that actively drives the bus (what ever bus that is). All the other nanos need their bus pins to be inputs (not configured for the bus). So you could have them being inactive by default and only access the bus once they found a matching hash.
But: if multiple nano's are configured for bus usage at a time, communication would be corrupted. In case the display uses a push-pull bus (SPI, UART, ...) this is even electronically an issue, because their bus pins would short the supply voltage and possibly get destroyed. So you need some kind of protection in that case, a current limiting resistor in the easiest form.
As mentioned in comments, the "clean" solution is to have one dedicated controller to be the coordinator.
Some thoughts:

there is a real (not just a hypothetic) chance for bus contentions, because multiple passwords lead to the same hash and you even want to compare hashes for multiple passwords. The occurence of such a collision needs to be expected, though it is not predictable when or if it actually happens.

you probably want to configure the cluster, e.g. to distribute the hash of interest among the Nanos or to stop the cluster when a match is found. Those things would be easier if there's one dedicated master which you can communicate with directly.

the coordinator would always have control over the display. What if you wanted to continously display information on the screen, e.g. a progress bar? That would be difficult to implement afterwards when there's no master.


text:
reading strings from multiple Arduinos
So I have 5 Nanos all trying to crack a password, the idea is each one has one fifth of the list so they can test 5 at a time, then when it is found, I want it to be displayed on a screen I have, the idea is to connect them all to a hub which would be the arduino uno, the Uno would then take the char was sent, and send it to the screen, it does not know which Arduino will send the char and the idea is to use serial.write but I am open to other options. What is the best way to go about accomplishing this task, is there some way I can have it reading the serial from all 5 Nanos, and can this be done without it being plugged into a computer?

I'm curious. For what purpose are you trying to build a password cracker based on Arduino? And why do you need to cluster them? Have you already tried with one Nano and it took to long? That is not a common thing to do with an Arduino

tbh I don't have a reason, I just had a bunch of nanos lying around, i was planning on using raspberry Pis for it originally but I realized I already had a bunch of nanos lying around. idk where the cluster idea came from, but really the project is mainly about the cluster, I wanted to see if I could achieve something like this. the cluster idea is just to speed things up, having more arduinos just increases the amount that can be tried drastically, Im just trying to get back into arduino after about a year

It's probably more straight forward if you use a multi-slave bus, like I2C, SPI, ...

I'd probably use RS485 or Ethernet for something like this (though ethernet is probably overkill for this application).

in your case you can simply wire all the serial pins together, nothing fancy or special. btw, a desktop can check more passwords in a second than a nano would in a day.

Presumably you will avoid having two Nanos try the same item from the
list. Then, only one Nano can find the answer, and only one will try to
transmit data at any given time. In such a situation, yes, you could
connect all five Nanos to the same serial link:

Connect the Uno's TX directly to the RX each Nano. They will all
receive the data transmitted by the Uno.
Connect the Uno's RX to the TX of each Nano through this circuit:

simulate this circuit – Schematic created using CircuitLab
As long as at most one Nano tries to Serial.print() (or
Serial.write()) at any given time, the Uno will receive the data just
fine, although it will not be able to tell which of the Nanos sent it.

The Nano devices can be wired in a daisy chain. Any character coming in must be immediately sent out. The chain would end where it connects to the Arduino.


text:
How to pre-design circuit before buying?
I am wanting to make a simple circuit that takes input from a movement sensor and plays a sound response.
To do this I think an ESP32 microcontroler would be optimal?
But how does one go about identifying parts and making sure they are compatible before buying?
For example I have no idea what sensor, speaker or battery sources to use. How does a total noob go about finding all this out in an efficient way?

Step one: read similar projects and tutorials. Step two: prototype using modules, breadboards, and wires.

Step #1: Steal! Search engines are your friend.
Step #2: (see step #1).

Look for published projects using parts that you want to use or to find out what parts someone else used, and how they connected them & coded for them.
Look up the datasheets for the parts you propose to use and read at least the introductions, to decide if they meet your needs. If you're project is for learning, not going into a bigger project (yet), you may not need this step if someone else's project has shown you the way. When you eventually come to designing your own, this step will be important.
As a beginner, copying from others is really the best/quickest way to 1) make stuff happen; and 2) not (or be less likely to...) blow up parts that cost money and take time to replace.
Once you've built a couple of projects you'll start to see common techniques of coding and of building circuits, that will lead you to more questions. (See step #1 above).
There's more, like learning some basic electrical and electronic theory and practice, if you haven't already, but that can come a little later and will make more sense when you have some hands-on experience.


text:
Micronucleus firmware 2.6.1 - Activate bootloader put D- pin to high
I flashed my ATTINY85 Digispark v3.0 with micronucleus firmware 2.6.1 and it works fine, the onboard led lights up and the another led blinks twines every 500ms (not sure way but it seams like everything is working correcly). But now I don't understand how to activate the "flash" mode to upload my program or upload a new bootloader.
I'm familiar with pull-up resistor but have never used it on a USB pins before (If I'm not mistaking the bootloader is activated to receiver programing when USB Data minus have a pull-up resistor and the board is reset and not only powered on).
Below are the condition to enter bootloader, text copied from micronucleus github page. https://github.com/ArminJo/micronucleus-firmware#entry_d_minus_pullup_activated_and_entry_ext_reset-entry-condition
ENTRY_D_MINUS_PULLUP_ACTIVATED_AND_ENTRY_EXT_RESET
Activate the bootloader only if the D- pin is high, i.e. a pull-up resistor is attached and powered and we have an ENTRY_EXT_RESET condition. Useful if the pull-up is powered by USB V+ and NOT ATtiny VCC to save power. In this case often a schottky diode is connected between V and VCC.
I have tried using a resistor from USB V+ to USB D- and resetting it using PIN 5 to ground but the leds just blinks to indicate a reset but no connection to is establish.
So if someone knows how this should work let me know.


text:
How many ADS1115 ADCs can I connect to a single Arduino Mega 2560
I know we can connect 4 ADS1115s to an Arduino Mega 2560.
Is there any limit on the number of ADS1115s we can connect to the Mega giving each a different address? I have to connect at least 36 ADS1115s.

you could try connecting all 36 ... pull one of 36 address lines high and talk to that one selected device

256(+?)
With 8 TCA9548A 1-to-8 I2C Multiplexers on different I2C addresses, it is a multiplication problem: You can expand the Arduino Mega's I2C port on Digital Pins 20&21 to 8 multiplexers *  8 multiplexer ports * 8 ADS1115 addresses to 256.
It might be possible to go much further if you can wire and code multiple levels of multiplexers.


text:
How can I get an external program to change values inside the Arduino C++ code?
How can I get some constantly changing values from a separate C++ program entered and uploaded into the Arduino?
I notice when I upload code to the Arduino in the IDE it takes about a second to start moving. This is also a problem. I would like there to be no delay after instructions to the motor change.
My goal is to get a trained neural network model from the PyTorch C++ version to control the motor's spin and speed. I would assume the IDE does not allow one to import PyTorch?
I tried looking around on the Arduino website for this, but it seems like the IDE is the only option. My solution would be something that imports the Arduino library into a C++ program just like I import the PyTorch library into my C++ program.
My ficticous C++ code. Just written to illustrate what I would like to happen.
import pytorch
import arduino

// if I had an encoder on the motor giving position readings as inputs (I know this isn't how it's done in real code)
sensors = arduino_encoder_sensors

// trained model
m = pytorch.load_torch_model('model')

// model taking sensors as inputs and outputting desired speed and distance executions to the motor
speed, dist = m(sensors)

Arduino Code:
const int stepPin = 8;
const int dirPin = 9;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  for(int x = 0; x < dist; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(speed);
    digitalWrite(stepPin,LOW);
  delay(1000); // One second delay
}

the Arduino sketch runs on the Arduino, you can send values to the Arduino over serial port

Thank you. I'm looking around for this option. Any examples what code into the serial port looks like? Is it something I can send out of any C++ program? I can't picture how this works. Not the USB, but a serial port?

your fictitious code has no I/O to another device ... it also has a 1 second delay, during which the arduino is doing nothing ... see blinkWithoutDelay example sketch

It sounds like self modifying code, that will not work, it takes a lot of time. Why not set up a communication link so they can talk to each other. You can use CAN, Ethernet or something else depending on how much data and how fast it has to be transfered. RS485 will work with the serial port in the Arduino. Remember if the processor only has one USART that will also have to be used for uploading code etc.  The data can be saved in RAM. You can use software serial or another Arduino that has more than one port.

It's difficult to understand what you're asking. An Arduino program is just C++ code; if a library is compatible you can import it. Arduinos can also be very resource-constrained, so the type of Arduino is important to know. Any editor/IDE with some form of Arduino support can be used (e.g., I use the Arduino IDE, VS Code, and CLion).

Is it a copy and paste error, that you don't have a loop() function? Currently your code isn't compilable. And are you missing a closing bracket for the for loop? Currently the delay is inside the for loop, but I think you mean it to be outside.

What values?  Both ways?  From arduino -> otherComputer and from otherComputer -> Arduino?

Your question seems very confused, so I will try to shine a light on some basic distinctions.

How can I get some constantly changing values from a separate C++ program entered and uploaded into the Arduino?

In your whole question you seem to confuse program and data. The program on the Arduino doesn't need to change with every changing of the values. Instead you would have a constant program, which receives changing values from the PC.
So it seems you want to send data from your python program on your PC to the Arduino. This data doesn't have anything to do with the actual program on the Arduino. The program just should use the data to act accordingly. You can use any of the communication interfaces that are usable with Arduinos and PCs, though the simplest option would be the Serial interface, which gets bridged to your PC via the USB port. The Serial interface is what you see in the Serial Monitor.
How to use a serial port in python can be googled quite easily. For the Arduino side there are many tutorials and examples about it online. You would also need to think about your communication protocol, which you want to impose on the Serial byte stream. For example you could use ASCII encoded text, each message delimited to the next by a newline character '\n', each message containing first the command and then needed parameters. Since only you know what exactly you want to send to the Arduino, you need to design this yourself.

I notice when I upload code to the Arduino in the IDE it takes about a second to start moving. This is also a problem.

This is due to the bootloader. When you upload a program this is done via the Serial interface. Normally microcontrollers can only be programmed over specialized interfaces (like ISP). But Arduinos (and other microcontrollers) can be programmed with a bootloader. That is a program sitting on the microcontroller, which runs anytime you power the microcontroller on your reset it. On Arduinos it will listen on the Serial port for a moment in the case that you want to upload a new code. If yes, then it handle the communication and write the new code to the Arduinos flash memory. If not, it will execute whatever program currently is saved in flash.
So you cannot avoid this delay without changing or deleting the bootloader. Deleting it would mean that you need a programmer board to upload new code (another Arduino can do that). Changing it would also require a programmer board, because you would need to write the new bootloader version to the Arduino with it.
I would debate if this delay is really a problem. It only appears on a reset, like when you upload new code. And why would you want to reset the Arduino or upload new codes that fast? For doing your motor movement you don't need new programs on the Arduino for every movement; you need a code that will move according to data send through the Serial interface. And that doesn't require resetting. And it works fast.
That said, with your current code (ignoring the obvious syntax problems most likely from copy and past errors) you will still have delays, even when you implement Serial communication. In general you shouldn't use long delay() calls. You use delay(1000), which makes the Arduino twiddle its thumbs for one whole second each loop iteration. Instead use the non-blocking coding style shown in the BlinkWithoutDelay example that comes with the Arduino IDE. It uses the millis() function as a clock, checking it regularily for the time to do something. There are many tutorials about that online.

My goal is to get a trained neural network model from the PyTorch C++ version to control the motor's spin and speed. I would assume the IDE does not allow one to import PyTorch?

No, it doesn't. It is based on Java, not on python. As described above you need to write your own python program and use a fitting serial port python module for the communication over the Serial interface. In that python program you can import PyTorch, do your  neural network processing and then send the resulting commands over Serial to the Arduino.

I tried looking around on the Arduino website for this, but it seems like the IDE is the only option. My solution would be something that imports the Arduino library into a C++ program just like I import the PyTorch library into my C++ program.

It is not really clear what you mean here. For communicating with an Arduino over Serial you can use any program that can interface with a serial port on your PC. There are many programs dedicated for this. Since you want to do your neural networking stuff in python, just use a fitting python module that handles serial port connections.
If you talk about writing programs for Arduinos and uploading them: This can be done in many other IDEs other than the Arduino IDE. Dave Newton mentioned some in his comment: VS Code and CLion. I also remember the Atom IDE. Or you can write your code in any text editor of your liking and then compile and upload the code with the Arduino CLI tool (that's what I do mostly).

I hope this clears up the confusion a bit so that you now can work toward a working solution.

I want to import PyTorch and a saved model into the Arduino IDE. I didn't know if this was possible, but I'm working on figuring out if that is possible now. If I can't import PyTorch and the model into the IDE then I need the Arduino library and ability to 'upload' code to the Arduino device in some other way that I am not yet aware of. This is what I am asking. I'd appreciate an upvote on my question. I don't see any part of it as confused. I'm not being snarky when I say that. I am NOT going to be using Python. If someone would just suggest a method other than the IDE I would give them a gr

@Ant But if you don't want to use python, why do you want to import PyTorch, which is a python library? And you definitely cannot import PyTorch in the Arduino IDE or an Arduino program. Just completely different frameworks. There might be C++ libraries for neural networks which are Arduino compatible, but then the Uno is most likely a bad choice, since it has so few RAM and processing power. Does the model fit in 2KB RAM? I think there are microcontroller boards dedicated to AI stuff with way more RAM and processing power (most likely not directly by Arduino but Arduino compatible).

PyTorch is available in a C++ version. I am using PyTorch in C++

Ah, ok, must have overread that. Sure, you can include any C++ libraries in your code that you like. You will need to place these libraries either in the libraries folder or in the same folder as the sketch so that the Arduino IDE finds them. Though I don't know of they are compatible or usable with Arduinos. You can try it. I would guess that you run into memory problems on the Uno. Also have a lookout for dynamic memory allocation, which is often really bad on microcontrollers due to memory fragmentation. Tomorrow I eill change my answer to fit better

Dave Newton answered that I could import any C++ library. I didn't realize the IDE was flexible enough to do that. Since he said that I have been trying to install the C++ version of PyTorch. It's taking me hours to get it installed with the right CUDA version and getting Pytorch 'built' after the install. The answer to my OP is to launch Arduino in an env with Libtorch installed and put #include <torch/torch.h> in the IDE. I think. Should work, I'm told here.

I was thinking about memory earlier today. Yes, I might need a custom upgrade!


text:
xQueueGenericReceive error on ESP32 (using FastLED which relies on FreeRTOS) for adapted MeteorRain LED animation
I'm trying to adapt the MeteorRain animation from Tweaking4All to work on segments of my light string (vs using the entire string) and I'm getting an error in FastLED.show() (on a line that is used repeatedly with the same variables before it crashes the "ESP32 DEVKIT V1"). The decode of the ESP32 shows an error in clockless_rmt_esp32.h (which is about as far as I have visibility and ability to troubleshoot the problem.)
Looking through Google results, I find people who have the same error, usually related to memory allocation, but I can't make a connection to FastLED.
The code:
#define FASTLED_INTERNAL // add this before including FastLED.h
#include <FastLED.h>

#define LED_PIN     12
#define COLOR_ORDER RGB
#define CHIPSET     WS2811
#define PIXELSECTIONS 2     // there are two segments of christmas lights
#define HORZPIXELS 5        // with 5 lights across connected to
#define VERTPIXELS 12       // 7 lights that hang vertically
#define NUM_LEDS (HORZPIXELS + VERTPIXELS) * PIXELSECTIONS
#define NUM_COLS PIXELSECTIONS
#define NUM_ROWS VERTPIXELS + HORZPIXELS
#define BRIGHTNESS  50

CRGB rawleds[NUM_LEDS];
CRGBSet leds(rawleds, NUM_LEDS);

unsigned long animationsCycleStartTime = millis();
int genericCounter=0;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(115200);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(rawleds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness( BRIGHTNESS );
}

void loop() {
   meteorRain(0xff,0xff,0xff,10, 64, true, 30);
}

void meteorRain(byte red, byte green, byte blue, byte meteorSize, byte meteorTrailDecay, boolean meteorRandomDecay, int SpeedDelay) {

  int metaNUM_LEDS = (HORZPIXELS + VERTPIXELS);
  for(int i = 0; i < metaNUM_LEDS+metaNUM_LEDS; i++) {

    // fade brightness all LEDs one step
    for(int j=0; j<metaNUM_LEDS; j++) {
      if( (!meteorRandomDecay) || (random(10)>5) ) {
        metaFadeToBlack(j, meteorTrailDecay );
      }
    }

    // draw meteor
    for(int j = 0; j < meteorSize; j++) {
      if( ( i-j <metaNUM_LEDS) && (i-j>=0) ) {
Serial.print("i=" + String(i) + ";j=" + String(j) + ";i-j=" + String(i-j));
        metaSetPixel(i-j, red, green, blue);
Serial.println(" done");
      }
    }
Serial.println("to show");
    FastLED.show();
Serial.println("to wait");
    delay(SpeedDelay);
  }
  genericCounter = (genericCounter>=PIXELSECTIONS) ? 0 : genericCounter+1 ;
}

void fadeToBlack(int ledNo, byte fadeValue) {
 #ifdef ADAFRUIT_NEOPIXEL_H
    // NeoPixel
    uint32_t oldColor;
    uint8_t r, g, b;
    int value;

    oldColor = strip.getPixelColor(ledNo);
    r = (oldColor & 0x00ff0000UL) >> 16;
    g = (oldColor & 0x0000ff00UL) >> 8;
    b = (oldColor & 0x000000ffUL);

    r=(r<=10)? 0 : (int) r-(r*fadeValue/256);
    g=(g<=10)? 0 : (int) g-(g*fadeValue/256);
    b=(b<=10)? 0 : (int) b-(b*fadeValue/256);

    strip.setPixelColor(ledNo, r,g,b);
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   leds[ledNo].fadeToBlackBy( fadeValue );
 #endif
}

// this method transposes the relative pixel to the actual pixel
// for example, on the second pass of loop the code says to use
// pixels 0-16 but since the genericCounter is at 1 this method
// activates pixels 17-33
void metaSetPixel(int metaPixel, byte red, byte green, byte blue) {
  int actualPixel = (genericCounter * (HORZPIXELS + VERTPIXELS)) + metaPixel;
  setPixel( actualPixel, red, green, blue);
}

void metaFadeToBlack (int metaPixel, byte meteorTrailDecay) {
  int actualPixel = (genericCounter * (HORZPIXELS + VERTPIXELS)) + metaPixel;
  fadeToBlack(actualPixel, meteorTrailDecay );
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
   // FastLED
   rawleds[Pixel].r = red;
   rawleds[Pixel].g = green;
   rawleds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}

The raw error from Serial console trace:
13:50:53.499 -> ⸮⸮�⸮�⸮⸮⸮�@#P#⸮N⸮1h⸮0,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
13:50:53.499 -> mode:DIO, clock div:1
13:50:53.499 -> load:0x3fff0018,len:4
13:50:53.499 -> load:0x3fff001c,len:1044
13:50:53.499 -> load:0x40078000,len:10124
13:50:53.499 -> load:0x40080400,len:5856
13:50:53.499 -> entry 0x400806a8
13:50:55.042 -> i=0;j=0;i-j=0 done
13:50:55.042 -> to show
13:50:55.076 -> to wait
13:50:55.076 -> i=1;j=0;i-j=1 done
13:50:55.076 -> i=1;j=1;i-j=0 done
13:50:55.076 -> to show
13:50:55.110 -> to wait
...[snip]...
13:51:01.299 -> to show
13:51:01.299 -> to wait
13:51:01.334 -> i=0;j=0;i-j=0 done
13:51:01.334 -> to show
13:51:01.334 -> /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/queue.c:1443 (xQueueGenericReceive)- assert failed!
13:51:01.334 -> abort() was called at PC 0x40085e41 on core 1
13:51:01.334 ->
13:51:01.334 -> ELF file SHA256: 0000000000000000
13:51:01.334 ->
13:51:01.334 -> Backtrace: 0x40084e74:0x3ffb1df0 0x400850e9:0x3ffb1e10 0x40085e41:0x3ffb1e30 0x400d1371:0x3ffb1e70 0x400d171d:0x3ffb1e90 0x400d1801:0x3ffb1ed0 0x400d11bb:0x3ffb1f10 0x400d125b:0x3ffb1f80 0x400d2231:0x3ffb1fb0 0x400860f9:0x3ffb1fd0
13:51:01.372 ->
13:51:01.372 -> Rebooting...
13:51:01.372 -> ets Jun  8 2016 00:22:57
13:51:01.372 ->
13:51:01.372 -> rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
13:51:01.372 -> configsip: 0, SPIWP:0xee
13:51:01.372 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
13:51:01.372 -> mode:DIO, clock div:1
13:51:01.372 -> load:0x3fff0018,len:4
13:51:01.408 -> load:0x3fff001c,len:1044
13:51:01.408 -> load:0x40078000,len:10124
13:51:01.408 -> load:0x40080400,len:5856
13:51:01.408 -> entry 0x400806a8

The decoded error:
Decoding stack results
0x40084e74: invoke_abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/esp32/panic.c line 156
0x400850e9: abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/esp32/panic.c line 171
0x40085e41: xQueueGenericReceive at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/queue.c line 1443
0x400d1371: ClocklessController12, 77, 77, 154, (EOrder)10, 0, false, 5>::showPixels(PixelController(EOrder)10, 1, 4294967295u>&) at /Users/jaireaux/Documents/Arduino/libraries/FastLED/platforms/esp/32/clockless_rmt_esp32.h line 288
0x400d171d: CPixelLEDController(EOrder)10, 1, 4294967295u>::show(CRGB const*, int, CRGB) at /Users/jaireaux/Documents/Arduino/libraries/FastLED/controller.h line 408
0x400d1801: CFastLED::show(unsigned char) at /Users/jaireaux/Documents/Arduino/libraries/FastLED/controller.h line 90
0x400d11bb: meteorRain(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, bool, int) at /Users/jaireaux/Documents/Arduino/libraries/FastLED/FastLED.h line 500
0x400d125b: loop() at /Users/jaireaux/Documents/Arduino/temp/temp.ino line 33
0x400d2231: loopTask(void*) at /Users/jaireaux/Library/Arduino15/packages/esp32/hardware/esp32/1.0.6/cores/esp32/main.cpp line 23
0x400860f9: vPortTaskWrapper at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port.c line 143


text:
Arduino fade in/out 5 leds circuit acting wierd
I have a simple arduino project with 5 leds, the project should start with led 1 fade through 50 millisec to reach full brightness, then led 2 and so on until led 5 then turn them all off and loop.
here is an image for the circuit (pardon the messy look my first time):

"all leds cathod are connected"
and here is the code :
 int led[5]={3,5,6,9,10};
// led pins array (pwm)
void setup() {
  // put your setup code here, to run once:
  for (int i = 0; i < 5; i++){
    pinMode(led[i], OUTPUT);
    }
    // set each pin as an output
}

void loop() {
  for (int i = 0; i < 5; i++){
    int pin = led[i];
    // storing the value of the current pin in a variable
    int j = 0;
    while(j <= 50){
      j++;
      delay(1);
      analogWrite(pin,j*2);
    }
    /* the while loop is used to make the fade effect
    by increasing the duty cycle by 2% each millisec
    over 50 millisec */
  }
  delay(200);

  for (int z = 5; z > -1; z--){
    int pin = led[z];
    analogWrite(pin,0);
    }
    // turning off all leds
    delay(50);
}

the problem is as follows :
the first round of the loop the circuit acts as expected led 1 on then 2 etc then they all turn off and loops again, on loop 16 led 1 turns off and the loop continues only with leds from 2-5 and on loop 31 led 4 and 5 turns off and only led 2 and 3 keep on going.
Edit 1 : i just found something interesting on arduino's official page
(pins supporting pwm 3, 5, 6, 9, 10, 11 )
pwm frequency 490 Hz (pins 5 and 6: 980 Hz)
so could the frequency result in this error?
Edit 2 : the issue was resolved with a really wierd change in the code
the very first line of code " int led[5]={3,5,6,9,10};" i changed the size of the array from 5 to 6 like this " int led[6]={3,5,6,9,10};" and the issue was resolved, I discovered this while i was trying to use 4 leds and i forgot to change the size, if anyone could explain how did this change helped solve the problem ?

Your second loop (for (int z = 5; ...) starts with z=5, which is an out-of-bound array index and might produce unpredictable behaviour. This also explains why your "fix" worked (you simple made the array larger). Make the loop start with z=4.

You need one resistor for each LED. Otherwise, the brightness of one LED affects the brightness of the others.

Your problem may be in your count down code. Specifically this loop:
for (int z = 5; z > -1; z--){

Z starts at 5, and you then try and access element 5 of a 5-element array. That sounds reasonable until you remember arrays are 0-based, so there is no element 5, only elements 0-4.
So you're reading data that you shouldn't be reading. Just reading shouldn't have any effect though, so :shrug:...
Anyway, there's some "best practice" things you should do to improve your code:

Use 8-bit values to store your pins (uint8_t)
Make your pins array const so it's never modifyable
Replace your while loop with a simpler to understand and follow for loop
Keep your loops as simple count-up and use math to work out which array entry you want.
Keep variables to the smallest storage size needed for the values you're working with.

For example (untested):
const uint8_t led[5] = { 3,5,6,9,10 };
// led pins array (pwm)

void setup() {
  for (uint8_t i = 0; i < 5; i++) {
    pinMode(led[i], OUTPUT);
  }
}

void loop() {
  for (uint8_t i = 0; i < 5; i++){
    int pin = led[i];
    for (uint8_t j = 0; j < 50; j++) {
      delay(1);
      analogWrite(pin, j * 2);
    }
  }

  delay(200);

  for (int z = 0; z < 5; z++) {
    int pin = led[4 - z];
    analogWrite(pin, 0);
  }

  delay(50);
}

Also as noted in the comments you must have one resistor per LED and never connect all the cathodes together like that. The brightness of each LED is determined by the current flowing through it. That current is the current through the resistor, which is determined by the forward volgage of the LEDs. The more LEDs you have on the more that current is split between the LEDs. And different LEDs will have different forward voltages, and the lowest one will "win" affecting the current that the resistor allows. It's all a horrible mess and must be avoided at all costs. The only times you can have just one resistor for multiple LEDs are a) if you have a series chain of LEDs making them in effect just one LED with a higher forward voltage, or b) can absolutely guarantee that one and only one LED will ever be turned on at a time.

it sounds like the most reasonable issue, i will try it and accept the answer if it solved the issue but why changing the array size solved the problem

@AhmedH2O By changing it to a 6 element array it's valid to access elements 0-5. It's not valid to access them with a 5 element array.

Here is the @Majenko code output

The code same as the one posted in the other answer. You can find the simulation link here --> https://wokwi.com/arduino/projects/318609194610590292
I also hooked up a logic analyser and here is how it looks :) You can look how the Duty cyle is becoming larger afer every cycle.


text:
I can't show the button pressed on the GLCD ST7920?
I have a small project that i want to show my keypad pressed on my GLCD but when i pressed keypad, even on serial it is fines but on GLCD it can't show my characters. Could you tell me what the problem and what should i do to solve!.  my GLCD library is BasicGLCD!

#include <Keypad.h>
#include <EEPROM.h>
#include <basicGLCD.h>
basicGLCD GLCD;
/*long four = 0;
long three = 0;
long two = 0;
long one = 0;
*/
int adress = 0; // gia tri dia chi luu du lieu
const byte rows = 4; //so hang
const byte columns = 4; // so cot

int holdDelay = 100; // thoi gian tre de xem la nhan 1 nut de tranh nhieu~
int n = 3; //
int state = 0; // neu state=0 khong nhan, state=1 nhan thoi gian nho , state = 2 nhan giu lau
char key = 0;
int i=1;
//dinh nghia cac gia tri tra ve
char hexaKeys[rows][columns] =
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'},
};

byte rowPins[rows] = {4, 5, 6, 7}; // cách nói chan Arduino
byte columnPins[columns] = {12, 13, 2, 3};// cách nói chan Arduino

//cài đặt thư viện keypad
Keypad keypad = Keypad(makeKeymap(hexaKeys), rowPins, columnPins, rows, columns);
//////////////////////////////////////////////////////
void setup() {
  Serial.begin(9600);//bật serial, baudrate 9600

 // GLCD.setCursor(4, 0);
  //GLCD.sendString("WELCOME....");

  //////
  GLCD.setDataPins(23,25,27,29,31,33,35,37);
  GLCD.setRSPin(A2);
  GLCD.setCSPins(A0, A1);
  GLCD.setENPin(A4);
  GLCD.setRWPin(A3);
  if(GLCD.init() != 1) {
    Serial.println("You have to set all pins");
    return 0;
  }
  else {
  GLCD.sendString("   WELCOME  ");
  GLCD.setCursor(10, 0);
  delay(500);
  GLCD.clear();}
  //////////////////////////////////////////

 GLCD.setCursor(0, 1);
 GLCD.sendString("Loai IVT: ");
 GLCD.setCursor(0, 2);
 GLCD.sendString("TG mau : ");
 GLCD.setCursor(0, 3);
 GLCD.sendString("CSCD :");

}
//////////////////////////////////////////
void loop()
{
  char temp = keypad.getKey();
  if ((int)keypad.getState() ==  PRESSED) {
    if (temp != 0) {
      key = temp;
    }

    //xem kq
  if(temp)
    {if(temp == '+')
    {GLCD.clear();}
    if(temp == '=')
    {i=i+1;}
    GLCD.setPage(RIGHT);
    GLCD.setCursor(5,i);
    GLCD.sendData(temp);
    ;
    }
 delay(500);
}
}

do you see the word WELCOME on the LCD?

Yes, it shows WELCOME first and "Loai IVT", "TG mau","CSCD " after, but when i press keypad to sent the number in each parameters  but it doesn't work.  it just shows any dot in the GLCD

add debugging code to your sketch ... use Serial.print() to determine what the code is doing

Well , in serial i don't see anything, the keypad code is from example it work well when indepentdent but when it has GLCD , i can't see anything on Serial monitor


text:
NodeMCU dev board shows 13 for ADC when grounded - why?
I have a NodeMCU 1.0 ESP-12E development board.  Trying to hook up a LM35 to measure temperature.  For that I need to use the analog pin A0. However it seems my sensor is out by about 4C.  I traced this to an offset error - when the board is connected via USB to the PC, and I connect analog pin A0 to analog ground with a jumper on the board, I read 13 from analogRead(A0).  I should be getting 0.  I confirmed with a voltmeter that A0 is at ground potential.  I have nothing else connected to the board.  When I feed in 3.3V to A0, I get 1024.  When I hook up the LM35 which outputs 210mV, I get a reading of 81 which is 13 off (based on the standard analogValue / 1024 * 3300 calculation).
What am I doing wrong?

just subtract 13 from the adc read, problem solved.

Won’t work as I said, it is 13 when wifi is off, 2-3 if wifi is on. That will not be reliable.

The input A0 is not actually an ADC input. Instead it's the input to a voltage divider which then goes to the ADC input. The ESP8266's ADC is only capable of reading up to about 1.1V, so the makers of the NodeMCU helpfully created a small voltage divider (two resistors) to drop the input voltage to the range the ADC can cope with.
Except it's not perfect.
The resistors used aren't 100% precise, so the actual values you get from the ADC vary slightly from board to board. To get more precise readings you will have to first calibrate your ADC by providing known stable voltages to the ADC and logging the read values. Or you can measure the resistors used on your board and use those in the calculation to determine actually what value is being seen by the ADC.
Or you can use an external ADC that doesn't require the voltage divider circuit to function, which would be my preferred method, since the internal ADC is not great.

Thanks for the response.  I am aware of the voltage divider, however their tolerances would not be enough to cause a reading of 13 when shorted to ground - surely?  13 is the equivalent of 41mV.  Also, I just observed something else - when I start WiFi on the device, the shorted-to-ground reading drops to 3.  This is very strange...

The ADC is tightly coupled to the WiFi functionality. It's a really really crap arrangement. You really would be better using an external ADC.

Just ordered an ADS1115 - will give that a go - thanks again.


text:
Controlling a 5V fan and ultrasonic fogger with an arduino - do I need an external power supply?
I know the whole controlling a fan with an arduino thing is getting old, but somehow I still don't get it to work. Tried to answer it based on other questions but I am too much of a newbie to extrapolate the info there to my specific problem.
For my project of building an arduino-controlled mushroom grow box, I need to control a PC fan and ultrasonic fogger. I chose these two products:
DC 3-12V Ultrasonic Fogger,
DC 5V Fan
I hoped that by using 5V devices, I could connect them to the 5V pin of the arduino to power them. However, with the whole setup (see circuit and photo), they don't run. I'm using a BC337 transistor. I tried them both separately, but nothing.

I know that there is a resistor missing in the photo, I forgot to put it back in when I took it.

The fan works if I just insert it between 5V and GND but the fogger doesn't do anything.
The code works (and is fairly hard to mess up) but I'm including it anyway.
const int fan = 3;

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

void loop() {
  digitalWrite(fan, HIGH);
}

Do I need a higher voltage power supply or is something wrong with my transistor choice? Which parts would be a better fit? Or am I entirely on the wrong track?
In the end the full thing should also contain an LCD display and a SCD41 sensor, both connected via I2C.

Thanks in advance!

the fan red wire is not connected to any part of the circuit

About the ultrasonic fogger:
The product description is misleading. This is a pure transducer. That means it does not generate its own ultrasonic frequency and is thus not DC. You need to provide an AC voltage at the frequency of 113kHz (though one reviewer states to have received products with a resonance frequency of 108kHz. Maybe just try out what you have). You can use utilize Timer1 to generate a fitting square wave at one of its output compare pins.
Note: Since you are more at the lower end of the foggers voltage rating you might see a bad performance when you get it to work. For it to work with its full power you should probably drive it with 12V, utilizing its full range.
About the fan:
As jsotola already stated in the comments, the red wire of the fan is not connected to the circuit. If you look at your breadboard you will see that the blue and red lines are interrupted in the middle of the breadboard. This means, that the rails are disconnected here (divided into the left and the right part of the breadboard). Move the red fan cable to the left of the red LED jumper wire. Then you should be connected.

Oh boy, now I feel dumb. Seems like I never used so much space on the breadboard before to notice this. I'll try your suggestions and hope that the fogger has enough power at 5V - or else get higher voltage power source for it! Thank you so much for the quick help

In regards with your schematics

Are you sure you want your stuff working only when both D3 and D5 are up? Because it seems to me you connected them in series, so if one transistor is down, nothing's gonna work.

check the power rating of the ultrasonic transducer, if you get your power source from the computer USB port, you will get at best about 2.2W from the 5V pin. It may turn out that it may be insufficient to produce any notable effect from the transducer with that, especially if you have the fan powered too.

Most modern PC USB ports (except maybe a laptop running very conservative power settings) will merrily provide at least 5V1A despite lack of negotiation. Even if it runs through the regulator (though I think USB power in usually doesn't), that gives us 800mA - 50mA for the arduino = 750mA * 5V = 3.75W. The transducer is rated 1.5W and the fan is likely 1.0-1.5W, so there's plenty of headroom.

You're right, I meant to put them in parallel and completely messed up the second circuit drawing in my panicky state yesterday! Thanks for pointing this out.


text:
ESP8266 NodeMCU Lolin V3 and using Firebase to update its software OTA
I want to update software OTA on multiple of my nodemcu devices that are currently sending data to my firebase database. I found this tutorial (https://medium.com/firebase-developers/over-the-air-arduino-firmware-updates-using-firebase-part-1-3e874ad9f93e) for ESP32 and tried adapting it to work with one of my nodemcu however it writes no binary and "gives up". I am not sure why/how to modify the code further. I am currently running core 2.7.4 as upgrading does not allow me to upload code to my nodemcu.
I have attached part of my code below and output I get in serial monitor. I am able to connect to wifi, change my "updatebit", and send data to firebase so there is no issue there.

#include <Firebase.h>
#include <FirebaseArduino.h>
#include <FirebaseCloudMessaging.h>
#include <FirebaseError.h>
#include <FirebaseHttpClient.h>
#include <FirebaseObject.h>

//#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>

#include "Updater.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"

#define FIREBASE_HOST "..."
#define FIREBASE_AUTH "..."

#define FIRMWARE_URL \
"http://..."
HTTPClient http;

void setup() {
....
}
void loop() {
  if(updatebit==1){
    updateFirmware();
  } else {
  }
}

void updateFirmware() {
  // Start pulling down the firmware binary.

  http.begin(FIRMWARE_URL);
  int httpCode = http.GET();
  if (httpCode <= 0) {
    Serial.printf("HTTP failed, error: %s\n",
       http.errorToString(httpCode).c_str());
    return;
  }
  // Check that we have enough space for the new binary.
  int contentLen = http.getSize();
  Serial.printf("Content-Length: %d\n", contentLen);
  bool canBegin = Update.begin(contentLen);
  if (!canBegin) {
    Serial.println("Not enough space to begin OTA");
    return;
  }
  // Write the HTTP stream to the Update library.
  WiFiClient* client = http.getStreamPtr();
  size_t written = Update.writeStream(*client);
  Serial.printf("OTA: %d/%d bytes written.\n", written, contentLen);
  if (written != contentLen) {
    Serial.println("Wrote partial binary. Giving up."); //content length printed in serial
monitor is 42 but 0/42 bytes are written and it says "Wrote partial binary. Giving up."
    return;
  }
  if (!Update.end()) {
    Serial.println("Error from Update.end(): " +
      String(Update.getError()));
    return;
  }
  if (Update.isFinished()) {
    Firebase.setInt("updatebit",0);
    Serial.println("Update successfully completed. Rebooting.");
    // This line is specific to the ESP32 platform:
    ESP.restart();
  } else {
    Serial.println("Error from Update.isFinished(): " +
      String(Update.getError()));
    return;
  }
}

If I add the "s" in http changing from
#define FIRMWARE_URL \
"http://..."

to
#define FIRMWARE_URL \
"https://..."

I get "HTTP failed, error: connection failed" in serial monitor

only httpCode 200 is sucess

Yes i guess so?

you have if (httpCode <= 0) {

ah I should change it too httpCode!=200

adding the s in http makes no difference now as I never get 200

yes that is the true problem. solve that

I am really not sure how. I tried only running the sketch from the link below under the heading "Fingerprints - secure but annoying" but I still don`t get HTTP_CODE_OK.
https://maakbaas.com/esp8266-iot-framework/logs/https-requests/

and what error code do you get?

-1, connection failed. I am using this tool to create the fingerprint (https://www.grc.com/fingerprints.htm). I am using ("96 84 07 DF 0B 1C F6 58 14 DF D7 33 35 57 51 9B 15 4D 8C E7"). My host is just like in example https://api.github.com

you need http.begin(client, FIRMWARE_URL); where client is  WiFiClientSecure. (what error code did you get before you changed http to https?)


text:
Is there a need to put a delay in the main loop
Im a complete beginner. Generally speaking, is there any need at all to have a delay in the main loop()? Im not used to writing infinite loops
Is it correct to say that the delay() command is simply helpful for tutorials (i.e turn light on, wait, turn light off. wow!) but normally speaking a delay would not be helpful, and instead we are just rapidly infinitely polling our connected devices. Is that correct?
(I get that in some specialized cases it might be helpful to put a delay in the loop. Im not asking about the specialized cases.)

Like anything, it depends--I'm not sure there's a "normally speaking" given the wide range of Arduino applications. "delay" is perfectly suitable when there are no other time-sensitive processes (interrupts, background tasks, etc.) happening during the delay.

@DaveNewton  If you want to post an answer please do so. Comments under questions are for clarifying the question, which this comment does not do. If you make a proper answer you may well get credit for it, and people can comment on the accuracy or otherwise of your answer.

There is no absolute need for any Arduino program to use delay()
The blink without delay sketch that is included in the standard sketch examples is the canonical illustration of this.
In most cases you don't need to poll your sensors thousands of times a second. It is good discipline to only poll sensors as often as makes sense for the specific application. Sometimes this might be once every five minutes. For example an ambient temperature sensor. In those cases there is nothing to be gained be polling a thousand times a second. To do so wastes resources and is a poor habit that could be troublesome for battery powered applications.
For example, the use of millis() for timing allows you to effectively poll several peripherals each at different intervals, perhaps averaging some readings to reduce noise, perhaps also updating a display at other intervals that suit human perception.
For long running battery powered applications it is likely that you will benefit from finding out about putting the microcontroller to sleep using sleep() or deepSleep() and using interrupts to wake it. A real time clock (RTC) or the watchdog timer interrupt can perhaps be used to schedule your sensor readings and other actions, perhaps in conjunction with millis().
For very simple programs that don't need precise timings. delay() can be the simplest and clearest way to manage timings.

+1 Good answer. I would add that sometimes one needs to rate limit specific actions, which rely on hardware or other code, to avoid problems (like buffer overruns, filling up the Serial buffer, which then blocks execution),...). Using delay() is one easy way to do it, though by far not the best.

In many cases, rate-limiting the polling is only useful if you sleep. On a mains-powered application, polling thousands of times a second is fine, and is easier.

No, there is no need to use delay() at all. Unlike the sleep() or deepSleep() commands, delay does not save power or do anything else that's special.
The standard implementation of delay is just doing a busy-wait until the time has elapsed, something like:
void delay(int ms)
{
    int end = millis() + ms;
    while (millis() < end) {}; // do nothing
}

So for the CPU itself, this just wastes CPU cycles, it doesn't save any power.


text:
Need help with Bluetooth component for TinyCircuit
I am looking to get some assistance to learn how to program the Bluetooth module for TinyCircuits.
I am currently using the UARTPassThrough.ino example to try and learn BlueNRG's functions.
I see that in the UARTPassThrough.ino code, the loop() function calls the aci_loop() function in UART.ino. I'm not too sure what are ACI commands. What does the aci_loop() function do for its Bluetooth functionality?
void aci_loop() {
  HCI_Process();
  ble_connection_state = connected;
  if (set_connectable) {
    setConnectable();
    set_connectable = 0;
  }
  if (HCI_Queue_Empty()) {
    //Enter_LP_Sleep_Mode();
  }
}

Also, when I try to use the aci_gap_start_general_discovery_proc() function, the value returned is 255. What does the value 255 mean?
Main .ino file:
void setup() {
  SerialMonitorInterface.begin(9600);
  while (!SerialMonitorInterface); //This line will block until a serial monitor is opened with TinyScreen+!
  BLEsetup();
}

void loop() {
  aci_loop(); //Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short.
  BLEdiscoverymode();
}

Added own function to UART.ino file:
void BLEdiscoverymode() {
  uint8_t output;
  output = aci_gap_start_general_discovery_proc(0x4000, 0x4000, 0x00, 0x01);
  PRINTF("--Bluetooth function return value: %d--\n", output);
}

Output from Serial Monitor
03:44:21.572 -> --Bluetooth function return value: 255--
03:44:23.774 -> --Bluetooth function return value: 255--
03:44:25.989 -> --Bluetooth function return value: 255--
03:44:28.208 -> --Bluetooth function return value: 255--
03:44:30.407 -> --Bluetooth function return value: 255--

Help would be much appreciated.
My TinyCircuit uses these components:

TINYZERO PROCESSOR BOARD

TINYSCREEN OLED TINYSHIELD

BLUETOOTH LOW ENERGY TINYSHIELD (ST)
(Uses the BlueNRG-MS chipset with the SPBTLE-RF module)

Lithium Ion Polymer battery - 3.7V 150MAH

Why are you asking the same question again? If you have new information you should edit it into the original question instead of asking a new one

You may be better off asking the authors through a github issue since they are far more likely to know what this does than we do (since this is some unknown third party board and library and not something many other Arduino users even know exists, let alone have a clue how to use).


text:
ATtiny85 giving multiple wake from IDLE if INT0 held low
Desired behaviour:

Go to IDLE sleep mode.
When PB2 (blue trace) goes low wake up and give a 10 ms HIGH on PB1 pulling a pull-up low (yellow trace on Figure 1).
Go to 1.

What I get:

Figure 1. (1) The input triggers, (2) the CPU wakes from sleep, (3) the CPU goes back to sleep and wakes up repeatedly until (9) the input goes high again.
I want one 10 ms low pulse and then go back to sleep until the next negative going edge on PB2 regardless of how long PB2 is held low.
Even though I set MCUCR to falling edge of INT0 the device seems to wake repeatedly when PB2 is held low. My code below attempts to solve this by switching to rising edge interrupt if the input is low and falling edge interrupt if the input is high. The result is shown in Figure 1.
void setup(){
  ADCSRA &= ~_BV(ADEN);               // ADC off. ADC not used.
  pinMode(reedPin, INPUT);
}

void loop(){
  system_sleep();                     // Go straigth to sleep.
  // ---- System woken up by interrupt. ---------
  if (!digitalRead(reedPin)) {        // Check that input is low.
    pinMode(outPin, OUTPUT);          // Enable output.
    digitalWrite(outPin, HIGH);       // Pull motor sensor input low by MOSFET.
    delay(pulseTime);                 // Pulse time.
    digitalWrite(outPin, LOW);        // Pulse off.
  }
}

// From http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/
void system_sleep() {
  MCUCR |= _BV(ISC01);                    // Required for both rising and falling edge interrupt.
  if(digitalRead(reedPin)) {              // Input is high so set interrupt for detecting low.
    MCUCR &= ~_BV(ISC00);                 // Clear MCUCR bit 0 for falling edge interrupt.
  } else {                                // Input is low so set interrupt for detecting high.
    MCUCR |= _BV(ISC00);                  // Set MCUCR bit 0 for rising edge interrupt.
  }
  GIMSK |= _BV(INT0);                     // Enable Pin Change Interrupts
  set_sleep_mode(SLEEP_MODE_IDLE);        // Leaves the clock running for elapsedMillis.
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep
  // ZZZZZZZZZZZzzzzzzzzzzz .......
  // ------- CPU is now asleep and awaiting interrupt. ----------------------
  cli();                                  // Disable interrupts on wake up.
  sleep_disable();                        // Clear SE bit.
}

ISR(INT0_vect){                           // Wake up.
  GIMSK = 0;                              // Disable external interrupts. (Only need one to wake up.)
}

Can anyone guide me through this?
Many thanks.

@jsotola, no joy. Still the same.

here is some sleep code you could try ... no idea if it actually works (i have no way to test) ... https://github.com/DaveCalaway/ATtiny/blob/master/Examples/AT85_sleep_interrupt/AT85_sleep_interrupt.ino

The library in that code simplifies things a lot. I've got it now triggering on falling edge and again on rising. I'll keep digging. Thanks.

section 9.2 may help (page 49) ... https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

The Arduino core configures a timer to deliver a periodic interrupt.
This interrupt is used to implement millis(), delay(), etc. Your
code assumes the external interrupt is the only one the microcontroller
can receive. I guess the timer interrupts may be the cause of the
observed behavior.
I suggest configuring the interrupt for falling edges and leaving it
always on. The ISR can take care of starting the pulse, and setting a
flag to let the main loop know the pulse is active. The main loop can
then stop the pulse when it has been on for long enough:
volatile bool pulse_active;     // whether the pulse is on
volatile uint32_t pulse_start;  // time when it started

ISR(INT0_vect) {
    // Start the pulse.
    digitalWrite(outPin, HIGH);
    pulse_active = true;
    pulse_start = millis();
}

void loop() {
    // End the pulse if it's time to do so.
    if (pulse_active && millis() - pulse_start >= pulseTime) {
        digitalWrite(outPin, LOW);
        pulse_active = false;
    }

    // Take a little nap.
    sleep_mode();
}

Note that the little nap in the code above can be interrupted by either
the external interrupt or the timer interrupt.


text:
Can I use AREF to supply a circuit, when in internal mode? (Nano)
When analogReference(INTERNAL) is set (1.1V), can I use the AREF pin to supply a circuit? E.g. like this:
AREF —— R1 —— button switch —— A4 —— R2 —— GND

where A4 is configured as analog input (forming a resistive voltage divider with R1 and R2).
Is this safe to do? The reference manual talks about having a capacitator on AREF, or only capacitive loads.
You can find the datasheet here: see 23.2 (page 205), Figure 23-1 (block circuit diagram, page 206), and section 23.5.2 (Page 211).

probably not ... what does the reference manual say about current sourcing capacity of the pin? ... please provide a link to the reference manual ... add link to the question ... do not add in a comment

@jsotola: It says “Note that VREF is a high impedance source, and only a capacitive load should be connected in a system.”

Unfortunately the ref manual does not mention sourcing capacities.

Why do you want to do that? I would consider such usage of VREF out of spec. If you really need to do that you can use an opamp to build a voltage follower. That will preserve the voltage and also handle the direct current needed. Though I'm not sure what that does to the stability of the reference voltage (not an expert in analog signal handling)

Why not use the 5V output?

@chrisl: would you promote your comment as answer, please? Add Gils question. Good enough as answer. :-)


text:
Nodemcu Lolin v3 Timeout error
I am getting the Arduino console error "the selected serial port serial.serialutil.SerialTimeoutException: Write timeout
does not exist or your board is not connected". I recently upgraded to esp8266 version 3.0.2 and cannot upload a simple blink led sketch to my board. Does anyone know how to resolve this? I would like to be able to use the latest core although downgrading to version 2.7.4 allows me to upload sometimes.
Arduino Code:
#define LED_BUILTIN 2

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                // but actually the LED is on; this is because
                                // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Console output:
Arduino: 1.8.13 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"
Executable segment sizes:
ICACHE : 32768           - flash instruction cache
IROM   : 231724          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 26793   / 32768 - code in IRAM          (IRAM_ATTR, ISRs...)
DATA   : 1496  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 876   ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 25608 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 260889 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27980 bytes (34%) of dynamic memory, leaving 53940 bytes for local variables. Maximum is 81920 bytes.
esptool.py v3.0
Serial port COM4
Connecting...
Traceback (most recent call last):
File "C:\Users\ab\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2/tools/upload.py", line 66, in
esptool.main(cmdline)

File "C:/Users/ab/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool\esptool.py", line 3552, in main
esp.connect(args.before, args.connect_attempts)

File "C:/Users/ab/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool\esptool.py", line 519, in connect
last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)

File "C:/Users/ab/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool\esptool.py", line 499, in _connect_attempt
self.sync()

File "C:/Users/ab/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool\esptool.py", line 438, in sync
timeout=SYNC_TIMEOUT)

File "C:/Users/ab/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool\esptool.py", line 376, in command
self.write(pkt)

File "C:/Users/ab/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool\esptool.py", line 339, in write
self._port.write(buf)

File "C:/Users/ab/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/pyserial\serial\serialwin32.py", line 325, in write
raise SerialTimeoutException('Write timeout')

serial.serialutil.SerialTimeoutException: Write timeout
the selected serial port serial.serialutil.SerialTimeoutException: Write timeout
does not exist or your board is not connected
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Are you sure that you have the correct COM port selected?

Yes, since downgrading the core to 2.7.4 allows me to upload.


text:
rfid module not working (rc522)
i brought a rfid module which is rc 522 but when i upload the code it is not reading the card  even when i upload example code i have returned it 2 times and got it replaced but the same problem may i know the solution
#include "SPI.h" // SPI library
#include "MFRC522.h" // RFID library (https://github.com/miguelbalboa/rfid)

const int pinRST = 9;
const int pinSDA = 10;

MFRC522 mfrc522(pinSDA, pinRST); // Set up mfrc522 on the Arduino

void setup() {
  SPI.begin(); // open SPI connection
  mfrc522.PCD_Init(); // Initialize Proximity Coupling Device (PCD)
  Serial.begin(9600); // open serial connection
}

void loop() {
  if (mfrc522.PICC_IsNewCardPresent()) { // (true, if RFID tag/card is present ) PICC = Proximity Integrated Circuit Card
    if(mfrc522.PICC_ReadCardSerial()) { // true, if RFID tag/card was read
      Serial.print("RFID TAG ID:");
      for (byte i = 0; i < mfrc522.uid.size; ++i) { // read id (in parts)
        Serial.print(mfrc522.uid.uidByte[i], HEX); // print id as hex values
        Serial.print(" "); // add space between hex blocks to increase readability
      }
      Serial.println(); // Print out of id is complete.
    }
  }
}

this is one of the many codes i used

What gets printed? You have a lot of serial prints there, can you please edit the question and share what you see?

i just see nothing

Possibly you have wired it incorrectly. Without seeing any photos, links to the module you bought, or schematics, it is very hard, if not impossible, to say.

SDA                           10,
SCK                            13,
MOSI                      11,
MISO                     12,
IRQ                          UNUSED,
GND                      GND,
RST                                   9,
3.3V                                 3.3V,  i dont feel they are wrong


text:
Keyboard.h not found on Arduino nano
I am trying to use keyboard on my Arduino nano, but i get this error:
'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

As per the answer in Keyboard.h not found, I tried change the board to Arduino Leonardo, even though the script gets compiled it doesn't get uploaded (keeps on saying uploading for a long time).
This is the code I use:
#include <Keyboard.h>
void setup() {
  Keyboard.begin();
}
void loop() {
}

If you also change the board itself, it'll work. The Uno has different MCU and it doesn't have physical USB interface in it.

As said above you cannot use the Keyboard library on the Nano. It just doesn't have the necessary hardware

To convert the comments into an answer:
You cannot (!) use the Keyboard library on the Arduino Uno/Nano/Mini. It needs a native USB interface to configure it as a HID device, but the Uno/Nano/Mini all use the Atmega328p, which doesn't have a native USB interface. These Arduinos use an additional chip on the board which acts as USB-UART-bridge.
You can compile the code for the Leonardo, because it has a native USB interface. But you cannot (!) upload code, which is compiled for the Leonardo, to an Uno/Nano/Mini. Its a completely different chip.
What to do now: Get an Arduino board which has a native USB interface, for example the Leonardo or the Micro.


text:
ESP32 Classic Bluetooth Set Password
I am using ESP32 classic Bluetooth Feature for data transfer. I am using the SerialToSerialBT example. I am able to scan and discover the Bluetooth device from my smartphone. But the pairing is without any security/passcode. It simply pairs immediately. How to make the pairing using PIN/Passkey entry?
Hardware: ESP32 DEV Kit V1
Software Arduino IDE
Code:
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  delay(5000);
  Serial.println("Starting..");
  SerialBT.begin("MyESP32"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");

}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

the BluetoothSerial header files has bool setPin(const char *pin); (PIN as personal identification number)


text:
LCD displays more digits than serial monitor
I am doing a BPM monitoring system. The serial monitor displays accurate BPM values ranging from 60 to 100+. But my LCD display is not accurate. Example, on the serial monitor, my bpm is about 67, but on the LCD it displays 676. What do I need to do to fix it?
PulseSensorPlayground pulseSensor; // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

void setup() {
    Serial.begin(9600); // For Serial Monitor
    lcd.begin();
    lcd.backlight();

    // Configure the PulseSensor object, by assigning our variables to it.
    pulseSensor.analogInput(PulseWire);
    pulseSensor.blinkOnPulse(LED13); //auto-magically blink Arduino's LED with heartbeat.
    pulseSensor.setThreshold(Threshold);

    // Double-check the "pulseSensor" object was created and "began" seeing a signal.
    if (pulseSensor.begin()) {
        Serial.println("We created a pulseSensor Object !"); //This prints one time at Arduino power-up, or on Arduino reset.
    }
}

void loop() {
    int myBPM = pulseSensor.getBeatsPerMinute(); // Calls function on our pulseSensor object that returns BPM as an "int".
    // "myBPM" hold this BPM value now.
    if (pulseSensor.sawStartOfBeat()) { // Constantly test to see if "a beat happened".
        Serial.println("♥ A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
        Serial.print("BPM: "); // Print phrase "BPM: "
        Serial.println(myBPM); // Print the value inside of myBPM.

        lcd.setCursor(0,0);
        lcd.print("BPM: "); // Print phrase "BPM: "
        lcd.print(myBPM);
    }
    delay(50); // considered best practice in a simple sketch.
}

I fixed the formatting and the indentation for you. You should always keep the indentation right (the Arduino IDE even has an autoformatting function for this), because it helps you spot structural errors.

What happens if you add lcd.print("    "); after the other LCD code to fill the space behind the BPM with spaces? I suspect that the additional 6 comes from a former display call and just is retained because you don't overwrite it. Adding the spaces will make sure, that the space after the BPM is always empty.

I am thinking the same thing. And if I am understanding this correctly, you mean adding lcd.print("    "); after lcd.print("BPM: ");? I already did sir but the former display still keeps displaying.

@AccelLim: You need to insert lcd.print("  "); after lcd.print(myBPM);. You want the last digit of the number to be removed.

If you use the standard LCD lib from Arduino you could clear the Screen with lcd.clear() instead of simply position the cursor to (0,0) with lcd.setCursor(0,0). Link: https://www.arduino.cc/en/Reference/LiquidCrystalClear

As PMF said: Insert it after lcd.print(myBPM);. Then please report back

its working fine now. Thank you very much :)

The additional "6" seems to come from one of the first values. Maybe the first value printed is just a rogue value and all the following values are correct.
The point is that this rogue value may take one more character on the display than the other (correct) values. And when you just move the cursor and print again the previously displayed text is only changed if it is overwritten by the new text. The correct values are shorter, so the last digit of the rogue value is not overwritten. This of course doesn't happen with Serial, since Serial doesn't print to the same space again and again (like a LCD does with its limited space).
What to do now: You can use lcd.clear() to remove all text from the display before printing new values. Though this can lead to a noticeable flicker on the display. Often it is better to just make sure to overwrite all possible leftover text with spaces via lcd.print(" ");. Insert this after the lcd.print(myBPM) (since you want to remove all leftover digits after that). In this case you only have 1 leftover digit, so one space is enough. To be sure that this won't happen again when for whatever reason you get more than one leftover digit you can use multiple spaces (lcd.print("    ");).