text:
interrupt from a button and wait until serial port 1 has a message
I'm a little bit loss because I'm learning how to use the interruptions on Arduino.
I'm creating a program to read an RFID code that arrives if an RFID transmitter is close to the antenna (a little antenna board RFID). I  have two operating modes: one where I associate my board to an RFID, so I will act only where my RFID code is identified ( I save the RFID code on the board). and another mode where I read all the RFID codes and I save it.
I have one configuration step where if the user push a button, I want to wink a led to indicate that we are waiting for the presentation of the RFID code to associate to the board. I try to make a code and I have some problems to get out of the condition where I'm waiting for the RFID code (serial1).
Here is my code:
#include <Wire.h>

//const int reception_rfid = 15;
const int btnAssociation = 2; // bouton pour indiquer que l'on souhaite faire l'appareillage des RFID (interruption)
const int SwitchModeConfig = 4;
const int LedAssociationEnCours = A0;

int compteurLedAsso;

const int BUFFER_SIZE_RFID = 13;
char buf[BUFFER_SIZE_RFID];

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(SwitchModeConfig, INPUT_PULLUP);
  pinMode(btnAssociation, INPUT_PULLUP);
  pinMode(LedAssociationEnCours, OUTPUT);
  ConfigurationAssociation();
  digitalWrite(LedAssociationEnCours, HIGH);
}

void loop() {
  delay(100);
}

void ConfigurationAssociation(){
  int stateSwitch = digitalRead(SwitchModeConfig);
  if(stateSwitch == LOW){
      attachInterrupt(digitalPinToInterrupt(btnAssociation), InterruptAssociation, RISING);
      Serial.println("Mode association");
    }else{
      detachInterrupt(digitalPinToInterrupt(btnAssociation));
      Serial.println("Mode aleatoire");
    }
}

void InterruptAssociation(){
  compteurLedAsso = 0;
    Serial.println("Ouverture de l'Association d'un code RFID");
    while (Serial1.available() == 0 && compteurLedAsso <= 600)
    {
      // clignoter la led rouge sur A0
      digitalWrite(LedAssociationEnCours, LOW);
      delay(5000);
      digitalWrite(LedAssociationEnCours, HIGH);
      delay(5000);
      compteurLedAsso++;
      Serial.println(compteurLedAsso);
    }

    if(Serial1.available() > 0){
      int codeRFID = Serial1.readBytes(buf, BUFFER_SIZE_RFID);
      Serial.println("CodeRFID: ");
      for(int i = 0; i < codeRFID; i++)
        Serial.print(buf[i]);
    }
      //Serial.println(compteurLedAsso);
      //compteurLedAsso++;
    Serial.println("Fin de l'attente code RFID");
}

void requestEvent() {

}

First problem: I know that when we are inside a interruption we can't count the time pass on a while, I would like to wink the led 2 minutes: waiting the presentation of the RFID code to save and once the 2 minutes pass away I get out of the interruption. How make to wait 2 minutes for RFID code on serial1 port inside an interruption? my reception RFID board works fine and TX is connected to RX1 (pin 19) of Arduino mega (I verify on another code where reading RFID works)

Second problem: when my board is inside the interruption that comes from a push button (connected on pin 2) I stay always on the while loop even when my RFID transmitter is reading an RFID code, I can't get out of and I don't know why! maybe you can help to understand and find a solution please?

The thing is: Inside an ISR (Interrupt Service Routine) not only does time measuring with millis() not work, delay() also won't work (it uses the same interrupt mechanism as millis() in the background). Neither does anything else, that depends on their own ISR to execute - like receiving serial data. The hardware Serial interface can receive single bytes without depending on interrupts, but to get these bytes into the buffer (and to actually use them via Serial) you need to let other ISRs execute.
You should NEVER write an ISR, which executes for a long time. Keep it in the microseconds, maximum in the very low millisecond range. How long you can get here until you see negative effects depends on other factors. You really should only do minimal work in an ISR and the rest in the main code.
A common code structure for this looks as follows:

In your main code you don't use any delay() calls. Everything timed should be done with millis() (like in the BlinkWithoutDelay example that comes with the Arduino IDE), so that it won't block execution. Also no long loops inside of loop(). Make sure, that your loop() function can iterate freely and fast.
In global scope you define a flag variable. A simple one byte variable, marked as volatile.
In your ISR you are doing nothing but setting this variable. Depending on your situation you might wanna set it depending on an digital input via digitalRead(), which is still fast, so OK to do.
In your main code you use an if statement to check for this flag variable to be set. On most loop() iterations this won't be executed. Only, if the flag variable got set inside the ISR, it will get executed. This is the place where you write the code handling the event. At the end of the block you then only need to reset the flag variable, so that you are ready for the next interrupt to happen.

This would look somewhat like this:
int button_pin = 2;
volatile bool button_flag = false;

void setup(){
  pinMode(button_pin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button_pin), button_ISR, RISING);
}

void loop(){
  if(button_flag){
    // Handle interrupt here
    button_flag = false; // Reset flag variable to be ready for next interrupt
  }
}

void button_ISR(){
  button_flag = true;
}

Note, that the button_flag variable is defined as volatile, so that the compiler doesn't cache its value is some register and instead always reads the actual current value of it (not optimizing it).
In your code you should probably use another coding concept named Finite State Machine (FSM). This is the easiest method to implement a code with different states/stages while still keeping it non-blocking. You can read up about FSMs on the web (or for example in my answer to this question).
The gist is, that you use a variable, that represents the state, that your code is currently in. In loop() you then only ever execute the code for the current state. Changing to a different state is done by setting the state variable. The state, that your current code needs, are probably CHECK_FOR_SINGLE_RFID_TAG and ASSOCIATE_SINGE_RFID_TAG (though you can name these like you want). A simple FSM with this can look like the following:
#define CHECK_FOR_SINGLE_RFID_TAG 0
#define ASSOCIATE_SINGLE_RFID_TAG 1

// single byte variable so that we don't need to bother about atomic reads/writes
uint8_t state = CHECK_FOR_SINGLE_RFID_TAG;

void loop(){
  switch(state){
    case CHECK_FOR_SINGLE_RFID_TAG:
      if(Serial1.available()){
        // read Serial1 here, check the RFID tag ID against the saved one
        // and execute code accordingly
      }
      break;

    case ASSOCIATE_SINGLE_RFID_TAG:
      if(Serial1.available()){
        // read Serial1 here and save the new RFID tag ID in a variable
        // then reset the state variable to automatically go back to check mode
        // after the new RFID tag is enrolled
        state = CHECK_FOR_SINGLE_RFID_TAG;
      }
      // Use the BlinkWithoutDelay idiom to blink your LED non-blocking
      // something like
      // if(millis() - led_timestamp > led_interval){
      //   digitalWrite(led, !digitalRead(led));
      // }
      break;
  }
}

You see, how we define out possible states, save the current one in a variable and act according to it inside of loop()? This concept is really powerful, so it is totally worth it to learn.

Note: I've used a variable of type uint8_t (a single byte) to keep this interrupt safe (you can read up about this by searching for something like arduino interrupt atomic read or arduino interrupt safe variable) for the next part and the defines to give each value a readable name. You could use an enum for that, though while writing this I got on a tangent about the size of an enum, which seems 16 bits on AVR (like the Arduino Mega), unless you use a specific compiler flag, according to this blog article. This explanation is not that important for you right now, but I also wanted to explain, why this doesn't use enums.

Now we can combine this with our interrupt code from above. In this case we don't need a seperate flag variable anymore. We can directly set the state variable inside the ISR:
#define CHECK_FOR_SINGLE_RFID_TAG 0
#define ASSOCIATE_SINGLE_RFID_TAG 1

volatile uint8_t state = CHECK_FOR_SINGLE_RFID_TAG;

int button_pin = 2;

void setup(){
  pinMode(button_pin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button_pin), button_ISR, RISING);
  Serial.begin(115200);
  Serial1.begin(115200);
}

void button_ISR(){
  state = ASSOCIATE_SINGLE_RFID_TAG;
}

void loop(){
  switch(state){
    case CHECK_FOR_SINGLE_RFID_TAG:
      if(Serial1.available()){
        // read Serial1 here, check the RFID tag ID against the saved one
        // and execute code accordingly
      }
      break;

    case ASSOCIATE_SINGLE_RFID_TAG:
      if(Serial1.available()){
        // read Serial1 here and save the new RFID tag ID in a variable
        // then reset the state variable to automatically go back to check mode
        // after the new RFID tag is enrolled
        state = CHECK_FOR_SINGLE_RFID_TAG;
      }
      // Use the BlinkWithoutDelay idiom to blink your LED non-blocking
      // something like
      // if(millis() - led_timestamp > led_interval){
      //   digitalWrite(led, !digitalRead(led));
      // }
      break;
  }
}

You can see, the button_ISR() is very small, thus very fast. And our loop() also runs unblocked, so the next iteration of it will come very fast and it will then execute the state, that we set in the ISR.
Note: When reading from Serial, make sure, that you don't use functions, that block for a long time. For example Serial.readString() will take 1s to execute (since that is the default timeout), which would block the non-blocking code (no good).

Hi! whao!! Thank you so much for all these super explanations very complete and clear! :) i'm gonna read all and see the exemples of FSM because i don't know anything about it for be honest. I will back with news or maybe answers about my problem if is ok with u. Again, thank u for ur help :)

*i will back with news or maybe QUESTIONS instead :)

I come back with news, thanks to your help @chrisl and EdgarBonet i understand how to make FSM to improved my arduino code.  it's working! thank u so much again to the both! :)

chrisl's answer brings many excellent points, and I highly recommend you
study it in detail. There are just a few points I would personally add
or amend:

an ISR should probably not last more than a few tens of microseconds,
and many bad things could happen during a 1 ms ISR (missed clock
tics, lost serial input...)
a loop() iteration should not take more than a few milliseconds
there is no point in using an interrupt for reading a button: the user
will keep the button pressed for many milliseconds, and you will have
many opportunities for catching it in loop(); interrupts bring
complexity that is only worth it when you have to deal with
sub-millisecond timings
do not worry about the size of an enum unless you need to care about
sub-microsecond timings

Now, my take at this problem. The first step is to define the state
machine. I may call the states NORMAL and ASSOCIATION. The
transitions would be:

NORMAL → ASSOCIATION when a button press is detected
ASSOCIATION → NORMAL when either an RFID code is read or after a
timeout

My tentative implementation:
// Attempt to read an RFID without blocking.
// Returns the found RFID code as a pointer to a NUL-terminated buffer,
// or nullptr if no RFID is available right now.
char *read_rfid() {
    // Implementation left as an exercise to the reader.
}

