message:
How to change the I2C address of the AS5048B?

I saw [this video][1] from James Bruton. See the links to the GitHub repos in the video description.

I bought [a few AS5048B boards from AMS][2], so I can measure the position of my stepper motors.

In the `sosandroid` repo, I ran `program_address` and was able to get one of them working, but they all have the same I2C address, and because I want to have 6 of them running simultaneously, it of course won't work. I know I could get an I2C multiplexer...

I also tried setting the A1 and A2 pins on the AS5048B to high and low, which change the I2C address (for a total of 4)... But I want to change the I2C address permanently for each board.

It looks to me like `program_address` is supposed to permanently program the I2C address, which the user can specify in the .ino file:

    // Construct our AS5048B object with an I2C address of 0x40
    AMS_AS5048B mysensor(0x40);

But no matter what I set it to (e.g. `0x40, 0x41, 0x42, 0x43, 0x44`), [the Arduino I2C scanner][3] always finds `0x44`, which is the default address, so the `program_address` must not be working.

EDIT: the default address is actually `0x40`. I must have programmed it to `0x44` without knowing (I was playing around with this board trying to figure this all out).

I know that normally the I2C addresses cannot be changed, but it looks like [this one][4] can:

Here's a snippet from the link above. It says the OTP bits can be programmed/burned (only once!). My understanding is that the I2C address is saved in the OTP bits.

> Program the OTP bits permanently:
> 1. Write dec.253 into the OTP control register (dec.3) to enable the special programming mode
> 2. Set the Burn bit (dec.8) in the OTP control register (dec.3) to enable automatic programming procedure
> 3. Write dec.0 into the OTP control register (dec.3) to disable the special programming mode

I am using the Teensy 4.1 using PlatformIO in VS Code, and I also tried using an Arduino Uno in the Arduino IDE.

My wiring is as follows:

[![wiring][5]][5]

**So how do I program the I2C address on the AS5048B boards?**

EDIT:
-----
- I changed an image to text, and cleaned things up.

