text:
ESP32 PWM with extended resolution doesn't work as expected
I have attached an RGB-LED to three output lines of the ESP32 and I'm trying to fade all colors independently. Since it didn't work with my code, I went back to the basic ESP32 ledcWrite_RGB sample program, extracts copied for reference:
uint8_t ledR = 25;
uint8_t ledG = 33;
uint8_t ledB = 32;

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

  ledcAttachPin(ledR, 1); // assign RGB led pins to channels
  ledcAttachPin(ledG, 2);
  ledcAttachPin(ledB, 3);

  // Initialize channels
  // channels 0-15, resolution 1-16 bits, freq limits depend on resolution
  // ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);
  ledcSetup(1, 12000, 8); // 12 kHz PWM, 8-bit resolution
  ledcSetup(2, 12000, 8);
  ledcSetup(3, 12000, 8);
}
void loop()
{
  Serial.println("Send all LEDs a 255 and wait 2 seconds.");
  ledcWrite(1, 255);
  ledcWrite(2, 255);
  ledcWrite(3, 255);
  delay(2000);

  // ... run some color fade tests ...
}

With this code, everything works as expected. Now according to the documentation the resolution (third parameter of ledcSetup) can be changed up to 20 bits. If I change the resolution to 12 bits (and increase the max value to 12^2 - 1 = 4095) it still works fine. But if I change it to 13 bits, all of a sudden, nothing happens any more. The LED stays dark all the time.
Now I know that a PWM resolution of 12 or 13 bits isn't particularly useful for driving a LED, but still I would like to know why this isn't working.
Edit I just found that the kernel dumps this message when it's not working:
[     3][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
E (31) ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution. div_param=208
[    33][E][esp32-hal-ledc.c:75] ledcSetup(): ledc setup failed!
E (37) ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution. div_param=208
[    50][E][esp32-hal-ledc.c:75] ledcSetup(): ledc setup failed!
E (54) ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution. div_param=208
[    67][E][esp32-hal-ledc.c:75] ledcSetup(): ledc setup failed!

Does this mean that there's a limit imposed by the product of frequency and resolution?

it can only turn the pin on and off so many times per second. When you use more bits, it uses more ons/offs, heh; that's what a bit is. Think of a human analogy; you can recite more 5 digit codes in one minute than you can 10 digit codes...  There's a tradeoff between resolution and frequency as you've noticed. There's nothing you can do to "fix" this hardware limit.

and if you don't have audio feedback issues with your hardware (the leds or driver buzzing), there's little human advantages to anything over about 4khz, and as you increase frequency, your switching costs will rise, generating more heat and increasing the effects of any capacitance in the wiring or strips, which (ironically) further reduces the practical resolution (number of dim levels achievable).

@dandavis I'm seeing that it has to do with the internal oscillator required, but the frequency of the (theoretical) PWM signal doesn't change when the resolution is increased (only the duty cycle can be set more accurately). What I'm actually looking for is a documentation about this. How is the limit of frequency x resolution defined?

If you use, say, 16b instead of 8b, or go slower in freq, then the equivalent "010" will become "001100" or "000111000" as needed, so while the apparent output won't change, the internals that encode the duty cycle will. You can look at the freq of a 2 bit or the rez of a max freq to get an idea of the over-all bandwidth available. iirc, it's about 80mbps/2^bits.


text:
Arduino Pro Mini doesn't automatically reset
I have an issue with my Arduino pro mini.
Yesterday, I uploaded a sketch a few times on the pro mini, with an FTDI adapter, and everything worked fine. Today I'm trying to re-upload a sketch, but now, for some obscure reasons, my Arduino pro mini doesn't want to reset itself. I need to manually reset it. Since it is embedded in s case, I can't do that if I want to upload a sketch.
EDIT: I managed to make some tests, and it would seem that the DTR pin on the mini doesn't work anymore. When I short the DTR PIN to GND, the mini doesn't reset itself. I believe that could be a reason. But why? And how? It was working a day ago.
I soldered the FTDI like that, and it didn't work several times.
(At the moment I left it unsoldered because I don't want to solder it yet):

Can anyone complete my intuition?
Thanks in advance.

Did you solder it? Or did you use a "female" connector soldered? Please [edit] your question and add this information, optimally with an actual picture of your assembly.

I edited the question, the connection is soldered, but it doesn't work

You have nothing else connected to the board besides the FTDI adapter? You have selected the "Arduino Pro or Pro Mini" from the standard AVR based Arduino support and not something else (e.g. minicore)?

No, I have only my FTDI, and I selected "Arduino Pro or Pro Mini" from the standard AVR based Arduino.

"When I short the DTR PIN to GND, the mini doesn't reset itself" if you are doing that with the FTDI adapter still soldered you are either trying doing what the FTDI adapter is already doing (which is of no use) or you are trying to short out DTR by connecting it to ground while FTDI is trying to drive it high (not really a good idea either).

Well it is of use, to determine if the FTDI or the mini is the problem. I'm not sure if the FTDI isn't sending the signlal, or if the signal isn't reaching the internal Atmega328. And what do you mean by "connecting it to ground while FTDI is trying to drive it high". To reset the arduino, the DTR pin must go low (to GND) ? Or did I badly understood this thread ? : Mini reset issue

I'm not sure how to go about this without it turning into a lengthy discussion. At any given moment FTDI chip is internally connecting DTR to either 5V (in your case) or GND. What happens if you jumper DTR to the same thing the FTDI chip is connecting it to? Nothing. It was already connected.  What happens if you connect it to the opposite thing? A large amount of current flows as you attempt to connect 5V and GND to each other through the FTDI's DTR pin. If you did this previously it's not unlikely that this is why your auto-reset no longer works. It is not diagnostically useful.

Well the FTDI chip is supposed to be connected to the DTR pin, but I need to make sure it still does (it's a cheap FTDI board btw). If that's wrong do you have any idea of how I could diagnose my board ? Or even solve the problem maybe ? And no I tried to GND it that after the auto reset wasn't working anymore, it's not the problem

Let us continue this discussion in chat.

Given your last message in the chat it sounds like this will not be clarified and resolved. If that's the case you should probably delete the question so it is not floating around in the system forever like that.

Is this is an actual photo of your FTDI and mini? I can't tell whether the FTDI pins are soldered to the mini. If not, I would guess that the problem is an unreliable electrical connection at one of the pins, and look there for the problem.
If it helps, this is what I use for my embedded devices. The FTDI is in the USB-A connector. The embedded end is just a female connector that pushes onto the 6 pins on the board. This cable supplies +5v; there are also ones that supply 3.3v.

Thanks for your answer, the connection is soldered.

In that case, I'd check the resistance of the solder joints including trying to wiggle them; then trying to narrow it down by swapping FTDI boards if you have another; and likewise, swapping the mini board.

Thanks for your answer, the connection is soldered. I don't think it's a connection problem, I verified the soldered connection, tried to bend them, there's nothing to do.
Thanks for you picture, it seems I have the same connections. Really don't know where to look ...

The reset pulse issued by the USB-Serial adapter via the DTR line may be of low amplitude (3.3V). This is occasionally too low for the Pro Mini reset function.  Sometimes, it helps to solder a 47k resistor across the reset button contacts, lowering the initial DC level of the reset input. This applies to 5V/16MHz and 3.3V/8MHz versions of the Pro Mini.

source: Stack Exchange

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

sort: votes


text:
Unable to acquire AP network IP and DNS on a ESP32 MCU
I'm getting the following error on serial output (verbose mode) when my smart device , ESP32 S3 tries to connect over WIFI to the Access point (AP). The SSID is TheScientist
Below is the serial output:
Connecting to TheScientist
[  1064][D][WiFiGeneric.cpp:929] _eventCallback(): Arduino Event: 0 - WIFI_READY
[  1098][V][WiFiGeneric.cpp:338] _arduino_event_cb(): STA Started
[  1099][V][WiFiGeneric.cpp:97] set_esp_interface_ip(): Configuring Station static IP: 0.0.0.0, MASK: 0.0.0.0, GW: 0.0.0.0
[  1099][D][WiFiGeneric.cpp:929] _eventCallback(): Arduino Event: 2 - STA_START
.......[  4750][V][WiFiGeneric.cpp:360] _arduino_event_cb(): STA Disconnected: SSID: TheScientist, BSSID: 3c:cd:5d:a7:f1:13, Reason: 15
[  4750][D][WiFiGeneric.cpp:929] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[  4758][W][WiFiGeneric.cpp:950] _eventCallback(): Reason: 15 - 4WAY_HANDSHAKE_TIMEOUT

Although the verbose debug serial output shows a
Reason: 15 - 4WAY_HANDSHAKE_TIMEOUT
in reality the timeout is due to usage of a password longer than the 32 char allowed on ESP32 MCUs . In summary, any ESP32 MCU to successfully connect to any WIFI Access Point , the Network password must not exceed 32 char long.

it also can't be shorter than 8 chars...

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


text:
DS18B20 temperature sensor crashes MbedOS on Arduino Nano RP2040?
I'm trying to use the DS18B20 sensor with Arduino Nano RP2040.
No matter which library I use, it seems to crash MbedOS as soon as the driver is initialized. I get 4 short and 4 long flashes of the orange LED, which as I found somewhere indicates a crash.
I was trying with DS18B20 library (https://github.com/matmunk/DS18B20) as well as the DallasTemperature one (https://github.com/milesburton/Arduino-Temperature-Control-Library).
At first I suspected that the issue is in my code as it interfaces with multiple different devices (EEPROM, SHT30, etc.) and this may interfere with 1-wire interface, but if I upload just the examples from these libraries the effect is the same.
I know that the Arduino is OK, as it can run other code absolutely fine, and the sensor is OK as well since I can read it with RaspberryPi.
Does anyone have similar problems? Is there some workaround?

It's difficult to say much without being able to recreate the problem or at least inspect the code and potentially wiring as well. For certain values of "similar" you may get responses that aren't not exactly answers as they may not have anything to do with the problem you're actually having. You can edit your question to include more details.

@timemage As I said, the problem emerges even with example code from linked libraries. The wiring is not particularly interesting, just a 4.7k resistor between Vcc and data lines. I know that wiring is OK since I can connect RPi instead of Arduino and have readouts. I also suspect that incorrect wiring would prevent communication with the sensor but not outright crash the OS.

Yeah, sorry, I did miss that. If I stumble cross a DS18B20 I'll at least try it with an RPI pico (the closest thing I have to what you're using). But, I don't know how likely I am to find one or when. I can at least cancel out the -1. Hopefully someone will recreate the problem and have something useful to say about it long before I'm able to.

add a lot of debugging code to your program ...determine where it hangs

@jsotola I found out it hangs in DS18B20 constructor for the DS18B20 library and in begin() method for DallasTemperature.

Test Setup
I have wired an DS18B20+ to an RPI Pico and used a 4.7K pullup. The RPI Pico is a stand-in for your board. It uses the  arduino:mbed_rp2040:pico core rather than the arduino:mbed_nano:nanorp2040connect that yours does. However, I'm guessing they're similar enough.
Test result
When I attempt the to use the matmonk DS18B20 library you mention, I see similar pattern on the RPI Pico's onboard LED. Just the attempt to construct the object was sufficient to crash. Construction fairly directly defers to the OneWire library. So, I tried the OneWire library's own example for reading the DS18B20 (with some appropriate modification) and it crashes in the same manner. This lead to searching for and finding issues for the RP2040 on the OneWire github page resulting in (among others) this find. The answer mentions OneWireNG.
The OneWireNG DallasTemperature example works
Or rather, it's the library that works. But, this is the relevant example for it that works for me. I made the following modifications.

All Serial usages were replaced with SerialUSB because I am using the USB connection for the Serial Monitor (well, a terminal emulator).

I changed the one wire object to use GPIO28 because it was conveniently close to the pins where I was picking up 3.3V and GND: OneWire  ds(28);

It seems plausible that you could change the #include <DS18B20.h> usages in the two libraries you cited to #include "OneWireNg_CurrentPlatform.h" and find that they then work fine. I have not tried this yet. If that's of particular interest to you I will try it and update(Update below). However, this stock example from the OneWireNG library is not crashing and is printing temperatures that rise and fall expected when I manipulate the temperature of the sensor.
OneWireNg with Matmunk and DallasTemperature libraries
In general
It turns out that it is unnecessary to modify libraries that were using the original OneWire, not even just changing the #include. Despite the OneWireNg example using "OneWireNg_CurrentPlatform.h" it also provides a OneWire.h header. It is sufficient to have OneWireNg installed but the original OneWire library must uninstalled (or moved out of the libraries directory) so as not to confuse the build process into selecting the original library based on the header name over the OneWireNg library. The OneWireNg authors may have used the OneWireNg specific header in the examples to avoid this problem wit their examples when both libraries were installed. They've gone out of their way to make it compatible with the original, but below are reports of specific tests with the two libraries mentioned anyway.
Matmunk library with OneWireNg
With OneWireNg installed and the original OneWire not installed, the Multiple example form the matmunk library worked with the same minor modifications mentioned before (I used pin 28 rather than 2 and SerialUSB rather than Serial). In case your wondering the only reason why I switched from testing Single to Multiple is the latter didn't require that I first find and enter my part's address. That example is printing temperatures that rise and fall in accordance with manipulation of the sensor.
DallasTemperature with OneWireNg
Likewise I tested with the Multiple example from the DallasTemperature library. Same kind of modifications to the example. I changed ONE_WIRE_BUS to 28 for my setup. I changed Serial to SerialUSB. And runs normally and prints expected temperatures under manipulation of the sensor.

Thanks so much! Using OneWireNg instead of OneWire indeed solves the problem. I looked for problems in DallasTemperature and DS18B20 libraries, but somehow it did not occur to me to look into the OneWire itself.

It didn't work for me.
I removed the OneWire library and installed OneWireNg.
I installed Mathias Munk Hanson's DS18B20 library and loaded the sketch found at this address: https://github.com/matmunk/DS18B20/blob/1.0.0/examples/Multiple/Multiple.ino Arduino Nano RP2040 crashes as soon as the sketch is loaded.

@MauroPagano, I see your comment was converted from an answer. I point that out mostly for the benefit for everyone (most people) that can't see that. It seems like it's the same content that I'd put under the "Matmunk library with OneWireNg" header. So maybe that's why it was converted to a comment. If you were trying to address that part of my answer, then I'm not entirely sure what to say except perhaps if you found a difference it was in the version of OneWireNg, which for me was almost certainly the 0.12.2 I'd linked.


text:
how do I wire a 2nd Adafruit TMP117 board to my Adafruit Metro by I2C?
I want to connect two TMP117 boards to one Metro (ie. Arduino).
(the first, addressed at 48 the 2nd at 49.)
Should 2nd board's 4 wires simply attach (ie. solder) in parallel to 1st board's 4 wires?
(ie. 3.3v, gnd, SCL, SDA)
background...
I want to read temperatures from two boards at once, in near real time and write to Windows file.

yes ...........

You are correct almost. Connection in parallel is correct however you cannot read both at once, the bus supports talking to only device at a time. You will need to read one then the other. I do not know for sure if it is possible to get them to synchronize conversion but I think not.


text:
Program Arduino using Eclipse on Mac in 2022
I started experimenting with Arduino a few weeks ago. My host is Mac OS and I have used Eclipse for many years, so my first choice is to use an Eclipse plugin. The most recent discussion of the Eclipse/Arduino solution is years old and I have been unable to get anything working.
The marketplace has "Sloeber, the Arduino Plugin for Eclipse". When I try to install this I get these errors:
An error occurred while collecting items to be installed
session context was:(profile=_Applications_Eclipse_embedcpp-2022-12_Eclipse.app_Contents_Eclipse, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,org.eclipse.nebula.cwt,1.1.0.202212191054
No repository found containing: osgi.bundle,org.eclipse.nebula.widgets.cdatetime,1.5.0.202212191054
No repository found containing: osgi.bundle,org.eclipse.nebula.widgets.oscilloscope,1.4.0.202212191054
No repository found containing: org.eclipse.update.feature,org.eclipse.nebula.widgets.oscilloscope.feature,1.4.0.202212191054
No repository found containing: osgi.bundle,org.eclipse.nebula.widgets.oscilloscope.source,1.4.0.202212191054

for Sloeber problem go to "Install New Software" and change the url for nebula repository to https (or http? I think you need both http and https url for successful install of that component.)

Thanks, I copied the nebula repository to a 'http' url and installed "Nebula Release all Widgets and Examples" manually from there. Then I installed Sloeber (trusting the certificate) and that seems to have worked. So it is now installed and I can try to figure out how to use it. This was a simple solution and much appreciated.

It is working!! I created a new sketch, implemented a version of 'Hello, World' for Eclipse and got this output in the console:
setup
Eclipse Hello

I am using the Sloeber plugin now. The installation required changing the nebula repository to url to "http" in the "Install New Software" as described by Juraj in the first comment.
However, connecting from Sloeber to the Arduino was unreliable at first. Following Juraj's suggestion, I've been deleting and rebuilding the serial connection after each upload or power cycle to form a connection reliably.
If I forget to reset the serial connection it sometimes forms a partial connection where the host can see serial output from the Arduino but not be able to send commands back.

what Arduino do you use? for Arduinos with native USB a reset always disconnects USB, then the bootloader connects, then the sketch connects. It is better to disconnect Serial Monitor before upload for Arduinos with native USB.

It is an Elegoo Mega 2560 R3. I've been doing software for a long time but this is my first attempt to work with hardware.

so a Mega shouldn't have this problem. I use Sloeber 5 years now and I never had problems with Mega


text:
Using a limit switch to stop a stepper motor
I am building a machine with a moving bed, the bed moves forward and backward. I need to incorporate a limit switch at the two ends that makes sure the motors stop at the two extremes. I have 2 stepper motors controlled by TB6600 motor drivers, I am trying to start with 1 limit switch (SS-5Gl2) and advance from there.
My 1st question is how I get the code to stop steppers if limit switch is closed?
// Define stepper motor connections and steps per revolution:
#define dirPin1 2
#define stepPin1 3
#define dirPin2 5
#define stepPin2 6
#define stepsPerRevolution 200 // We may need to change 200 to 1600 to get more precise control, i.e. decimals verse integers

#define Lim1 8

int direction = 0;
int remainder = 0;
long travel = 0;
long revolutions = 0;

void setup() {

  // Declare pins as output:
  pinMode(stepPin1, OUTPUT);
  pinMode(dirPin1, OUTPUT);
  pinMode(stepPin2, OUTPUT);
  pinMode(dirPin2, OUTPUT);

  pinMode(Lim1, OUTPUT);

 //Desired travel distance, in mm !!!! set here !!!!
travel = 1;
//Desired direction !!!! set here !!!! move die in(ccw) = 1, back out(cw) = 0 !!!!
//direction = 0; did not work, need boolean?

// Set the spinning direction counterclockwise (die in) or clockwise (die out):
//if(direction = 1) digitalWrite(dirPin, HIGH);
//if(direction = 0) digitalWrite(dirPin, LOW);

//set direction manually, uncomment HIGH for die in, LOW for die back out
digitalWrite(dirPin1, LOW);
digitalWrite(dirPin2, LOW);
//digitalWrite(dirPin, LOW);

digitalWrite(Lim1, OFF) //

//calculating number of revolutions based on mm input. Does not yet account for partial revs - variable is truncated, integers are default. Would need another loop to handle the remainder
//6.659 (microns) constant is based on 1.25mm acutator screw pitch, and ratio in gearbox
revolutions = 1000.00*travel/6.659;
//attempt to output the stored value to PC for debug purposes

Serial.print("revolutions = ");
Serial.print(revolutions,4);
}

void loop() {

   // Spin the stepper motor X revolutions fast, speed (delay) apparently limited by voltage. 42v should go faster?
   //Required a nested loop because integers on the UNO are limited to ~32k
  for (int i = 0; i < revolutions; i++) {

   if (digitalRead(Lim1 == OFF)){}

   else {
      for (int j = 0; j < stepsPerRevolution; j++) {
       // These four lines result in 1 revolution:
      digitalWrite(stepPin1, HIGH);
      digitalWrite(stepPin2, HIGH);
      delayMicroseconds(250);
      digitalWrite(stepPin1, LOW);
      digitalWrite(stepPin2, LOW);
      delayMicroseconds(250);
      }
  }
  }

   while(1){}

}

// These four lines result in 1 revolution: ... that should say // These six lines result in 1 step:

You are doing every step manually directly via digitalWrite(), so the principal would be to read the limit switch pin on every iteration of the inner for loop in an if statement. What to do in that if statement depends on what you want to do on hitting the limit switch. Currently you have an infinite empty loop after your motor code. So if you want to stop forever in that case you can create another infinite loop there. So something like this:
...
for (int j = 0; j < stepsPerRevolution; j++) {
   if(!digitalRead(Lim1)){
       while(true);
   }
   // These four lines result in 1 revolution:
   digitalWrite(stepPin1, HIGH);
   digitalWrite(stepPin2, HIGH);
   delayMicroseconds(250);
   digitalWrite(stepPin1, LOW);
   digitalWrite(stepPin2, LOW);
   delayMicroseconds(250);
}

Note that this assumes that you have connected the limit switch to ground and use the digital pin with a pullup resistor.

But you have 2 other problems with your limit switch code:

You set your limit switch pin Lim1 as output, though to read a switch you need to configure it as input. And if you want to use a pullup resistor (in contrast to a pulldown resistor) you can activate the internal pullup in the same step:
 pinMode(Lim1, INPUT_PULLUP);

When reading the limit switch inside the outer for loop you write
 if (digitalRead(Lim1 == OFF)){}

You are doing the equality comparison between OFF and the pin number and not between OFF and the return value of digitalRead(). You need to place the parentheses here correctly:
 if(digitalRead(Lim1) == OFF){}

Above I used the equivalent form
 if(!digitalRead(Lim1)){}

with the negation operator !

Besides that you are missing the Serial.begin() with the baudrate, that you want to use, in setup().

Thank you for your answer, I am really new and completely confused.

// Define stepper motor connections and steps per revolution:
#define dirPin1 5
#define stepPin1 2
#define dirPin2 6
#define stepPin2 3
#define stepsPerRevolution 200 // We may need to change 200 to 1600 to
get more precise control, i.e. decimals verse integers'
#define limPin1 8
#define CW 0x1
#define CCW 0x0

int remainder = 0;
long travel = 0;
long revolutions = 0;
bool homed = false;

void setup() {

  // Declare pins as output:
  pinMode(stepPin1, OUTPUT);
  pinMode(dirPin1, OUTPUT);
  pinMode(stepPin2, OUTPUT);
  pinMode(dirPin2, OUTPUT);
  pinMode(limPin1, INPUT_PULLUP);

//Desired direction !!!! set here !!!! move die in(ccw) = 1, back
out(cw) = 0 !!!!
//direction = 0; did not work, need boolean?

// Set the spinning direction counterclockwise (die in) or clockwise
(die out):
//if(direction = 1) digitalWrite(dirPin, HIGH);
//if(direction = 0) digitalWrite(dirPin, LOW);

//set direction manually, uncomment HIGH for die in, LOW for die back
out
digitalWrite(dirPin1, LOW);
digitalWrite(dirPin2, LOW);

//attempt to output the stored value to PC for debug purposes
Serial.begin(9600);
Serial.println("test");
}

//main routine
void loop() {
Homing();
}

void Homing() {
     // Spin the stepper motor X revolutions fast, speed (delay)
     apparently limited by voltage. 42v should go faster?
     //Required a nested loop because integers on the UNO are limited to
     ~32k
     if (homed == false)
  {
    //calculating number of revolutions based on mm input. Does not yet
   account for partial revs - variable is truncated, integers are
default.
   Would need another loop to handle the remainder
        //6.659 (microns) constant is based on 1.25mm acutator screw
pitch,
    and ratio in gearbox
        float travel = 2.0;
        float revolutions = 1000.00*travel/6.659;
    int totalStepsOut = revolutions * stepsPerRevolution;
    Serial.print("revolutions = ");
    Serial.println(revolutions,4);
    digitalWrite(dirPin1, CCW);
    digitalWrite(dirPin2, CCW);
    for (int j = 0; j < totalStepsOut; j++) {
      bool limState = digitalRead(limPin1);
      if (limState == false)
      {
        //Limit is triggered
        HomingReturn();
        break;
    }
    else
    {
        //Limit is not triggered
        // These six lines result in 1 revolution:
      digitalWrite(stepPin1, HIGH);
      digitalWrite(stepPin2, HIGH);
      delayMicroseconds(250);
      digitalWrite(stepPin1, LOW);
      digitalWrite(stepPin2, LOW);
      delayMicroseconds(250);
      }
    }
   }
   //Add stuff here to do whatever you want after homing
   Serial.println("Homed");
}

void HomingReturn()
{
  //set direction for reverse
  digitalWrite(dirPin1, CW);
  digitalWrite(dirPin2, CW);
  Serial.println("Reversing");
  //Desired travel distance, in mm !!!! set here !!!!
  float travel = 0.1;
  float revolutions = 1000.00*travel/6.659;
  int totalStepsOut = revolutions * stepsPerRevolution;
  for (int j = 0; j < totalStepsOut; j++) {
    //drive back
    digitalWrite(stepPin1, HIGH);
    digitalWrite(stepPin2, HIGH);
    delayMicroseconds(250);
    digitalWrite(stepPin1, LOW);
    digitalWrite(stepPin2, LOW);
    delayMicroseconds(250);
      }
      homed = true;
     Serial.println("Done");
   }

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.


text:
Detecting the difference between a deep sleep wake signal and a manual wake button press
When my ESP8266 wakes itself from sleep (i.e. D0 sends wake signal), I want it to do something different to when I manually wake the device with the reset button.
I have the RST and D0 pins connected, so that the device can wake itself from sleep. I also have a button connected to RST which pulls to ground when pressed, so that I can wake the device manually on demand.
How do I differentiate between the device being awoken by itself, or manually by the button press?
I tried using system_get_rst_info/getResetInfoPtr to determine what action has awoken the device, but it seems that if I reset manually after the device went to sleep, the REASON_DEEP_SLEEP_AWAKE reason is returned since that value is based on how the device went to sleep/reset rather than how it woke up.
Disclaimer: I already found a solution (answer below), but it's more complex than I wanted, so I am posting this question to see if anyone else can think of a simpler solution.

if you use ntp, you could cache the expected wakeup time in rtc ram or even spiffs and compare the stored value with the established time upon reboot. If you happen to manually reset right on schedule it would mis-report, but that should be rare and you have a work-around if such precision is needed.

Oh that's a good idea!

was thinking; if you subtract millis() from the net time upon reboot, you can get a really good idea of the utc time of reset by eliminating the wifi connection time. With logging you might also realize it takes say 10ms to reset, and add that into your formula to get it even more accurate/precise.

I came up with two solutions (3 if you count the combo), both involve connecting the manual reset button to another pin on the MCU (so I can check if it's still pressed when starting).
Solution 1: Generate a reset pulse
The problem with the manual reset button is that it's only on release that it resets, since while the RST pin is held low, the MCU won't start.
To solve this, I used a positive edge monostable circuit to pulse the RST pin when the manual reset button is pressed down.
That way, I can hold the button down and the device starts. In the setup() function, I can check if the button is still pressed.
Solution 2: Use an RC delay circuit
I also considered that I could simply wake the device on button release, and use a debounce cap (very slow discharge) to see if the button was pressed in the last second (by checking the pin on the MCU to which the charged cap is connected).
Solution 3: A combination of 1 & 2
Combining 1 and 2, allowed me to wake the device on button down, and use the debounce cap to see if the button was pressed recently (in the last second).


text:
Xbox 360 controller commands to Uno-compatible board via USB module
I am trying to receive commands on a third-party Arduino-Uno-compatible board from an Xbox 360 controller via an M5Stack USB module but I am not seeing the behavior I expect (see heading Expected Behavior).
To be clear, I am talking about reading commands from an Xbox controller using an Arduino, not emulating an Xbox controller using an Arduino.
Hardware

A Bluno Nano. (An Arduino-Uno-compatible board in a Nano-like form factor with program uploading and serial communication via a matching Bluetooth USB dongle. However, I am using a wired USB connection to my PC instead.) The board is recognized as an Uno by the Arduino IDE. The same board has worked as expected for other projects.

An M5Stack USB module (with a MAX3421E chip), which is  primarily meant to be compatible with an M5Stack microcontroller module. Either way, the USB module communicates using SPI.

A wireless Xbox 360 controller, but I connected it to the USB module using a USB cable that plugs in to the controller with a seemingly proprietary connector. Should be in working order.

I am not using an Xbox 360 wireless receiver to connect to the Xbox controller, nor do I want to connect to it wirelessly.
Wiring

I connected the GND (#1/3/5), +5V (#28, VBUS), SCLK (#11, GPIO18), MISO (#9, GPIO19) and MOSI (#7, GPIO23) pins of the USB module to the corresponding pins of the Bluno Nano: GND, +5V, SCK (D13), MISO (D12), and MOSI (D11).

I tried pulling the USB module's EN pin (#6) up to +5V in attempt to make sure it's enabled.

I tried pulling the SS pin up/down. I have not tried connecting it to pins D10 or D8, both of which I have seen as SS pins on Arduino Nano pinout diagrams.

I have not tried connecting the INT pin (#2, GPIO35) to anything.

I believe these are the only useful pins on the USB module.

USB module schematic
The useful pinout is in the bottom right corner.

Attempts

Unplugging and re-plugging the Bluno Nano's USB cable with my PC.

Pressing the Bluno Nano's reset button.

Unplugging and re-plugging the Xbox controller's USB cable with the USB module, or vice versa (that is, starting with it unplugged).

Pressing or holding the center "X" button or other buttons on the controller, presumably to turn it on or hopefully enter some kind of connection-setup mode, maybe.

Using a wired USB mouse instead of the Xbox controller.

Trying various combinations of the above in different orders.

I have ensured that the USB module is receiving power (even though it seems to have no power indicator LED) by using it's additional 5V and GND pins to successfully drive a digital input pin on the Bluno Nano high or low.
I have ensured that the Xbox controller is receiving power because the center "X" button lights up upon being pressed.
Software

Windows 11

Arduino IDE 2.0

USB_Host_Shield_2.0 version 1.6.2 (latest) installed through the library manager. Note that this library seems to be primarily designed for a particular USB host shield, but I see it being used with other USB host shields, including in my USB module's documentation. There is a library for Xbox 360 therein which works with a USB controller or a wireless controller, with example sketches for each.

Either example sketch uploads successfully without errors (although the programmer sometimes gets stuck not responding, whereupon I disconnect, let it error out, reconnect, and retry uploading).
In the Arduino IDE Serial Monitor, I set the baud rate to 115200 to match that specified in either example sketch.
Expected behavior
To be printed in the Serial Monitor (<...> is how I indicate my comments):
XBOX USB Library Started  <instead of "OSC did not start" followed by unresponsiveness to controller button presses, etc.>
<Xbox controller commands upon controls/buttons being pressed, e.g., "LeftHatX: ...">

Attempts

The USB Host Shield 2.0 documentation says about use with an Xbox 360 controller: "To use it via USB use the XBOXUSB library or to use it wirelessly use the XBOXRECV library. Note that a Wireless controller can NOT be used via USB!". It is unclear to me if my wired USB connection to my wireless controller calls for the XBOXUSB or XBOXRECV library, so I tried both libraries (tried both accompanying example sketches) to no avail.

I tried removing the following code snippets one-by-one and in some combinations, to no avail. The program uploads successfully in every case.
#include <SPI.h>

#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif

XBOXUSB Xbox(&Usb);
<...along with the code in `loop()` that requires it to be defined.>

if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nXBOX USB Library Started"));

The program failed here because Usb.Init() == -1.

I tried changing
if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nXBOX USB Library Started"));

to
while (Usb.Init() == -1);
Serial.print(F("\r\nXBOX USB Library Started"));

in attempt to keep trying to enable the connection (while I pressed the controller's "X" and other buttons) to no avail.

I also tried changing the same snippet to
Usb.Init()

in attempt to ignore the -1 return value (which I presume represents an error) and proceed anyway, to no avail.

Using an older version of the USB Host Shield 2.0 library.

Setting the following in the library's settings.h, with no apparent change in output.
/* Set this to 1 to activate serial debugging */
#define ENABLE_UHS_DEBUGGING 1

Setting the following in XBOXUSB.cpp and XBOXRECV.cpp, with no apparent change in output.
#define EXTRADEBUG // Uncomment to get even more debugging data
#define PRINTREPORT // Uncomment to print the report send by the Xbox 360 Controller

For trying with a wired USB mouse instead of the Xbox controller, I used USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino, attempted additionally with some of the above modifications, to no avail in any case, leading me to believe that the problem is not specific to the Xbox controller or library for it.
I have also tried the example sketch from the M5Stack USB module documentation after removing parts that would be specific to an M5Stack microcontroller module and unecessary for testing purposes. This was no different.

I am completely lost on what else to try hardware- and software-wise. I have tried searching many questions. I suspect that I'm missing something simple and obvious, or that my setup can't work for whatever reason.
Thank you

Update
After getting past the Usb.Init() problem by connecting the USB module's SS pin, the connection with the Xbox controller still wasn't being established and commands were not being received.

UPDATE: I've gotten past Usb.Init() successfully by connecting the SS pin to D10 (either with XBOXUSB or XBOXRECV) but the main code in loop() that is now reached is not working either because Xbox.Xbox360Connected == 0. This is the case even if I check Xbox.Xbox360Connected after a delay or after pressing buttons on the Xbox controller.

UPDATE: I've gotten exactly the same thing working but with the wired USB mouse and USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino.

I tried pulling the SS pin up/down - I was about to suggest that the SS pin is usually controlled by software, and that asserting it usually signals the start of a "transaction" - however the protocol defines that.

You are certain that the controller also sends its data via the USB and not just wireless?

@NickGammon I think you're right about the SS pin. Regarding whether the USB is for data and not solely for power, I can't be 100% sure, but I suspect that it is for data because the USB cable's proprietary connector with the Xbox 360 controller has a sort of 'cuff' around it that seems to very intentionally block the "Connect" button on the back of the controller from being pressed; the USB cable appears to preclude a wireless connection by design. How do I test it -- try to play using the controller in a Faraday cage? :D

Well, if you had a USB analyser (which aren't cheap) you could see if the data being sent changes as you press buttons.

@NickGammon Thanks! I might consider trying a different controller and/or cable, buying an Xbox 360 wireless receiver, or using a joystick instead of the controller.

I discovered that, upon plugging the USB cable into my PC rather than the USB module, the controller appears as "Xbox 360 Wireless Controller via Play & Charge Kit" under "Xbox 360 Peripherals" in the Device Manager.
Turns out, "Play & Charge Kit" refers to the controller's removable rechargeable battery and the USB cable.
According to this, "The play and charge kit only carries power. It does not carry the data required to connect a controller to a PC."


text:
Arduino does not connect to MQTT local broker
I have an Arduino Mega with Ethernet connected to a router by cable. Also I have a PC connected to the router (by Wifi) where also the local MQTT broker is installed (mosquitto). Althought the Arduino Ethernet connection seems ok, the MQTT connection does not: I get the return code -2
This is the full code, there are several functions but the MQTT init is the one that fails:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h> // Librería para MQTT

byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x3A, 0xC4 };
byte ip[] = { 192, 168, 1, 100 };
byte gateway[] = { 192, 168, 1, 2 };
byte subnet[] = { 255, 255, 255, 0 };

EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

const char *MQTT_BROKER_ADRESS = "192.168.1.101";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "mqttx_7c0a0ed3";

void SuscribeMqtt()
{
    mqttClient.subscribe("hello/world");
}

void OnMqttReceived(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Received on ");
    Serial.print(topic);
    Serial.print(": ");
    String content = "";
    for (size_t i = 0; i < length; i++)
    {
        content.concat((char)payload[i]);
    }
    Serial.print(content);
    Serial.println();
}

void InitMqtt()
{
    mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT);
    mqttClient.setCallback(OnMqttReceived);
}

void ConnectMqtt()
{
    Serial.print("Starting MQTT connection...");
    if (mqttClient.connect(MQTT_CLIENT_NAME))
    {
        SuscribeMqtt();
        mqttClient.publish("connected","hello/world");
    }
    else
    {
        Serial.print("Failed MQTT connection, rc=");
        Serial.print(mqttClient.state());
        Serial.println(" try again in 5 seconds");
        delay(5000);
    }
}

void HandleMqtt()
{
    if (!mqttClient.connected())
    {
        ConnectMqtt();
    }
    mqttClient.loop();
}

void CheckLinkStatus() {

  auto link = Ethernet.linkStatus();

  Serial.print("Link status: ");

  switch (link) {
    case Unknown:
      Serial.println("Unknown");
      break;
    case LinkON:
      Serial.println("ON");
      break;
    case LinkOFF:
      Serial.println("OFF");
      break;
  }
  delay(1000);
}

void setup() {

  // You can use Ethernet.init(pin) to configure the CS pin
  //Ethernet.init(10);  // Most Arduino shields

  Serial.begin(9600);

  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

  delay(1500);

  InitMqtt();

}

// put your main code here, to run repeatedly:
void loop() {

  CheckLinkStatus();

  HandleMqtt();

}

I have done ping from the PC IP (192.168.1.101) to the Arduino IP (192.168.1.100) and it is ok. What could be the issue?.

What is in the logs of the MQTT broker?

@StarCat how do I check the log file? I am not able to find it.

@StarCat maybe I can't find it because I am executing mosquitto as a service? also I am not able to modify conf file

is the port open on Firewall?

Maybe find an app you can run on a different computer or your phone to verify that you can connect into your mosquito server on the PC.

I finally found the issue! As @Juraj pointed out, there was some problem with mosquitto which was blocked by the windows 10 firewall. I am sure of this because when I executed mosquito with permissions and properly using the cmd, a windows firewall windows popped up and then I unblocked it and after that Arduino was able to connect

@timemage I have installed MQTT Explorer on the PC, it is very useful to check the traffic. Thanks!

@StarCat I was finally able to run mosquitto correctly, also I am writing now the log into a text file. In my answer I have put all the code. Thanks.

The issue was coming from mosquitto local broker, which was being blocked by windows 10 firewall. When I executed mosquitto with the correct permissions on its folder (read and write for "all users") and with correct mosquitto configuration file, the following window popped up and I clicked on to allow both private and public connections:

I also use the following batch file to load mosquitto and it works all the time:
cd "C:\Program Files\mosquitto"
del mosquitto.log
mosquitto -v -c mosquitto.conf

This is the content of my mosquitto configuration file:
listener 1883
allow_anonymous true
log_type error
log_type warning
log_type notice
log_type information
connection_messages true
log_timestamp true
log_dest file C:\Program Files\mosquitto\mosquitto.log

Now I am able to use MQTT from Arduino connected to a router.

With a bit of research you can see that return code two is:
2    Connection refused: client identifier not allowed by server.
My guess is that you forgot to add the login details in the code, or the code fails because the client ID is not a c-string. Try something like this (replace with appropriate values):
    if (client.connect(clientId.c_str(), mqttUsername, mqttPassword)){

It was a firewall isse when executing mosquitto, but thanks anyway!


text:
Best way to get JSON from struct vector class
I have a vector which consist of a struct, see below:
struct FileInformation
  {
    String name;
    size_t filesize;
  };

std::vector<FileInformation> FileInformations;

How do I get JSON out of it the easiest way?

for cycle and print?

Using ArduinoJson:
DynamicJsonDocument doc(2048);
for (const FileInformation& item : FileInformations) {
  JsonObject& obj = doc.createNestedObject();
  obj["name"] = item.name;
  obj["filesize"] = item.filesize;
}
serializeJson(doc, Serial);

This will produce a JSON document that looks like this:
[
  {"name": "command.com", "filesize": 1234},
  {"name": "config.sys", "filesize": 2345},
  {"name": "autoexec.bat", "filesize": 3456}
]

Please read the tutorial for more information.


text:
DHT11 temperature and humidity sensor Code
I’ve got a question about this code I’ve attached please- would it be correct to read it like this:
After defining the variable temperature and humidity and assigning measurement_timestamp to millis(), an if loop first checks if millis - measurement_timestamp < 3000 unsigned long (which doesn’t make sense to me) and then if a reading is read, it = true?
Is this correct please?
Code:
static bool measure_environment( float *temperature, float *humidity )
{
  static unsigned long measurement_timestamp = millis( );

  /* Measure once every four seconds. */
  if( millis( ) - measurement_timestamp > 3000ul )
  {
    if( dht_sensor.measure( temperature, humidity ) == true )
    {
      measurement_timestamp = millis( );
      return( true );
    }
  }

  return( false );
}

Please post code as text, not as images (and certainly not as screenshot-taken-with-a-cellphone)

Apologies, thought images were acceptable on site

code in an image cannot be copied and tested ... also, some people here cannot view images

That makes sense, apologies

The code makes sense to me.
The comment, "/* Measure once every four seconds. */" is inaccurate. It will measure when the time since last measurement is greater than 3 seconds.
Because of "static unsigned long measurement_timestamp = millis( );", measurement_timestamp will NOT be initialized to millis() every time the function is called - it will only be initialized once for lifetime of the run. Otherwise, it would never cause a measurement since "if( millis( ) - measurement_timestamp > 3000ul )" would never be true.
The first call sets measurement_timestamp= to millis() [the current timer value] and the function returns "false"
When called 3.001 sec later, "if( millis( ) - measurement_timestamp > 3000ul )" is true - a measurement is taken, "measurement_timestamp" is updated to the current millis() and the function returns "true".
It returns "false" for the next 3 seconds and then "true" and so on.
see https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c
and How can I handle the millis() rollover?
Hope it helps.

Hi, thank you for making things clearer- so I was wrong. What does the 3000ul mean please?

@Tom 3000ul is a literal constant and they have variable types just like other variables. In this case, the constant 3000 is designated as an unsigned long [ul] type, as is appropriate, see https://cplusplus.com/doc/tutorial/constants/ To put it simply, millis() measures in millisecond and when the difference between the last timestamp and the current millis() count is > 3000 milliseconds (3 seconds) go do your thing :)


text:
Detecting an approximate angle/location of a light source using phototransistors
Note: [I am approximately two weeks into learning Arduino and hence have little experience with utilizing Phototransistors.]
My plan revolves around placing four identical Phototransisors which are spread approximately 10cm apart on a breadboard in a V configuration. Each Phototransistor is connected to one of the "analog In" pins respectively (I am using the Arduino Uno), with the long leg attached to 5V while the short leg is connected to ground via a 220-ohm resistor. In the center of this setup, I plan to place a servo that will face the direction of the light beam emitted from a flashlight.
(I want this project to be allocated in a dark room with any external lighting calibrated),The idea is to identify the phototransistor which has the highest analog value (closest to the light source). With this information, I want to be able to compute an approximate angle of the light source to then write it on my servo.
You can find the attached datasheets below (All the components are from the Arduino starter kit :) ).
[Datasheet for the Phototransistor]
[Datasheet for the Servo motor]
[Datasheet for the 220 ohm Resistor]
Here is what I have so far for the code:
#include <Servo.h>
Servo myServo;
const int transistorPin1 = A0;
const int transistorPin2 = A1;
const int transistorPin3 = A2;
const int transistorPin4 = A3;
void setup() {
  myServo.attach (10);
  Serial.begin (9600);
}
void loop() {
 int reading1 = analogRead (transistorPin1);
 int reading2 = analogRead (transistorPin2);
 int reading3 = analogRead (transistorPin3);
 int reading4 = analogRead (transistorPin4);
 int reading [] = {reading1, reading2, reading3, reading4}; //This is an array for the values:
 int maxReading = reading [0], maxSensor = 1; // I am setting the maximum reading and the Phototransistor that corresponds to it:
   for (int i = 1; i <= 3; i++){ //Setting this for the other three phototransistors:
     if (reading[i] > maxReading){
     maxReading = reading[i];
     maxSensor = i + 1;
     }
   }
}

So my question is: What is the most efficient way to compute the angle of the lighsource? And is my method even relevant for this application?
Thank you for taking you time to read this! Your support will be very much appreciated!
Edit 1:
Explanation of my hardware setup:
This project is allocated on two connected breadboards which means that there are no moving parts. The only moving component is the one single servo that is fixed in position.
The phototransistors, (as mentioned above), are placed in a V configuration which too are stationary. The servo is allocated behind the phototransistors and can only rotate 180 degrees. (You can see the attached illustrations below, I apologize in advance for any technical errors or my horrible drawings.)

As you can visualize on the first image, I do not plan on a complete 360 degree rotation which probably complicates the issue further. Any suggestions on how I can code this would be greatly appreciated! Once again thank you for your time.

See this  https://www.instructables.com/Arduino-Sunflower-an-Electronic-Sundancer/ or google for Arduino Sunflower or solar tracker for more examples. I believe the most effective ones have the light sensors mounted on the panel which the servos moves. The servos continues to position the panel until all photosensors deliver exactly the same measurement. Can you say something about the physical construction of your project.

Thank you for your reply, the link you sent me was quite helpful however I have noticed that the project mentioned utilizes two servo motors for a full 360 degrees rotation (covering all three x, y, and z coordinates). I, unfortunately, have to resort to utilizing one servo motor which only provides me with 180 degrees. Another issue I have noticed is that the light sensors are not stationary and are rotated by a robot "chassis". Due to my project being entirely based on breadboards the method used will not work for my application. I hope my edit will clarify the idea a little bit better.

Your efforts are well thought out, but make use of others before you, e.g., https://arduino.stackexchange.com/questions/36597/detecting-the-light-source-location-using-multiple-photoresistors (yes, I know they are LDRs, but the task is similar). Also, make some effort to calibrate your phototransistors, even if it is just to check the levels when a light source is 6 inches away - they need to be as identical as possible and fixed 220s may not be good enough. Finally, remember you only have 1 ADC and are switching channels, check that you are obeying speed limits, so to speak. // end two cents.

Just to get started, I'd probably look at the photo transistor which gives the strongest light value and use that as the current starting point (0,60,120 or 180 degrees assuming that is how the transistors have been distributed around the servo) then look at the adjacent transistors to work out how much, and in which direction, to bias the result away from the starting point. The result is sent to the servo. Repeat every X ms.  Your hardware configuration is unusual in that all the sensors are static. Most tracking type projects move the sensors towards the light source.

This really helped! It took me a while but I managed to get it to kind of work. The servo is jittery but I am satisfied. I will attach a youtube URL later today to show my results. Thank you guys for replying!

In principle, you only need two phototransistors, a left and a right one. The quotient of the values from the ad-convertor (Vleft/Vright) will tell you where to find the light source. If the quotient > 1 then the light source is at the left side, if the quotient < 1 then the light source is at the right side. Most likely there is no lineair relationship between the quotient and the angular position of the light source. This relationship depends on the housing and the positioning of the diodes in their housings. One possibility is to do a calibration beforehand and use a lookup table during operation. The calibration could be done by placing the breadboard with photodiodes on a rotating platform with the light source in front and then record Vleft and Vright at various angles (in 1 degree steps?) of the platform in relation to the light source.
If two photoresistors don't give you the required precision and/or range, you can use more photoresistors and use the pair which is best 'looking' in the direction of the light source.

The value could also be subtracted, and the sign gives the direction. In any case both light sensors should have the same sensitivity.


text:
Is it possible to sample a signal with a sample frequency of 48kHz?
I want to have a filter with a 48kHz sample frequency, is that possible using the esp32?
Here is a part of the code i developed using the arduino IDE:
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);

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);

  /*
     The following function allows you to obtain more information
     related to the state of network and IoT Cloud connection and errors
     the higher number the more granular information you’ll get.
     The default is 0 (only errors).
     Maximum is 4
  */
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
}

void loop() {
  ArduinoCloud.update();
  Pot = (float) analogRead(PinADC_sensor_35) * 3.3 / 4096;

  float t = micros()/1.0e6;
  float xn = sin(2*pi*200*t);

  delayMicroseconds(21);
  //delay(0.020833);

  float H1yn = (1/1)*(H1yn1*(-0.2025) + 0.6*xn + 0*xn1);
  xn1 =xn;
  H1yn1 = H1yn;

  float H2yn = (1/1)*(H2yn1*(-0.2025) + 1*H1yn + 0.3*xn2 );
  xn2 = H1yn;
  H2yn1 = H2yn;

  float H4yn = (1/1)*(H4yn1*(-0.9097) + 1*H2yn - 1*xn4);
  xn4 = H2yn;

  SinalQuadrado = SinalQuadrado + H4yn*H4yn;
  k++;

Does the delayMicroseconds(21) have any effect? I stop the program for 21 mili seconds (48kHz) to sample a signal.

You need to take into account all the other things going on in the loop as well, not just the delay. Your sampling frequency will probably be nowhere near 48kHz.

@StarCat How can i certify that i have a sampling frequency of 48kHz?

@jsotola Perhaps that's a bad computation in my part. But even if i use the delay function with 21milliseconds how can i be assured the signal will be sampled at 48kHz?

21us is the correct value for 48kHz, but the rest of your code also takes time to execute. I would guess that the Arduino cloud update is taking significantly longer (since network action mostly takes some time to execute). Probably you need interrupts to do this, though I'm not sure how this works with an ESP32


text:
How do I control the rotation of my servo?
#include <Servo.h> // servo library
Servo servo;
int trigPin = 5;
int echoPin = 6;
int servoPin = 7;
int led= 10;
long duration, dist, average;
long aver[3];   //array for average

void setup() {
  Serial.begin(9600);
  servo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  servo.write(0); // close cap on power on
  delay(100);
  servo.detach();
}

void measure() {
  digitalWrite(10,HIGH);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(15);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  dist = (duration/2) / 29.1; // obtain distance
}

void loop() {
  for (int i=0; i<=2; i++) {
  // average distance
  measure();
  aver[i] = dist;
  delay(10); // delay between measurements
  }

  dist = (aver[0]+aver[1]+aver[2])/3;

  if (dist < 50) { // Change distance as per your need
    servo.attach(servoPin);
    delay(1);
    servo.write(0);
    delay(3000);
    servo.write(150);
    delay(1000);
    servo.detach();
  }

  Serial.print(dist);
}

This is my first time in robotics. The servo is a Tower Pro SG90. It rotates over 360° and ony spins in one direction, but I want it to rotate for just about 90° and to rotate back to its original place after. This is the code I used. I'm making a trash bin where the lid automatically opens.

Please no code as image. copy and paste the code as text and format it correctly by selecting it in the question editor and clicking on the {} button

You should buy a normal servo, not a servo with continuous rotation. The Tower Pro SG5010, for example, should basically meet your needs.
But depending on the size of the bin and the mechanical control of the lid, you may want to choose a servo with greater actuating force.

A continuous rotation servo cannot be set to specific angles, only specific speeds. That's the point for continuous rotation servos.
So for your trash bin you should buy a normal servo (not continuous rotation). Such servo can be moved to specific angles between 0 and 180°.


text:
How to read analog sensor data with different timers in arduino
I have three analog sensors like voltage, temperature and pressure. I need to measure the voltage and temperature every 10 ms and I need to measure the pressure alone every 30 ms by using the timers in an Arduino.
How can I do this?

see the BlinkWithoutDelay example in Arduino IDE Examples menu

Have you seen this library? https://www.avdweb.nl/arduino/timing/virtualdelay

please add your code to your post

You only need one timer for this, which triggers every 10ms. Then read pressure only every third time. Or you can just use millis() or micros() depending on the rest of your code. Please share that code and explain what it should do

start with BlinkWithoutDelay as @Juraj mentioned ... do not delete any part of the code ... add a counter variable and set it to zero... go to the part of the program where the LED is updated ... add a function to measure voltage and temperature ... if the counter = 0, then measure pressure ... increment counter ... if the counter = 3, then set counter to zero ... when everything works  then change the delay variable from 500 to 10

". . . by using the timers in Arduino." You have multiple options depending on how deep you need to go for this exercise, listed here in order of increasing complexity. (1) The simple recording of the start time of an event and testing to see if its time slot has expired as in the already mentioned "blink without delay" sketch. (2) Using ready made timer libraries which can call user specified functions at defined intervals etc. and (3) direct configuration of hardware timers to trigger interrupt service routines, directly manipulate gpio pins etc.

May this help as starting point! Not tested
void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
}

unsigned long previousMillis1;
unsigned long previousMillis2;

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis1 >= 10) {
    int val1 = analogRead(A0);
    int val2 = analogRead(A1);
    Serial.print("Values from A0 and A1: ");
    Serial.print(val1);
    Serial.print(" ");
    Serial.println(val2);
    previousMillis1 = currentMillis;
  }

  if (currentMillis - previousMillis2 >= 30) {
    int val3 = analogRead(A2);
    Serial.print("Value from A2: ");
    Serial.println(val3);
    previousMillis2 = currentMillis;
  }
}

Thank you for your kind help Mr. Carlos Costa, but i am in need to use timer 1 or 2. without using millis i have to read the sensor data

Presumably it is a school project. Are you allowed to use ready made libraries or do you have to use direct configuration of the timer's hardware registers? Which Arduino are you using? In any case, the datasheet for the microcontroller is a good (but heavy going) start.


text:
Why 5V instead of 3V3?
I'm still quite new to electronics, so please forgive me if the answer is obvious.
I was wondering why virtually all the example circuits I find use the 5V power supply with resistors for all the components instead of the 3V3 power supply directly.
Even for the most simplistic "Blink" example, they use 5V pin and a 220 Ohm resistor to protect the LED instead of using the built-in 3.3V pin.
Yes, I know that in former times "everything" ran on 5V, but since we already have a lower voltage built-in, why not use it and reduce the number of components needed?
TIA for anyone who can solve this puzzle for me.
mav

Could you give an example of a circuit that uses 5V for the supply and resistors for all the components? My guess is that these resistors would still be necessary even if the circuit ran on 3.3V (possibly with different values). For example, the current through an LED should always be limited (by a resistor or otherwise), regardless of what voltage supply it's connected through. With a 3.3V supply you would still need a resistor although possibly a lower value.

The reason that you will still find many examples using 5V is that the "classic" Arduino Uno that many hobbyists start out with still runs on 5V.

First, even with 3.3V, an LED needs a resistor to limit the current through it. So, running with 3.3V doesn't solve that particular problem. Try Googling for "LED current limiting resistor".
Second, many Arduinos are designed to run using 5V. In many cases they have an input power jack which can accept a range of voltages and use a voltage regulator to convert it down to 5V,
Why not convert down to 3.3V you might ask? Well, the higher the voltage, the faster the processor can run, within its design limits. For example, the Atmega328P (which is in the Arduino Uno, and others) could only run at 13 MHz at 3.3V rather than 16 MHz.

... instead of using the built-in 3.3V pin

But that pin is only provided for convenience. You can't turn it on or off by a program.
The higher voltage (5V vs 3.3V) can be more convenient in some situations, for example switching motors on and off, or with other devices designed to work with 5V.
Motors or other high-power devices are typically turned on with MOSFET transistors. To be efficient, they need to fully turn on (have a low resistance between Source and Drain) and even so-called "logic level" MOSFETs typically require 5V to fully turn them on, rather than 3.3V. If you tried to control a motor with a 3.3V based board you would probably need extra components to turn the MOSFET on properly, so lowering the voltage could potentially add components, not reduce them.
On the other hand, many components these days are designed to work with 3.3V (or lower) so the choice of 5V is a bit of a compromise.

Also: USB, which is a very common way of powering devices these days, is 5V by default (extending to higher voltages on request with USB-C Power Delivery)

"For example, the Atmega328P could only run at 13 MHz at 3.3V rather than 16 MHz" is a  bit confusing, given that faster CPUs use lower voltages. But the reason is obviously not the same.

@PMF But, those faster CPUs that allow runtime frequency scaling generally also scale down voltage at lower frequencies, and most people who intentionally underclock their system do so so they can also under-volt it (and therefore save power).

@PMF - I am just quoting (extrapolating) from the figures in the datasheet. In the case of the Atmega328P, there are speed limits depending on voltage. And you can actually use less power by using a lower voltage, trading off speed for power savings. For various reasons, heat probably being the main one, modern high-speed CPUs would indeed use lower voltages, but they would be designed with that in mind.

@NickGammon That was what I was talking about. Higher voltages result in higher heat losses. And if you want to overclock a CPU, you typically have to increase the voltage (to make sure the electronics can properly switch from high to low) - and install a large heat sink.


text:
Arduino nano 33 BLE serial port not working with C# app
I use an Arduino Nano with some sensors and send data to a PC using the serial port. I just got a new Arduino Nano 33 BLE and tried the same code but its not working. So for testing I just wrote some simple test code on the Arduino Nano 33 BLE side:
void setup()
{
  Serial.begin(57600);
}

void loop()
{
  if (Serial.available())
  {
    char c = Serial.read();
    Serial.write(c);
  }
}

This just sends back whatever arrives through the COM port. Using the Arduino IDE Serial Monitor this works very well with the Arduino Nano 33 BLE.
I also made this very simple C# test code (Windows Forms app):
SerialPort serialPort = new SerialPort("COM17", 57600);
serialPort.ReadTimeout = 4000;
serialPort.WriteTimeout = 4000;
serialPort.Encoding = Encoding.ASCII;
serialPort.DataReceived += SerialPort_DataReceived;
serialPort.Open();
if (serialPort.IsOpen)
{
    Debug.Print("COM port open");
}

This C# code works perfect with my good old Arduino Nano but it doesn't work with the Arduino Nano 33 BLE. I have the COM port open message so the port exists and it is open, but then nothing else, no timeout, nothing.
I already lost one day trying out all sorts of combinations but it just doesn't work, my C# app can't communicate with the Arduino Nano 33 BLE. It looks like a serial port issue so I think I'll put it on hold for now...
EDIT:
The rest of my test code, for reference:
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        Debug.Print(serialPort.ReadExisting());
    }
    catch (Exception exception)
    {
        Debug.Print(exception.Message);
    }
}