void loop() {
    static enum {NORMAL, ASSOCIATION} state;
    static uint32_t started_association;  //  association start time

    char *rfid = read_rfid();
    switch (state) {
        case NORMAL:
            if (rfid) {
                Serial.print("Read RFID code: ");
                Serial.println(rfid);
            }
            if (digitalRead(btnAssociation) == LOW) {
                Serial.println("Starting association");
                mode = ASSOCIATION;
                started_association = millis();
            }
            break;
        case ASSOCIATION:
            if (rfid) {
                assocate_rfid(rfid);
                Serial.println("Association successful, code: ");
                Serial.println(rfid);
                mode = NORMAL;
            }
            if (millis() - started_association >= assocation_timeout) {
                Serial.println("Association timeout");
                mode = NORMAL;
            }
            break;
    }
}

There are a few things I left out here, most notably:

The LED blinking, which should be done in the style of the Blink
Without Delay example
The function read_rfid() that reads the serial port in a
non-blocking fashion. For this, you will need to have a rule for
deciding when a message is complete. This could be a message
terminator (if the reader does send one) or a timeout.

Finally, I would recommend you read a couple of blog posts by Majenko:

The Finite State Machine is a tutorial on the implementation of
finite state machines
Reading Serial on the Arduino teaches you how to read the
serial port in a non-blocking fashion.

Thank you so much for your help :) with your responses i can understand so many things and improve my code :) i keep going on my projet! thanks for ur help! :)


text:
Bad symbols in the serial monitor when connected via USB 3.0
I tested DHT11 + Arduino Uno with a very basic example sketch.
The Arduino board was connected to USB 3.0 and sometimes I saw incorrect symbols in the serial monitor, e. g. "Humidit?: _7%" instead of "Humidity: 37%". This strange effect disappears when I connected the board to USB 2.0. Baudrate in code was always same as baudrate in the terminal settings.
When I increase baudrate I see less bad symbols but they not disappear while Arduino connected to USB 3.0.
The OS is Ubuntu 20, this was the first time I connect the board to USB 3.0. Is this behavior normal?
The sketch:
/**
 * DHT11 Sensor Reader
 * This sketch reads temperature and humidity data from the DHT11 sensor and prints the values to the serial port.
 * It also handles potential error states that might occur during reading.
 *
 * Author: Dhruba Saha
 * Version: 2.1.0
 * License: MIT
 */

// Include the DHT11 library for interfacing with the sensor.
#include <DHT11.h>

// Create an instance of the DHT11 class.
// - For Arduino: Connect the sensor to Digital I/O Pin 2.
// - For ESP32: Connect the sensor to pin GPIO2 or P2.
// - For ESP8266: Connect the sensor to GPIO2 or D4.
DHT11 dht11(4);

void setup() {
  // Initialize serial communication to allow debugging and data readout.
  // Using a baud rate of 9600 bps.
  Serial.begin(9600);

  // Uncomment the line below to set a custom delay between sensor readings (in milliseconds).
  // dht11.setDelay(1500); // Set this to the desired delay. Default is 500ms.
}

void loop() {
  int temperature = 0;
  int humidity = 0;

  // Attempt to read the temperature and humidity values from the DHT11 sensor.
  int result = dht11.readTemperatureHumidity(temperature, humidity);

  // Check the results of the readings.
  // If the reading is successful, print the temperature and humidity values.
  // If there are errors, print the appropriate error messages.
  if (result == 0) {
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.print(" °C\tHumidity: ");
    Serial.print(humidity);
    Serial.println(" %");
  } else {
    // Print error message based on the error code.
    Serial.println(DHT11::getErrorString(result));
  }
}

You are using the UNO's internal serial transceiver, right?

@timemage I guess yes, in this moment I don't know communication variants except default

That really sounds like either a bad cable or a bad USB port on the PC.  The Arduino itself isn't aware of the difference whether it is 2.0 or 3.0.  When you change from 2.0 to 3.0 are you using the same cable just in a different port on the PC?

@Delta_G yes I'm using the same cable. USB 3.0 is on a PCI-E extension board but other devices (BT & WiFi dongles, flash cards) work correctly with this cable, this port and its neighbours. Much better than with built-in 2.0 ports of motherboard.

I still think the issue is going to be on the PC end of the connection somewhere.

Please check if there is any baud rate mismatch. I mean, you have defined serial.begin(9600) in your code. Open the serial monitor selecting the same baud rate please. If that is not the problem, please check the cable. If you have any other operating system, like windows, please check your whole setup with that too.

source: Stack Exchange

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

sort: votes


text:
RP2040 1.28 WAVESHARE TOUCH LCD
I'm using this library successfully for almost a year now. I used GC9A01 & GC9A01 with touch and it is great. Lately I purchased a RP2040 1.28 WAVESHARE TOUCH LCD which I thought it would be easy to manage as it uses the same hardware , but ... no luck.
I tried the clock example and used the Dev-Device-Declaration#waveshare-rp2040-lcd-128 but nothing comes on the screen.
Does anybody had any experience with this module? Any help would be appreciated.
Lucas

Your question seems to be "Does anybody had any experience with this module?" How will an answer to that help you?

Very simple,This is a way to start a good conversation if the answer is positive.

That is the difficulty. This is a Q&A site. There are places that can work like that. The Arduino Forum, Reddit, Discord, etc. Here the idea is to ask questions that are answerable with little to no back-and-forth discussion. I doubt you want people post answers that say "yes" or "probably." If you edit your post to contain a single clear answerable question you're more likely to have luck getting a useful answer. If you re-post this on the Forum or wherever, still you're better off providing the next step on the assumption that someone is familiar with it. Just means one less round trip.

Got it, I understand your spirit. Nevertheless there should be space (depend on the question) for generic questions because this improves knowledge, this is my point of view of course and I do not expect to change the rules. Thanks for been polite and honest.

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


text:
if statement for changing serial output breaks the integer used for rest of code
I want to get back in to coding so i am re-teaching myself some basics before i tackle a bigger project.
This fault is confusing the . out of me.
I have modified the fading LED code from the beginner pages to now include a dual colour led and now serial and lcd screen output of the current state of the led.
(My project will include all of these hence the combo).
All was well with the fading led.
It starts off,  fades up in green, when at max brightness, turns off green, switches to red then fades down.
Switches back to green and repeats.
Then i added serial and LCD output and now, the led colour part of the code breaks when ever i try and reference the currently active led pin to write that colour (As a string) to serial.
My code is below.
#include <LiquidCrystal_I2C.h> ///LCD library

int ledr = 6;         // the PWM pin the red LED is attached to
int ledg = 5;         // the PWM pin the green LED is attached to
int led;              // the active LED pin
int brightness = 0;   // how bright the LED is
int fadeAmount = 10;  // how many points to fade the LED by
//char colour;           // to use for displaying led colour as string in serial and lcd
LiquidCrystal_I2C lcd(0x27, 20, 4); //I2C LCD display address 0x27 with 20 cells x 4 rows display

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  pinMode(led, OUTPUT);                                   // setup pin for led
  Serial.begin(9600);                                     // start serial
  analogWrite(13, 0);                                     // turn off led 13
//  Serial.println("Green fade up - Red fade down");       // write this to serial
//  delay(1000);                                           // wait 1 sec to see it in serial
  led = ledg;                                             // set led active pin to ledg

  }

void loop() {
  if (brightness <= 0) {                // if brightness <= 0,
  led = ledg;                           // set active led to ledg (green)
//  colour = 'Green';
 };

  if (brightness >= 255) {              // if brightness >=255, turn off last led (ledg, green), acivate ledr (red) with one cycle crossover.
  led = ledr ;                          // set active led to ledr (red)
  analogWrite(led, 255);                // set active led (ledr, red) to 100%
  led = ledg;                           // set active led to ledg (green)
 analogWrite(led, 0);                   // set active led ledg (green) to off
 led = ledr;
// colour = 'Red';                            // set led to ledr (red)

 };

  analogWrite(led, brightness);         // set active led to current brightness

  brightness = brightness + fadeAmount; // change the brightness for next time through the loop:

  if (brightness <= 0 || brightness >= 255) {   // reverse the direction of the fading at the ends of the fade:
    fadeAmount = -fadeAmount;
  };

                                   // below is outout to serial
  Serial.print(led);               // print the current active led pin and brightness to serial in the format (pin" - "brightness")
  Serial.print("  -  ");           // print " - "
//  Serial.print(colour);            // print the current colour of the led

// if (led = 5); {
//  Serial.print("Green");
//   };

//if (led = 6); {
// Serial.print("Red");
//  };

  Serial.print("  -  ");          // print " - "
  Serial.println(brightness);     // print the brightnesss of the led

                                  // below is outout to LCD
  lcd.setCursor(0, 0);            // move cursor the first row
  lcd.print("LED Pin + Colour");  // print message on the first row
  lcd.setCursor(0, 1);            // move cursor to the second row
  lcd.print(led);                 // print active led pin on the second row then
  lcd.print(" : ");               // print "+" then
//  led.print(colour);              // print the colour of the currently active led
  lcd.setCursor(0, 2);            // move cursor to the third row
  lcd.print("LED PWM (0-255)");   // print message on the third row
  lcd.setCursor(0, 3);            // move cursor to the fourth row

  if (brightness <= 99) {         // if to check for <100 brightness value and clear 3rd cell if true.
    lcd.setCursor(2, 3)  ;        // move cursor to line 4, cell 3
    lcd.print(" ");               // clear cell
    };                            // end if

  lcd.setCursor(0,3);             //move cursor back to start of row 4
  lcd.print(brightness);          // print message the fourth row
  delay(50);                      // wait for (x) milliseconds to slow the dimming effect
}

Please ignore the references to char colour. thats a different issue i'm having :(
When i un-comment either or both of the if statements below ** Serial.print(colour); ** it breaks. the led still fades in and out but the colour change stops working and it will only fade using the colour of the if statement i'm using.
Below is a good led switch without either if statements active
Led 6 (red) fades out and led 5 (green) fades up
6  -    -  40
6  -    -  30
6  -    -  20
6  -    -  10
6  -    -  0
5  -    -  10
5  -    -  20
5  -    -  30
5  -    -  40

Below is with the first if active active
5  -  Green  -  40
5  -  Green  -  30
5  -  Green  -  20
5  -  Green  -  10
5  -  Green  -  0
5  -  Green  -  10
5  -  Green  -  20
5  -  Green  -  30
5  -  Green  -  40

(green (string) is now shown as the if is active).
Green (5) was on when it should have been red.
Same thing with only the other if active but it would have been Red.
with both active,
6  -  GreenRed  -  40
6  -  GreenRed  -  30
6  -  GreenRed  -  20
6  -  GreenRed  -  10
6  -  GreenRed  -  0
5  -  GreenRed  -  10
6  -  GreenRed  -  20
6  -  GreenRed  -  30
6  -  GreenRed  -  40