As @6v6gt requested, I used the I2C scanner and it is still showing 0x40 (on this particular board), so it must not have been programmed (unless it's possible to program it to 0x40 even though 0x40 is its default value). The only thing I changed from the `program_address` repo is this line in the .ino file:

    // Construct our AS5048B object with an I2C address of 0x40
    AMS_AS5048B mysensor(0x48);

I changed the 0x40 to 0x48. But now I am getting this in the serial monitor:

    Angle degree : I2C error: 2
    359.9780273437

Since I must have programmed the other board to 0x44 successfully, I am trying to think of what I did differently, but I don't remember.

There are hundreds of lines of code in `program_address` (and the .h and .cpp file), so I probably shouldn't post all of it here. But here's [the GitHub repo][6].

  [1]: https://www.youtube.com/watch?v=KN4wAZHtbzc
  [2]: https://www.mouser.ca/ProductDetail/985-AS5048B-TS_EK_AB
  [3]: https://playground.arduino.cc/Main/I2cScanner/
  [4]: https://ams.com/documents/20143/36005/AS5048_AN000386_1-00.pdf/3fc346bf-2379-6a45-9adb-1fe5407b8889
  [5]: https://i.stack.imgur.com/jUHkC.png
  [6]: https://github.com/sosandroid/AMS_AS5048B/tree/master/examples/program_address

body:
> but they all have the same I2C address

No, they have 4 possible addresses, based on how you configure A1 and A2. So you can have 4 different addresses immediately.

> But I want to change the I2C address permanently for each board.

For each board, set up A1 and A2 differently.

This only gives you 4 different addresses, not 6. You could conceivably connect 8 devices to two different Atmega328 chips, and have them do the readings and forward the results using a protocol you devise, to your "main" board. The Atmega328 chips only cost around $US 5 each so this isn't a big deal.

Another approach would be to run SDA and SCL through a multiplexer chip, so that you enable one batch of 4 chips and then the other batch. Without trying it out, it is hard to say if this would work satisfactorily.


sender: user

sender: assistant

body:
The device slave I2C address consists of the hardware setting on pins A1, A2 **and upper MSBs programmable by the user.** It is the setting of the MSBs, in addition to A1/A2 that I believe the OP is after.

The information provided by @Nick Gammon concerning A1 and A2 is correct, but does not consider the other 5 bits (the MSBs). It appears that you can, indeed, permanently set a new I2C slave address on the device.

You need to read the [programming application note][1] very carefully, but they explain how to burn those bits into the register....it seems straightforward and is really just four steps, but I suppose it can be a little daunting, e.g.,
"***slave address consist of 5 programable bits (MSBs) and the hardware setting of Pins A1 and A2 I²C address <4> is by default not programmed and due
to the inversion defined as '1'***"

The application note gives an example of the 4 steps....
[![enter image description here][2]][2]

It may be the case that you already changed the I2C address default to 0x44 by following the instructions. [edited to add] Can you post the complete program [Arduino IDE code] that you used to *try* to change the I2C address?

  [1]: https://ams.com/documents/20143/36005/AS5048_AN000386_1-00.pdf/3fc346bf-2379-6a45-9adb-1fe5407b8889
  [2]: https://i.stack.imgur.com/Bv7Mb.jpg


message:
How to write single binary code to output pin

I am relatively new to arduino and coding in general and im just looking for a code to write a single string of binary code e.g.; "01000111101"
To a specified output pin instead of copying and pasting

"Digital write (high)
Digital write (low)
Etc."

preferably with the option to change speed between bits.
Would be very appreciative for someone to help me out

body:
If timing is not critical, consider dividing the number of interest by 2. If there was a remainder set the Arduino pin to 1. If not set it to 0. Then delay for as long as needed. Keep doing this until there is nothing left to divide 2 into.

However, sending out data in serial fashion is as old as computers. Likely older. Consequently there are a lot of built in features which do this.  Specifically, it is not necessary to explicitly code up a function to convert a value to serial data. Even on an Arduino.


message:
Good practice to assign shift-register pins at the same time?

I'm new to bit register manipulation and am trying to set input and output values of some pins. The code sample I have on hand does it this way::

    DDRD |= (1 << 2);
    DDRD |= (1 << 4);
    DDRD &= ~(1 << 5);
    PORTD |= (1 << 2);
    PORTD &= ~(1 << 4);
    PORTD &= ~(1 << 5);

I have two questions:
1. This is part of a code where I'm attempting to determine the time for a capacitor's discharge between pins 2 and 4. The arduino helpfiles mention that there may be a benefit to triggering both pins at once. Therefore: Is it is it possible to do `DDRD |= B00010100;` and `PORTD |= B00000100;` or combine the first three `DDRD`  lines so it happens simultaneously, or does it have to be separately called?

2. Why is it `PORTD &= ~(1 << 4)` and not `PORTD |= ~(1 << 4);`Can this conflict with the previous state of PORTD.

body:
>     DDRD |= (1 << 2);
>     DDRD |= (1 << 4);

The equivalent to that is:

    DDRD |= (1 << 2) | (1 << 4);

However I prefer `bit` because it does the shift for you:

    DDRD |= bit(2) | bit(4);

---

> Why is it `PORTD &= ~(1 << 4)` and not `PORTD |= ~(1 << 4);`

`PORTD &= ~(1 << 4)` is turning a bit **off**. First you invert the sense of the bit with the **ones complement operator** (~) and then by **anding** it, it means that all bits are retained except that one. So this is basically turning bit 4 off. If you used `|=` it would turn all of the other bits **on**.

Equivalent code:

    PORTD &= ~bit(4);

Based on your example you meant bit 5 not bit 4.

---

>     PORTD |= (1 << 2);
>     PORTD &= ~(1 << 4);
>     PORTD &= ~(1 << 5);

That is turning on bit 2, and turning off bits 4 and 5, and leaving the rest unchanged.

---

> Thanks. In that case would DDRD &= B00000000; DDRD |= B00010100; have a similar result ...

If you do `DDRD &= B00000000;` then you are setting all bits to zero. So the simple equivalent to the above would be:

    DDRD = B00010100;

This is a straight assignment, so you don't need to clear any bits.

Or, you could write:

    DDRD = bit(2) | bit(4);

---

> Do you know if bit() faster or is it cleaner compared to 1 << x; or is it better for me to hook up a scope to test this myself?

It is **exactly the same**. `bit` is just a `#define`  in the Arduino.h file, as follows:

    #define bit(b) (1UL << (b))

So all it does is save you writing the brackets and the shift left operator. It expands out to the same as what you were writing and thus will execute at the same speed, and take the same amount of memory.


message:
How to drive two Stepper motors and use an Ultrasonic sensor together?

I am working on an autonomous robot using two 4-pin stepper motors, HC-SR04 ultrasonic sensor, 2 L298N motor drivers (one for each motor), and an Arduino Uno. My problem is that when I use the stepper motors with the Stepper library, only one motor works at a time. My solution was to control the one step at a time in a short period of time, which worked, however, this introduces a new problem. The ultrasonic sensor requires a delay to work, but this makes the movement of the robot quite slow and jittery as it works only by one step at a time. When I remove the delay from the ultrasonic sensor, it starts returning the correct value, but then also returning 0 right after each correct value. My solution was to ignore the returned 0, but this is not ideal.

How can I use two stepper motors at the same time and use an Ultrasonic sensor?

Here is my code:

    #include <Stepper.h>
    #include <Ultrasonic.h>

    /*
     * Pass as a parameter the trigger and echo pin, respectively,
     * or only the signal pin (for sensors 3 pins), like:
     * Ultrasonic ultrasonic(13);
     */
     Ultrasonic ultrasonic(13, 12);
     int distance;

     int driveSpeed = 100;
     int stepsPerRevolution = 200;
     int leftMotorStep = 0;
     int rightMotorStep = 0;

     // Time interval between steps for both motors
     const int stepInterval = 10;  // Adjust as needed

     // Last step time for each motor
     unsigned long leftMotorLastStepTime = 0;
     unsigned long rightMotorLastStepTime = 0;

     Stepper rightMotor(stepsPerRevolution, 8, 9, 10, 11);
     Stepper leftMotor(stepsPerRevolution, 4, 5, 6, 7);

     void setup() {
       Serial.begin(9600);
       rightMotor.setSpeed(driveSpeed);
       leftMotor.setSpeed(driveSpeed);
     }
     void loop() {
       distance = ultrasonic.read();

       Serial.print("Distance in CM: ");
       Serial.println(distance);
       delay(250); //This delay makes the motors behave strangely

       if (distance < 15) {
         Serial.println("AVOIDING OBSTACLE!");
         // Perform obstacle avoidance behavior
         avoidObstacle();
       } else if (distance < 30) {
         Serial.println("APPROACHING OBSTACLE!");
         // Perform slow approach behavior
         slowApproach();
       } else {
         Serial.println("DRIVING!");
         // Perform normal driving behavior
         drive();
       }
     }

     void avoidObstacle() {
       // Stop the robot
       halt();

       // Rotate the robot to avoid the obstacle
       leftM();

       // Delay to allow the rotation to complete
       delay(1000);
     }

     void slowApproach() {
       // Slow down the motors
       int slowSpeed = 50;
       rightMotor.setSpeed(slowSpeed);
       leftMotor.setSpeed(slowSpeed);

       // Move the robot forward slowly
       forwardM();

       // Delay to allow the slow approach
       delay(1000);
     }

     void drive() {
       // Set the motors back to the normal speed
       rightMotor.setSpeed(driveSpeed);
       leftMotor.setSpeed(driveSpeed);

       // Move the robot forward
       forwardM();
     }

     void forwardM() {
       rightMotor.step(1);
       leftMotor.step(1);
     }
     void leftM() {
       rightMotor.step(1);
       leftMotor.step(-1);
     }
     void rightM() {
       rightMotor.step(-1);
       leftMotor.step(1);
     }
     void reverseM() {
       rightMotor.step(-1);
       leftMotor.step(-1);
     }
     void halt() {
       rightMotor.step(0);
       leftMotor.step(0);
     }

body:
Try this code.

Here is a simulation. https://wokwi.com/projects/366108641014000641

Click on the sensor to set the distance in the simulation

NOTE: centimeters is `cm`, not `CM`.

Not tested on hardware.

```lang-cpp

// https://arduino.stackexchange.com/questions/93302/how-to-drive-two-stepper-motors-and-use-an-ultrasonic-sensor-together

#include <Stepper.h>
#include <Ultrasonic.h>

/*
 * Pass as a parameter the trigger and echo pin, respectively,
 * or only the signal pin (for sensors 3 pins), like:
 * Ultrasonic ultrasonic(13);
 */

 Ultrasonic ultrasonic(13, 12);

 int distance;

 int slowSpeed          =  100;
 int driveSpeed         = 1000;
 int stepsPerRevolution =  100;
 int leftMotorStep      =    0;                         // current step speed and direction
 int rightMotorStep     =    0;

 int stepSpeed          =   10;                         // this is the motor speed

 const int stepInterval =    1;                         // Time interval between steps for both motors

 unsigned long leftMotorLastStepTime  = 0;              // Last step time for each motor
 unsigned long rightMotorLastStepTime = 0;

 Stepper rightMotor(stepsPerRevolution, 8, 9, 10, 11);
 Stepper leftMotor (stepsPerRevolution, 4, 5,  6,  7);

 void setup() {
   Serial.begin(9600);
   rightMotor.setSpeed(1);
   leftMotor. setSpeed(1);
 }

 void loop() {

  distance = ultrasonic.read();

  Serial.print("Distance in cm: ");
  Serial.print(distance);  Serial.print("\t");

  switch (distance) {                              // used switch/case for cleaner looking code
    case 0 ... 14:
      Serial.println("avoid");
      avoidObstacle();                             // Perform obstacle avoidance behavior
      break;

    case 15 ... 29:
      Serial.println("approach");
      slowApproach();                              // Perform slow approach behavior
      break;

    default:
      Serial.println("drive");
      drive();                                     // Perform normal driving behavior
      break;
  }

  rightMotor.step(rightMotorStep);                 // this actually moves the motors
  leftMotor .step(leftMotorStep);
}

 void avoidObstacle() {
   halt();                                          // Stop the robot
   leftM();                                         // Rotate the robot to avoid the obstacle
 }

 void slowApproach() {
   rightMotor.setSpeed(slowSpeed);                  // Slow down the motors
   leftMotor. setSpeed(slowSpeed);
   forwardM();                                      // Move the robot forward slowly
 }

 void drive() {
   rightMotor.setSpeed(driveSpeed);                 // Set the motors back to the normal speed
   leftMotor. setSpeed(driveSpeed);
   forwardM();                                      // Move the robot forward
 }

 void forwardM() {
   rightMotorStep =  stepSpeed;                     // select direction of step only
   leftMotorStep  =  stepSpeed;                     // do not move motor
 }                                                  // actual stepping is done at end of loop()
 void leftM() {
   rightMotorStep =  stepSpeed;
   leftMotorStep  = -stepSpeed;
 }
 void rightM() {
   rightMotorStep = -stepSpeed;
   leftMotorStep  =  stepSpeed;
 }
 void reverseM() {
   rightMotorStep = -stepSpeed;
   leftMotorStep  = -stepSpeed;
 }
 void halt() {
   rightMotorStep =  0;
   leftMotorStep  =  0;
 }

```


message:
Determine if a XIAO ESP32C3 is charging

When the XIAO ESP32C3 is charging a LiPo battery, there is a small LED on the board that lights up. Is there any way to access this information in an Arduino program?

body:
No, according to the [schematic](https://files.seeedstudio.com/wiki/XIAO_WiFi/Resources/Seeeduino-XIAO-ESP32C3-SCH.pdf) it's not wired to any pin on MCU.

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

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


message:
Powering a NodeMCU as well as a GSM module

I'm trying to connect a GSM module(sim800L) with a NodeMCU to execute remote operations. But the GSM module cannot be powered using the NodeMCU. So, what are the other ways to power the board as well as the module. Also I want to connect directly to a wall power supply instead of using a battery.

body:
After a bit of researching, I have found the following solution:-

A DC-DC buck converter (such as the LM2596) can convert a 12 V 2A rated power supply down to 4 V (the value is adjustable) which can then be used to power the module.


message:
Can't mount microSD card with Freenove ESP32 WROVER Module and Sparfun MicroSD module

I'm using Freenove's ESP32 WROVER Module with their GPIO expansion board as shown in the image below:

[![Circuit image][1]][1]

I'm trying to integrate Sparkfun's microSD module in the circuit. [Here's my sketch][2]. However, I'm unable to mount the card despite it works fine using an ESP32-CAM board with integrated SD card reader.

Any clues on what I'm doing wrong?

  [1]: https://i.stack.imgur.com/uYA7m.jpg
  [2]: https://www.dropbox.com/s/1isx64ksknl4cnr/esp32_microsd_module.ino?dl=0

body:
Your pinout to the SD is unclear from the picture, but I can see that you are using **pin 15**, which is the MTDO strapping pin- which will cause issues for sure.

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

You can learn more here about using alternative pins here:

https://randomnerdtutorials.com/esp32-spi-communication-arduino/

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


message:
How do I use a transmitter and receiver to send string messages conditionally to a receiver?

I'm working on a project to build a plant monitor that works from the outside with Arduino that picks up light and water values from it's environment then uses a nRF24L01 with an antenna and I've come across a roadblock in the code with using a transmitter and receiver, heres the code fully below.

Appreciate any help, been stuck for weeks trying to figure this out.

Transmitter Code
```
/*
 * NAME: <Mario Ronci>
 * Healthy Plant Monitor  V2  T
 *
 *
 */

 //** **/
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

int ldrValue;
int sensorPin = A0;    // select the input pin for the Water Comparator
int sensorValue = 0;
int light_threshold = 650;
int water_threshold = 850;
String dark_message = " ALERT:Plant is Dark!";
String bright_message =" Brightness Achieved! ";
String water_message1 = " Plant has enough water.";
String water_message2 = " Need Water...!";
String healthy_message = "Plant is Healthy!";
String unhealthy_message = "Unhealthy...!";
//String engineerinfo = "Mario Ronci 2023";

void setup() {

  pinMode(LDR, INPUT);
  pinMode(POT, INPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
  Serial.println(engineerinfo);
  // put your setup code here, to run once:
radio.begin();
  //set the address
  radio.openWritingPipe(address);
  //Set module as transmitter
  radio.stopListening();

}

//This checks if the plant is getting enough light,//
//by taking a acceptable or unacceptable light value
//from a LDR and prints the value to the serial monitor
//and if the light value is acceptable

void ldrCheck(int device, int duration1,int duration2){

ldrValue = analogRead(device);

if(ldrValue >= light_threshold)

{
  messageLight = light_message + String(ldrValue);
  sendByteMessage(); // Call the function to send the byte message
   delay(duration1);// Wait for some time before sending the next message

}

if(ldrValue < light_threshold){
  messageLight = dark_message + String(ldrValue)
  byte messageBytes[message.length() + 1]; // Create a byte array to store the message
  delay(duration2);
}

void sendByteMessage() {
  byte messageBytes[message.length() + 1]; // Create a byte array to store the message

  // Convert the string message into a byte array
  message.getBytes(messageBytes, message.length() + 1);

  // Send the byte array through the transmitter
  radio.write(&messageBytes, sizeof(messageBytes));
}

}

////This checks if the plant is getting enough water,//
//by taking a acceptable or unacceptable hydration value
//from a LDR and prints the value to the serial monitor
//and if the hydration value is acceptable , the yellow LED will turn on
//and blink, if it's not it will print a message to the serial monitor
//to alert you

//********* Note replace POT with hydrometer code*********//
void potCheck(int device,int duration3){

potValue = analogRead(device2);

if(potValue > water_threshold)
{
  Serial.print(potValue);
  Serial.println(water_message1);

}

else{
  Serial.println(water_message2);

}

}

//This checks if the plant is getting enough water and light
//, if it's not it will print a message to the serial monitor
//to alert you and if it is getting enough it will print a
//message to the serial monitor telling you the plant is healthy

void healthyCheck(int led_4,int duration4,int duration5){

if((ldrValue >= light_threshold) && (potValue > water_threshold)){
digitalWrite(led_4, HIGH);
Serial.println(healthy_message);
delay(duration4);
}

else{
digitalWrite(led_4,HIGH);
delay(duration5);
digitalWrite(led_4,LOW);
delay(duration5);
Serial.println(unhealthy_message);

}

}

void loop(){

//This calls the function/method

//in loop call transmitter

ldrCheck(LDR, 1000,100 );
sendByteMessage(LDR)
potCheck();
healthyCheck(2000,800);

}

```

Receiver Code

```
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

//Create an rf24 object

RF24 radio(9,8) ; //CE,CSN

//address through which two modules communicate.

const byte address[6]  = "00001";

void setup() {

while(!Serial);
 Serial.begin(9600);

 radio.begin();

 //set the address
 radio.openReadingPipe(0, address);

 //set module as receiver
 radio.startListening();

}

void loop() {
  //Read the data if available in buffer

  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.print(ldrValue);
    Serial.println(light_message);
  }
```

**What specifically do you need help with?**

I'm trying to modify original code to work with the transmitter and receiver functionality
before I had code that used leds meaning the plant monitor would turn on certain colored LEDs based on condition.Now in V2 of this project i decided to do away with the LED's and make the goal to have communication between the componets from the outside to send messages about the plant status inside where another arduino would print to the serial monitor

I need help with having the transmitter code work with the conditional statements atm I'm confused where to insert the each piece of code so the transmitter sends a message to the receiver and prints in the serial monitor.It should work as the componets take inputs from the environment like the ldr, then that value is stored and applied to if statment , if x is this value then send this message and then the transmitter sends the message to the receiver that prints it to the serial monitor

**What have you tried?**

I've tried to create a seperate variable for the message I want to send along with the analog sensor values from the ldr.( I've not gotten to the hydrometer yet I only got the wiring for it done) Turn the ldr from int to a string and then call the variable in the byte message function within a function for checking for ldr values. Then in the receiver code i tried testing by writing Serial Print for each value but It's not working and I think its because the value is out of scope.Not in the same sketch.

**What do you think the problem is?**

I think it may be the order of the code and or syntax,maybe if I put the transmitter code outside of the ldr check function it would work, but im not sure. Could also be that the datatypes are strings and ints and changing that to the bytes isn't as straightfoward as I thought.

The actual build and components

Master  (  transmitter ) takes inputs from the environment using a Ldr and hydrometer
both water and light values and sends it to the slave microcontroller the receiver, wiring is correct.
[![enter image description here][1]][1]

Slave ( receiver) processes the values from the transmitter and prints them in the serial monitor the messsage it recieves will depend on conditions such as light value thresholds  and water value thresholds in simple terms if the light  or water values exceed a certain value or are below a certain value it will send a different message for each situation.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/BIsNK.jpg
  [2]: https://i.stack.imgur.com/nS2YM.jpg

body:
I figured the issue out.

1. code was a mess but after troubleshooting it for a while the if statements didn't make sense and had no good flow to them plus too complicated. I had copied and pasted some code without making sense of it.

2. It worked when I focused on one component like @jstola said. The photoresistor only and so the main thing is to add the conditional then turn string into a byte message and then void loop sends byte message to receiver arduino. Then the next part there were symbols appearing in the serial monitor and that was weird. So I experimented with the char data type instead of string and worked. Also use chatgpt as well for some syntax help.

Now I have base to work from. So next is to tackle the hydrometer.

**Transmitter Code - with photoresistor only**

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(9, 8); // Create an instance of the RF24 object

const byte address[6] = "00001"; // Set the pipe address

int ldrValue;
int sensorPin = A2;    // Select the input pin for the LDR
int light_threshold = 650;
String light_message = "Plant has enough light :";
String dark_message ="Alert: Plant is Dark! :" ;
String water_message1 = " Plant has enough water.";
String water_message2 = " Need Water...!";
String healthy_message = "Plant is Healthy!";
String unhealthy_message = "Unhealthy...!";

void setup() {

  pinMode(sensorPin, INPUT);
  radio.begin();
  radio.openWritingPipe(address);
  radio.stopListening();

}

void loop() {
  ldrCheck(sensorPin, 1000, 100);
}

void ldrCheck(int device, int duration1, int duration2) {
  ldrValue = analogRead(device);

  if (ldrValue >= light_threshold) {
    String message = light_message + String(ldrValue);
    sendByteMessage(message);
    delay(duration1);
  }
  else {
    String message = dark_message + String(ldrValue);
    sendByteMessage(message);
    delay(duration2);
  }
}

void sendByteMessage(String message) {
  byte messageBytes[message.length() + 1];
  message.getBytes(messageBytes, message.length() + 1);
  radio.write(&messageBytes, sizeof(messageBytes));
}

```

**reciever Code - with photoresistor only**

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(9, 8); // Create an instance of the RF24 object

byte address[6] = "00001"; // Set the pipe address

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, address);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char message[32] = ""; // Create a character array to store the message
    radio.read(&message, sizeof(message));
    processMessage(message);
  }
}

void processMessage(char* message) {
  String receivedMessage = String(message); // Convert the character array to a String
  Serial.println(receivedMessage);
  delay(1000);
}

```

result:

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

[Video][2]

  [1]: https://i.stack.imgur.com/VOy7X.png
  [2]: https://www.linkedin.com/posts/mario-ronci-a1a774b0_agriculture-agriculturetechnology-environmental-activity-7074186222914416640-A_di?utm_source=share&utm_medium=member_desktop


message:
ArduinoJSON - How to check if array is empty

Parameters file defines the creation of entities and stored in flash. Its structure is given, and all fields ( keys & values ) are given.
In current phase - those parameters are hard-coded in a `const char* cont_params`, as shown below.

My goal, is when array is empty, for example `RF_2entity` - means that current MCU does not uses its RF abilities, and will not init any RF entities. The way `RF_2entity` is defined below, as empty array, `[]` , ArduinoJSON's `isNull()` function return `0` in that case.

How can I keep parameters file's structure and logic, rather that fill its values with `255` for example.

      Serial.begin(115200);
      StaticJsonDocument<1200> doc;
      const char *cont_params = "{\"entityType\": [1,1,1,1],\
                        \"SWname\": [\"SW_0\",\"SW_1\",\"SW_2\",\"SW_3\"],\
                        \"SW_buttonTypes\": [2,1,1,1],\
                        \"SW_timeout\": [10,11,12,13],\
                        \"SWvirtCMD\":[0,0,0,0],\
                        \"Winname\": [],\
                        \"WextInputs\": [],\
                        \"WinvirtCMD\":[],\
                        \"RF_2entity\": [],\
                        \"v_file\": 0.5}";
      DeserializationError err = deserializeJson(doc, cont_params);
      JsonArray array = doc["Winname"].as<JsonArray>();
      serializeJsonPretty(array,Serial);
      Serial.println(array.isNull());

output:

    []0

body:
The method `isNull()` is not what you want. It tells you whether the instance holds an array at all or not. And of course, your specific instance holds an array, though an empty one. Therefore, the method correctly returns `false`, aka `0`.

As [the API documentation][1] shows, there are more methods to use.

What you want is `size()`, which returns the number of elements in the array. It will even return `0` on an instance without an array.

  [1]: https://arduinojson.org/v6/api/jsonarray/


message:
Sending values with pyserial does not function if there is also sensing on Arduino Due

I'm using an Arduino Due to make a feedback loop using python, but this does not seem to function. The python code I'm using is the following:

    from serial import Serial
    board = Serial('COM11',9600)
    board.write('100'.encode()) # 100 is taken as an example

In fact, if I just use Arduino to measure the sensor voltage, it succeeds. It's the same if the voltage is sent without measuring the sensor. But, as soon as I put both simultaneously, the sensor is good but nothing is read by the Arduino.
However, if I send the voltage not using Python but using the Arduino IDE, everything is okay.

It seems that the Arduino can't do the two operations at the same time, but this is weird. Here is my Arduino code:

```
int const controller = DAC0; // Set the controller output pin
int const sensor = A1; // Set the sensor pin
double MeanNumber = 500;

void setup() {
  Serial.begin(9600);
  pinMode(controller, OUTPUT);
  analogReadResolution(12);
}

double get_voltage(int Measure)
{
  double voltage;
  voltage = Measure * 3.3 / 4095.0;
  return voltage;
}

void loop() {
  double Measure = 0;

  double voltage;
  for (int i = 0; i < int(MeanNumber); i++) // Realize an average each MeanNumber value
  {
    Measure = Measure + analogRead(sensor) / MeanNumber;
    delay(1);
  }

  // Send the averaged measure to python
  voltage = get_voltage(Measure);
  Serial.println(voltage,4);

  // Get the feedback from python
  if (Serial.available() > 0)
  {// Verify if data are available
    String receivedData = Serial.readString(); // Read the voltage value from bytes to string
    float value = receivedData.toFloat(); // Convert the voltage into float
    analogWrite(controller,value); // Send the signal via the Arduino
  }

}
```

Do you have an idea of what is wrong with my job?

body: Opening a Serial connection will reset the Arduino.  The python code may be doing that when it creates the port.  Put a Serial.print("Starting") line in your setup function to see if that's what is happening.


message:
Arduino Uno Gravitech Rev 3.0 with avrdude CLI (Mac OS) - Is my script correct?

I am dealing with an Arduino Nano board rev 3.0 from Gravitech.
There is a program inside that I'd like to download to a HEX file. Thus I can upload it to other Arduino Nano boards.

I'm a newbie with Arduino. Therefore I've read much documentation on the internet and I came to the point to use `avrdude` in the command line as Arduino IDE does not provide a feature to perform a download to an HEX file (as far as I've understood).

I've installed all the necessary software on my Mac OS Mojave (avrdude v7.0 using 'Mac Ports'). And after powering up and connecting the Arduino Nano board to a USB port of my Mac, I launched the following command line:

`avrdude -p m328p -D -c arduino -P /dev/tty.usbserial-A9077L99 -U flash:r:programme_arduino.bin:r -v -x attempts=4`

I obtain the classical message
>stk500_recv(): programmer is not responding

I've noticed that the 'Rx' led and the 'L' led were blinking during the attempts.

From your perspective, do the options look good (-p -c ...)?

[![Arduino Nano Gravitech v3.0][1]][1]

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

body:
Your first problem is the no-response complaint. You said "I've noticed that the 'Rx' led and the 'L' led blank during the attempts." Is "blank" a typo (i.e., the LEDs *do* blink?) or did you mean they do nothing? Are you using the same cable you used to program the nano? Can you swap with another cable? Test this cable with another nano? Is the port ID typed correctly (/dev/...etc)?

Double-check the programmer ID (-c option) and part number (-p option) by querying AVRDUDE (specify '?' instead of a valid value on each of those).

For the -U option, you'll want to name the output file with a .hex extension, and specify the file-format as 'i' for intel hex:<br>
 `-U flash:r:programme_arduino.hex:i`

[Here is the AVRDUDE reference][1] I used.

Update:

I agree that your port ID must be correct and the cable is working, since your LEDs are blinking. But you get an error message about "not responding". Does the Nano have a bootloader in it? Could the boot-loader have been damaged when you uploaded the code (e.g., the code is large enough to over-write some of the bootloader)?

Is binary code in the Nano the only copy, or do you have the source code for it? If you have the source, you can recompile it (if necessary) and retrieve the resulting .hex file. Would that solve your problem? By setting the IDE to produce verbose output, you'll see the path to the temporary files, including the .hex file. Then use Finder (or a Terminal command, if you are comfortable with that) to copy that temporary .hex file to someplace safe.

Update 2:

> Are bootloader ROM area and Flash ROM area two different memory areas?

Not separate - the boot-loader is placed at the top of Flash. It is possible for a large enough program to over-write it - I'm not sure whether that has to be specifically allowed, such as by setting fuses. If it does get over-written, it obviously becomes unusable.

I wonder if the flash can be read using a hardware programmer? Do note that these chips have lockout-fuses that can be set to prevent further programming or reading of the flash.

Since the code in this device seems valuable to you, I would suggest putting this Nano board aside, and only experiment with another, hopefully identical, board. On the new board -
- Upload a sketch to it;
- Copy the AVRDUDE command line used to by the IDE to upload it, and modify it as you've already described. Of course, this command will already have the board-specific parameters;
- Use the modified command to download the sketch to another file, and compare it to the file that was just uploaded.

Once you can do this successfully, apply that last step to copy the sketch from your valuable Nano, then put that board away again. Load and test the downloaded code on your experimental Nano. Don't forget to include the valuable Nano's EEPROM - it might contain some critical data.

  [1]: http://www.avrlearning.com/140/avrdude-command-line-reference.php


message:
How do I turn on 3 LEDs in a repetitive sequence where all three LEDs would then turn OFF when the push button used is released?

Basically, how do I modify my code listed below to turn **ON** each of the three LEDs one at a time in a repetitive sequence while keeping the push-button pressed?
- Red (3 sec),
- Yellow (1 sec), and
- Green (3 sec).

I'm trying to get all three LEDs to turn **OFF** when the push button is released.

The code I wrote that doesn't allow me to achieve what I'm trying to do (I'm not sure where I went wrong):
```
#define Button_Pin 2  //Push Button Pin
#define LED_Pin_1 11 //Red LED
#define LED_Pin_2 10 //Yellow LED
#define LED_Pin_3 9  //Green LED

byte Button_State;

void setup() {
  pinMode(Button_Pin, INPUT);
  pinMode(LED_Pin_1,  OUTPUT);
  pinMode(LED_Pin_2,  OUTPUT);
  pinMode(LED_Pin_3,  OUTPUT);

  Serial.begin(9600);
  Serial.println("Design Part B - Digital I-O Control");
  delay(1000);
}

void loop() {
  Button_State = digitalRead(Button_Pin);
  Serial.print("Button State: ");
  Serial.print(Button_State);

  if (Button_State == 1){
    digitalWrite(LED_Pin_1, HIGH);
    delay(3000); //Wait for 3 Secs
    digitalWrite(LED_Pin_2, HIGH);
    delay(1000); //Waits for 1 Sec
    digitalWrite(LED_Pin_3, HIGH);
    delay(3000);
    Serial.println(" --> Button Pressed --> LED ON");
  }
  else{
    digitalWrite(LED_Pin_1, LOW);
    digitalWrite(LED_Pin_2, LOW);
    digitalWrite(LED_Pin_3, LOW);
    Serial.println(" Button is Released --> LED OFF");
  }
}
```

[![The circuit layouts being used][1]][1]

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

body:
You need a [state machine](https://en.wikipedia.org/wiki/Finite-state_machine) (to remember which LED is currently on) and use `millis()` to find the current time, in a loop, which is testing whether the switch is closed or not.

If the switch is closed you compare the time now (with `millis()`) to the time you turned that particular LED on. When the time is up you advance the "state" (eg. a counter) to the next one, and remember the new time that this state change happened.


body:
Having examined several sample sketches, including the recommended one, and watching instructional YouTube videos to grasp the fundamentals of Arduino programming, I am delighted to announce that my understanding of programming the Arduino and comprehending its functions has significantly improved, considering my novice status.

I can confidently assert that this question has been resolved, and I have enclosed the code that fulfills the initial requirements that was asked of me.

    #define pushButton_pin 2
    #define grn_LED_pin 9
    #define yel_LED_pin 10
    #define red_LED_pin 11

    bool pushButton_state;

    void setup() {
    pinMode(pushButton_pin, INPUT);
    pinMode(grn_LED_pin, OUTPUT);
    pinMode(yel_LED_pin, OUTPUT);
    pinMode(red_LED_pin, OUTPUT);

    Serial.begin(115200);

    Serial.println("Use push button (digital input) to control 3 LEDs (digital
    output)");
    delay(1000);
    }

    void loop() {
    pushButton_state = digitalRead(pushButton_pin);
    Serial.println(pushButton_state);
    if (pushButton_state == 1) {
    digitalWrite(grn_LED_pin, LOW);
    digitalWrite(yel_LED_pin, LOW);
    digitalWrite(red_LED_pin, HIGH);
    Serial.println(" :push button state is 1, red LED is ON");
    delay(2000);
    digitalWrite(grn_LED_pin, LOW);
    digitalWrite(yel_LED_pin, HIGH);
    digitalWrite(red_LED_pin, LOW);
    Serial.println(" :push button state is 1, yel LED is ON");
    delay(1000);
    digitalWrite(grn_LED_pin, HIGH);
    digitalWrite(yel_LED_pin, LOW);
    digitalWrite(red_LED_pin, LOW);
    Serial.println(" :push button state is 1, grn LED is ON");
    delay(2000);
    } else {
    digitalWrite(grn_LED_pin, LOW);
    digitalWrite(yel_LED_pin, LOW);
    digitalWrite(red_LED_pin, LOW);
    Serial.println(" :push button state is 0, all LEDs OFF");
    }
    delay(500);
    }


message:
How to offset PWM output so it would also have negative amplitude?

So PWM goes from 0 to 5V. How could I do -2.5 - 2.5V? Basically I am asking how to add offset to PWM signal. Should I use operational amplifier? How would I use it? I never had to deal with them, but I have LM2904P laying around.

body:
Consider removing the average of the PWM voltage by subtracting the [Direct Current (DC)][1] component of the PWM output.

Often, between different audio amplifiers stages, the DC component of the signal is removed through the use of [coupling capacitors][2]. The above link offers these guide lines for picking the value of the capacitor:

> Below is a basic rough guideline of capacitors that can be used for
> various frequencies.
>
> For coupling a 100Hz signal, a 10μF capacitor can be used.
>
> For a 1000Hz signal, a 1μF capacitor can be used.
>
> For a 10KHz signal, a 100nF capacitor can be used.
>
> For a 100KHz signal, 10nF capacitor can be used.
>
> For a 1MHz signal, a 1nF capacitor can be used.
>
> For a 10MHz signal, a 100pF capacitor can be used.
>
> For a 100MHz signal, a 10pF capacitor can be used.
>
> This is a rough estimate that will be effective the majority of the
> time. The only variable that could affect the above values is the
> resistance in parallel to the capacitor.

Consider the last paragraph above when designing your circuit.  The lower the input impedance of the circuit you are driving the more likely the possibility of unexpected results.  At which point you might consider adding the OpAmp suggest in the question.

  [1]: https://en.wikipedia.org/wiki/Direct_current
  [2]: http://www.learningaboutelectronics.com/Articles/What-is-a-coupling-capacitor


message:
Modbus rtu server library which logs the requests

Kindly seek help. In my project I want to ‘fake’ a smart meter via Modbus rtu server for a solis inverter.

Somehow the solis realizes that I am faking him, so I am wondering which Modbus rtu server library you can recommend to allow me seeing what registers the solis is querying?
As of now I am using Emilianov Modbus-8266 library to run the rtu server/slave and platform is an esp32 with max3485.

---

 So let me elaborate. Mine Solis simply sucks during low-light conditions. It can not decide if it shall charge or discharge, resulting in heavy oscialltion, jumping from feeding to much into grid and then taking to much from grid - peaks are ranging from +800Watt to -800Watt when it starts oscillating.

On the com-port you are true - here the solis acts as slave. But on its RS485 meter-port I understand the Solis acts as master and the smart meter is the slave.

My goal is to fake the smart-meter.

So topology would be:

Solis(master)-----(slave)ESP32(master)-----(slave)smartmeter

So I am looking for a solution that any read-request from the Solis is transparently passed-through to the smart-meter. But I want one register intercpeted (most likely total-active-power, which to mine understanding is the only value the solis want to bring back to zero in its control-loop).

As of now I can read the Solis and ther Seplos BMS via ESP32/RS485 successfully. I even have a running slave which I thought shall be good enough to get accpeted as fake-smart-meter, but it is not. The solis is asking for more register then my fake-solution is providing. hence mine ask, which ESP32 slave/server modbus library can print any request its arriving.

If my view is incorrect, kindly get me corrected.

body:
Try looking at this as a starting point

https://github.com/straga/Smart-Meter-Gateway

My approach has been different but will come back to this if my current approach fails.


message:
How to produce a USB CDC serial port for Arduino nano 33 BLE?

I'm trying to program an Arduino Nano 33 BLE bare-metal to get some precise timing and size measurements. I've managed to upload the code to my card, but I cannot communicate with it. More specifically, when I upload the code, the port 'deactivates' after I upload the code, so the serial monitor prints a `cannot exec '/dev/ttyACM0'` error.

Can someone help me figure out how to make it work? I've seen tutorials online but they're for AVR microcontrollers, and I've been told that this specific board isn't. I've also been told that I must include some code in my `c/cpp` file to produce a USB CDC serial port, but I don't know how to do that.

body:
The [Nano 33 BLE board][1] uses a [NORDIC nRF52840 processor][2] which contains the USB interface hardware inside the processor. The current Arduino Uno uses an Atmel (now owned by Microchip) processor and uses an external processor for USB communications. So any Arduino USB tutorial will be very different with respect to these two Arduino designs.

Normally, Arduino Sketches (Programs) are only part of all the software running on a processor. The preprogrammed software on a new Arduino board abstracts the more complex part of embedded programming from the average Arduino user. This likely includes a working USB port.

To do [bare metal programming][3] on a NORDIC nRF52840 processor, consider starting with the [NORDIC Software Development Kit (SDK)][4]. Also, most vendors support their own development boards (provide example programs and libraries) better then development boards made else where.  Consider this before committing to learning how to bring up a "bear metal" USB/CDC peripheral device using the Nano 33 BLE board.

An alternative approach: Many ports of Arduino occur on github.com.  The adaptation of the Arduino code may offer insights as to how the host processor's hardware works. The Nano 33 BLE preprogrammed software comes from [this github repository][5].

  [1]: https://content.arduino.cc/assets/NANO33BLE_V4.0_sch.pdf
  [2]: https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf
  [3]: https://en.wikipedia.org/wiki/Bare_machine
  [4]: https://www.nordicsemi.com/Products/Development-software/nRF5-SDK
  [5]: https://github.com/arduino/ArduinoCore-mbed


message:
Analogue input spikes

i have a project where i read two analogue inputs from two sensors and a pro Mini. I have some spikes in my readings that are present when i'm powering the system using a powerbank step-up module. When i use a 7805 and a 9V battery, the results seem clear. The spikes appear every 600-650ms.

Is there any way to filter them out on a hardware level without using code?

The frequency of the spikes is about 1.5HZ, too slow for a typical ripple of a "dirty" dc converter i think.
My first though was that the module was checking for sufficient load to stay powered on. I added a dummy load but nothing changed. The project is a datalogger and unfortunately i don't really want the code to do the filtering, as it's gonna cost me some speed.

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

  [1]: https://i.stack.imgur.com/MOjkt.jpg
  [2]: https://i.stack.imgur.com/pDiU1.jpg

body: On a hardware level, without a substantial delay, you could use active filters, such as active low-pass or band-pass filters, that can provide better control and customization over the filtering process.


message:
converting comma delimited Serial message to 7 Unsigned Long variables

Working on a project where I get an input where its a comma delimited string like:
```
"255,10000000,42949672950254,12,22".
```
and then the numbers (no commas), would be split into 6 Long variables
like
```
var1 = 255
var2 = 10000000
...
```
I wanted a function like this:

```
void extractIntegersFromString(String str, int& integer1, int& integer2, int& integer3, int& integer4, int& integer5, int& integer6, int& integer7) {
  int count = 0;
  String temp = "";

  for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);

    if (c == ',') {
      if (count == 0)
        integer1 = String(temp).toInt();
      else if (count == 1)
        integer2 = String(temp).toInt();
      else if (count == 2)
        integer3 = String(temp).toInt();
      else if (count == 3)
        integer4 = String(temp).toInt();
      else if (count == 4)
        integer5 = String(temp).toInt();
      else if (count == 5)
        integer6 = String(temp).toInt();
      else if (count == 6)
        integer7 = String(temp).toInt();

      count++;
      temp = "";
    } else if (c >= '0' && c <= '9') {
      temp += c;
    }
  }

  // Store the last integer if the string doesn't end with a comma
  if (temp != "") {
    if (count == 0)
      integer1 = String(temp).toInt();
    else if (count == 1)
      integer2 = String(temp).toInt();
    else if (count == 2)
      integer3 = String(temp).toInt();
    else if (count == 3)
      integer4 = String(temp).toInt();
    else if (count == 4)
      integer5 = String(temp).toInt();
    else if (count == 5)
      integer6 = String(temp).toInt();
    else if (count == 6)
      integer7 = String(temp).toInt();
  }
}
```
This function makes it work through ints, but I need the larger size of a Long.

P.S. I've tried the `atol()` function (and similar others), but that didn't work...

body:
String.toInt actually returns a long. See the code:

    long String::toInt(void) const
    {
     if (buffer) return atol(buffer);
     return 0;
    }

---

> I've tried the atol() function (and similar others), but that didn't work

Please post your "try", don't just say that you did it. Maybe you did it incorrectly.

---

Re your entire technique: There is a function [strtok](https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm) that is specifically designed to break up a string into substrings at a delimiter. You could use that rather than re-inventing the wheel.

However that doesn't solve your specific problem of converting the substrings into a long.


body:
First of all, it is worth noting that the third number in you example
message (100000000000, i.e. 1011) is too large to fit in an
`unsigned long`. On AVR-based Arduinos, and most non-64-bit platforms,
an `unsigned long` is 32-bits wide and can only hold numbers up to
4294967295 (about 4.3×109). I do not know of any easy way to
parse such a large number on AVR.

That being said, for parsing this kind of string into `unsigned long`
numbers, I would recommend the [`strtoul()` function][strtoul]. Compared
to `atol()`, it has the benefit that it tells you where the number it
read ended, so you know where to search for the next one: it saves you a
call to `strchr()`. It also allows some error-checking, so you know
whether the message does conform to the expected format.

Here is a tentative implementation:

```c++
/*
 * Parse up to `count` numeric values from `message`,
 * which must be in comma-separated-values format.
 *
 * Return the number of values successfully parsed.
 */
int parse_message(const char *message,
                  unsigned long *values, int count) {
    for (int i = 0; i < count; i++) {
        char *end;  // pointer to next non-digit
        values[i] = strtoul(message, &end, 10);
        if (end == message) return i;  // parsing failed
        if (*end == ',') end++;        // skip comma
        message = end;                 // move to the next field
    }
    return count;
}
```

And a small test sketch:

```c++
void setup() {
    Serial.begin(9600);

    unsigned long values[7];
    int count = parse_message("255,10000000,100000000000,0,255,12,22",
            values, 7);
    Serial.print(count);
    Serial.println(" numbers successfully parsed:");
    for (int i = 0; i < count; i++)
        Serial.println(values[i]);
}

void loop() {}
```

[strtoul]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaea44aa48bda8261f794dcb2d1e7ab2b2


message:
Serial plotting a pwm

I'm trying to plot the value of the pwm that increases (every 2 sec) then decreases to compare it to the value of an encoder. I was expecting a continued value (like a step ) during 2 seconds but instead I have a triangle signal.
Here is my code
```
const int pwmG = 2;
const int DirG = 8 ;
int a =0;

#define encoder1_CHA 18  //Left encoder
#define pin_channelB_left 6
int b =0;

void setup() {
  Serial.begin(9600);
  pinMode(pwmG,OUTPUT) ;
  pinMode(DirG,OUTPUT) ;
  attachInterrupt(digitalPinToInterrupt(encoder1_CHA),interruptUp,RISING);

  }

void interruptUp(){
  b = !b;

}

void loop() {
  Serial.println(b);
  //Serial.print(" ");
  pwm();

  //Serial.println(a);

  //Serial.println(b);
}

void pwm(){
   for (int i =0; i< 10; i++){
      a = a +5;
      analogWrite(pwmG, a);

      Serial.println(a);
      delay(200);
      }
      //Serial.println(b);

  for (int i =0; i< 10; i++){
    a = a -5;
    analogWrite(pwmG, a);

    Serial.println(a);
    delay(200);
  }
}
```
What I have :

[![][1]][1]

What I expected (exemple found on the internet :
[![What I expected (exemple found on the internet][2]][2]

  [1]: https://i.stack.imgur.com/7NWhO.png
  [2]: https://i.stack.imgur.com/8pept.png

body:
The first point here is, that the Serial Plotter will plot the values against time by connecting them with a straight line. This is just how it represents the data in the plot (it is just for ad-hoc visualization, not for detailed plotting and data analysis).

The second point is, that for each step you are sending only one value through the Serial interface, so only one data point per step. The Serial Plotter then plots this data point against time and connects it with the points for the other steps with a straight line. Thus you get sloped lines/triangle signal in the Serial Plotter.

The image, that you expected, looks like from an oscilloscope. This will have many more data points along the x-axis, not just one per step. Thus you can actually see the steps. If you want to reproduce the image with your code, then you can send the current value of `a` more often in each iteration of the for loop (like looping 20 times over sending the value and delaying about 10ms).


message:
How to change partition scheme with arduino-cli

I'm using arduino-cli to program an ESP32-S2.  If I compile my sketch using the default partition scheme

```
> arduino-cli compile -b esp32:esp32:esp32s2 sketch
```

a lot of space is allocated for SPIFFS and OTA, which I don't use.

```
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.
```

Thus. I'd like to use the `huge_app` scheme, as defined in the boards.txt:

```
esp32s2.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32s2.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32s2.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
```

However, selecting it doesn't have any effect:

```
> arduino-cli compile -b esp32:esp32:esp32s2 sketch --build-property build.partitions=huge_app
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.
```

Is my command line incorrect?  Why is arduino-cli not using the specified partition scheme?

body:
So, it turns out I have to add another build property:

```
> arduino-cli compile --build-property build.partitions=huge_app --build-property upload.maximum_size=3145728 sketch
```

where the `upload.maximum.size` is from the `boards.txt` file.  Indeed, a maze of twisty little files, all alike.


message:
I'm planning on using 2 arduino boards for my project. Should I use 2 voltage regulators for project or use 1 for both?

For context, my first board would contain a motor circuit with an L298N motor driver while my second contains a controlled heating system that uses 2 relays with PTC heating elements, DHT11 sensor, I2C LCD display, and 1 12V exhaust fan.

My input would be a 12V DC power adapter and I'm going to use it to run the motor, the fan, and the 2 heating elements.

Since I want to minimize the chances of my boards from overheating, I want to reduce the input voltage for my board to around 7V, so I want to integrate a voltage regulator circuit.

Should I include 2 voltage regulator circuits or should just utilize 1 for both boards?

body:
If you want an external voltage regulator, one should be plenty. In that case I would regulate down to 5V (not 7V) and connect that to the 5V pin on the board.

An alternative might be to just run the 12V from the battery through a diode or two, thus dropping 0.7V for each diode. Use a diode that can handle a reasonable amount of current, eg. 1N4004. Then you would still connect it to the normal "power input" socket (not the 5V pin).

I assume that the heating, motors, etc., are not being powered by the Arduino board, but directly from the battery via some sort of switching, like a MOSFET or a relay.


body:
I would use a buck or SEPIC regulator and feed Vin on each of the Arduino with about 7.5V from the one regulator. I prefer using Vin because of the additional filtering I get. Also be sure you are using appropriate drivers for your loads, such as relays or MOSFETs.

Consider replacing the L298N with a newer part, that will lose about 3V on the motor leads which is burnt up as heat in the device. There are many others that use MOSFET outputs which will drop less them 0.2 volts.


message:
Making a servo work for just once after a specific time period without hindering the sensors that are reading the data in a loop

I am making a cansat which will be launched on a sugar rocket. The cansat's Arduino nano will be operating sensors which will read the data and store it in an sd card and also a servo to deploy the parachute.

The problem is that I am not able to make code where I want all the sensors to be logging data in the sd card in a loop and a mini servo should perform a sweep angle of 90 degrees after 2 minutes of power supply to the Arduino.

I have made the code for sensors inputting data into sd card but the servo part is confusing me due to no possibility of putting servo code in void setup as the setup will first do the servo sweep after 2 minutes and then record data, neither can I put it in the loop as that also records the data after 2 minutes and I tried to put that into a new function but that's also not working.

Please give me a solution for this.
The code that I have made is below : ( just for sensors logging data in sd card )

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BMP085_U.h>
    #include <DHT.h>
    #include <SD.h>

    #define DHTPIN 10
    #define DHTTYPE DHT11

    DHT dht(DHTPIN, DHTTYPE);

    Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

    const int MQ2 = A0;

    File dataFile;

    void setup() {
      Serial.begin(9600);
      dht.begin();
      if (!bmp.begin()) {
        Serial.println("Could not find a valid BMP085 sensor, check wiring!");
        while (1) {}
      }
      if (!SD.begin(4)) {
        Serial.println("SD card initialization failed!");
        while (1) {}
      }
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile) {
        dataFile.println("Temperature, Humidity, Pressure, Gas");
        dataFile.close();
      } else {
        Serial.println("Error opening data file!");
      }
    }

    void loop() {
      float temperature = dht.readTemperature();
      float humidity = dht.readHumidity();
      sensors_event_t event;
      bmp.getEvent(&event);
      float pressure = event.pressure;
      float gas = analogRead(MQ2);
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile) {
        dataFile.print(temperature);
        dataFile.print(",");
        dataFile.print(humidity);
        dataFile.print(",");
        dataFile.print(pressure);
        dataFile.print(",");
        dataFile.println(gas);
        dataFile.close();
      } else {
        Serial.println("Error opening data file!");
      }
      delay(1000);
    }

body:
I assumed you would want to collect the data after you opened the parachute. And as Delta_G suggested, you would want to open the parachute as fast as possible and not gradually.

I also assumed you want to collect the data every second, based on your provided code, because it has a 1000-millisecond delay. With all that here is a code that might work: (I haven't tested it, but it should give an idea of how to get going)

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BMP085_U.h>
    #include <DHT.h>
    #include <SD.h>

    #define DHTPIN 10
    #define DHTTYPE DHT11

    DHT dht(DHTPIN, DHTTYPE);

    Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

    const int MQ2 = A0;
    const long parachute_timeout_ms = 2 * 60 * 1000;   // Open parachute after two minutes.
    bool parachute_opened = false;

    const long data_collection_interval_ms = 1 * 1000; // Collect data every second.
    bool start_collecting_data = false;
    unsigned long previous_ms = 0;

    File dataFile;

    void setup()
    {
      Serial.begin(9600);
      dht.begin();
      if (!bmp.begin())
      {
        Serial.println("Could not find a valid BMP085 sensor, check wiring!");
        while (1) {}
      }
      if (!SD.begin(4))
      {
        Serial.println("SD card initialization failed!");
        while (1) {}
      }
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile)
      {
        dataFile.println("Temperature, Humidity, Pressure, Gas");
        dataFile.close();
      }
      else
      {
        Serial.println("Error opening data file!");
      }

      previous_ms = millis();
    }

    void loop()
    {

      // Check to see if it's time to open the parachute.
      unsigned long current_ms = millis();

      if ((parachute_opened == false) && (current_ms - previous_ms >= parachute_timeout_ms))
      {
        // Your code to open the parachute
        // ... ... ..

        // Make sure this code doesn't execute again.
        parachute_opened = true;

        //...and then set the flag that tells the other part of the code
        // that it should start collecting data.
        start_collecting_data = true;
      }

      if ((start_collecting_data) && (current_ms - previous_ms >= parachute_timeout_ms))
      {
        collect_data();
        previous_ms = current_ms;
      }
    }

    void collect_data()
    {
      float temperature = dht.readTemperature();
      float humidity = dht.readHumidity();
      sensors_event_t event;
      bmp.getEvent(&event);
      float pressure = event.pressure;
      float gas = analogRead(MQ2);
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile)
      {
        dataFile.print(temperature);
        dataFile.print(",");
        dataFile.print(humidity);
        dataFile.print(",");
        dataFile.print(pressure);
        dataFile.print(",");
        dataFile.println(gas);
        dataFile.close();
      }
      else
      {
        Serial.println("Error opening data file!");
      }
    }


message:
ESP32-CAM OV2640 AS A SUN SENSOR

I want to use the ESP32-CAM as a sun sensor, the problem is that I would need to remove the lenses in order to put a membrane with a pinhole (like it's illustrated in the image) upon the CMOS, but I want to know first, will this make unoperable the OV2640? I want it to be working fine without the lenses, the second image is an illustrative of what I want to do.
[![Fig.1][1]][1]

[![Fig.2][2]][2]

  [1]: https://i.stack.imgur.com/hz9ka.png
  [2]: https://i.stack.imgur.com/DP2bP.png

body:
Consider using the ESP32-CAM as is. Instead use a [pin hole camera][1] box. Put the ESP32-CAM inside the box pointing it at the image of the sun at the back of the box. This approach mitigates problems associated with exposing the sensor to the elements and direct exposure to sun light.

In order to measure azimuth and elevation, consider mounting the device such that it points directly up from the surface of the earth.  And such that it is aligned to true North. Consider using an accelerometer to detect the device is normal to the surface of the earth. And a magnetometer to detect magnetic north.  And a GPS receiver to detect the position on earth.  Combine the GPS data with [ World Magnetic Model (WMM) data][2] to correct for magnetic declination.

  [1]: https://en.wikipedia.org/wiki/Pinhole_camera
  [2]: https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml


message:
How much maximum current do the Arduino Wemos D1 (R1 & R2) consume?

I have been powering my WeMos D1 R1 and D1 R2 Arduinos (with ESP8266) using a simple USB cable connected to a standard charger whose rating is 3.1 amps.  Is this sufficient to charge two such Arduino boards (it has two USB slots) simultaneously?

Also, should I be using the other Power Input which I understand is 9V?

All the specs I have seen specify the voltage but not the current usage.

Either way, what is the maximum amperage that the board might need/is rated for?  Is it different for the R1 vs. R2?  Is it possible to measure how much it is using from any of the pins?

body:
>  It is possible to measure how much it is using from any of the pins?

Put an ammeter (multimeter in current mode) in series with the power supply and measure it, when configured in the way you intend to use it.


message:
MacBook + BLE Microcontroller Incompatibility?

I've programmed an Adafruit Feather nRF52840 board to send MIDI signals to my computer via BLE. I can confirm that the board pairs successfully with an Android phone and a Windows PC, but my laptop (MacBook Pro 2021) will not recognize the board; it does not appear in the Bluetooth menu as an option for pairing. I've tried the following troubleshooting options:

1) Turned bluetooth off & on on laptop
2) Turned device off & on
3) Added the name of the board in the code (advertisement.complete_name = "BOARD_NAME")
4) Downloaded Bluefruit Buddy, Bluefruit Connect & Bluetility to find any BLE signals coming from the board (verdict: no trace!)
5) Tried a BLE smart dongle
6) Unpaired/forgot device from Android phone, attempt to re-pair with laptop
7) Attempted to connect the device via Apple’s Audio MIDI setup (https://support.apple.com/guide/audio-midi-setup/set-up-midi-devices-ams875bae1e0/mac)
8) Tried steps 1-7 with two additional MacBooks (2016 & 2022)