private void buttonSend_Click(object sender, EventArgs e)
{
    try
    {
        serialPort.WriteLine("HELLO");
    }
    catch (Exception exception)
    {
        Debug.Print(exception.Message);
    }
}

I'm no expert in C#, but I don't see you actually sending anthing. And where is SerialPort_DataReceived defined?

I only copy/past the essential code... but its there... gonna edit the question and add them

Have you actually made sure (for example through a debug message), that serialPort.WriteLine("HELLO"); is actually executed? From what you described the problem is in your C# app, not in the Arduino part

Using the Arduino IDE Serial Monitor this works very well with the Arduino Nano 33 BLE ... that means that the data is getting to your computer ... what you do with the data after it gets there is off topic here

As I also mention in my question, this C# code works fine with an Arduino Nano, so I'm sure the C# code is working. It just doesn't work with the new Arduino Nano 33 BLE. Probably something to do with he mbed layer... but it doesn't make sense, working with Arduino IDE Serial Monitor and not with a C# compiled app. I also read somewhere that the Arduino Nano 33 BLE USB serial port is virtual, so it is a pure software serial port and not a hardware conversion from serial to USB.

This code should be working. Maybe dumb question: Are you sure the port is the right one? IIRC there are some pitfalls when using the DataReceived event [others say it's completely broken] Try using a thread for the receive end instead.

@PMF yes the code works and it is the correct port, I'm used to this kind of code and serial code exchange, multi threading, events etc. There is really an issue with the new Arduino Nano 33 BLE I guess... I was hoping that someone had seen this before and have some kind of workaround...

I noticed that a lot of line discipline and flow control settings were not made explicit in your C# code, so it made me wonder what they were by default.
In particular DtrEnable appears to be false by default and Handshake is None by default (which seems to be irrelevant). The other default amount to 8N1. The first part I found interesting because it seems more typical in serial APIs for DTR to be automatically asserted when a port is opened when you're not explicitly asking it to.  If I'm reading the .NET documentation correctly, it isn't for your application. The original Nano doesn't much care about DTR apart from a falling edge triggering reset. The board is happy to communicate with it solidly either asserted or not. The original Nano's DTR is only capacitively coupled to reset; there's not a way for the code running on the AVR to respond to DTR (unless you count resetting). That lead to a question about to what extent a Nano 33 BLE would care about DTR.
As it turns out the Nano BLE does care. If I deassert DTR in test with pyserial the board stops sending traffic back. I can write while it's deasserted and after asserting again some queued data arrives. A test environment with pyserial is just more immediately available to me; if needed and I get a chance I'll set up a .net/C# test and confirm with that, but I suspect that won't be necessary. Seeing that result, I searched and found this Arduino Forum post with a somewhat similar problem description. The OP replies in answer to their own post saying:

Problem sorted out. Arduino nano BLE requires DTR and RTS signals to
be On. Then it works like FDTI.

Disabling RTS had no effect during my tests with pyserial. I'm not sure why it would. Perhaps they just asserted it preemptively. Being entirely a virtual port RTS doesn't really make sense for flow control. DTR might arguably still makes more sense in this context; at the level of serial signals it normally tells you something is paying attention on the other side of the connection. I'm not really surprised, either way, that the BLE sense would react to DTR being disabled by not sending data to the host; there's a lot of latitude in how these signals can be handled. That it's not automatically used when the port is opened (or until specifically requested) seems mostly a C# thing. But it looks like the different handling of DTR between the two boards that is making your code work with one but not the other.
So it would seem necessary and sufficient to add
serialPort.DtrEnable = true;

amongst your other settings following the opening of the port.
If there's truth to what the Arduino Forum poster said about RTS, then you would also need
serialPort.RtsEnable = true;

but this is not indicated by the tests I've done (though again with pyserial).

Tx @timemage, you saved my day... hell you saved my week! Yes I confirm that just adding DtrEnable = true does the trick. What the hell were they thinking about? This is a damn virtual port where you don't even have to specify the baud rate! And they care about the DTR signal state? Something that you normally leave unconnected in a hardware serial port? cheeeze...

I think get your frustration. But, to be clear with respect to it being virtual: the host computer doesn't know whether logical requests for changes in baud or DTR result in real world changes to signal levels and timing or that they just terminate the USB stack. From .NET's perspective, it doesn't even know the Serial API is being backed by USB peripheral and not an old style serial port.There's a long tradition of hijacking serial signals for purposes that you'd never guess based on their names.

A 1200 baud request together with DTR (and also RTS in the case of the Due and common ESP32/ESP8266 boards) are used in many Arduino type boards both only in the USB stack (where no actual DTR signal or uart timing exists) and also via transceivers to cause entry into bootloaders, to operate chip erasure, etc. I didn't have a specific reason (until testing) to think that the BLE would care (or not) at non-1200 baud (imaginary baud) rates. To the extent that I'm mildly surprised by anything here, it's in the default behaviour of .NET's SerialPort API.


text:
Is there a schematic for the ESP32S Dev Kit C V4 NodeMCU WLAN Development Board?
Recently I bought a ESP32S Dev Kit C V4 NodeMCU WLAN Development Board. I got it from azdelivery.de in Germany.
Now I am interested in the schematic for this board to learn more about it. Not Google, nor the support team at azdelivery.de could help me, but since the board is a Chinese mass product, I hope to find an answer here, where I could get the schematic.
Thank you!

Apparently az-delivery have a free e-book available for download on this ESP32 board. Have you looked at that? There's also a generic ESP32 Devkit C V4 schematic available.

Yes, I also have the e-book. It contains a general description of the board, the pinout, many technical details and some example sketches, but unfortunately no schematic of the board. The link with the schematic is new to me! Thank you so much!!!

Here is a webpage that provides ESP32 Devkit C schematic and pin definition. It may help you. But not sure if the dev board you got is same as the web provides. ESP32 Devkit C schematic

Thanks for the link! I’ll check that, when I’m back home again.

Espressif has schematics and more on their website. EZ-Delivery sells two different versions: One has a CP2101 USB-Interface, the other one uses a CH340 instead. If you have the CP2101 variant, this should match the one at Espressif's Website:
https://dl.espressif.com/dl/schematics/esp32_devkitc_v4-sch.pdf
More related docs are linked on their Website (scroll down to "Related Documents" here:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-devkitc.html#get-started-esp32-devkitc-board-front

Here is a webpage that provides ESP32 Devkit C schematic and pin definition.

ESP32 Devkit C schematic

OP's board is definitely not having a xQFN28 CP2102N USB chip.


text:
How to get rid of the second tab in Arduino IDE 2?
For a reason unknown to me, Arduino IDE 2.0.3 opens two tabs with the same name for this sketch. I'm not able to reproduce how to get into this situation.
Changes in one tab immediately changes the other tab as well.
How can I get rid of the second tab?

Things I tried:

File / Close (Ctrl+W) closes the whole sketch, i.e. Arduino IDE exists.
The usual key combination to close tabs (Ctrl+F4) does not work either.
I deleted all %AppData%\Local\Temp\.arduinoIDE-unsaved*.gfv2 folders
I deleted all %AppData%\Local\Temp\arduino-sketch-* folders
I deleted all %AppData%\Local\Temp\arduino-language-server* folders
I deleted all %AppData%\Local\Temp\arduino-ide2-* folders
I used Streams to check the INO file for alternate data streams
I deleted the folder %UserProfile%\.arduinoIDE

Maybe interesting: when I rename the sketch to HelloWorld2.ino, it opens only one tab. If I rename it back, I have two tabs again.
When I change the preferences to show the files in Sketchbook view, I only see one file:

The other sketches have been created when trying to reproduce the problem. They are not affected
The tooltip which shows the full file name is identical on both files:

The Registry does not contain suspicious information. I found only one occurrence of HelloWorld in
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths

Can give exact instructions on reproducing this? I downloaded 2.0.3 (though on Linux) and tried creating and opening essentially blank sketches in various ways and didn't observe this problem.

@timemage: unfortunately I can't (yet). I have also created a virtual machine and wanted to reproduce it, but it didn't happen.

@jsotola: the content changes in both tabs (seemingly instant)

@jsotola: updated the question: it shows only one file

@timemage: I have recorded a video when this issue occurred. From that video I can see that it started with a duplicate file name called sketch_dec27a.ino https://i.stack.imgur.com/IgHxa.png However, the video just shows this right after starting the IDE, nothing done.

@jsotola: the other one has a space in the name. It's a different sketch which is not affected and has no impact one the one without space. I deleted it and updated the screenshot. The problem still persists

search the windows registry for all instances of the text HelloWorld if you feel comfortable exploring the registry

For what it's worth I believe you. But, until I can reproduce the problem I don't think I'm going to have much luck finding a solution. The IDE seems to have had a recurring problem with this stemming from different causes some of which have supposedly been fixed. The IDE 2.0.X IDE definitely still has a lot of problems. In fact I just noticed another (unrelated) one trying to reproduce yours.

It seems there is a new bug for this issue: https://github.com/arduino/arduino-ide/issues/1791 I can't recall having used libraries yet, though.

How can I get rid of the second tab?

Press F1,
Type: View: Reset Workbench Layout into the Command Palette,
Press Enter,
IDE reloads.

If it does not help, get the layout data from the logs.

Open the DevTools with Ctrl/⌘+Alt+I built-in command,
Open the Console if it's not opened with Esc,
Right-click in the console and Save as...,
Share the data with the devs.

For example:
{"version":5,"mainPanel":{"main":{"type":"tab-area","widgets":[{"constructionOptions":{"factoryId":"code-editor-opener","options":{"counter":0,"kind":"navigatable","uri": ...

Absolute abuse of the F1 button for such a purpose, but anyway, resetting the workbench layout did it.

Seems a perfectly good use to me. =) Upvote.


text:
AD8232 - Measuring heart rate only if USB connector is touched. Grounding issue?
TL;DR
I can read out my heart rate but I have to physically touch GND of the Arduino or else the signal is just noise.
Description
So I've started to play around with an Arduino and wanted to try out a heartrate sensor module (AD8232).
The following is the code I am using for this:
const int CONNECTED_LED = 13;

const int LO_MINUS = 10;
const int LO_PLUS = 11;

bool disconnected = true;

enum State {
  CONNECTED,
  DISCONNECTED,
  LO_MINUS_DISCONNECTED,
  LO_PLUS_DISCONNECTED
};

enum State currentState = DISCONNECTED;

void setup() {
  Serial.begin(9600);
  pinMode(LO_MINUS, INPUT); // Setup for leads off detection LO +
  pinMode(LO_PLUS, INPUT); // Setup for leads off detection LO -
}

void loop() {
  State nextState = getState();

  if (nextState != currentState) {
    // Store the current state
    currentState = nextState;
    switch (nextState) {
      case DISCONNECTED:
        break;
      case LO_MINUS_DISCONNECTED:
        break;
      case LO_PLUS_DISCONNECTED:
        break;
    }
  }

  if (currentState == CONNECTED) {
    digitalWrite(CONNECTED_LED, HIGH);
    Serial.println(analogRead(A0));
  } else {
    digitalWrite(CONNECTED_LED, LOW);
    // Serial.println(-1);
  }

  delay(1);
}

State getState() {
  if (digitalRead(LO_MINUS) == 1 && digitalRead(LO_PLUS) == 1) {
    return DISCONNECTED;
  } else if (digitalRead(LO_PLUS) == 1) {
    return LO_PLUS_DISCONNECTED;
  } else if (digitalRead(LO_MINUS) == 1) {
    return LO_MINUS_DISCONNECTED;
  }
  return CONNECTED;
}

This is how I am connecting the boards (I double checked already twice)
AD8232  | Arduino UNO R3
------------------------
GND     |  GND
3.3v    |  3.3V
OUTPUT  |  A0
LD-     |  ~10
LD+     |  ~11
SDN     |  <not used>

I've followed this diagram for connecting the electrodes:

However, the result is a random signal unless I am touching the USB-connector or GND of the Arduino.
Below you can see the random signal and the moment I touched the connector. I noticed this by accident after hitting the reset button after wondering why on earth I only get this random signal:

So.. what's going on here? I have all three electrodes connected.
I've even tried to different modules (I bought the AD8232 two times) but I see the same issues with both modules.
If I touch something else e.g. a radiator (heater) then the signal becomes another kind of random. It only works touching the connector.
Since this appears like a grounding issue I checked for continuity from the GND pin of the AR8232 to the USB connector and continuity is given.
I'm not expert enough (yet) to see the problem. Anybody?

The Sparkfun tutorial https://learn.sparkfun.com/tutorials/ad8232-heart-rate-monitor-hookup-guide/all  links to a sketch which reads also pins 10 and 11 (to detect a lead placement/connection problem) which you are ignoring.

@6v6gt I have updated my code to the actual thing I am using. Both electrodes appear to be connected (only occasionally I see a disconnect) but most of the time I can read values from A0. It's just that it does not resemple a heartbeat ECG at all.

You are powering the module with 3.3 volts ? If you are using a 5 volt Uno, it will see a maximum analog reading of about 675  for peaks in a 3.3 volt signal. There does seem to be some clipping in the top range of the signal.

Yes, according to those tutorials and the module, the power should be 3.3V. Nothing I see makes sense here. I've tried some sanity checks because I started thinking maybe I killed the Atmega accidentally but basic "LED blinking" is still working fine. I've absolutely no idea what this thing wants from me XD

Interestingly, your serial plotter shows a range of 50 units (samples?) on the X axis. That would be about 50ms which, for a heart beat in the normal range, is clearly not enough. The Serial plotter with IDE version 1.8.19 shows a range of 500 units on the X axis which appears to be the same as the Sparkfun tutorial screen shots. Try increasing the delay until the full scale is 3 or 4 normal heart beats or export the results say to Excel and plot there.

@6v6gt I've just updated the code and the plot. It's weird.. I've tried several delays now. A heartbeat appears to take around a secod (according to Google) so I've tried 1, 10, 25, 50 and 100 milliseconds using delay() but I always get chaotic results. As you can see above, the plot is not continuos as if the electrodes weren't connected at times. It's very jittery and I have no idea why. If I press the sensors on the skin the average jumps around but that's about it. Not sure where the problem is..

Your code has multiple Serial.println() statements which could be causing the gaps. You should have only one (new line character) after printing the data line ( consisting of the 0, the 750 and the analog value). If there is a bad result, just print say 10 instead of the analog value so only numerical data is sent to the plotter. Maybe add a fourth plot that toggles between say 700 and 740 every 100ms.

Tried that. The values jump around between 300 and 700 -I can't comprehend what's going on. Either it's completely broken somehow or the plotter is not working as intended. I do set the output pin 13 to HIGH in order to see if I am connected or not - this light is flickering so it still kind of appears as if the connections aren't not working properly. I've tested everything for continuity with the multimeter so I don't think there's an issue - except the pads maybe but I didn't use them before. The other day I tested a smoke sensor which worked just fine ..

You'll see that the limited number of sample that the IDE V2.x.x Serial plotter allows (by default) has got some criticism. Also there is also an apparent work around at the end of this thread: https://github.com/arduino/arduino-ide/issues/803. One of your problems is that if you increase the delay between samples enough to be display about 2 seconds of data (say 40ms), if only 50 samples are allowed, you may miss the interesting peaks.

I was about to post the same link as I've extended the number of samples to 5k now but the result is just pure garbage..  I just don't get what the hell is going on here...

@6v6gt Okay so.. I kind of got it working.. it only works if I touch the USB connector of the Arduino. Only discovered this by accident. Any idea what the problem is? It should work without that, shouldnt it?

Read through the reviews here and see if anything jumps out. The reviews titled "Great But Bad Pinout", "Poor Signal-to-Noise (SNR) ratio", "It actually works! for hobby purposes" all seem to contain something that may be relevant to your problem.

@timemage hm, not sure. It appears that I myself need to be grounded because after touching GND the signal is "okay". Yeah it's very noisy but you could compute the heart rate with that. My problem is that I don't understand why I have to be grounded in order to get a signal. I thought this measures voltage differences between two points given a reference point.

Yes, I saw that. I'm saying that touching the USB shield could be having any number of effects related to the things mentioned in those reviews. I'm not able to test what happens if you run it on a battery or if you change the connections to the jack, or if you filter out your mains frequency. But you are.

I'm running it via the USB cable but I can try switching it to a battery. It's interesting because if I touch the radiator, then it will read a disconnect. If I touch the GND of the Arduino, it "works". Anything else is just random noise. Weird. ^^

Are you using electrodes that Sparkfun made or did you wire them yourself?

I am using the ones that came with the module itself.

One of your three ECG leads is equivalent to (human)body ground, and it's not making contact. I spent too long making this image to explain it, which should help you a lot more than it will me.  I mean, I don't have the board in my hands, so I cannot see which lead goes to which pin.  You can, easily, with a multimeter testing for continuity between the:
RIGHT ARM,
RIGHT LEG,
LEFT ARM (RA, RL, LA) solder spots, and the tip, ring, barrel of the jack.
Something to keep in mind though is the headphone jack switch.  When the plug is physically inserted, this switch opens.  Again, I'm not there to guide your multimeter, so this image is the best I can do for you.  One of your leads is going to be a grounding lead. It may be the "black" one, it may be the (traditionally) "RL" one, it may be another one, i can't tell.
When you touch USB ground you are effectively replacing the body contact of the missing ground lead. I made these images for you to better understand it.  You should be able to fault find this in a few minutes via you MM and continuity testing.

I've tested all three electrodes and I can detect continuity for each of them on the barrel of the jack. I don't think that's the problem. Like mentioned, I have two boards and two sets of electrodes and the issue is the same in both cases. However, is there any chance that it could be the power source? Right now I am powering it via USB cable from my PC. there might be a chance that I have to isolate the sensor and use a battery instead?

I can detect continuity for each of them on the barrel of the jack
erm... so....  all three electrodes are shorted to the barrel when plugged into the jack?  If that's the case you need to re-read what I wrote to you.

No, what I meant was RL, LA and RA are connected. The cables are fine.

I can't be any more helpful to you. The information you need is presented, and I cannot possibly be there to do it for you.


text:
How to fix the scambled output of the emojis in Arduino IDE 2?
I have relatively simple code printing some emojis:
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Hello world ❤♀♂✔");
}

Just in case it doesn't render very well, here's an image on how it looks like in Arduino IDE 2.0.3:

However, the Serial Monitor sometimes displays emojis and sometimes not. It varies from line to line like so:
Hello world �����������������♀�������♂✔����
Hello world ���������������♀♂✔
Hello world ��❤���������������������������������♂���✔
Hello world ❤��������������������
Hello world �������♀��������������✔����
Hello world ��������������♀�������������������
Hello world ��❤���������������������♂�������✔���

Again, there's how it looks like on my Windows 10 machine:

I verified that it's not a mistake in the baud rate. Both, Arduino and PC are set to 9600.
In Arduino IDE 1, the output is not colorful and some emojis are not rendered at all, but the result is much more consistent:

How to fix the scrambled output in Arduino IDE 2?

To be clear, this is a problem with handling any multi-byte UTF-8 encoding and potentially another problem on top of that with handling grapheme clusters. When I encountered this for the first time I think it was in using the degree symbol for a temperature reading (code point 0xB0) that encodes in UTF-8 as 0xC2 0xB0. Your odds of seeing the character correctly improve if you Serial.flush() and wait some time before and after multi-byte encodings and do not delay in the middle. In other words, increasing the odds that the Serial Monitor receive an entire UTF-8 sequence in a single buffer.

This is an issue of Arduino IDE 2.0.3. It was reported as issue 589 and issue 1405.
It was fixed on 9th of December 2022 [PR] and I can confirm it is fixed in nightly build 2.0.4-221229.


text:
How do I reset the recently used commands in Arduino IDE 2?
I am recording videos on Arduino IDE version 2. In one of the videos I want to explain how to enable a specific setting via the advanced properties. This requires using Ctrl+Shift+P (command palette).
However, my Arduino IDE now shows some commands I have used recently (sorry, screenshot is in German).

That's not the default. If someone has just installed Arduino IDE, he would need to scroll until he finds the entry. How do I reset the recently used items, so that I can record a proper video which requires scrolling?
Resetting the workbench layout does not help.

open the command palette
search and choose Preferences: Open Settings (UI)
in the preferences window, search for the setting workbench.commandPalette.history
set that value to 0 and it will not save the recent commands


text:
Can I configure the highlighting for escaped characters in a string?
Given a simple mistake like
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("\");     // note: " is escaped, so this won't compile
}

This is rendered in Arduino IDE 2.0.3 as

and the problem is hard to spot.
The Jetbrains IDEs have special highlighting for escaped characters like

which makes the problem more obvious because the two quotation marks have different color.
Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?
Because it was asked in the comments: no, the syntax highlighting does not highlight the escaped character when the string is complete. The backslash and quotation mark are both still green.

@hcheung "\" is not a string as it does not have a closing quotation mark. \" is an escaped character in a string.

"\" is an escape " without closing ", you might get the correct syntax highlight if you do "\"".

use a text editor that supports it

@jsotola: I'm working with children at the age of 10. I can't simply tell them to switch the editor.

@hcheung: No, it's not highlighted when the string is complete: https://i.stack.imgur.com/Dbb6x.png

Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?

Yes. You'll need to enable the Arduino language features provided by the language server. They're disabled by default.

Press F1,
Type Preferences: Open Settings (JSON),
Press Enter,
The settings.json file opens.

Add the following to the JSON and save it if you do not have auto-save enabled:
{
  "arduino.language.realTimeDiagnostics": true
}

My settings.json with the Arduino language features enabled.

Select a board. You can ignore the port selection if you like. The language feature should start, and you will see the error in the editor.

More details on the Advanced Settings are here.

Thanks. Undoubtedly, this is very helpful. The color of the escaped character is still the same, though.

In the JetBrains IDE, you wrote Serial.println("\"); and in the Arduino IDE Serial.println("\");     // note: " is escaped, so this won't compile. Can you please update your question about the syntax coloring in JetBrains with the longer example? Thanks! I compared the built-in C++ extension in VS Code with Arduino IDE, and they behave the same. The compiler error seems valid: Expected expression clang(expected_expression). I do not think you will be able to tweak the syntax highlighting in Arduino IDE.

My VSCode has syntax highlighting in strings: https://i.stack.imgur.com/Tq9iS.png Haven't used it for a long time, but IMHO I only use it for Typescript, not C++, so I don't think I have any C++ specific extensions installed and it even asks me whether I want to install some..

I am sorry I could not help you with this. This conversation only leads if we compare the same snippets in different IDEs and editors. I did not say VS Code, Arduino IDE, or other tools cannot apply different syntax coloring on a regex token, but your initial use case is different; it's a pure compiler error. Even the built-in StackOverflow snippet highlighting shows the same result as the Arduino IDE; please look at your original question and check the snippet.

I did another check and can confirm a bug in the Arduino IDE that does not highlight the regex matches. If there are no compiler errors, VS Code correctly highlights \d in the "\d+" string. Arduino IDE 2.0.3 fails to do it.

One more update. The regex syntax coloring works in the Arduino IDE with both the Light (Theia) and Dark (Theia) themes, not with the Arduino ones. Steps to reproduce. Your sketch: void setup() {} void loop() { Serial.println("\d"); }. \d is not highlighted. Open settings with Ctrl/⌘+,. Select one of the Theia themes from the dropdown, and close the dialog with OK. \d is highlighted. If I select any of the Arduino themes, it does not work. This is a theme bug.

If you want to give that an an additional answer, I'm happy to upvote and accept it.