Now, both colours are displayed despite the if statements and apart from the brief switch from 6 to 5 and back to 6 (It is supposed to, see code), the led is stuck on pin 6 (red)
I have tried if/else and two if statements and it has no effect.
from what i can tell, it is just the reference to (led = 5) or (led = 6) that causes the issue.
please help. I've spent 2 days trying to work it out and i am not very very confused.
Thanks.

The thing you've asked about (now answered) the commented out code colour = 'Green'; (not a string) are both things you should get warnings for if you increase the warning level in the IDE. May have saved you the two days.

i am not very very confused ... isn't  that a good thing?

your code is very messy... it is not not indented correctly ... please format your code sobthat each block is clearly delimited

You have an issue with = vs. ==.  One equal sign for assignment, two for comparison.  You also shouldn't have a semicolon on an if statement.  That semicolon acts as the only thing controlled by the if.  It translates to "if this then do nothing".  You want the stuff in brackets to be controlled by the if statement.  So no semicolon.
 if (led == 5) {
  Serial.print("Green");
 }

Awesome. thank you. I did not know the difference between = and ==.
I did know about the semicolon. I missed that one. Much appreciated.


text:
Can I make this changes to this diagram of a ESP32-CAM?
Have a good day! I am kinda new with electronics circuits, and therefore I got some doubts about this diagram of a ESP32-CAM
I want to use a 5V instead of 3.3V. Do i need to add some resistors or capacitors to do so?
If the on-off switch is for turn on/off the device?
the push switch. Its a button that when GPIO13 receaves changes on his signal activate a code (I mean, does it act like a button code activator) If its not how can I put a button so the  ESP32-CAM start /stop filming?
Thank you

I got the image from this source
http://technoreview85.blogspot.com/2019/08/ESP32spycam.html

you cannot apply 5 V to a 3.3 V pin

@jsotola it does have a 5v pin. But  I didn't know if I do so I needed to add some more components

The ESP32-CAM can be powered via the 3.3V or 5V pins. It is safe to apply 5V to the ESP32 Vcc pin. Just make sure that no other ESP32 pin is exposed to a voltage over 3.3V.


text:
Fade loop glitch
I am working on a little sub program to run a PWM LED. I have a larger program that gives me a non-blocking 10 ms delay.
It mostly works well, but I get a -1 thrown during the code execution that causes my LED to flicker. Any insight into where this comes from or a better way to do this would be appreciated.
int pulse = 9; // the PWM pin the LED is attached to
int pulsebrightness = 0; // how bright the LED is
int fadeAmount = 1; // how many points to fade the LED by
int holdpulseon = 0;
int holdpulseoff = 0;
int totalcycle = 0;

void setup() {
  pinMode(pulse, OUTPUT);
  Serial.begin(115200);
  Serial.println (" ");
  Serial.println ("Momentum Booting");
}

// the loop routine runs over and over again forever:
void loop() {
  delay(10);

  analogWrite(pulse, pulsebrightness); // set the brightness of pin 9:

  if (holdpulseon == 0 && holdpulseoff == 0) {
    pulsebrightness = pulsebrightness + fadeAmount; // change the brightness for next time through the loop:
  }

  if (pulsebrightness <= 0 || pulsebrightness >= 255) { // reverse the direction of the fading at the ends of the fade:
    fadeAmount = -fadeAmount;
  }

  if (pulsebrightness == 0 ) {
    holdpulseon++;
    if (holdpulseon == 50) { // 50*10ms cycle
      holdpulseon = 0;
      Serial.print (holdpulseon);
      Serial.println (" hold on");
    }
  }

  if (pulsebrightness == 255) {
    holdpulseoff++;
    Serial.print (holdpulseoff);
    Serial.println (" hold off");
    if (holdpulseoff == 5) { // 5*10ms cycle
      holdpulseoff = 0;
      totalcycle++;
    }
  }

  constrain(pulsebrightness, 0, 255);
  Serial.println(pulsebrightness);

  if (totalcycle == 2) {
    delay (500000);
  }
}

0
0
0
0
0 hold on
0
-1
0
0
0
0
0

which line prints the -1?


text:
How to set a sampling frequency of 10ksps AD7606 through Aurdino?
This is the code for interfacing AD7606 with arduino. This code is working and I am able to read all the 8 channels. But my requirement is to set 10ksps.
#include <SPI.h>

uint32_t startTime, elapsedTime, old_res;
#define SCALE_FACTOR 0.000152587890625

#define BUSY 32               // you can use any digital pin

#define START_CONVERSION 34   // you can use any digital pin
#define CHIP_SELECT 53        // SPI CS
#define D7_out 50             // SPI MISO there is no need to use MOSI port with the ad7606
#define RD 52                 // SPI SCLK

#define TOTAL_RAW_BYTES 16
SPISettings _spiSettings;

int bytesToRead = TOTAL_RAW_BYTES;
byte raw[TOTAL_RAW_BYTES];
uint16_t parsed[8];

//--------------SETUP-UP---------------------------
void setup()
{
  initial();
  Serial.begin(2000000);
  while(!Serial){} // wait for usb connection
  SPI.begin();
}
//---------------LOOP--------------------------
void loop()
{
  startTime = micros();
  readData();
  elapsedTime = micros() - startTime;
  if (elapsedTime != old_res)
  {
    Serial.print("Conversion time:\t");
    Serial.print(elapsedTime);
    Serial.println(" microseconds");
    old_res = elapsedTime;
  }
  parseRawBytes();

  for (int i = 0; i < 8; i++) {
    Serial.print((float)parsed[i] * SCALE_FACTOR, 5);
    Serial.print(",");
  }

  Serial.print("\r\n");
}
//-----------------------------------------
void initial()
{
  pinMode(BUSY, INPUT);

  pinMode(START_CONVERSION, OUTPUT);
  pinMode(CHIP_SELECT, OUTPUT);
  pinMode(D7_out, OUTPUT);
  pinMode(RD, OUTPUT);
  digitalWrite(START_CONVERSION, HIGH);
  digitalWrite(CHIP_SELECT, HIGH);

}
//-----------------------------------------
void parseRawBytes() {
  for(int i = 0; i<(sizeof(parsed) / sizeof(int));i++)
    {
      parsed[i] = (raw[i*2] << 8) + raw[(i*2)+1];
    }
}
//-----------------------------------------

//-----------------------------------------
void conversionPulse(uint8_t port)
{
  digitalWrite(port, LOW);
//  delayMicroseconds(1);
  digitalWrite(port, HIGH);
}
//-----------------------------------------
/*
1- start conversion START_CONVERSION HIGH
2- wait until the busy is LOW again
3- put the CS to LOW
4- Read a byte from the SPI
*/
void readData()
{
  conversionPulse(START_CONVERSION);
  while (digitalRead(BUSY) == HIGH) {
  //  delayMicroseconds(1);
  }
  SPI.beginTransaction(_spiSettings);
  digitalWrite(CHIP_SELECT, LOW);
  while (bytesToRead > 0) {
    raw[TOTAL_RAW_BYTES - bytesToRead] = SPI.transfer(0x00);
    bytesToRead--;
  }
  digitalWrite(CHIP_SELECT, HIGH);
  SPI.endTransaction();

  bytesToRead = TOTAL_RAW_BYTES;
}
//-----------------------------------------

What speed does it do now?

Hi Rohit Gupta, Now i am getting a sampling frequency of 1.8ksps,i checked this sampling frequency (start conversion signal) through dso.

Please format your code, this is very hard to read.

@PMF Hi PMF Please Refer I updated the code

I'm not sure about the capabilities of the ADC, but a quick estimate suggests this could be hard. An Arduino UNO has a clock frequency of 16 Mhz, requiring a 10kHz sampling rate would require that a single loop does not take more than 1600 clock cycles. Probably possible, but only with optimized code (e.g., remove unnecessary output)

Thank u for your response dear PMF


text:
TCP server on ESP32 CAM
I am writing a TCP server on ESP32 CAM to receive joystick coordinates as a JSON string. I have a TCP client on my laptop which sends joystick coordinates from a joystick connected to my laptop. In have implemented a 0.8 second throttling on the client side, such that JSON strings are only sent 0.8 seconds apart. When I test this, I am able to run the joystick reliably for about a minute before the ESP crashes due to a Guru Meditation Error.
This is the exception I get:
Guru Meditation Error: Core  0 panic'ed (IllegalInstruction). Exception was unhandled.
Memory dump at 0x4016797c: c00289c0 f01d0020 40004136
Core  0 register dump:
PC      : 0x40167980  PS      : 0x00060030  A0      : 0x40105dff  A1      : 0x3ffbc110
A2      : 0x00000002  A3      : 0x00000011  A4      : 0x3ffbe0d4  A5      : 0x00000000
A6      : 0x3ffbc13c  A7      : 0x0000005d  A8      : 0x80084f78  A9      : 0x3ffbc0f0
A10     : 0x00000001  A11     : 0x00000000  A12     : 0x00000000  A13     : 0x3ff42034
A14     : 0x0000001e  A15     : 0xfffffffe  SAR     : 0x00000017  EXCCAUSE: 0x00000000
EXCVADDR: 0x00000000  LBEG    : 0x4008a674  LEND    : 0x4008a690  LCOUNT  : 0xffffffff

Backtrace: 0x4016797d:0x3ffbc110 0x40105dfc:0x3ffbc180 0x400d5fd8:0x3ffbc1a0 0x400d5f21:0x3ffbc1c0 0x400d6a8e:0x3ffbc1f0 0x4016f10b:0x3ffbc220

This is my stack trace:
PC: 0x40167980: sub32 at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecp_curves.c line 980
EXCVADDR: 0x00000000

Decoding stack results
0x4016797d: sub32 at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecp_curves.c line 979
0x40105dfc: psram_cmd_end at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 385
0x400d5fd8: psramInit at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-psram.c line 69
0x400d5f21: initArduino at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-misc.c line 240
0x400d6a8e: app_main() at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\main.cpp line 70
0x4016f10b: main_task at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/freertos/port/port_common.c line 141

Sometimes I get this exception:
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1344
load:0x40078000,len:13964
load:0x40080400,len:3600
entry 0x400805f0
Guru Meditation Error: Core  0 panic'ed (LoadProhibited). Exception was unhandled.