I know that the BLE pairing functionality of the board is working, since it consistently pairs with an Android phone and a PC laptop; I just cannot figure out why it won't pair with my MacBook. I want to resolve this issue and ensure that the board can be used across platforms.

Are there any other troubleshooting actions I should try?

body:
Have you tried [Bluefruit Connect from Adafruit][1]? It is available in the Apple store. Don't quote me on this, but I read a long time ago, that Mac requires encryption for a BLE device to be recognized, whereas, most of the out-of-the-box Adafruit example doesn't use it.

I had a similar issue. And I used Bluefruit Connect to connect my device to my Mac.

[![enter image description here][2]][2]

  [1]: https://apps.apple.com/us/app/bluefruit-connect/id830125974
  [2]: https://i.stack.imgur.com/RWiO5.png


message:
Pass typedef to a function

I'm working with a ESP32S3 that will manage 2 I2S ports, so for the cleanness of my code and also because i'll work multiple I2S installations - deinstallations, i want to move all the functions to and ".cpp .h" file.

something like this

 1. I2S_functions.h
    ```
    #ifndef I2S_FUNCTIONS_H
    #define I2S_FUNCTIONS_H
    #include <Arduino.h>
    #include <driver/i2s.h>

    void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
    i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,int buf_count, int buf_len, bool apll);

    #endif

    ```

 2. I2S_functions.cpp