Core  0 register dump:
PC      : 0x401061a9  PS      : 0x00060030  A0      : 0x80085042  A1      : 0x3ffbc0f0
A2      : 0x00000001  A3      : 0x00000000  A4      : 0x0ffd114c  A5      : 0x00000000
A6      : 0x0000001e  A7      : 0xfffffffe  A8      : 0x00020000  A9      : 0x3ff44024
A10     : 0x700000eb  A11     : 0x00000000  A12     : 0x00000008  A13     : 0x3ffbc0cc
A14     : 0xb7a8d869  A15     : 0x3ff42080  SAR     : 0x0000000f  EXCCAUSE: 0x0000001c
EXCVADDR: 0x00000001  LBEG    : 0x40106144  LEND    : 0x4010614d  LCOUNT  : 0x00000000

Backtrace: 0x401061a6:0x3ffbc0f0 0x4008503f:0x3ffbc110 0x40105d02:0x3ffbc180 0x400d5fd8:0x3ffbc1a0 0x400d5f21:0x3ffbc1c0 0x400d6a8e:0x3ffbc1f0 0x4016f10b:0x3ffbc220

Which produces this stack trace:
PC: 0x401061a9: psram_set_cs_timing at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 674
EXCVADDR: 0x00000001

Decoding stack results
0x401061a6: psram_set_cs_timing at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 676
0x4008503f: psram_enable at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram_psram.c line 998
0x40105d02: esp_spiram_init at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/esp_hw_support/port/esp32/spiram.c line 163
0x400d5fd8: psramInit at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-psram.c line 69
0x400d5f21: initArduino at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\esp32-hal-misc.c line 240
0x400d6a8e: app_main() at C:\Users\ikibf\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.11\cores\esp32\main.cpp line 70
0x4016f10b: main_task at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/freertos/port/port_common.c line 141

This is the TCP server:
#include <WiFi.h>
#include <WiFiAP.h>

#include <WiFiClient.h>
#include <ArduinoJson.h>
#include "helper_funcs.h"
#include "esp_wpa2.h"
#include "wifi_credentials.h"   // contains wifi connection params

// JSON setup stuff
const int buffer_size = 512;
char json_buffer[buffer_size];
int buffer_index = 0;

const int port = 8990;

WiFiServer server(port);

// Rest of code
void setup(){
  init_motors();

  // connect to WiFi
  Serial.begin(115200);
   WiFi.disconnect(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WPA2_AUTH_PEAP, EAP_IDENTITY, EAP_USERNAME, EAP_PASSWORD);

  while(WiFi.status() != WL_CONNECTED){
    Serial.println("Connecting to WiFi....");
    delay(1000);
  }

  Serial.println("Connected to WiFi with IP: ");
  Serial.println(WiFi.localIP());

  // Start TCP/IP server
  server.begin();
  Serial.println("Started TCP/IP server");
}

void loop(){
  WiFiClient client = server.available();

  // if a client has connected to the TCP/IP server, read PWM data and use it
  if(client){
    Serial.println("Client connected");
    while(client.connected()){
      if(client.available()){
        char c = client.read();

        if((buffer_index != buffer_size-1) && (c != '\n')){
          json_buffer[buffer_index++] = c;
        } else {
          // parse the JSON object
          json_buffer[buffer_index] = '\0';
          StaticJsonDocument<buffer_size> doc;
          DeserializationError error = deserializeJson(doc, json_buffer);

          if(error){
            Serial.println("JSON parsing unsuccessful");
            Serial.println(error.c_str());
          } else {
            // get PWM data
            int x = doc["x"], y = doc["y"];
            Serial.print("X: ");
            Serial.println(x);
            Serial.print("Y: ");
            Serial.println(y);

            control_motors(x, y);
          }

          // reset JSON buffer for next data
          buffer_index = 0;
        }
      }
    }

    client.stop();
    Serial.println("Client disconnected");
  }

}

Does anyone know how I should solve this?

try to change the PSRAM setting in Tools menu

@Juraj I enabled PSRAM after chnaging the board to ESP Dev Module as the PSRAMoption was not available when using ESP32 Wrover Module. Unfortunately, the ESP will reboot randomly, which shuts down the server


text:
Whats the MPPZ 3610 on Arduino nano every
I'm curious what's the MPPZ chip on my Arduino nano everu

You mean MPM3610? https://www.monolithicpower.com/en/mpm3610.html

Do you have a photo of your MPPZ 3610? Or have you mis-read the code? Please [edit] your question and upload a (cropped) photo.

I just didn't understand it at first

From Arduino Nano Every datasheet:

MPM3610 (DC-DC)

Regulates input voltage from up to 21V with a minimum of 65% efficiency @minimum load
More than 85% efficiency @12V


text:
How execution time of code instructions influences signal between Arduino and DHT11?
I am exemining code for DHT11 from CircuitGeeks, variant without using lib. The problem is a mismatch between DHT11/DHT22 protocol and signals, which are read from sensor in scetch. Despite this, sketch is working and I would like to find out how.
#define DHT11_PIN   12

unsigned long TON_TIME = 0;
unsigned long TOFF_TIME = 0;

unsigned char data_byte[5];
unsigned int data_packet[40];
unsigned char bit_data = 0;
unsigned char checksum_byte = 0;
int bit_counter = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("DHT11 Humidity & Temperature Sensor\n");
  delay(1000);//Wait before accessing Sensor
}

void loop() {
  pinMode(DHT11_PIN, OUTPUT);
  digitalWrite(DHT11_PIN, LOW);
  delay(18);
  digitalWrite(DHT11_PIN, HIGH);
  pinMode(DHT11_PIN, INPUT_PULLUP);

  TOFF_TIME = pulseIn(DHT11_PIN, LOW);
  if (TOFF_TIME <= 84 && TOFF_TIME >= 76) {
    while (1) {
      TON_TIME = pulseIn(DHT11_PIN, HIGH);
      if (TON_TIME <= 28 && TON_TIME >= 20) {
        bit_data = 0;
      }
      else if (TON_TIME <= 74 && TON_TIME >= 65) {
        bit_data = 1;
      }
      else if (bit_counter == 40) {
        break;
      }
      data_byte[bit_counter / 8] |= bit_data << (7 - (bit_counter % 8));
      data_packet[bit_counter] = bit_data;
      bit_counter++;
    }
  }
  checksum_byte = data_byte[0] + data_byte[1] + data_byte[2] + data_byte[3];

  if (checksum_byte == data_byte[4] && checksum_byte != 0) {
    Serial.println("Humidity: ");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c]);
    }
    Serial.print("\t");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 8]);
    }
    Serial.print("\t");
    Serial.print(data_byte[0]);
    Serial.print("%");
    Serial.println(" ");

    Serial.println("Temperature: ");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 16]);
    }
    Serial.print("\t");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 24]);
    }
    Serial.print("\t");
    Serial.print(data_byte[2]);
    Serial.print("C");
    Serial.println(" ");

    Serial.println("Checksum Byte: ");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 32]);
    }
    Serial.println(" ");
    Serial.print("CHECKSUM_OK");
    Serial.println("");
    Serial.println("");
  }

  bit_counter = 0;
  data_byte[0] = data_byte[1] = data_byte[2] = data_byte[3] = data_byte[4] = 0;
  delay(1000);
}

Looking into the code there is 18 ms of LOW level for initialization. Then about 40 us of HIGH level, it can be considered as time between digitalWrite(DHT11_PIN, HIGH); and TOFF_TIME = pulseIn(DHT11_PIN, LOW); instructions. But then after 80 us of LOW level TOFF_TIME = pulseIn(DHT11_PIN, LOW); it should be 80 us HIGH level. Instead of this, the code is being continued by conditions for checking pulses length, which are responsable for data bits. If pulse length is 26-28 us it's 0, if 70 us - it's 1. I understand that with TON_TIME = pulseIn(DHT11_PIN, HIGH); instruction we will find length of HIGH pulses of data bits only.

Why 80 us HIGH level is passed, however this doesn't impact on interaction with sensor? Does it pass in time of executing instructions from  if (TOFF_TIME <= 84 && TOFF_TIME >= 76) to TON_TIME = pulseIn(DHT11_PIN, HIGH); ?

At the end of the 80 µs LOW from the HDT11, pulseIn(DHT11_PIN, LOW)
returns. At this point in time, the data line is HIGH, somewhere near
the beginning of the positive 80 µs pulse. Now, the code executes the
first pulseIn(DHT11_PIN, HIGH).
You cannot measure the length of a positive pulse if you missed the
rising edge. Thus, as pulseIn() finds the line HIGH, it will first
wait until it transition to LOW, then wait until in transitions back to
HIGH, and only then starting timing.
See for example the implementation of the counting loop in the AVR
core, or rather the C code that served to generate the assembly
implementation. It has three waiting loops:

wait for any previous pulse to end
wait for the pulse to start
wait for the pulse to stop


text:
How to send multiple and different bytes via SPI using custom function
I need to send multiple bytes via SPI to a controller.
I would like to have a function which I can use for doing that as I need to do some other things with it (timing, setting pin states etc.).
The issue is, that I need to pass a variying size of bytes and also I need to change these bytes in the code.
My not compiling try to do it:
const int CS = 9;
const int A_0 = 7;
#define STOP 0xFFF

void setup() {
 pinMode(CS, OUTPUT);
 pinMode(A_0, OUTPUT);
 digitalWrite(CS, 0);
 digitalWrite(A_0, 0);
 SPI.begin();
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (int []){0xE3, 0xE4, 0x00, 0x122, STOP});
 SPI.endTransaction;
 //some code
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (int []){0xE6, 0xE7, 0x02, STOP});
 SPI.endTransaction;
}

void DispData(int chip, int data[] ){
  digitalWrite(CS, chip);
  digitalWrite(A_0, 0);
  int i=0;
  delayMicroseconds(12);
  digitalWrite(A_0, 1);
  delayMicroseconds(7);
  while(data[i] != STOP)
  {
    SPI.transfer(data[i]);
    i++;
  }
}

I could get your code to compile with the solution described in the answer to this question. Note: In the first call to DispData you have 3 parameters, though the function only takes 2 parameters.

@chrisl I've corrected the function call with 2 parameters now. How did you do it exactly? I did not really understand the solution from your link.

@chrisl - Just to clarify: are you referring to the accepted answer or zett42's answer? I assume you mean the accepted answer but just wanted to be sure. :-)

@Greenonline The accepted answer. Should have mentioned that XD

After more searching I found one solution, using const int instead of int:
const int CS = 9;
const int A_0 = 7;
#define STOP 0xFFF

void setup() {
 pinMode(CS, OUTPUT);
 pinMode(A_0, OUTPUT);
 digitalWrite(CS, 0);
 digitalWrite(A_0, 0);
 SPI.begin();
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (const int []){0xE3, 0xE4, 0x00, 0x122, STOP});
 SPI.endTransaction;
 //some code
 SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
 DispData(1, (const int []){0xE6, 0xE7, 0x02, STOP});
 SPI.endTransaction;
}

void DispData(int chip, const int data[] ){
  digitalWrite(CS, chip);
  digitalWrite(A_0, 0);
  int i=0;
  delayMicroseconds(12);
  digitalWrite(A_0, 1);
  delayMicroseconds(7);
  while(data[i] != STOP)
  {
    SPI.transfer(data[i]);
    i++;
  }
}


text:
Confusion on bit shifting
I am trying to read-in two separate, 3 byte messages over CAN, add them together, and send back out over CAN, on a CANBED V1 which uses a Leonardo.
My confusion is using bit shifting.
If I attempt to shift 1 by 1..14 bits I seem to understand,
uint32_t hdbs = 1 << (14) ;
Serial.println(hdbs, BIN);
this codes gives me 100000000000000 in the display window if printing binary or 16384 decimal.
But if I try a bit shift of 15 or more
uint32_t hdbs = 1 << (15) ;
Serial.println(hdbs, BIN);
I am now confused as I get
11111111111111111000000000000000 or 4294934528 in decimal
What basic concept am I missing?  I tried using unsigned long, long, etc.,
If I do some simple math and use hdbs = 8 * 4095 I get the correct answer of 32760, but when I try 8*4096 I get 4294934528, which should be 32768 (which seems like would exceed a 16 bit unsigned, but I thought I was declaring hdbs as a 32 bit variable.

This is really more of a C++ question, but I don't know whether or not you know that. Roughly speaking, in C, C++ (and so "Arduino" language) expressions are evaluated for types in parallel with their values from the inside out following operator precedence rules much like regular algebra.
You must ensure the type on the left-hand-side of the << is already prepared to accept the resulting value. E.g.:
uint32_t hdbs = static_cast<uint32_t>(1) << 15;

uint32_t hdbs = (uint32_t)1 << 15;

uint32_t hdbs = uint32_t(1) << 15;

uint32_t hdbs = uint32_t{1} << 15;

uint32_t hdbs = 1UL << 15;

1 is of type int, which for Leonardo is a 16-bit type.
Usually when binary operators like + or / are evaluated for result type, the both sides are taken into account in something called usual arithmetic conversions. For << it just looks at the type of the thing being shifted and takes that. So your result of 1 << 15 is being evaluated in an int, which cannot store that value on the AVR. The fact that you later use that in initializing uint32_t hdbs is beside the point when calculating 1 << 15 itself.
I would have tentatively guessed you'd get 0x8000 which when converted to 32-bit under sign extension would have resulted in 11111111 11111111 10000000 00000000. But, an attempt to overflow a signed integer type like this is undefined. It cannot be reliability expected to produce any particular behaviour, let alone value.
Had you been using 32-bit chip like an ARM or ESP32/ESP8266, this would have just worked because the int type there is 32-bit.

Thats amazing!  Thank you!  I am such a newb (Mechanical Engineer) pretending to write hack code, super appreciate your time!

Ah, I was off by 8-bits on my "would guessed" thing. So, you are getting what I would have guessed. Though again, by "luck". Going to edit for that.

This is how C type cast works.
C expressions are of signed type by default. If an expression type has too small bit length than it may get also negative due to overflow (into the high bit which is also a sign bit).
Whenever a signed expression needs to fit into more bits, it gets expanded into longer signed value first (which is effectively the same as duplicating the high bit as many times as needed). And only after that, it will be converted to unsigned (which is basically no-op).
So to overcome this thing you need to change cast order by making 1U or 1UL instead of just 1. Then you will never run into signed values and, so, no sign bit expansion.


text:
How to make a stepper motor's speed follow a sine wave
I'm trying to have the rotational speed of a stepper follow that of a sine wave with a period of x seconds. So it starts at a speed of 0 at 0°, picks up and peaks at 90°, slows back down to 0 at 180°, back up to peak speed at 270°, and back to 0 at 360°, if that makes sense. I'm trying to have the period of the rotation adjustable as well.
Right now I'm having trouble even getting it to spin with what I have now. if I start at 0 speed it doesn't step and therefore doesn't continue with the sketch, or at least I think that's what's happening. Any advice on how to do this would be appreciated.
I'm using the equation (topSpeed) * sin((pi * time) / period) for the wave.
#include <Stepper.h>

const int stepsPerRevolution = 200.000;
const float pi = 3.14159265358979;
const int period = 5; // Seconds
const int topSpeed = 100; // RPM

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

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

void loop() {
  for (int tStart = millis(); (millis()-tStart) < period;) {
    float speed = topSpeed * (sin((pi * (millis() / 1000.000)) / period));

    if (speed = 0) {
      myStepper.setSpeed(1);
      myStepper.step(1);
    } else {
      myStepper.setSpeed(speed);
      myStepper.step(1);
    }
  }
}

Checking for equality in an if statement needs ==, not =, which is a  assignment

Disclaimer: This is not intended to be a complete answer, it is only
meant to help you with the math.
I find a contradiction in the problem statement:

it starts at a speed of 0 at 0°, picks up and peaks at 90°, slows back
down to 0 at 180° [...]

If the speed is a sinusoidal function, then at this point you have
completed the positive part of the period. The speed will now become
negative (i.e. the stepper will move backwards), and remain negative for
the second half of the period.

back up to peak speed at 270°, and back to 0 at 360°

No. It will reach peak (negative) speed at 90°, and back to zero speed
at 0°.
If you really want the stepper to turn always in the same direction, the
speed cannot be sinusoidal. What you can do instead is use a sinusoidal
function with an offset, such that the speed fluctuates between zero
and some maximum, instead of fluctuating between ±maximum.
The graph below represents speed as a function of time. The first curve
(“sine”) is a movement that rocks back and forth like: 0° → 90° → 180° →
90° → 0°. The “shifted sine” curve is a continuous rotation doing a full
revolution with a speed that is always non-negative.

If you want to properly describe the movement, you should integrate the
speed in order to find the (angular) position as a function of time. You
will find a continuous ramp (because of the shift in the speed)
superimposed with a sinusoidal movement, as in this graph:

If that may help, I did the integration for you and found this formula:
angle = 360° × (t/T − sin(4πt/T)/(4π))
where t is the current time and T the rotational period. This can then
be differentiated to get the speed:
speed = 360°/T × (1 − cos(4πt/T))


text:
Arduino Pro Mini & FTDI USB can't upload sketh
As the title says, I have an Arduino Pro Mini 3.3V & FTDI FT232RL that I connected to the arduino board. It worked for a while, on and off but the serial monitor wasn't working. Fixed that by using 57600 baud rate but now I get these errors. I tried multiple things from [this][1] post but they didn't work. Any help would be appreciated.
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x53
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xec
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x71
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x87
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x60
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe8
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x7d
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd0
Failed chip erase: uploading error: exit status 1

  [1]: https://arduino.stackexchange.com/questions/17/avrdude-stk500-getsync-not-in-sync-resp-0x00-aka-some-dude-named-avr-won


text:
Multiple Ultrasonic Sensors with Arduino and 74HC595 Shift Register
I'm currently developing a project aimed at streamlining the process of identifying available closets within my school lockers room. The objective is to utilize ultrasonic sensors to determine the occupancy status of each closet, ensuring that students can easily locate an unoccupied one without searching through each door. For testing purposes, I'm using an Arduino along with just 8 ultrasonic sensors and one 74HC595 shift register. The final implementation will involve an ESP32, expanding the system to cover approximately 48 closets, each equipped with its own ultrasonic sensor and LED indicator.
I searched about the 74HC595 shift register and tried to implement my own testing code.

the functionality i've aimed to implement:

This Arduino code is designed to interface multiple HC-SR04 ultrasonic sensors with an Arduino using a 74HC595 shift register. The shift register is utilized to control the VCC (power) of each ultrasonic sensor individually. The wiring involves connecting the echo pins of all sensors together and connecting them to a single Arduino pin (EchoPin). Similarly, the trigger pins of all sensors are connected together and linked to another Arduino pin (TrigPin). The ground pins of all sensors are connected to a common ground pin on the Arduino.
Upon pressing a button connected to pin A0, the Arduino initiates a distance measurement sequence. The 74HC595 shift register is used to selectively provide power to each ultrasonic sensor one at a time. This is achieved by shifting a binary value corresponding to a specific sensor's power pin into the shift register and updating the latch pin to activate the chosen sensor. The distance readings from each sensor are then obtained and stored in an array (sensorsValue).
The getDistance function calculates the distance using the HC-SR04 sensor's echo and trigger pins, based on the time it takes for the ultrasonic pulse to travel to the target and back.
Overall, this code enables efficient control and reading of multiple ultrasonic sensors through a single Arduino, optimizing power consumption by activating sensors selectively. The serial monitor outputs the distance readings for each sensor when the button is pressed.

my code :

/******************************************************************************/
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   Shifter.ino                                        :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: unknown <unknown@student.1337.ma>        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/02/28 21:26:13 by unknown          #+#    #+#             */
/*   Updated: 2024/02/28 22:55:14 by unknown         ###   ########.fr       */
/*                                                                            */
/******************************************************************************/

/*

   Trigger HC-SR04 units with a 74HC595

   Wiring :

    Arduino pin 2 to echo of all HCSR04
    Arduino pin 3 to trig of all HCSR04
    Arduino Ground pin to GND of all HCSR04

    74HC595 ` POWER ` pin (16) to vcc of the Arduino (5v)
    74HC595 ` OUTPUT 1 ` pin (15) to VCC of the first HCSR04
    74HC595 ` SERIAL INPUT ` pin (14) to Arduino pin (6)
    74HC595 ` OUTPUT ENABLE ` pin (13) to Arduino (GND)
    74HC595 ` REGISTER CLOCK / LATCH ` pin (12) to Arduino pin (7)
    74HC595 ` SHIFT REGISTER CLOCK ` pin (11) to Arduino (8)
    74HC595 ` SHIFT REGISTER CLEAR ` pin (10) to Arduino GND
    74HC595 pin (9) NOT USED

    74HC595 ` OUTPUT 2 ` pin (1) to VCC of the second HCSR04
    74HC595 ` OUTPUT 3 ` pin (2) to VCC of the third HCSR04
    74HC595 ` OUTPUT 4 ` pin (3) to VCC of the fourth HCSR04
    74HC595 ` OUTPUT 5 ` pin (4) to VCC of the fifth HCSR04
    74HC595 ` OUTPUT 6 ` pin (5) to VCC of the sixth HCSR04
    74HC595 ` OUTPUT 7 ` pin (6) to VCC of the seventh HCSR04
    74HC595 ` OUTPUT 8 ` pin (7) to VCC of the eighth HCSR04
    74HC595 ` Ground ` pin (8) to vcc of the Arduino (GND)
*/

/*When Clicking the button, Arduino will read the value of
  each sensor value continuously (the first sensor, then the second , ...) and store it in  the sensors_value double array*/
int btn_trigger = A0;

// HCSR04 echo && trig pins
const int EchoPin = 2;
const int TrigPin = 3;

// Binary pin values for shift register
const int sensorsPin[8] = {
  B00000001,  /*1*/
  B00000010, /*2*/
  B00000100, /*4*/
  B00001000, /*8*/
  B00010000, /*16*/
  B00100000, /*32*/
  B01000000, /*64*/
  B10000000 /*128*/
};

double sensorsValue[8] = {
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
  0.00,
};

// Pin connected to ST_CP of 74HC595
const int latchPin = 7;

// Pin connected to DS of 74HC595
const int dataPin = 6;

// Pin connected to SH_CP of 74HC595
const int clockPin = 8;

// Pin connected to MR (SRCLR) of 74HC595 (active low)
const int clearPin = 9;

double getDistance(int triggerPin, int echoPin);

void setup() {
  Serial.begin(9600);
  Serial.println("HCSR04BitShiftV1 Initialization...");

  pinMode(btn_trigger, INPUT_PULLUP);

  pinMode(EchoPin, INPUT);
  pinMode(TrigPin, OUTPUT);

  // Set pinMode for 74HC595 pins
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);

  // Additional pin for clearing the shift register
  pinMode(clearPin, OUTPUT);
  digitalWrite(clearPin, LOW);  // Clear the shift register initially
}