```
#include "I2S_functions.h"

void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,
int buf_count, int buf_len, bool apll)
{
  const i2s_config_t i2s_config =
  {

    .mode = I2S_MODE,
    //.mode = (i2s_mode_t)(I2S_MODE),
    .sample_rate = I2S_SAMPLE_RATE,

    .bits_per_sample = I2S_SAMPLE_BITS,
    .channel_format = I2S_CHANNEL,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),

    .intr_alloc_flags = 0, // default interrupt priority
    .dma_buf_count = buf_count,//cambiado de 8 a 64
    .dma_buf_len = buf_len,
    .use_apll = apll
  };

  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
}
```

 3. main.ino

```
#include "I2S_functions.h"

// I2S config //////
#include <driver/i2s.h>

#define I2S_PORT I2S_NUM_0
//#define I2S_SAMPLE_RATE  (44100)
float I2S_SAMPLE_RATE=44100;
int I2S_SAMPLE_BITS=32;
//#define I2S_SAMPLE_BITS  (32)
#define bufferLen 1024
#define I2S_READ_LEN (16*1024)

void setup ()
{
  i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
I2S_BITS_PER_SAMPLE_32BIT,I2S_CHANNEL_FMT_ONLY_LEFT,I2S_COMM_FORMAT_STAND_I2S,8,bufferLen,false);

}
```

But when i compile this, i got errors passing the second argument which is "I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE"

a copy from the error:
```
C:\Users\.ino: In function 'void setup()':
test_10seg_V2:52:39: error: invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]
   i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
                        ~~~~~~~~~~~~~~~^~~~~~~~~~~~
In file included from C:\Users\.ino:2:
C:\Users\I2S_functions.h:6:50: note:   initializing argument 2 of 'void i2s_install(i2s_port_t, i2s_mode_t, float, i2s_bits_per_sample_t, i2s_channel_fmt_t, i2s_comm_format_t, int, int, bool)'
 void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,

exit status 1
invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]

```

**Essentially i have 2 questions**. While i looked in the github from the esp32 i found off that there is some typedef of the I2S config (https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/esp32/include/hal/include/hal/i2s_types.h). I've never worked with this type of structs before so i am guessing how should i use it and specially how should i pass this type of variables to a function.
```
typedef enum {
    I2S_BITS_PER_SAMPLE_8BIT    = 8,            /*!< data bit-width: 8 */
    I2S_BITS_PER_SAMPLE_16BIT   = 16,           /*!< data bit-width: 16 */
    I2S_BITS_PER_SAMPLE_24BIT   = 24,           /*!< data bit-width: 24 */
    I2S_BITS_PER_SAMPLE_32BIT   = 32,           /*!< data bit-width: 32 */
} i2s_bits_per_sample_t;

/**
 * @brief I2S bit width per chan.
 *
 */
typedef enum {
    I2S_BITS_PER_CHAN_DEFAULT        = (0),      /*!< channel bit-width equals to data bit-width */
    I2S_BITS_PER_CHAN_8BIT           = (8),      /*!< channel bit-width: 8 */
    I2S_BITS_PER_CHAN_16BIT          = (16),     /*!< channel bit-width: 16 */
    I2S_BITS_PER_CHAN_24BIT          = (24),     /*!< channel bit-width: 24 */
    I2S_BITS_PER_CHAN_32BIT          = (32),     /*!< channel bit-width: 32 */
} i2s_bits_per_chan_t;
```