void loop() {
  // Check if the button is pressed
  int buttonState = digitalRead(btn_trigger);

  if (buttonState == LOW) {
    Serial.println("Getting Distance ...");
    // Iterate through each sensor
    for (int i = 0; i < 8; i++) {
      // Set the latchPin LOW before sending data
      digitalWrite(latchPin, LOW);

      // Shift out the binary value for the current sensor
      shiftOut(dataPin, clockPin, MSBFIRST, sensorsPin[i]);

      Serial.print("Shifted Value: ");
      Serial.println(sensorsPin[i], BIN);

      // Set the latchPin HIGH to update the shift register
      digitalWrite(latchPin, HIGH);

      // Get the distance for the current sensor and store it in the array
      sensorsValue[i] = getDistance(TrigPin, EchoPin);

      // Print the distance for debugging
      Serial.print("Sensor ");
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(sensorsValue[i]);
      Serial.println("cm");
      // Delay between sensor readings
      delay(1000);
    }
  }
}

/*Get the Distance value*/
double getDistance(int triggerPin, int echoPin)
{
  unsigned long duration = 0;
  double distance = 0.0;
  float soundspead = 0.034;

  digitalWrite(triggerPin, LOW); // Clear the trigger
  delayMicroseconds(2);
  // Sets the trigger pin to HIGH state for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);
  // Reads the echo pin, and returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  Serial.print("Pulse Duration: ");
  Serial.print(duration);
  Serial.println(" microseconds");

  distance = (soundspead * duration) / 2;
  return distance;
}

Wiring :

Problem :

But I've encountered a big problem which is that the pulse duration readings for all ultrasonic sensors consistently show 0 microseconds, resulting in distance readings of 0.00 cm. This suggests that the pulseIn function, responsible for measuring the duration of the echo signal, is not receiving valid signals or is not functioning as expected. I suspect potential problems in the wiring, shared echo, and trigger pin configurations, as well as issues with the timing of trigger signals, echo signal reception, and the overall configuration of the 74HC595 shift register.

Output :

HCSR04BitShiftV1 Initialization...
Getting Distance ...
Pulse Duration: 0 microseconds
Sensor 1: 0.00cm
Pulse Duration: 0 microseconds
Sensor 2: 0.00cm
Pulse Duration: 0 microseconds
Sensor 3: 0.00cm
Pulse Duration: 0 microseconds
Sensor 4: 0.00cm
Pulse Duration: 0 microseconds
Sensor 5: 0.00cm
Pulse Duration: 0 microseconds
Sensor 6: 0.00cm
Pulse Duration: 0 microseconds
Sensor 7: 0.00cm
Pulse Duration: 0 microseconds
Sensor 8: 0.00cm

Clarification :

I apologize for any confusion caused by my initial message. To clarify, in my first attempt, I inadvertently connected the ultrasonic sensor's trig pin directly to the output of the shift register, rather than controlling the power of each sensor individually. Additionally, I used separate pins on the Arduino for each sensor's echo pin. While this configuration did work, it resulted in the utilization of a significant number of pins . That's why I thought using shift register to control sensors would be a better approach.
Initially, I attempted to control four ultrasonic sensors by connecting their trig pins directly to the output of the shift register. Here is the link to the corresponding Tinkercad project!
In my second attempt, I explored a different approach by connecting the VCC of all sensors to the outputs of the shift register for control, aiming to minimize the number of pins used. You can view the project on Tinkercad via the following link
as I mentioned before Indeed, each closet has its own ultrasonic sensor, all connected to a single ESP32. My plan involves using 6 shift registers, each controlling 8 ultrasonic sensors with one 74HC595, thereby minimizing the number of pins used to 2 main pins shared among all shift registers and six separate control pins (one for each shift register). While using 48 ultrasonic may seem excessive and complex, that's the task I've been assigned. However, I'm exploring whether it's feasible or if alternative sensor options would be more suitable in terms of cost and functionality.
I would be extremely grateful for your guidance. Thank you in advance for any help you can provide.

I'm not sure I understand your concept. You're triggering all sensors with just one pin and also expect the echo on a single pin, the shift register only controls which sensor has "power". Unfortunately, a sensor that does not have power may still interfere with your measurement, as the resistance of the output lines to ground is not infinite. Also, I doubt that the shift register can provide enough power on its outputs to drive the sensors.

Any particular reason you use ultrasonic sensors? Wouldn't a simple LED sensor barrier be easier?

The 74HC595 datasheet claims 6mA output current. This guide states a working current for the typical HC-SR04 ultrasonic sensor module as 15mA, which is - in fact - higher than 6mA. So I would second PMF here. And also you probably need to isolate each echo pin somewhat with a diode. Depends on if the echo pin gets actively driven in each state.

why do you have eight ultrasonic sensors, when the final product will have only one?

@jsotola I think the OP means that "each [of the 48 closets] has it's own ultrasonic sensor", but all connected to a single ESP32.

@PMF Thank you for your response and insights. I apologize for any confusion caused by my initial message. To clarify, in my first attempt, I inadvertently connected the ultrasonic sensor's trig pin directly to the output of the shift register, rather than controlling the power of each sensor individually. Additionally, I used separate pins on the Arduino for each sensor's echo pin. While this configuration did work, it resulted in the utilization of a significant number of pins . That's why I thought using shift register to control sensors would be a better approach.

@PMF Initially, I attempted to control four ultrasonic sensors by connecting their trig pins directly to the output of the shift register. Here is the link to the corresponding Tinkercad project: https://www.tinkercad.com/things/35OOmRfpQJs-ultrasonic-distance-sensing-with-shift-registers/editel?returnTo=%2Fdashboard%3Fcollection%3Ddesigns%26type%3Dcircuits&sharecode=_WTT3Y3u6X5gkH5PY6UbP6dCHOSni9hURti0_H86PB0

@PMF In my second attempt, I explored a different approach by connecting the VCC of all sensors to the outputs of the shift register for control, aiming to minimize the number of pins used. You can view the project on Tinkercad via the following link:
https://www.tinkercad.com/things/4VS2loCt9BO-shifter/editel?returnTo=%2Fdashboard%3Fcollection%3Ddesigns%26type%3Dcircuits&sharecode=BCOL5jWmQpCFJMlmZkSDTaiuxuDvl_GYz6KLmYQfPEY

@PMF as u mentioned to jsotola Indeed, each closet has its own ultrasonic sensor, all connected to a single ESP32. My plan involves using 6 shift registers, each controlling 8 ultrasonic sensors with one 74HC595, thereby minimizing the number of pins used to 2 main pins shared among all shift registers and six separate control pins (one for each shift register). While using 48 ultrasonic may seem excessive and complex, that's the task I've been assigned. However, I'm exploring whether it's feasible or if alternative sensor options would be more suitable in terms of cost and functionality.

If connecting the echo pins to individual input pins works, that could be a possible solution. You could use an Arduino Due instead of an ESP32 - it's a bit more expensive but has more than 50 input pins.

@PMF Thank you for suggesting the Arduino Due as an alternative to the ESP32. However, purchasing an Arduino Due in my country's electronic stores is quite expensive. I'm still exploring options to use ultrasonic sensors with a shift register while minimizing the number of pins used as much as possible. In my opinion, it might be more efficient to consider using alternative sensor types with the shift register instead of ultrasonic sensors. Do you have any suggestions for alternative sensors that could be used in this setup?

One possible alternative I already mentioned above was a LED light barrier. A led on one side and a photoresistor on the other side of the cabinet. Or they could even be on the same side if the cabinets are metallic. I use https://sensorkit.joy-it.net/de/sensors/ky-033 with some reflective tape on the other side for a similar application.

@PMF Thank you for your recommendation regarding the IR sensor or the LED and photoresistor combination as alternatives for detecting the occupancy of the cabinet. I will certainly explore the possibility of using them with my colleague. Additionally, I'm considering that while the recommended sensors you suggested are affordable, they may work just fine if they are well-positioned in the cabinet to detect the entire cabinet space.


text:
Control a JQC-3F relay with ESP32
I have this circuit I build and I have a problem. When I activate/deactivate SW1, I can hear the RLY1 flip on and off which is fine. But when I activate the PIN 13, the RLY2 do not work. When the relay is connected, I can measure 1.1V but when I disconnect the relay, my multimeter show me 3.3V.
Anyone have an idea of what I could do to fix this issue and be able to control my 3V relay with PINS in ESP32?

simulate this circuit – Schematic created using CircuitLab

the ESP32 cannot provide enough current to activate a relay ... research how to drive a relay with a microcontroller

Thank you so much, I didn't formulated that in that way in Google, I found how to do it, it now work with the usage of a transistor :D

You should post an answer, as comments get deleted over time.


text:
ESP32 pseudo hardware flow control for Bluetooth SPP
I'm using an ESP32 as a Bluetooth SPP to USB-serial null modem between a MacBook Pro (via SPP) and a laptop running Windows 11.
The ESP32 program logic is about as simple as it gets:
int nextByte;
void loop() {
    nextByte = Serial.read();
    if (nextByte > 0) {
        if (bt.isReady())
            bt.write(nextByte & 0xff);
        else
            dieAndBlinkLed();
    }
    nextByte = bt.read();
    if (nextByte > 0)
        Serial.write(nextByte & 0xff);
}