my questions are

**1.-** I would like to understand how this structs works. I want to clean my code the most that i could, and that mean passing a lot of functions out of the main file. So any resource is well welcome to improve my coding skill.

**2.-** Why the code fails passing this 2 variables "I2S_MODE_MASTER|I2S_MODE_RX" ?. Is there any special way of passing this variables when are 2 options at once?.

Thanks for your replies!

body:
Answer to Question 1: The `typedef` code you posted is `enum` and not `struct`. Look up C++ Enumeration and you will find lots of good tutorials. Here is [one video][1].

Answer to Question 2:  You need to typecast the argument for your function to accept it as `i2s_mode_t`.

    i2s_install(I2S_PORT, (i2s_mode_t)(I2S_MODE_MASTER|I2S_MODE_RX), ... ... ...);

  [1]: https://www.youtube.com/watch?v=OWlbuyQ2eig


message:
Copy Uno Analog Input Configuration To ESP32

I started a project using the arduino uno and as a challenge I'm attempting to make it work with the esp32 but I've run into a roadblock. I may not describe it in proper terms, but I noticed that the analog input signal on the esp32 functions *differently* from how analog input works on the uno. After some research I found that the esp32 has a default analog width of 12, instead of the default 10 on the uno. This got me wondering what other analog settings (reference voltage, pin attenuation, width, etc.) on the esp32 are different from the uno and how I might go about getting similar results on the esp32. I found [this][1] useful page detailing some functions to mess around with the adc channels but, other than ```analogSetWidth()```, I haven't been able to figure out what they do. I tried messing around with the functions mentioned in the linked page, but I ultimately made things worse.