At the Mac & Windows ends, I'm using JSerialComm with event-driven reads and blocking direct writes.
The problem I'm having is, if I call port.writeBytes(byteArray, byteArray.length) with a byteArray that's longer than approximately 520-540 bytes (i.e. slightly longer than 512, but way less than 768 or 1024, let alone 4096), it seems to silently drop bytes.
I have JSerialComm's receive listener configured to buffer bytes and deliver them to my callback when a 0 byte is received (I'm using COBS to escape-out zero bytes). It seems to be dropping the heads and delivering only the 520-540 byte tails of each frame, but I'm not really sure what's happening between the moment I call port.writeBytes() on the Mac end and send a chunk larger than ~540 bytes to the Bluetooth SPP port and the moment the callback at the other end delivers only the tail end.
If push came to shove, I suppose I could rewrite the program to use 500-byte frames (~509-512 bytes with overhead) instead of 4000-byte frames (~4010-4028 bytes with overhead), but then the relative overhead would quadruple from ~0.6% to ~2.5% (every frame has a 4-byte header at the start, a 4-byte crc32 at the end, and 1-16 bytes of COBS overhead... 1, plus one for every 254+ bytes in a row without at least one zero byte).
Before I throw in the towel, I'm trying to get a better understanding of what the actual hard constraints imposed by esp32 Bluetooth SPP are, and make sure I'm not just making a stupid mistake somewhere along the line that's causing behind the scenes flow control to fail in a way I can fix.
Off the top of my head, I can think of the following points of failure:

JSerialComm's handling of the bytes before delivering them to OSX
OSX's serial buffer overflowing because the bluetooth spp stack is declining to accept bytes while it's busy (re)transmitting earlier ones
my esp32 event loop being too slow and dropping bytes
serial wire loss between the esp32 and cp2102
overflowing the cp2102's buffer in between USB polls
USB control mode being unable to ferry the bytes from the cp2102 through the USB port fast enough (64 bytes/millisecond max... assuming it actually gets called every millisecond, and most of those 64 bytes are available for use)
the cp2102 driver on Windows overflowing its own buffer before JSerialComm grabs its contents
JSerialComm itself having a buffer smaller than ~576 bytes and overflowing before it sees the next 0 and delivers the chunk to my callback