tl;dr What analog input settings (analog width, pin attenuation, etc.) on the esp32 are different from the uno?

  [1]: https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/api/adc.html

body:
Per the advice of @6v6gt, I was able to find [this][1] resource and [this][2] resource that told me the following information about the ADC configuration for the Uno's MCU (aka ATmega328P):

 - The analog width defaults to 10 bits (** definitely the most important)
 - The reference voltage is determined by the AVCC (power source) by default
 - The ADC clock defaults to a divisor of 128 (assuming 13 ADC cycles per conversion)

Wasn't able to find anything useful about pin attenuation, though.

  [1]: https://www.best-microcontroller-projects.com/arduino-adc.html
  [2]: https://ece-classes.usc.edu/ee459/library/documents/ADC.pdf


message:
USB OTG and ESP32-S2

I have an [ESP32-S2-DevKitM-1][1] which is supposed to able to act as USB HID device.

But whatever I try using either ESP-IDF or Arduino-IDE, I can't get any data from it.

I ran [this esp-idf example][2].

I also ran the arduino example.

I [connected][3] GPIO20/19 to D+/D- of a USB cable.

When I plug in that cable, my host computer logs:

```
usb 1-6: new full-speed USB device number 93 using xhci_hcd
usb 1-6: device descriptor read/64, error -71
usb 1-6: device descriptor read/64, error -71
usb 1-6: new full-speed USB device number 94 using xhci_hcd
usb 1-6: device descriptor read/64, error -71
usb 1-6: device descriptor read/64, error -71
usb usb1-port6: attempt power cycle
usb 1-6: new full-speed USB device number 95 using xhci_hcd
usb 1-6: Device not responding to setup address.
usb 1-6: Device not responding to setup address.
usb 1-6: device not accepting address 95, error -71
usb 1-6: new full-speed USB device number 96 using xhci_hcd
usb 1-6: Device not responding to setup address.
usb 1-6: Device not responding to setup address.
usb 1-6: device not accepting address 96, error -71
usb usb1-port6: unable to enumerate USB device
```

The esp-idf example fails to send, because `tud_mounted()` is false, and the arduino-ide example fails on `SendReport(): not ready`.

How can I get the ESP32-S2 to talk USB with my host computer?

  [1]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/hw-reference/esp32s2/user-guide-devkitm-1-v1.html
  [2]: https://github.com/espressif/esp-idf/tree/master/examples/peripherals/usb/device/tusb_hid
  [3]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/peripherals/usb_device.html#hardware-usb-connection

body:
This problem went away when I replaced my DIY USB cable connection with an [Adafruit USB-C breakout board][1].

I checked all the connections of my cable, but somehow it would not work, until I replaced it.

  [1]: https://www.adafruit.com/product/4090


message:
Arduino unable to read 0x41 and 0x42 (reads others just fine (ICT bill acceptor)

Here is my issue:

My code successfully recognizes and accepts $1 (0x40) and $20 bills (0x43), but it fails to recognize, display, process, anything for the $5 bill (0x41), and $10 bills (0x42). Also, when I say "Arduino", I mean TTGO btw...

I have verified that the bill acceptor is indeed sending the correct value (0x41) for the $5, and $10 (0x42) bills using an external monitoring tool like Docklight, and I used an oscilloscope too! All signals from all bill types were near identical and valid. However, the Arduino code does not seem to receive those two values (and ONLY those two values) at all... Meanwhile, it will display every other little thing there is... I have my code setup where it displays all incoming bytes, be it B.A. (bill acceptor) idle signals, rejection signals, everything, but it goes 100% blank, MIA, for 0x41 and 0x42... WHY?!?! So frick'n random...

===================================================

**Just so you all know, this is how the bill acceptor (B.A.) works:**

 1. Insert a bill into BA
 2. BA sends the corresponding HEX value (ex. 0x40) of the bill to my Arduino (Using RS232 cables and an RS232 to TTL converter (the converters are confirmed to be 100% operational BTW))
 3. Once the Arduino "sees" the HEX value for a bill of N value, it will then send 0x02 to the BA to accept the bill.
 4. If 0x02 is NOT sent to the BA within 5 seconds, then it will reject the bill and spit it back out the front.
 5. Code then adds that value to "total count"

OFC, my code is setup where the only way an accept (0x02) signal is sent is IF 0x4N is received... So, the fact that 0x41 and 0x42 disappear into thin air means 0x02 is never sent so those two values are always rejected... Very, very, simple stuff, so the fact that it consistently is unable to ONLY NOT read 0x41 and 0x42 while clearly displaying all other sent HEX values is causing me unlimited headaches and conniptions... Programming... YAY! -_-

So, anyone... please, do you know what's going on? The signal is 100% being generated, and my code, below, is setup to display all incoming bytes, but it acts like 0x41 and 0x42 do not exist at all! Nothing. Nada. Zilch. WTF? It literally handles everything I can throw at it... except 0x41 and 0x42!!! FUUUUUUUUUUUU!!! So mad...

**HERE IS THE ICT RS232 PROTOCL FOR MY BILL ACCEPTOR - [http://tdmegalit.ru/upload/iblock/401/ict_protocol.pdf][1]**

**ALSO, I HAVE ALL DIP SWITCHES CORRECTLY SET, POWER SUPPLY IS PERFECT, ALL WIRES ARE TESTED AND PERFECT, RS232 TO TTL CONVERTERS ARE PERFECT. I GUESS IT IS SOFTWARE SERIAL, OR THE TTGO**

So with all that said, **below is my code**. It is a part of a much great whole of a program, so to remove the possibilities of the rest of the code causing the error, I reduced it to what you see below, but the problem persist... bruh

Also, I have included the **Serial Monitor LOG**. The LOG below shows startup, and then a 1, 5, 10, and 20 dollar bill being inserted...

**SERIAL MONITOR LOG:**

    PLZ NOTE, I ADDED SPACES TO SHOW WHATS GOING ON...
    ====================================================================

    ... Received: 0x80       //IDLE SIGNALS (BA POWERED ON BEFORE "SETUP" SENT)
    ... Received: 0x8F
    ... Received: 0x80
    ... Received: 0x8F
    ... Received: 0x80
    ... Received: 0x8F

    SETUP - ...Sent: STX     //SETUP TO INITALIZE BA
    SETUP - ...Sent: DLE
    SETUP - ...Sent: ETX
    =======================
                             //INSERTED $1 (0x40) SUCCESS!!!
    ... Received: 0x40
    $1 accepted
    ... Sent: 0x02
    ... Received: 0x10
                             //INSERTED $5 and 5 seconds later 0x29>>0x29>>0x2F = Rejection
    ... Received: 0x29
    Bill rejected
    ... Received: 0x29
    Bill rejected
    ... Received: 0x2F
                             //INSERTED $10 and 5 seconds later 0x29>>0x29>>0x2F = Rejection
    ... Received: 0x29
    Bill rejected
    ... Received: 0x29
    Bill rejected
    ... Received: 0x2F
                             //INSERTED $20 (0x43) SUCCESS!!!
    ... Received: 0x43
    $20 accepted
    ... Sent: 0x02
    ... Received: 0x10

**BILL ACCEPTOR CODE:**

    #include <SoftwareSerial.h>

    SoftwareSerial BA(32, 33);  // RX, TX

    int billCounter = 0;

    void setup() {
      Serial.begin(9600);
      BA.begin(9600);
      delay(3000); //WAIT BC TRESH

      BA.write(0x02); // Send the initialization command (STX)
      Serial.println("SETUP - ...Sent: STX");
      BA.write(0x10); // Send the command to enable the bill acceptor
      Serial.println("SETUP - ...Sent: DLE");
      BA.write(0x03); // Send the end of text character (ETX)
      Serial.println("SETUP - ...Sent: ETX");
      Serial.println("=======================");
    }

    void loop() {
      if (BA.available()) {
        byte receivedByte = BA.read();
        Serial.print("... Received: 0x");
        Serial.println(receivedByte, HEX);

        if (receivedByte == 0x29) {
          delay(200);
          Serial.println("Bill rejected");
          // Handle bill rejection here (e.g., display message or perform necessary actions)

        } else if (receivedByte == 0x40) {
          delay(200);
          Serial.println("$1 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $1
          billCounter += 1;

        } else if (receivedByte == 0x41) {
          delay(200);
          Serial.println("$5 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $5
          billCounter += 5;

        } else if (receivedByte == 0x42) {
          delay(200);
          Serial.println("$10 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $10
          billCounter += 10;

        } else if (receivedByte == 0x43) {
          delay(200);
          Serial.println("$20 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $20
          billCounter += 20;

        } else if (receivedByte == 0x44) {
          delay(200);
          Serial.println("$50 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $50
          billCounter += 50;

        } else if (receivedByte == 0x45) {
          delay(200);
          Serial.println("$100 accepted");
          BA.write(0x02); // Send the HEX value 0x02 to accept the bill
          Serial.println("... Sent: 0x02");

          // Increment the counter by $100
          billCounter += 100;
        }
      }
    }

  [1]: http://tdmegalit.ru/upload/iblock/401/ict_protocol.pdf

body:
The default for Arduino Serial is `8 data bits, no parity, one stop bit`. The first page of your linked documents says: `Start bit 1, Data bit 8, Parity bit Even, Stop bit 1`. The mismatched parity parameter could explain a partial failure of this communication. The documentation for the Serial begin() method describes the various configuration options.

However, see also this thread: https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535
It appears that the various software serial libraries do not support EVEN parity settings. Use a hardware serial port on your TTGO Arduino instead. This may mean using SoftwareSerial for the debug printing (maybe with a USB/UART adapter) and dedicating the hardware serial port to your bank note reader.


body:
> The default for Arduino Serial is 8 data bits, no parity, one stop
> bit. The first page of your linked documents says: Start bit 1, Data
> bit 8, Parity bit Even, Stop bit 1. The mismatched parity parameter
> could explain a partial failure of this communication. The
> documentation for the Serial begin() method describes the various
> configuration options.
>
> However, see also this thread:
> https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535
> It appears that the various software serial libraries do not support
> EVEN parity settings. Use a hardware serial port on your TTGO Arduino
> instead. This may mean using SoftwareSerial for the debug printing
> (maybe with a USB/UART adapter) and dedicating the hardware serial
> port to your bank note reader.

Thank you 6v6gt! Using HardwareSerial was the answer and setting the parity bit to EVEN was the answer too :D Here is what I did to fix it if anyone ever needs to see this answer in the future...

**Also note, here is the logic:**

The default for hardware serial is SERIAL_8N1, but I needed to use SERIAL_8E1 for the even parity because:

SERIAL_8N1 means "8" bits, "N"o parity, and "1" stop bit (hence 8N1)

SERIAL_8E1 means "8" bits, "E"ven parity, and "1" stop bit (hence 8E1)

**Here is the chart I used to get the protocol format I needed:**

    /* Baud-rates available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200, 256000, 512000, 962100
     *
     *  Protocols available:
     * SERIAL_5N1   5-bit No parity 1 stop bit
     * SERIAL_6N1   6-bit No parity 1 stop bit
     * SERIAL_7N1   7-bit No parity 1 stop bit
     * SERIAL_8N1 (the default) 8-bit No parity 1 stop bit
     * SERIAL_5N2   5-bit No parity 2 stop bits
     * SERIAL_6N2   6-bit No parity 2 stop bits
     * SERIAL_7N2   7-bit No parity 2 stop bits
     * SERIAL_8N2   8-bit No parity 2 stop bits
     * SERIAL_5E1   5-bit Even parity 1 stop bit
     * SERIAL_6E1   6-bit Even parity 1 stop bit
     * SERIAL_7E1   7-bit Even parity 1 stop bit
     * SERIAL_8E1   8-bit Even parity 1 stop bit
     * SERIAL_5E2   5-bit Even parity 2 stop bit
     * SERIAL_6E2   6-bit Even parity 2 stop bit
     * SERIAL_7E2   7-bit Even parity 2 stop bit
     * SERIAL_8E2   8-bit Even parity 2 stop bit
     * SERIAL_5O1   5-bit Odd  parity 1 stop bit
     * SERIAL_6O1   6-bit Odd  parity 1 stop bit
     * SERIAL_7O1   7-bit Odd  parity 1 stop bit
     * SERIAL_8O1   8-bit Odd  parity 1 stop bit
     * SERIAL_5O2   5-bit Odd  parity 2 stop bit
     * SERIAL_6O2   6-bit Odd  parity 2 stop bit
     * SERIAL_7O2   7-bit Odd  parity 2 stop bit
     * SERIAL_

**CODE SOLUTION:**

    #include <HardwareSerial.h>

    HardwareSerial BA(1);  // Use Hardware Serial on TTGO

    void setup() {
      Serial.begin(9600);
      BA.begin(9600, SERIAL_8E1, 32, 33);  // (Baud rate, Protocol, RX, TX)
      ...  //rest of my code


message:
Improving moving mouse loop to optimize speed

Code:
```
#include <Mouse.h>
#include <hiduniversal.h>
#include "hidmouserptparser.h"
#include <USBController.h>

USBController controller;
USB Usb;
HIDUniversal Hid(&Usb);
HIDMouseReportParser Mou(nullptr);
String x;
String y;
boolean isX;
int recv;

void setup() {
 Mouse.begin();
 Usb.Init();
 delay(200);

 if (!Hid.SetReportParser(0, &Mou))
  ErrorMessage<uint8_t > (PSTR("SetReportParser"), 1);
}

void loop() {
   Usb.Task();
 recv = controller.read();
   if ((recv-48)==29){ // recv = M
  // , : -4
  // /n : -38
  x="";
  y="";
  isX = true;
  while (true){
   recv = controller.read();
   if (recv!=0 && recv!=2){ // filter out 0 and 2
    if ((recv-48)==-38){ // -38 is a line break
     break;
    }
    else if ((recv-48)==-4){ // switch to y value after comma
     isX = false;
     continue;
    }

    if (isX){
     x+=String(recv-48);
    }
    else{
     y+=String(recv-48);
    }
   }
  }
  Mouse.move(x.toInt(),y.toInt());
   }
}

void onButtonDown(uint16_t buttonId) {
 Mouse.press(buttonId);
}

void onButtonUp(uint16_t buttonId) {
 Mouse.release(buttonId);
}

void onMouseMove(int8_t xMovement, int8_t yMovement, int8_t scrollValue) {
 Mouse.move(xMovement, yMovement, scrollValue);
}

```
I'm using an Arduino leonardo with a usb host shield. My goal is to move my cursor to a specific location based on the data read in. Format of the data read in is "MX,Y" and a line break.

In the main loop,
- I read the data and subtract 48 because that's the real number.
- Then I check if the first character is M because that is where the beginning of my data starts.
- Then I filter out 0 and 2 because those values are useless to me and randomly appear.
- I loop to add the integer values as strings to x then switch to y after the comma appears.
- Then I convert the `string` values to `int` and `mouse.move`.

The problem is the mouse movement is slow and jittery and I think it's because the `toInt` and `String()` methods are slowing it down. How could I improve my algorithm?

body:
This:

> ```c++
> while (true){
>     recv = controller.read();
>     // ...
> }
> ```

is a _blocking_ loop. This means that, while executing this part of the
code, the Arduino is stuck for an indeterminate amount of time, and can
do nothing else. Specifically, it cannot run `Usb.Task()`, which could
well be the cause of the jittery behavior you are experiencing.

I would recommend reading the incoming data in a _non blocking_ fashion:
each time there is a byte to be read, read it and move on. Do not wait
for the subsequent bytes. Only when you find an end of line would you
handle the data you received. For example:

```c++
// Parse and execute a command received through USB.
executeCommand(String &command) {
    // Implementation left as an exercise to the reader.
}

// Whether we are presently receiving characters from a command.
bool receivingCommand = false;

// Received command, may be incomplete.
String command;

void loop() {
    Usb.Task();
    if (controller.available()) {
        char c = controller.read();
        if (!receivingCommand && c == 'M') {  // start of command
            receivingCommand = true;
        } else if (receivingCommand && c == '\n') {  // end of command
            executeCommand(command);
            command = "";
            receivingCommand = false;
        } else if (receivingCommand) {  // body of command
            command += c;  // buffer the received character
        }
    }
}
```

A better approach would be to avoid the `String` class, which is not
friendly to your Arduino's memory, and use a plain C string, as
explained in [Reading Serial on the Arduino][majenko]. This, however, is
likely unrelated to your jitter issue.

[majenko]: https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27


message:
Why does a simple LED Blink not work using mbed.h PWM and Arduino Nano BLE?

I have set up a very simple test program to blink an builtin LED using PWM. Following the [mbed example][1] and setting the period to 4 seconds (0.25 Hz) and duty cycle to 0.5, the expected behaviour is for the LED to be on for 2 seconds and off for 2 seconds. However, the actual behaviour is that the LED flashes extremely quickly (almost imperceptable to the eye).

```arduino
#include "mbed.h"

mbed::PwmOut ledPin = mbed::PwmOut(P0_13); //builtin led pin

void setup() {
  ledPin.period(4.0f);
  ledPin.write(0.0f);
}

void loop() {
  // put your main code here, to run repeatedly:
  ledPin.write(0.5f);
}
```

I have tried adding `delay()` and `wait_ns()` with different times in the main loop, tried having the main loop empty and setting the duty cycle in the `setup()` function as well as changing the period to larger numbers just in case it was in milliseconds all to no avail. Not quite sure what I'm missing from this extremely simple example.

  [1]: https://os.mbed.com/handbook/PwmOut

body:
The example you linked has an infinite, but empty, loop - `while(1);` - following setting up the PWM.

Your loop repeatedly executes `ledpin.out(0.5f);`

I didn't find the .out() member function to know what it does but my first thought would be comment out the contents of your loop() function and let it also run as an empty infinite loop. Then I'd look at the .out member function and find out what its action is. Output to a pin is usually a boolean. If that is the case with .out(), then 0.5f will be converted to an integer 0 which is identical to boolean 'false', and this loop would repeatedly turn off the LED, and at around a megahertz.


message:
Barebones AVR - Connecting RESET pin to Vcc

I want to build my first barebones AVR circuit.

I plan on NOT having a RESET button. For this reason, is it valid if I connect the ATMEGA's `RESET` pin to `Vcc` directly?

What I mean by this, is that in this scenario, I will not be using a pull-down resistor as well. Just straight to `Vcc`.

EDIT: This is a part of the schematic:

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

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

body:
According to the datasheet linked to by hcheung in their comment, [datasheet][1], on page 41 it states "Figure 10-2. MCU Start-up, RESET Tied to VCC".

I believe it would be OK to tie the pin directly to Vcc.

I also believe the graphical data presented in "Figure 10-2" could be miss-leading if the reader didn't know what Vcc meant, and also because there is no horizontal axis to specify that they are talking about elapsed time, not voltage change.

**EDIT**

Regarding your comment "Thanks, but now I am not sure if this setup will work with Sparkfun's Pocket AVR Programmer.".

Looking at page 40 of the datasheet, a internal pull-up resistor is built into the MCU.

[![enter image description here][2]][2]

You could leave the reset pin not connected and see if it still works as expected. Perhaps a high impedance DVOM would show Vcc on that pin. Some people say leave it disconnected if there are no issues from EMI. [EEV Blog - Is it ok to leave atmega328p reset pin floating?][3]

The data sheet also mentions the power on reset timeout which may allow you to program the MCU with your programmer once it first starts, (assuming you have tied the reset pin to Vcc and you leave the reset pin disconnected on your programmer).

Another option would be to program the MCU, then connect the reset pin to Vcc through a couple of solder pads you can bridge with a blob of solder.

Once the reset pin is tied to Vcc, using a programmer connected to that pin will likely result in the magic smoke being released from the MCU, your programmer, or both.

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
  [2]: https://i.stack.imgur.com/Nl1Rq.jpg
  [3]: https://www.eevblog.com/forum/beginners/is-it-ok-to-leave-atmega328p-reset-pin-floating/


body:
>  I updated the question with a pic. I am using ATMega328. I intend to program the chip using Sparkfun's AVR Programmer.

Then don't tie /RESET to VCC. The programming won't work. What are you doing? Trying to save one resistor? If you have J2 as a programming interface, then /RESET needs to be able to be pulled low to start the programming sequence. Either remove J2 altogether and program the chip in advance of going on the board, or use the pull-up resistor. Don't tie it to VCC.