Before tackling the possibility of a JSerialComm-related problem at StackOverflow, I want to eliminate anything esp32-related as a potential problem.
So.. first... is there any possibility that the way I'm relaying data between the ports a byte at a time could be the problem? For what it's worth, dieAndBlinkLed() has never triggered... and the problems I've observed so far have involved data entering the pipeline at the Mac/bluetooth-SPP end and ending up at the USB/Windows end.
Does anybody have any idea what the max sustainable SPP bitrate between a Macbook Pro (M3, 2023 edition) and esp32 a few inches away even IS?
As I understand it, SPP uses timeslices and a "raw" link rate somewhere in the neighborhood of 1-2mbps. However, I've also gotten the impression that you're only "guaranteed" (in the loosest sense) 1 slice per period, and that you normally can only use more than one if a whole complicated chain of dependencies and conditions is satisfied... including "both bluetooth modules are from the same vendor", "same bluetooth stack at both ends", and "bluetooth stack itself is willing to use more".
AFAIK, Espressif and Apple almost beyond doubt don't satisfy the "both bluetooth modules from same vendor" requirement, and "same bluetooth stack" would probably be the final deathblow even if they did (because everything Apple does is proprietary).
(UPDATE: It looks like the effective best-case transfer rate for normal SPP is 128kbps... anything faster is a vendor-proprietary extension that probably won't work in this situation).
Is there anything I can/must do at the esp32 end to eliminate  it as a likely chokepoint? Like, is the size of the esp32's local bluetooth and/or Serial port buffer something that's configurable via esptool.py? Or, as theorized earlier, is the esp32 itself (and the software running on it) likely to be the least of my problems?
Any additional insight anyone might have about SPP (via JSerialComm or otherwise) between an ESP32 and "real" computer is welcome, though I suspect that's probably something I'll have to ask at StackOverflow.

Update
I ran some experiments at three different baudrates, and transmitted 501 510-512 byte packets with varying delays between them.
Surprising discovery: reducing the baudrate made things worse

with 200ms delay between packets, I received 499, 499, and 500 packets at 57600, 115200, and 230400 baud respectively.
with 100ms delay between packets, I received 404, 474, and 486 packets at 57600, 115200, and 230400 baud
with 50ms delay between packets, I received 47(!!!), 335, and 423 packets at 57600, 115200, and 230400 baud
with 25ms delay between packets, I received 14(!!!), 75, and 311 packets at 57600, 115200, and 230400 baud

Revised theory about what I think might be going wrong: I think the bluetooth stack is buffering the outbound bytes and lying to the serial port driver that they've been sent, and reducing the baudrate makes things worse by creating a logjam further downstream.

At 57600 baud, a block of data hits the ESP32 at some much higher signaling rate via bluetooth, then logjams in the esp32 because it's trying to shove all 500 bytes through a metaphorical cocktail straw into the cp2102.
At 230400 baud, a block of data takes longer to transmit between the Macbook and ESP32 than the baudrate would suggest, but the combination of throttling the rate it's being fed to the Macbook's bluetooth stack and using a fast baudrate between the ESP32 and CP2102 allows the incoming buffer on the esp32 to be emptied almost immediately upon receipt.

Assuming I'm right, I think I somehow need to find a way to get the serial port library to recognize when the bluetooth stack's outbound buffer is full. I don't know whether the problem is with my code, with the serial port library (JSerialComm), or can't be solved at all within the constraints of Java's ability to communicate with Apple's bluetooth stack.

The read() is blocking call and it might be waiting for example whole second until it times out. Meanwhile other serial might have steady flow of bytes that nobody consumes for long time

Where do you see that read() is a blocking call? I was under the impression that it immediately returns a value between 0..255 if there's at least one byte in the buffer, and -1 if the buffer is empty (source: https://www.arduino.cc/reference/en/language/functions/communication/serial/read/)

You are right, I had it somehow "stored" in memory as blocking, but it was for readString and similar https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/

If it's any consolation, I almost wish you had been right, because at least then I'd have an explanation of where the problem is occurring.
My current (as yet unverified) theory is that maybe JSerialComm's writeBytes() blocks until the bluetooth stack merely accepts the bytes for sending, as opposed to blocking until they're confirmed to have been sent. So, JSerialComm and I might be relentlessly throwing huge byte arrays at it expecting the buffer to already be empty, and eventually overflowing the bt stack's own buffer without any warning.

Maybe try to measure how long it stays on different parts of loop (probably just set some pins before and clear after it and watch it on oscilloscope)


text:
Arduino board with StandardFirmata doesn't respond to C# and Python client
I have a Seeeduino XIAO board with Firmata running on it. I'm currently trying to write C# client to communicate with this board.
I have tried using Iot.Device.Arduino, SolidSolis.Arduino and pyfirmata for that purpose but I'm struggling with problem - board doesn't respond to any requests sent by my apps.
However, when I use Windows Remote Arduino Experience app, board is being successfuly found and I can control pins, retrieve info etc.

I use these programs to communicate with board:

using Iot.Device.Arduino;

var arduino = new ArduinoBoard("COM3", 57600);
Console.WriteLine(arduino.FirmataVersion.Major); // This throws System.TimeoutException

import pyfirmata
port = 'COM3'
board = pyfirmata.Arduino(port)
print(board.firmata_version) # prints 'None'

StandardFirmata runs on Arduino.

This was added into Boards.h:

#elif defined(SEEED_XIAO_M0)
#define TOTAL_ANALOG_PINS 11
#define TOTAL_PINS 17 // 11 digital / analog + 1 DAC output + 2 i2c + 3 spi
#define VERSION_BLINK_PIN LED_BUILTIN
#define PIN_SERIAL1_RX 7
#define PIN_SERIAL1_TX 6
#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 10)
#define IS_PIN_ANALOG(p) ((p) >= 0 && (p) <= 10)
#define IS_PIN_PWM(p) ((p) >= 1 && (p) <= 10)
#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4
#define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) // SDA = 4, SCL = 5
#define IS_PIN_SPI(p) ((p) == 4 || (p) == 10 || (p) == 9 || (p) == 8) // SS = A4
#define IS_PIN_SERIAL(p) ((p) == 6 || (p) == 7)
#define PIN_TO_DIGITAL(p) (p)
#define PIN_TO_ANALOG(p) (p)
#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p)
#define PIN_TO_SERVO(p) (p) // deprecated since v2.4

I've tried to rebuild Windows Remote Arduino Experience app with modifications - I've made it log every bytes it sends to Arduino or receives from Arduino. Then I've tried sending those bytes manually but result was still the same - board was not responding
There is a device in Device manager:

USB device with Serial port (COM3) (ID - USB\VID_2886&PID_802F&REV_0104&MI_00)

P.S. How do I know that the board is not responding and it's not the app that doesn't work? The board has RX and TX leds, RX one blinks always but TX blinks only when I use Windows Remote Arduino Experience app.
What I am doing wrong? Is there any error in setup or code I've written?

does the serial monitor in the Arduino IDE show  data from the arduino?

@jsotola Yes, when I connect the board I receive long capability message, starting with F0 6B F7

When using Iot.Device.Arduino I strongly recommend to use ConfigurableFirmata, as it is optimized for that. StandardFirmata may not support some features the library expects. Do note that the standard link speed has been changed to 115200 baud.

The problem was in serial port connection settings. When I used these i was finally able to get response from board:
var port = new SerialPort("COM3", 115600);

port.Open();

port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.DataBits = 8;
port.Encoding = Encoding.UTF8;
port.RtsEnable = true;
port.DtrEnable = true;
port.BreakState = false;


text:
Non-blocking analogRead for Arduino Nano 33 BLE sense
I need an alternative to analogRead() that doesn't block the processor. I've managed to find a lot of solutions for this for other boards, but not something that's compatible with nrf5240 like the one that's on Arduino Nano 33 BLE sense. Does something like this already exist? Would it be difficult to make?

It has mbed-os rtos, so you can do it in another thread. Or you can read nRF58240 Product specification and use EasyDMA (it has even sample rate, multiple channels setup, ..)


text:
About MAX30102, MLX90614 & Nodemcu-32s
I am using Nodemcu-32s with MAX30102 & MLX90614.
I noticed a thing that when I was working with both sensor individually then both of them were working fine but when I started them using together by connecting them on breadboard then both of them were not working.
I checked by changing jumper wires & checking almost all holes of breadboard, then I came to know that both jumper wires & bread board are working fine.
After that, when I started using them individually again then I got "sensor not found" error.
I am not sure where I am making mistake.
I am connecting

MAX30102 Pins
Nodemcu-32s Pins

Vin
5V

SDA
G21

SCL
G22

GND
GND

MLX90614 Pins
Nodemcu-32s Pins

Vin
5V

GND
GND

SDA
G21

SCL
G22

I don't know if my sensors were burnt or not so how can I verify for the same? Apart from this I am not aware how can I get accurate Pulse Rate & SpO2

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". If your sensors worked before you put them on the same I²C bus at the same time, and they don't work individually now, chances are high that there is a wiring error or a damage. Are the sensors working, when you revert to your very first circuits? -- On your last statement: Please separate issues, ask a separate question for this. Probably this makes sense only after you have working sensors again.

what have you tried so far? On paper I mean.


text:
beginner 7-segment code using 74hc595
Was trying this basic circuit using 74HC595 but 7-segment doesn't light at all in Anode Common. When switched to Cathode common, it just stays at 9 instead. Trying to achieve changing value from 0-9 after clicking the button. The code I used:
int data = 0;
int clock = 2;
int latch = 1;
int button = 3;

byte segment[10] = {B11111100, //0
                     B11000000, //1
                     B11011010, //2
                     B11110010, //3
                     B01100110, //4
                     B10110110, //5
                     B10111110, //6
                     B11100000, //7
                     B11111110, //8
                     B11100110, //9
                    };
void setup()
{
  pinMode(button, INPUT);
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
}

void loop()
{
  digitalWrite(latch, LOW);
  shiftOut(data, clock, LSBFIRST, segment[9]);
  digitalWrite(latch, HIGH);
}

Do you have the part number for the display? That would help. Also a schematic or a picture which clearly shows all the wiring.  But a schematic is much preferred. Also, all the code. Most of the time it is asked to reduce the code down to only the part that does not work. But they mean all of the reduced version of the code.

What do you mean "it just stays at 9 instead"? Your code just writes the digit 9 to the display (repeatedly and very fast), so isn't this what you want?

Thank you for adding a schematic.

@aims, if the answer works for you please accept it. If it does not, please add a comment. The goal is to create a list of searchable questions and accepted answers for others to use in future.

If the display works when wired up for common cathode then likely it is a common cathode LED display.
Going on, it would appear that the only thing this code does is write out data to display the number "9" over and over again:
  shiftOut(data, clock, LSBFIRST, segment[9]);

To test the display, add lines with different indices into the array which contains the 7 segment display patterns. For example:
  shiftOut(data, clock, LSBFIRST, segment[0]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[1]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[2]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[3]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[4]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[5]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[6]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[7]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[8]);
  delay(1000);
  shiftOut(data, clock, LSBFIRST, segment[9]);
  delay(1000);

... should cycle through numbers 0 through 9 then repeat.
Adding a momentary push button is difficult because of mechanical switch bounce. Because the processor can sample the switch very fast, random switch bounces can make a project such as this one appear broken. Displaying what appears to be random numbers.
Read how to de-bounce a push button here in the arduino.cc document pages.
The best approach to writing a good program is to remove all calls to delay(). Instead, after reading how to de-bounce a switch, consider creating a state machine where each button push will advance to the next state. Create 10 states where each state display a different number 0 through 9.


text:
Very slow to connect to WiFi with ESP32 (minutes, not seconds)
I am having some issues with connecting to WiFi with an ESP32 board. It is very sloooooooooow. The first few times I tried, I left it alone for 20 minutes and it still wasn't able to connect. So I thought it didn't work. So I tried to use MicroPython and ESP-IDF and they both worked, although MicroPython was somewhat slow (~10-20 seconds), but ESP-IDF was instantaneous. Then I went back to Arduino and this time it eventually connected after 260 seconds (> 4 minutes). Another try took 420 seconds (7 minutes). Has anyone else seen similar issues?
What I have tried:

Tried another board of the same model to ensure it's not defective.
Tried a different WiFi AP with the same results.

Although MicroPython and ESP-IDF framework work fine, I am still hoping to stick with Arduino for its simplicity and my hatred for Python, but don't hold it against me if you're fond of it :-).
My board:
ESP-WROOM-32(https://www.amazon.com/gp/product/B0B764963C). In Arduino IDE, I'm choosing "ESP32-WROOM-DA Module". I have also tried "uPesy ESP32 Wroom DevKit" with the same results.
The core version is "esp32 by Espressif Systems" 2.0.11.
My network setup:
TP-Link EAP225, running as a dedicated AP, not a router. My router is Linksys WRT1900ACS running OpenWrt 19.07.2 r10947-65030d81f3.
The other setup I tried is a D-Link DIR-842 running as both an AP and a router, although I didn't connect the upstream port.
My code:
#include <WiFi.h>

const char* ssid = "delingtest";
const char* password = "XxxxxYyyy00";

void setup() {
  Serial.begin(115200);
  Serial.println(millis()); // To time the connection
  Serial.print("Connecting to WiFi network ");
  Serial.print(ssid);

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

  do {
    Serial.print(".");
    delay(5000);
  } while (!WiFi.isConnected());

  Serial.println("done.");
  Serial.println(millis()); // To time the connection
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
}

Additional info:

When I used MicroPython, I connected interactively. Reference: https://docs.micropython.org/en/latest/esp8266/tutorial/network_basics.html
For ESP-IDF, I used sample code here: https://github.com/espressif/esp-idf/tree/master/examples/wifi/getting_started/station
I checked the log on the DHCP server (running OpenWRT), the time between receiving the DHCP request and offering the IP address was quick (see below).

Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPDISCOVER(br-lan) 40:22:d8:78:7a:38
Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPOFFER(br-lan) 192.168.1.145 40:22:d8:78:7a:38
Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPREQUEST(br-lan) 192.168.1.145 40:22:d8:78:7a:38
Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPACK(br-lan) 192.168.1.145 40:22:d8:78:7a:38 esp32-787A38

Edit:
I added some code to do a ping to the gateway after establishing the connection:
  IPAddress ip (192, 168, 1, 1);
  bool ret = Ping.ping(ip);

And timed it. Every ping took about 4-5 seconds. So, it's not just slow to connect to the WiFi network, it's also very slow do ping, and probably to do everything else.
Edit on edit:
After turning on verbose logging, I realized that what ping actually does is to the effect of ping -c 5, with 1 second between pings. So, it does take 4ish seconds no matter what. Originally I thought it only sent one ping per call.

Got it. Thanks. It's "esp32 by Espressif Systems" 2.0.11

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read some pages of the [help]. Is your comment the solution to your issue? If so, please write an actual answer and mark it as accepted. This is not a forum.

@thebusybee "Is your comment the solution to your issue?" Comments were deleted that would have made it easier for you to see that it isn't an answer to their question. It is a response to being asked for the core version they used, and then having that question about core version explained to them, which is what they then understood ("got it") and then replied with ("2.0.11").

@timemage Then now, after I added this information to the question, where it belongs, that misleading comment can be deleted, too.

That probably should have been done by whoever deleted the comments. Mostly I just didn't want them fighting a re-open over the confusion.

Huh, I just tried a 3rd board and I think I have found the root cause. If the board is inserted in a breadboard. It's slooooooow, or even impossible to connect. But if I pull it out, it seems to connect in a few seconds. So, I guess the problem really is the breadboard interfering with the on-board antenna. I'll probably need to get a 32U with an external antenna connector for the final product.

that's very good troubleshooting ... if the final product does not contain a large metal part, then the external antenna may not be required

Thanks. I'm working on a garage opener, so it'll need to close to the motor which is mounted on the ceiling with angle beams. And the WiFi signal is probably not the best in the house. I'll get the software part figured out first. We'll see.


text:
Serial com register formula
i am working on a atmega328p, learning to uses its registers instead a coding with common arduino code.
i've found this formula to get the baud rate on the Serial port (using USART protocol) :

how could i type this in C language ? or specifically in the arduino IDE ?
--
i made some researches and discovered that it could write it that way :
float _baudrate = (16000000/(16*9600));

then i convert the value to int (because i need an integer value)
int _baudrate_int = (int)_baudrate;enter code here

all this for a 9600 baudrate of course.
But when i do this, i don't understand why, the code does not calculate it right. i'm supposed to have 103-104 and i get 710.
it will work if i type (16*9600) product manually. Which is 153600
float _baudrate = (16000000/153600);

then i get the right baudrate result. but what if i want the code to calculate everything ? how can i do ?
where's my mistake with this line of code ?
float _baudrate = (16000000/(16*9600));

how would you do it on paper?

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". Then come back and [edit] your question to provide the source you have so far. Please add where specifically you are stumbling. BTW, general C questions are better asked on [so], especially if they don't have a relation to Arduino. But it is fine here, since you are asking about the Arduino IDE. Are you aware that you are programming C++ if you use the Arduino IDE? C++ and C are different languages.

Here:

float _baudrate = (16000000/(16*9600)

other than the missing parenthesis and semicolon, you have an integer
overflow. The issue is that, on AVR-based Arduinos, an int is only
16-bits long. The constants 16 and 9600 being small enough to fit in
an int, they are implicitly given the int type. Then, their
multiplication is also done with the int type, and the product
overflows and wraps modulo 216 to 22528.
You can fix this by giving either or both of these numbers the L
suffix, which will make them use the long data type. Alternatively, if
you want a floating point calculation, you can use .0 as a suffix.
Not that the avr-libc provides a header file with some macros for this
calculation, which is then done by the preprocessor:
<util/setbaud.h>: Helper macros for baud rate
calculations. You can use them as follows:
#define BAUD 9600
#include <util/setbaud.h>

void set_baud_rate() {
    UBRR0 = UBRR_VALUE;
#if USE_2X
    UCSR0A |= _BV(U2X0);
#else
    UCSR0A &= ~_BV(U2X0);
#endif
}

Edit:
To answer the question in a comment: yes, the L suffix creates a
long constant, and is thus similar to creating a long variable
(except it is a constant instead of a variable).
I suggest you take a look at the line below from setbaud.h. In the case
where U2X0 is not needed, the baud rate register value is computed as:
#define UBRR_VALUE (((F_CPU) + 8UL * (BAUD)) / (16UL * (BAUD)) -1UL)

A few things to note:

It is all computed with integers, no floating point. Actually, the
computation is performed by the compiler, at build time, not by the
Arduino.
The suffix UL is for unsigned long
Adding 8 before dividing by 16 is a way to round the result to the
nearest integer, instead of rounding to zero. Ties are rounded up.
There is -1UL at the end, as this is required by the UART hardware
(it is in the formula from the datasheet).

yeah i know for the missing parenthesis and semicolon. just made a wrong ctrl+c ctrl+v.

I added the L suffix and it worked. impressive, it works ! and i understand what you explained and the fact it will make them use long data type. i have an other little question : is putting the L suffix the same that doing an other variable and make it = (long)variable ? if you see what i mean

yes i understand. the same formula with a 8-addition and giving it long type before rounding it and converting to integer.