message:
Accelerometer value meaning

I'm currently using the MPU-6050 accelerometer to receive the acceleration and angular velocity data. I'm trying to process the data for my experiment but I can't understand the exact meaning of it. I have threee questions about the situation. I append the arduino code below.

First, I happen to know that the AcX value of the code below means how much the sensor is inclined along the x axis. Is there other way to get acceleration directly? or Do I have to use formula(v = v_0 + a*t)?

Second, for the gyro sensor, I can't understand the meaning of the value. Does it sends the angular velocity or angular acceleration and if it is one of these, what's the limit?

 Third, according to code, it receives data in the form of 2^14(14bit) but sometimes it sends value way over the limit. How can I translate raw data to rather regular unit like degree and rad?

Thank you

```#include <Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,GyX,GyY,GyZ;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
  Serial.println("CLEARDATA");
  Serial.println("LABEL,TIME,AcX,AcY,AcZ,GyX,GyY,GyZ");
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers

  // deviding the 16bit input??
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  //Serial.print("AcX = ");
  Serial.print(AcX);
  Serial.println(",");
  //Serial.print(",");
  //Serial.print(" | AcY = ");
  //Serial.print(AcY); Serial.print(",");
  //Serial.print(" | AcZ = ");
  //Serial.print(AcZ); Serial.print(",");
  //Serial.print(" | GyX = ");
  //Serial.println(GyX);
  //Serial.print(" | GyY = ");
  Serial.println(GyY); //Serial.print(",");
  //Serial.print(" | GyZ = ");
  //Serial.println(GyZ);
  delay(200);
}

body:
> Is there other way to get acceleration directly? or Do I have to use
> formula(v = v_0 + a*t)?

The code appears to be currently retrieving the raw X, Y & Z acceleration and storing it in AcX, AcY & AcZ.  The equation "v = v_0 + a*t" appears to be [deriving velocity][1].  So the question is confusing.

> ...for the gyro sensor, I can't understand the meaning of the value. Does
> it sends the angular velocity or angular acceleration

The accelerometer sensors measure acceleration.  As the last question ultimately asked for angles, the gyroscope is not needed.  However, on page 12 in the [MPU-6050 specifications][2] the dimensions of the gyroscope is given in degrees per second or angular velocity.  Likely the mechanism within the chip depends on the [Coriolis effect][3]

> ...and if it is one of these, what's the limit?

On the same page [the MPU-6050 chip specification][2] shows a table containing values such as GYROSCOPE SENSITIVITY & Full-Scale Range.  Consider reading these and other values regarding the gyroscope.

> ...according to code, it receives data in the form of 2^14(14bit) but
> sometimes it sends value way over the limit.

The code retrieves a high 8 bit and low 8 bit value for each axis of the accelerometer and the gyroscope.  This makes a 16 bit value.  Not a 14 bit value.

> How can I translate raw data to rather regular unit like degree and
> rad?

 1. To obtain an angle in degrees only the accelerometer is required.
 2. Consider calibrating the accelerator for offset and magnitude errors before using the raw values.
 3. Consider constraining the problem such that the accelerometer is only rotated around the Z-axis.
 4. The angle can be found by taking the inverse tangent of the ratio of the calibrated X acceleration and calibrated Y acceleration.

Other considerations:

 - If angles are desired in 3 dimensional space consider using commonly referred to values such as pitch, roll & yaw.  In which case many situate the accelerometer such to use these equations:

[![enter image description here][4]][4]

The above equations, a discussion and some example code can be found [here][5].

 - So far, all the equations discussed use trigonometry and can go to infinity (unusable results) given certain inputs.  The mathematical equivalent of [gimbal lock][6] if you will.  To avoid this consider using [quaternions][7].  This mathematical method of representing rotation in 3 dimensional space does not suffer the above problem, is easier for computers to calculate and is used extensively in computer graphics.

  [1]: https://en.wikipedia.org/wiki/Equations_of_motion#Constant_translational_acceleration_in_a_straight_line
  [2]: https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Datasheet1.pdf
  [3]: https://en.wikipedia.org/wiki/Coriolis_force
  [4]: https://i.stack.imgur.com/7j1zY.png
  [5]: https://wiki.dfrobot.com/How_to_Use_a_Three-Axis_Accelerometer_for_Tilt_Sensing
  [6]: https://en.wikipedia.org/wiki/Gimbal_lock
  [7]: https://en.wikipedia.org/wiki/Quaternion


sender: user

message:
how can I accurately recieve potentiometer values over the USB port?

I want to read the analog values of my ardunio uno into a separate c++ program. On the Arduino I have a serial port initialized for 9600 baud:

    int sensorPin = A0;    // select the input pin for the potentiometer

    int sensorValue = 0;  // variable to store the value coming from the sensor

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

    void loop() {
      // read the value from the sensor:
      sensorValue = analogRead(sensorPin);
      Serial.println(sensorValue);
    }

The output value should be right around 390, given the current settings. My serial port reading code seems to read the port fine, but only displays some of the characters sometimes.... some of the time, it reads the value fine. other times I get one or 2 of the characters, such as 3, or 39.

    #include <stdio.h>      // standard input / output functions
    #include <stdlib.h>
    #include <string.h>     // string function definitions
    #include <unistd.h>     // UNIX standard function definitions
    #include <fcntl.h>      // File control definitions
    #include <errno.h>      // Error number definitions
    #include <termios.h>    // POSIX terminal control definitions
    #include <iostream>
    using namespace std;

    int main(){
     const char* device ="/dev/ttyACM0";
    /* Open File Descriptor */
    //int USB = open( device, O_RDWR| O_NONBLOCK | O_NDELAY );
    int USB = open( device, O_RDWR| O_NOCTTY );

    /* Error Handling */
    if ( USB < 0 ){
    cout << "Error " << errno << " opening " << device << ": " << strerror (errno) << endl;
    }

    /* *** Configure Port *** */
    struct termios tty;
    struct termios tty_old;
    memset (&tty, 0, sizeof tty);

    /* Error Handling */
    if ( tcgetattr ( USB, &tty ) != 0 ) {
       cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << endl;
    }

    /* Save old tty parameters */
    tty_old = tty;

    /* Set Baud Rate */
    cfsetospeed (&tty, (speed_t)B9600);
    cfsetispeed (&tty, (speed_t)B9600);

    /* Setting other Port Stuff */
    tty.c_cflag     &=  ~PARENB;            // Make 8n1
    tty.c_cflag     &=  ~CSTOPB;
    tty.c_cflag     &=  ~CSIZE;
    tty.c_cflag     |=  CS8;

    tty.c_cflag     &=  ~CRTSCTS;           // no flow control
    tty.c_cc[VMIN]   =  1;                  // read doesn't block
    tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
    tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

    /* Make raw */
    cfmakeraw(&tty);

    /* Flush Port, then applies attributes */
    tcflush( USB, TCIFLUSH );
    if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
       cout << "Error " << errno << " from tcsetattr" << endl;
    }

    if ( tcsetattr ( USB, TCSANOW, &tty ) != 0){
    cout << "Error " << errno << " from tcsetattr" << endl;
    }

    /* Allocate memory for read buffer */
    char buf [1024];
    memset (&buf, '\0', sizeof buf);

    /* *** READ *** */
    int n = read( USB, &buf , sizeof buf );
    cout << "buffer: " << &buf << endl;
    /* Error Handling */
    if (n < 0)
    {
         cout << "Error reading: " << strerror(errno) << endl;
    }

    /* Print what I read... */
    cout << "Read: " << buf << endl;

    close(USB);
     return 0;
    }

How can I read the correct value being sent every time?

sender: assistant

body:
A [USB connection][1] is actually very complex.  And [serial communications (or the CDC class of USB)][2] is only 1 of over a dozen protocols used over USB.  Most cheap embedded processors save money by leaving out this feature.  Most Arduino's use cheap embedded processors.  For instance, the classic [Arduino Uno][3] needs a [second chip (search for New USB in this link)][4] to even talk Serial over the USB port.  Fortunately this is what [Serial.print()][5] does.  It takes care of setting up the Serial protocol over the USB port for you.  And will send your data over that connection.

How you pick up that data at the other end of the USB connection is usually beyond the discussion range of this stack exchange site.  But if you are on a windows machine it will probably be one of the COM ports.  And on Linux it will probably be something like /dev/ttyUSB0 or 1.

  [1]: https://en.wikipedia.org/wiki/USB
  [2]: https://en.wikipedia.org/wiki/USB_communications_device_class
  [3]: https://store.arduino.cc/usa/arduino-uno-rev3
  [4]: https://learn.adafruit.com/arduino-tips-tricks-and-techniques
  [5]: https://www.arduino.cc/reference/en/language/functions/communication/serial/print/


body:
There are a few issues at play here. One is that the Arduino
resets every time you open the serial connection on the PC side. You can
prevent this by putting a 1 µF (or more) capacitor between 5V and
RESET. A second issue is that the tty driver may be keeping old data in
its buffer, and you get this data when you open the connection. The
third issue is that `read()` returns as soon as it is able to read
_some_ data: it doesn't wait until it has got `sizeof buf` bytes.

To fix those issues, I suggest:

1. Have some form of handshake, where the PC sends a request to the
   Arduino, and then the Arduino acknowledges and starts to send the
   data. The PC program would then discard everything preceding the
   acknowledgement.
2. On the PC, repeatedly `read()` until you have a full line (which ends
   with CRLF). You may want to use a line-oriented stream if you want
   the libc to handle this for you: see fdopen(3) setlinebuf(3).

**Edit**: A very simple example of handshake: the PC sends `S` (for
“start”), then the Arduino sends `OK`, then it starts sending the data.
On the Arduino side:

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

    // Wait for the 'S' (start) command from the computer.
    while (Serial.read() != 'S')
        /* wait */ ;

    // Send acknowledgement.
    Serial.println("OK");
}
```

A longer “start” command would be more robust, but a bit more complex to
handle on the Arduino. The PC should wait a bit before sending the
command (in case the Arduino is restarting), or maybe send it multiple
times until it gets an answer.


message:
I am building a coin operated machine and am using arduino uno its working but i have to press the switch twice for credit to show on seven segment

```
int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
volatile byte  num = 0;
int coinPin = 2;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(coinPin), inc_counter, RISING );
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);
  pinMode(pin4, OUTPUT);
}

void display(int num) {
  digitalWrite(pin1, bitRead(num, 1));
  digitalWrite(pin2, bitRead(num, 2));
  digitalWrite(pin3, bitRead(num, 3));
  digitalWrite(pin4, bitRead(num, 4));
}

void loop() {
  Serial.print(num);
  Serial.print("credit(s) towards balance");
  display(num);
  delay(500);
}

void inc_counter() {
  num++;
}
```

body:
Based on the code supplied, you are only updating the display every half second because of the `delay(500)`. You could press the button a number of times in 500mills.

I feel it may be better to update a flag and check that in your loop to increment your value and trigger the display update.

Based on the info provided, this may help in your endeavours.

```c++
int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
int coinPin = 2;
int num = 0;
volatile bool coinFlag = false; // When true there is a coin.

void coin_present()
{
    coinFlag = true;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(coinPin), coin_present, RISING);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(pin3, OUTPUT);
    pinMode(pin4, OUTPUT);
}

void display(int num)
{
    digitalWrite(pin1, bitRead(num, 1));
    digitalWrite(pin2, bitRead(num, 2));
    digitalWrite(pin3, bitRead(num, 3));
    digitalWrite(pin4, bitRead(num, 4));
}

void loop()
{
    // If the flag is set increment num and then display value.
    if (coinFlag)
    {
        //We have a coin, reset the flag first.
        coinFlag = false;

        num++;        // Increment value
        display(num); //
        Serial.print(num);
        Serial.println("credit(s) towards balance");
    }

    // No need for a delay as only `coinFlag` being `true` will update the display.
}
```

Hope this helps in someway.


message:
how to config the Arduino ADC'S input on A0 instead of use default?

I am try to build this AC-DC meter, the code original used default A3 as input, how can change the input on A0?
the link:
https://simple-circuit.com/arduino-autoranging-ac-dc-voltmeter-with-trms/

Thanks for help
Adam

 ```cpp

/**************************************************************************
 *
 * Arduino autoranging AC/DC voltmeter.
 * Voltage and frequency are printed on 1602 LCD screen.
 * This is a free software with NO WARRANTY - Use it at your own risk!
 * https://simple-circuit.com/
 *
 *************************************************************************/

#include <LiquidCrystal.h>   // include Arduino LCD library
// LCD module connections (RS, E, D4, D5, D6, D7)
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);

// define autoranging channel pins
#define CH0  2
#define CH1  3
#define CH2  4
#define CH3  5

const uint16_t Time_Out = 50000,  // time out in microseconds
               Periods  = 10;     // number of periods of measurement (for AC voltage only)

// variables
byte ch_number;
const uint16_t res_table[4] = {2444, 244, 94, 47},  // voltage divider resistances in tenths kOhms
               total_res = 22444;                   // total resistance in tenths kOhms
uint16_t current_res;
volatile byte per;

void setup(void)
{
  pinMode(CH0, OUTPUT);
  pinMode(CH1, OUTPUT);
  pinMode(CH2, OUTPUT);
  pinMode(CH3, OUTPUT);

  lcd.begin(16, 2);     // set up the LCD's number of columns and rows
  lcd.setCursor(1, 0);
  lcd.print("Voltage:");

  ch_number = 0;
  ch_select(ch_number);

  // ADC and analog comparator configuration
  ADMUX  = 0x03;
  ADCSRA = 0x87;
  ADCSRB = (0 << ACME);  // select AIN1 as comparator negative input
  ACSR   = 0x13;         // turn on analog comparator

}

// analog comparator ISR
ISR (ANALOG_COMP_vect)
{
  byte count = 0;
  for(byte i = 0; i < 50; i++) {
    if ( ACSR & 0x20 )
      count++;
  }

  if(count > 48)
    per++;
}

// main loop
void loop()
{
  bool dc_flag = 0; // DC voltage flag bit
  int32_t sum = 0;  // sum of all readings
  uint16_t n = 0;   // number of readings (samples)

  ACSR = (1 << ACI);   // clear analog comparator interrupt flag
  ACSR = (1 << ACIE);  // enable analog comparator interrupt

  uint32_t current_m = micros();  // save current millis
  byte current_per = per;         // save current period number
  while ( (current_per == per) && (micros() - current_m < Time_Out) ) ;

  if( micros() - current_m >= Time_Out ) {  // if there's time out event ==> voltage signal is DC
    dc_flag = 1;
    for (byte i = 0; i < 200; i++) {
      ADCSRA |= 1 << ADSC;   // start conversion
      while(ADCSRA & 0x40);  // wait for conversion complete
      int16_t an = (int16_t)(ADCL | (uint16_t)ADCH << 8) - 511;
      sum += an;
      n++;         // increment number of readings
      delay(1);
    }
  }

  else {   // here, voltage signal is AC
    current_m = micros();  // save current millis()
    per = 0;
    while ( (per < Periods) && (micros() - current_m < (uint32_t)Time_Out * Periods) ) {
      ADCSRA |= 1 << ADSC;   // start conversion
      while(ADCSRA & 0x40);  // wait for conversion complete
      int32_t an = (int16_t)(ADCL | (uint16_t)ADCH << 8) - 511;
      sum += sq(an);  // sq: square
      n++;            // increment number of readings
    }
  }

  ACSR = (0 << ACIE);  // disable analog comparator interrupt
  uint32_t total_time = micros() - current_m;  // used to claculate frequency

  // voltage calculation
  float v;
  if(dc_flag)   // if voltage signal is DC
    v = (4 * sum)/n;   // calculate Arduino analog channel DC voltage in milli-Volts

  else  // here voltage signal is AC
    v = 4 * sqrt(sum/n);   // calculate Arduino analog channel RMS voltage in milli-Volts

  // claculate actual (input) voltage in milli-Volts (apply voltage divider equation)
  v = v * (float)total_res/current_res;
  v /= 1000;  // get voltage in Volts

  uint16_t v_abs = abs(int16_t(v));
  if( (v_abs >= 10 && ch_number == 0) || (v_abs >= 100 && ch_number == 1) || (v_abs >= 250 && ch_number == 2) ) {
    ch_number++;
    ch_select(ch_number);
    delay(10);
    return;
  }

  if( (v_abs < 220 && ch_number == 3) || (v_abs < 80 && ch_number == 2) || (v_abs < 8 && ch_number == 1) ) {
    ch_number--;
    ch_select(ch_number);
    delay(10);
    return;
  }

  char _buffer[8];
  lcd.setCursor(0, 1);
  if( v < 0)
    lcd.print('-');
  else
    lcd.print(' ');
  if(v_abs < 10)
    sprintf( _buffer, "u.u", v_abs, abs((int16_t)(v * 100)) % 100 );
  else if( v_abs < 100)
    sprintf( _buffer, "u.u", v_abs, abs((int16_t)(v * 10)) % 10 );
  else
    sprintf( _buffer, "u ", v_abs );

  lcd.print(_buffer);
  if(dc_flag)
    lcd.print("VDC        ");
  else {
    lcd.print("VAC ");
    // calculate signal frequency in Hz
    uint32_t period_time = total_time/Periods;
    float freq = 1000000.0/period_time;
    sprintf( _buffer, "u.uHz", (uint16_t)freq % 100, (uint16_t)(freq * 100) % 100 );
    lcd.print(_buffer);
  }

  delay(500);    // wait half a second

}

void ch_select(byte n) {
  switch(n) {
    case 0:
      digitalWrite(CH0, HIGH);
      digitalWrite(CH1, LOW);
      digitalWrite(CH2, LOW);
      digitalWrite(CH3, LOW);
      break;
    case 1:
      digitalWrite(CH0, LOW);
      digitalWrite(CH1, HIGH);
      digitalWrite(CH2, LOW);
      digitalWrite(CH3, LOW);
      break;
    case 2:
      digitalWrite(CH0, LOW);
      digitalWrite(CH1, LOW);
      digitalWrite(CH2, HIGH);
      digitalWrite(CH3, LOW);
      break;
    case 3:
      digitalWrite(CH0, LOW);
      digitalWrite(CH1, LOW);
      digitalWrite(CH2, LOW);
      digitalWrite(CH3, HIGH);
  }
  current_res = res_table[n];
}

// end of code.

```

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

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

body:
The input to the ADC is selected by the four least-significant bits of
the “ADC Multiplexer Selection Register”, aka `ADMUX`. It is set to
analog input 3 by this line of code:

```c++
ADMUX  = 0x03;
```

Change this line to `ADMUX = 0;` and the ADC will read pin A0.


message:
How to fix serial communication problem between Arduino UNO and sim900A

I've connected the arduino UNO to the sim900a. But after checking the serial communication between the two I keep getting these output.

[![][1]][1]

Here is the connections and code that I used

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900A(2, 3);
    // Connect the SIM900A TX to Arduino pin 2 RX.
    // Connect the SIM900A RX to Arduino pin 3 TX.
    char c = ' ';
    void setup()
    {
     // start th serial communication with the host computer
     Serial.begin(9600);
     while (!Serial);
     Serial.println("Arduino with SIM900A is ready");
     // start communication with the SIM900A in 9600
     SIM900A.begin(9600);
     Serial.println("SIM900A started at 9600");
     delay(1000);
     Serial.println("Setup Complete! SIM900A is Ready!");
     }
     void loop()
     {
      // Keep reading from SIM900 and send to Arduino Serial Monitor
      if (SIM900A.available())
      { c = SIM900A.read();
        Serial.write(c);
       }
      // Keep reading from Arduino Serial Monitor and send to SIM900A
      if (Serial.available())
      { c = Serial.read();
       SIM900A.write(c);
      }
     }

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

How can I fix this?

  [1]: https://i.stack.imgur.com/Lqnqh.jpg
  [2]: https://i.stack.imgur.com/CrYn8.jpg

body:
You are using the wrong pins on the SIM900A to communicate with your Arduino.

That specific module has a MAX232 interface on it to convert TTL UART to RS232. That is not compatible with the Arduino unless you add another MAX232 to undo the conversion that the one on the board does.

Instead you need to use the other 3-pin header at the other end of the board.  It should ([according to this site](https://microcontrollerslab.com/sim900a-gsm-module-pinout-examples-applications-datasheet/)) be wired like this:

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

Of course you can use other pins than 0/1 on your Arduino, as long as you connect them to the right place on the SIM900A module as shown in that diagram.

Also note what I take to be a pair of jumpers bridging pins on the header you're currently connecting to (ring around them in the diagram).

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


message:
Read serial with header and end marker

I am trying to use [Topway display][1] for HMI lcd with Arduino. This display using RS232C protocol [at docs][2] it has a "Communication Packet Structure" like this.

[![enter image description here][3]][3]

**So my query should start with AA and end with CC 33 C3 3C**.  This sample reading code was taking [topway youtube channel][4].

    Serial.write(0xaa); // packet head
    Serial.write(0x3e); // VP_N16 read command
    Serial.write(0x00); // VP_N16 address
    Serial.write(0x08);
    Serial.write(0x00);
    Serial.write(0x00);
    Serial.write(0xcc); // packet tail
    Serial.write(0x33); // packet tail
    Serial.write(0xc3); // packet tail
    Serial.write(0x3c); // packet tail

3E is the command (for reading) code and this is the list of all commands. [docs over here][2]

[![enter image description here][5]][5]

The point is parsing of smart LCD's response at the original. They use [this code][4]: (at first comment)

         while (!Serial.available()) {}
         if (Serial.read()==0xaa) {                     // packet head
         packet_OK=1;
         while (!Serial.available()) {}
         if (Serial.read()==0x3e) {                   // packet command
          while (!Serial.available()) {}
          temp_h=Serial.read();                      // read back value high byte
          while (!Serial.available()) {}
          temp_l=Serial.read();                      // read back value low byte
          while (!Serial.available()) {}
          if (!(Serial.read()==0xcc)) {packet_OK=0;} // packet tail
          while (!Serial.available()) {}
          if (!(Serial.read()==0x33)) {packet_OK=0;} // packet tail
          while (!Serial.available()) {}
          if (!(Serial.read()==0xc3)) {packet_OK=0;} // packet tail
          while (!Serial.available()) {}
          if (!(Serial.read()==0x3c)) {packet_OK=0;} // packet tail
          }
          else
          {packet_OK=0;}
         }
         else
         {packet_OK=0;}

It looks nasty and cumbersome because I must write different method for each LCD display commands. **Is there any way to read all serial response them as a char array with starting marker "0xAA" and read until finishing marker "0xCC 0x33 0xC3 0x3C" and after that parse it?**

You can watch and check this code on [youtube][4]

  [1]: https://www.topwaydisplay.com/product/smart-lcd/smart-lcd-module-HMT070ATA-1C
  [2]: https://www.topwaydisplay.com/sites/default/files/2020-06/Topway-Smart-LCD-SGTools-Handbook.pdf
  [3]: https://i.stack.imgur.com/CF810.png
  [4]: https://www.youtube.com/watch?v=t7VGK24kyLE
  [5]: https://i.stack.imgur.com/y1WwH.png

body:
The short answer to your question is “yes, there is a way”. Multiple
ways actually. You could write a _blocking_ function, which follows more
or less the logic of the example you show, blocking while waiting for
each new byte. Or you could write a _non blocking_ function, which
always return _immediately_ and, either gives you the complete packet,
or tells you that no full packet has been received so far.

The non-blocking way may be a bit more complicated, but it is more
useful, because you program can do other stuff, and be responsive, while
waiting for a packet. Here is my take at it. It is based on a [finite
state machine][fsm]:

```c++
// Return whether the payload of this command is of string type.
bool command_payload_is_string(uint8_t command);

// Return the expected packet length for the provided command,
// excluding header and tail.
int packet_length(uint8_t command);

// Attempt to read a packet, but do not block.
// Return a pointer to a static buffer holding the packet,
// or nullptr if no complete packet was received this time.
uint8_t *read_packet() {
    const uint8_t expected_header = 0xaa;
    const uint8_t expected_tail[4] = {0xcc, 0x33, 0xc3, 0x3c};

    // Return immediately unless we have a byte to process.
    if (Serial.available() == 0) return nullptr;
    uint8_t data = Serial.read();

    static uint8_t buffer[BUFFER_SIZE];
    static int bytes_received, bytes_expected;
    static enum {
        EXPECTING_HEADER, EXPECTING_COMMAND,
        EXPECTING_STRING, EXPECTING_PAYLOAD, EXPECTING_TAIL
    } state = EXPECTING_HEADER;
    switch (state) {
        case EXPECTING_HEADER:
            if (data = expected_header)
                state = EXPECTING_COMMAND;
            break;
        case EXPECTING_COMMAND:
            buffer[0] = data;  // command byte
            bytes_received = 1;
            if (command_payload_is_string(data)) {
                state = EXPECTING_STRING;
                // bytes_expected is not relevant in this case.
            } else {
                state = EXPECTING_PAYLOAD;
                bytes_expected = packet_length(data);
            }
            break;
        case EXPECTING_STRING:
            if (data == '\0') {  // end of string
                buffer[bytes_received++] = '\0';
                state = EXPECTING_TAIL;
                bytes_expected = 4;
                bytes_received = 0;
            } else if (bytes_received < BUFFER_SIZE - 1) {
                buffer[bytes_received++] = data;
            } else {
                // Do nothing. As the string is too long
                // to fit in the buffer, this byte is discarded.
            }
            break;
        case EXPECTING_PAYLOAD:
            buffer[bytes_received++] = data;
            if (bytes_received >= bytes_expected) {
                state = EXPECTING_TAIL;
                bytes_expected = 4;
                bytes_received = 0;
            }
            break;
        case EXPECTING_TAIL:
            // If we don't get the expected tail,
            // give up and wait for a new header.
            if (data != expected_tail[bytes_received++]) {
                state = EXPECTING_HEADER;
                break;
            }
            // If the tail is all right, return the buffer
            // and get ready for the next packet.
            if (bytes_received >= bytes_expected) {
                state = EXPECTING_HEADER;
                return buffer;
            }
    }
    return nullptr;
}
```

It will be up to you to implement `packet_length()`. See jstola's
comment on why it is needed.

You would use `read_packet()` like this:

```c++
void loop() {
    uint8_t *packet = read_packet();
    if (packet)
        parse_and_handle(packet);

    // the rest of the program, never blocked by read_packet()...
}
```

**Edit**: According to your comment, some commands have a payload which
is a string of unknown length, but [seemingly NUL-terminated][nul]. I
edited the code, and added an extra `EXPECTING_STRING` state to handle
this special case. It is up to you to implement the boolean function
`command_payload_is_string()`.

[fsm]: https://majenko.co.uk/blog/finite-state-machine
[nul]: https://arduino.stackexchange.com/questions/85360/how-to-convert-a-string-to-hex-array


message:
Find OK or ERROR in serial string

I am trying to figure out how to capture the `OK` or the `ERROR` from a SIM800l.

I have tried
```
mySerial.println("AT");
while (mySerial.available() > 0 ) {
String str = mySerial.readString();
Serial.println(str);
     if (str.equals("OK")) {
        Serial.println("ok");
     } else {
        Serial.println("unknown");
     }
   }

```

But I always getting nothing back?

body:
You can use `.indexOf` to find characters in a String. It returns a `-1` if a match is not found. See https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

```c++
mySerial.println("AT");
String str;

while (mySerial.available() > 0 )
{
    str = mySerial.readString();
    Serial.println(str);

    if (str.indexOf("OK") != -1)
    {
  Serial.println("ok");
    } else if (str.indexOf("ERROR") != -1)
    {
  Serial.println("error!");
    } else {
  Serial.println("unknown");
    }
}
```


message:
Arduino Reset via Software (every day)

Dear Stack Exchanger's,

I want to reset my Arduino and system in every 24h for preventing frozen software and also other connectivity stuffs.

I wrote a program which connects a digital pin to reset pin of Arduino and I want to reset with that way.

For example my code :

```
unsigned long myTime; // Millis() function time value
int timeExpected = 5000; // I want to reset it in every 5 secs for testing.
const int RESET_PIN = 2; // Reset pin's connection

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN,OUTPUT);
}
void loop() {
  digitalWrite(LED_BUILTIN,HIGH);
    myTime = millis();
    Serial.println(myTime); // prints time since program started
     delay(1000);

   if(myTime % timeExpected == 0) {
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
     Serial.println("RESET");
    //digitalWrite(RESET_PIN, LOW);(I just test with LED_BUILTIN Low function)
    }

  }
```

I have tried the watchdog timer but I cannot do it for 24 hours.
If you have another solution for reset in 24h please tell me and send me the related article/book/link etc. I will check and implement into my code.

UPDATE:
I have done this but it does not reset at very 5s .
Code :
```
#include <avr/wdt.h>
unsigned long myTime;
int timeExpected = 5000;

void setup() {
  Serial.begin(9600);
Serial.println("Setup started :");
// make a delay before enable WDT
// this delay help to complete all initial tasks
delay(2000);
wdt_enable(WDTO_2S);
}

void loop() {
    myTime = millis();
    delay(1000);
    Serial.println(myTime); // prints time since program started
   if(myTime == timeExpected) {
     Serial.println("RESET");
    wdt_reset();
    }
```

body:
You can do an almost immediate full reset with watchdog by activating it 'on place'.
```
wdt_enable(WDTO_15MS); // resets the MCU after 15 milliseconds
while (true);
```

You can use millis() for timing the reset as any other timed function.


body:
You can use the watchdog timer, but you have to change the way you measure the elapsed time. Try this code:

    #include <avr/wdt.h>

    unsigned long myTime; // Millis() function time value
    unsigned long elapsedTime;
    unsigned long timeExpected = 5000; // I want to reset it in every 5 secs for testing.
    const int RESET_PIN = 2; // Reset pin's connection

    void setup() {
      Serial.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
      myTime = millis();
      Serial.println("INIT");
      wdt_enable(WDTO_2S); //Enable wdt every two seconds

    }
    void loop() {

      //************RESET HANDLER********************//
      elapsedTime = millis() - myTime;
      if (elapsedTime > timeExpected) {
        Serial.print("RESET");
        while (1); //Intentionally halt the program, so the watchdog performs the reset
      }
      //**********************************************
      //****************REST OF THE PROGRAM***********
      wdt_reset(); //Ensure one call to this function at least one time in two seconds or less
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println(elapsedTime); // prints time since program started
      delay(1000);
    }

Please note that if you have multiple delays in your program, you have to ensure the call to wdt_reset() in order to prevent unwanted resets.
Personally I try not to use delays and would recommend avoid delays as much as possible. You may check out [this tutorial][1] if you want to see how to avoid delays. If you achieve avoiding delays you can call wdt_reset() just one time at the begining of the loop.

  [1]: https://youtu.be/xcvXUCih30Y


message:
How to fade LED in a defined time using FastLED

I'm using FastLED library, Arduino Nano and 5 addressable LEDs (WS2812B).
I'd like to create the sequence in the image attached. (all in white color for example)

I know how to turn ON each LED every 0.2 sec and I know how to fade.
I don't know how to make sure each LED goes from 0% brightness to 100% in 0.4 sec + start fading in the next LED after 0.2 sec.

Here is a fading LED:

    void loop() {
   uint32_t cur_ms = millis();
  if (cur_ms - fade_ms > 200) {
   fade_ms = cur_ms;
   brightness += 5;
   leds[0] = CHSV(255, 0, brightness);
  }

 FastLED.show();
 // delay(10);
}

Can anyone help me figure it out?
[![enter image description here][1]][1]

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

body:
One of the SimpleTimer libraries such as [this one by Marcello Romani][1] (which I mention because I have used it; there are others). It creates a timers object that has 10 (in this case) software-based timers with a variety of operating modes (run once, run x times, run forever, e.g.).

The basic idea (for a 1-LED example) is that you write a function (known as a "callback" to step up the brightness of an LED by one step. Let's call it `stepUp()`.

You write another callback function to turn off the LED and start a timer that will call `stepUp()` at whatever interval you choose for as many times as it takes to reach 100%. Let's call this one `cycleLED()`.

In your `setup()`, you'll start another timer that will call `cycleLED()` as often as you want that process to run - every 1200 mSec in this case - and for as many times (or forever) as you choose.

In your loop() function, you'll need a call to your timer object's .run() function as often as possible - that is what makes the timers work, and it is the timers that will call your callback functions to make your LEDs behave as you want them to.

So far, we one fading-up LED, and I'd recommend you implement this much at first.

There are two ways to go from here. You can write the above pair of callbacks for each LED, but they will be nearly identical and why write maintain the same code, several times over? Or you can use another feature of the library - a pointer-to-void argument to the callback function - in which you can pass any value, such as an LED's number or address, so that one callback could operate on the specified LED.

If you go with first option, your `setup()` function will need to to start 5 timers, one for each `cycleLED()` function (which would need to have distinct names, of course), and those timers start-times will need to be staggered.

With the second option, you would write a third callback, `allCycles()` that sequences the starts of each `cycleLED()` in turn. In this case, your `setup()` function would only need to start a timer to repeatedly call `allCycles()`.

There's a lot there, if these are new concepts. If so, it will be a lot easier to experiment with the SimpleTimer library doing something trivial at first, like flashing (not fading) one LED, then several LEDs, until this way of coding timed events feels less foreign.

  [1]: https://github.com/marcelloromani/Arduino-SimpleTimer


message:
SMBus on ATTiny204

So I want to connect multiple LED Panels with dynamic addressing to a Master Controller.
Seems like SMBus should be able to do that, however I don't find any Library for the Arduino framework.
Does SMBus require Hardware implementation and if if works in Software is there a library for that and does it even work on the ATTiny?

body:
The AVR chips lack hardware support for bus arbitration when operating as a slave device in I2C, which would be required for it to work as SMBus with ARP.

You would have to write your own bit-banged driver to act as a slave whilst monitoring the SDA pin whenever it transmits to look for bus collisions.

A better solution would be to allocate each device a unique address using an address space of your choosing (to give you enough addresses for uniqueness) at build / programming time. A bus of some design (maybe RS485 would be a good choice for this) can then be scanned looking for, and cataloguing, what addresses are in use.


message:
NRF24 and Arduino Nano Every usage

Im building an RC car project and using 2 NRF24's for communication. I own an Arduino Uno, Nano and Nano Every. The NRF's work great with the Uno and Nano in any combinations but using a Nano Every either as TX or RX doesn't work.

I have tried the NRF24 and NRFLite and both say "Cannot communicate with radio".

When using the NRFLite library examples Basic_TX on the Uno/Nano and Basic_RX on the Nano Every, the Uno/Nano says transmission was successful even though the Every says "Cannot communicate with radio". This lasts about 1 second before the Uno/Nano says the transmission failed again. This happens every time you reset the Every. It is as if the NRF24 gets powered on but then is unable to communicate with the Every.

I am using power adapters for the NRF's and powering them through the 5v pin. No luck with capacitors either. Have swapped out all the wires and also double checked all connections.

Is there something wrong with the Nano Every? Does it work with a NRF24 for anyone?

I have completely ran out of ideas to fix this.
Thank you in advance

body:
I stucked with the same problem too when use nRF24L01+ and Arduino Nano Every to transmit data to Arduino Uno with nRF24L01+. So I have solved the problem as follows below. I hope it could help you and for somebody else.

1. First of all you should add Arduino megaAVR Boards in the boards manager.

1.1 It is first necessary to add the URL of their Boards Manager JSON file in: File > Preferences > Additional Boards Manager URLs and Paste the link: https://raw.githubusercontent.com/amperka/iskra-boards/master/package_amperka_index.json

1.2. Then go to Tools>Boards Manager, search Arduino SAMD Boards and install it

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

1.3. Choose Arduino Nano Every in Tools>Board>Arduino megaAVR Boards>Arduino Nano Every

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

2. Upload the library for RF24. It must be compatible for architecture megaavr because  Arduino Nano Every uses Microchip ATmega4809. I use the latest version RF24-1.4.1.
Here is the link to the library: <https://www.arduinolibraries.info/libraries/rf24>

3. You should check whether you connected nRF24L01+ and arduino correctly.

The pinout of Arduino Uno is as follows:
5V - VCC if you connect nRF24L01+ via nRF24L01+ adapter (I use adapter)
or 3.3V - VCC without adapter

GND - GND

9 pin - CE

10 pin - CSN

11 pin - MOSI

12 pin - MISO

13 pin - SCK

not connected - IRQ

However, I use another pinout for Arduino Nano Every. When I use the same pinout as Arduino Uno it can't find nRF24L01+. You can check it in Serial Monitor by using a sketch below. If you get zeros in the third line, for example, something like this: RX_ADDR_P0-1 = 0x0000000070 0x0000000000. It means that Arduino Nano Every isn't connected to nRF24L01+ correctly and Arduino Nano Every doesn't see it.
I suppose the problem with the library of RF24 and it should be fixed. Perhaps I'm wrong and the problem with another things.

So I use the following pinouts for Arduino Nano Every:
5V - VCC if you connect nRF24L01+ via nRF24L01+ adapter (I use adapter)
or 3.3V - VCC without adapter

GND - GND

10 pin - CE

A3 - CSN (if you will get zeros in the third line RX_ADDR_P0-1 in Serial Monitor then change A3 to another one. You can vary pin from A5 and so on until A0). do not use A7 and A6 because on some model dev boards, A6 and A7 are analog input only.

11 pin - MOSI

12 pin - MISO

13 pin - SCK

not connected - IRQ

The sketch for checking:
```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(10,A3);  // for arduino nano every
//RF24 radio(9,10); // for arduino uno

const uint8_t num_channels = 128;
uint8_t values[num_channels];
void setup(void)
{
  Serial.begin(9600);
  printf_begin();
  radio.begin();
  radio.setAutoAck(false);
  radio.startListening();

  radio.printDetails();
  delay(5000);

  radio.stopListening();
  int i = 0;
  while ( i < num_channels )  {
    printf("%x",i>>4);
    ++i;
  }
  printf("\n\r");
  i = 0;
  while ( i < num_channels ) {
    printf("%x",i&0xf);
    ++i;
  }
  printf("\n\r");
}
const int num_reps = 100;

void loop(void)
{
  memset(values,0,sizeof(values));
  int rep_counter = num_reps;
  while (rep_counter--) {
    int i = num_channels;
    while (i--) {
      radio.setChannel(i);
      radio.startListening();
      delayMicroseconds(128);
      radio.stopListening();
      if ( radio.testCarrier() )
        ++values[i];
    }
  }
  int i = 0;
  while ( i < num_channels ) {
    printf("%x",min(0xf,values[i]&0xf));
    ++i;
  }
  printf("\n\r");
}
int serial_putc( char c, FILE * ) {
  Serial.write( c );
  return c;
}

void printf_begin(void) {
  fdevopen( &serial_putc, 0 );
}
```

Here is the correct output in Serial Monitor
the third line without zeros: RX_ADDR_P0-1 = 0xf0f0f0f0d2 0xc2c2c2c2c2
```
SPI Speedz = 10 Mhz
STATUS  = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1 = 0xf0f0f0f0d2 0xc2c2c2c2c2
RX_ADDR_P2-5 = 0xc3 0xc4 0xc5 0xc6
TX_ADDR  = 0xf0f0f0f0d2
RX_PW_P0-6 = 0x20 0x20 0x20 0x20 0x20 0x20
EN_AA  = 0x00
EN_RXADDR = 0x02
RF_CH  = 0x00
RF_SETUP = 0x14
CONFIG  = 0x0f
DYNPD/FEATURE = 0x38 0x38
Data Rate = 1 MBPS
Model  = nRF24L01+
CRC Length = 16 bits
PA Power = PA_HIGH
ARC  = 15
```

the next two lines are a list of available channels that should be read from top to bottom (i.e. we have 127 channels, еру channels are presented in 16-bit version, the first line is the first digit of each of 127 channels, the second line is the second digit of each of 127 channels).
```
00000000000000001111111111111111222222222222222233333333333333334444444444444444555555555555555566666666666666667777777777777777

0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

```

then the level of noisiness of the channels is displayed.
There are noise from the channel 09 to the channel 3f approximately.
this noise from my wifi router and some another electronics.
you should choose free channels for your purpose.
```
00000010114663444533233300000000001000011233544433221100112223212010000000000000000000000000000000000000000000000000000000000000

00200000035575656777697332111321022125625559643632551111000333012000000000100000010001000000001000000000000011010000000000000000

00000001135a9a767767c89a85646565866555645897434644445200121212122000000000000000000000001000000000000000011000000010000000000000

00101000035567667357878a51123341220322335373542222122000112313112000000001010000000001000000020000000010000000000000100000000010

11000011047587577457694521122232111121243247542232210100002222111000000000100002000002000000000000000000000000000010000000000000
```

Note:
1. Check Tools. There should be:
Board:Arduino Nano Every;
Registers emulation: "ATMEGA328";
Port:COM#(Arduino Nano Every).

2. some transmission errors can occur due to poor contacts between wires and pins of arduino, so the wires should be soldered.

If everything is ok, then you can use your sketches for the receiver and transmitter respectively. Good luck!

  [1]: https://i.stack.imgur.com/Jqag3.png
  [2]: https://i.stack.imgur.com/nowU0.png


message:
Using index of to search for multiple characters

In my Arduino project, a string will be received. I understand using ```.indexof``` to find the placement of a certain character in the string. My problem is that I need to find the first occurrence of any letter A-Z and haven't found any resources regarding using ```or```  statements in an ```.indexof``` aka ```string.indexof("a" || "b" ....)```.

Is this something that is not possible using indexof functions and if so is there any function that I can use to solve this! Thanks!

body:
Here are two functions that I hope help in your endeavours. You can supply either a String or a char array and you should get the first position of an alpha character. Returns -1 if not present.

See https://www.arduino.cc/reference/en/language/functions/characters/isalpha/

Update:

Thanks to great comments from Edgar & Mat I have updated the functions with best practise and cost improvements.

```c++
int alphaPos(const char* str)
{
  for (int i = 0; str[i] !=0 ; ++i) {
    if (isAlpha(str[i]))
    {
      return i;
    }
  }

  return -1;
}

int alphaPos(const String& str)
{
  return alphaPos(str.c_str());
}

/*
    Usage:

    String bobble = "&&&88434a";
    int x = alphaPos(bobble);

    if (x != -1)
    {
      ...x has the position in the string
    }
    else
    {
     ...There is no alpha char present.
    }
*/
```


message:
How to reset ESP32 after a certain duration?

I would like to reset my ESP32 from the software, how do I do it and how to make it do this at regular intervals.

body:
Hope this helps.

```c++

uint32_t resetAfterMillis = 30000; // Reset after 30 seconds.
uint32_t lastResetWas;

void setup() {
   lastResetWas = millis();
}

void loop() {
  uint32_t now = millis();
  if (now >= lastResetWas + resetAfterMillis)
  {
      lastResetWas = now;

      // Whatever you want to do here
      ESP.restart();

  }

}
```


message:
MPU 6050 only reads 0 in output

I am new to using MPU 6050. I am stuck at a basic code of getting readings from the sensor. The code I used is attached below. Its the one with GY 521 breakout board. Concluding that my sensor is broken I have changed sensor and now using the third one. Still no luck. FYI I have run the i2c scanner code to check whether arduino(nano) can detect the sensor. The code responds to all the sensors I tried. I have no clue what I am doing wrong. If someone could provide some suggestions it would be helpful
```/*
    MPU6050 Triple Axis Gyroscope & Accelerometer. Simple Gyroscope Example.
    Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
    GIT: https://github.com/jarzebski/Arduino-MPU6050
    Web: http://www.jarzebski.pl
    (c) 2014 by Korneliusz Jarzebski
*/

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

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

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // If you want, you can set gyroscope offsets
  // mpu.setGyroOffsetX(155);
  // mpu.setGyroOffsetY(15);
  // mpu.setGyroOffsetZ(15);

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();

  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:     Serial.println("Stops the clock and keeps the timing generator in reset"); break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
    case MPU6050_CLOCK_PLL_ZGYRO:      Serial.println("PLL with Z axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_YGYRO:      Serial.println("PLL with Y axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_XGYRO:      Serial.println("PLL with X axis gyroscope reference"); break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:  Serial.println("Internal 8MHz oscillator"); break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:        Serial.println("2000 dps"); break;
    case MPU6050_SCALE_1000DPS:        Serial.println("1000 dps"); break;
    case MPU6050_SCALE_500DPS:         Serial.println("500 dps"); break;
    case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());

  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();

  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);

  delay(10);
}
```

body:
I hope it is useful for debugging ...

Only a sketch I found ([here][1]), not remembering if I have tested ...

```cpp
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}
```

There is also a [long example sketch][2] ...

  [1]: https://playground.arduino.cc/Main/MPU-6050/#short
  [2]: https://playground.arduino.cc/Main/MPU-6050/#sketch


body:
You do not tell us what is the problem so my guess is address or level.
If you get "Could not find a valid MPU6050 sensor, check wiring!" this is an address problem. By default MP6050 uses x068 as I2C address. If you have something else connected to the bus, there might be a conflict. If so, connect AD0 to 3.3V (pull-up with a 2.2kOhms resistor) to set address to 0x69 (use I2C scanner in /example/wire to make sure).
If you see zeros, this might be a logic level problem:
To elaborate on the previous answer, the MP6050 is a 3.3V device. The GY 521 circuit has a voltage regulator (5V->3.3V) bUt on output it still uses 3.3V TTL logic level. With some noise, bad contacts or long wires, the Arduino may fail to read the I2C properly. Had similar problems, solved using a bidirectional logic level shifter between a Uno and the MPU6050. You can get pre-assembled 4-channels board (same size as GY521 board) for ~ 1US$. I hope this helps


message:
Arduino Pull-Down Resistors

I'm building what I thought was a simple Arduino Nano project... right up until it caught fire!

I am a long-time reader of stack exchange and I always find the answers to my questions somewhere on Google, but this seems to be a bit of a head scratcher.

The project is a 4 pin 7 segment LED screen with a timer that counts when Analog pin 0 receives a voltage signal of ~2.5-5v.

Testing the project worked as expected, but when I soldered everything together, I was getting static or white noise from the Analog pin with no voltage being supplied.

I figured I needed a Pull-Down resistor to keep the Analog pin grounded until it received a voltage signal to get rid of any interference.

I connected a 220ohm resistor DIRECTLY from GND and DIRECTLY to Analog Pin 0 and connected the voltage signal wire to Pin 0 as well.

When I actually tested the hardware while connected to the car battery, that's when it shorted out and caused a mini fire.

I was able to read the voltage with my multimeter before the chip burnt out, I was reading ~15.5v total. I'm guessing it's the car battery plus the input voltage on Pin 0.

I only do clean and precise soldering, so there were no unaccounted for connections.

I'm unsure if the issue was too many volts running through the Nano altogether or because I don't really understand how the Pull-Down resistor works and messed that up.

Please help me understand what the issue is and what I can do for a solution.

Thank you.

[![Schematic][1]][1]

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

body: You violated the voltage input specification of A0 by a lot. What happened is what I would expect. The input protection diode on A0 conducted the battery voltage (- the protection diode drop) into the VCC of the Nano, this overvoltage fried just about all semiconductors and possibly several of the passive components on the board. It sounds like they do what they do when abused and they let the smoke out destroying the Nano and possible several other components. Hopefully this explains what happened. If you had connected the resistor between A0 and the battery it might have survived.


body:
**Input power**

Car power systems operate between 13 and 15 volts when the car is running. Might be too high for the voltage regulator on the Nano. Mine is a AMS1117 which goes up to 15v. Sounds like that's what fried based on your description. Some fail closed circuit, so may have exposed the ATMega to 14v. There's some alternative voltage regulators with the same footprint that will go up to 20v or more input, look for one of those. SOT-223 footprint.

**Button**

The Nano/ATMegs has internal pullups. I'd use those; connect the one side of your button to ground rather than 5v, and the other to the Nano digital input. In your code, activate on LOW rather than HIGH. Then you can skip your external pullup.

**Pullups**

220 ohms is a very strong pulldown for the 5v signal. It will be seeing .11 watts of power dissipation. Use something higher like 10K or 100K. Put a 1K resistor on the 5v signal to limit it's current. You're Arduino is only sensing the voltage, so with a 10K to GND and 1K from 5v signal, the resistor divider will signal 4.5v, plenty for your Nano to detect "HIGH".


message:
How to convert a String to Hex array

I am trying use a HMI display. If I want to send a data, for example I want to write "TOPWAY" to 0x00000080 address it should like that:

        Serial.write(0xaa); // packet head
        Serial.write(0x42); // VP_N16 string write command
        Serial.write(0x00); // VP_N16 address
        Serial.write(0x00);
        Serial.write(0x00);
        Serial.write(0x80);
        Serial.write(0x54); //T
        Serial.write(0x4f); //O
        Serial.write(0x50); //P
        Serial.write(0x57); //W
        Serial.write(0x41); //A
        Serial.write(0x59); //Y
        Serial.write(0x00); //string end with "\0"
        Serial.write(0xcc); // packet tail
        Serial.write(0x33); // packet tail
        Serial.write(0xc3); // packet tail
        Serial.write(0x3c); // packet tail

I want to make a method like SendString(String abc) to send that like above. I need convert string a hex array and call in Serial.write(array[i]). Can you hep me?

body:
I don't know anything about the particular display, but based on the information provided I hope this is at least shows the foundation of one way you could approach a final solution.

**Update:**
* Incorporated great improvements and a fix from Edgar in the comments.
* String overload.
* Display baud rate suggested by mehmet

```c++
#define DISPLAY_DEVICE Serial
#define DISPLAY_DEVICE_BAUD 9600

static uint8_t displayPktStart[] = {
    0xaa, // packet headchar
    0x42, // VP_N16 string write command
    0x00, // VP_N16 address
    0x00, // ...Fill
    0x00,
    0x80
  };

static uint8_t displayPktEnd[] = {
    0x00, // End of text
    0xcc, // packet tail
    0x33, // packet tail
    0xc3, // packet tail
    0x3c // packet tail
  };

void writeDisplay(const char* text)
{
  // Write packet headers
  DISPLAY_DEVICE.write(displayPktStart, sizeof displayPktStart);

  // Send text
  DISPLAY_DEVICE.print(text);

  // Write packet tail
  DISPLAY_DEVICE.write(displayPktEnd, sizeof displayPktEnd);
}

void writeDisplay(const String& text)
{
  writeDisplay(text.c_str());
}

void setup()
{
  DISPLAY_DEVICE.begin(DISPLAY_DEVICE_BAUD);
}

void loop()
{
  String msg = "TOPWAY";
  writeDisplay(msg);

  delay(2000);
  writeDisplay("Peanuts taste like chicken");
  delay(500);
  writeDisplay("");
  delay(1000);
  writeDisplay("No. Seriously");
  delay(2000);
}

```


message:
How to Burn Bootloader with custom Fuses

I have a Atmega328p IC without external Crystal (My target).

When I use a arduino to burn the bootloader to my target, the Arduino as ISP sketch changes the fuses of my target, so it tries to use its external crystal, which is not connected, So it cannot proceed the bootloader burn.

[![external crystal][1]][1]

How can I modify the Fuse settings while Burning bootloader with arduino?

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

body:
You need to either adjust the current board fuse settings in `boards.txt` or create a new board variant that matches your settings.

For example the Uno is set up with:

```
uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0xFD
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex
```


body:
You can use [MiniCore][1] boards support package for Arduino IDE to work with nonstandard AVR boards or breadboard setups. This core has many settings in Tools menu to set different parameters of the board.

  [1]: https://github.com/MCUdude/MiniCore


message:
L298N motor controller board EN pins

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

  [1]: https://i.stack.imgur.com/WPIzj.png
For this device are the enable pins meant to be connected to PWM pins?
If so then how am I able to use this device with an arduino uno?
The uno does not have any pwm pins right?

body:
The uno pins are 3, 5, 6, 9, 10, 11.

See https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

Usage:
```c++
analogWrite(pin, value);
```


body:
The people over at [How to Mechatronics][1] have a great introduction to this board and using it with an Arduino Uno.

The enable pins are for turning the motors on and off. See the table for the different settings. [![Enable pin truth table][2]][2] But the EN pin is also used for controlling the motor speed.

PWM is used to adjust the speed the motors turn at. Rather than simply turning the enable pin fully “on” (i.e, full speed), PWM is used to adjust the voltage and thereby control the speed the motors turn.

So the short answer is yes, you can connect a PWM signal to the EN pins.  Yes a UNO can produce PWM (as answered by others)

  [1]: https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
  [2]: https://i.stack.imgur.com/7WDf3.jpg


message:
L298 motor controller board

[![enter image description here][1]][1]
Hello I have 2 questions:
A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.
B) What is the purpose of the black plastic casing that I have pointed out?

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

body:
> A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.

Those aren't "casings", those are diodes. They are part of the circuit and must be left alone.

> B) What is the purpose of the black plastic casing that I have pointed out?

That is a "jumper" and is used to connect the +5V pin to the internal 5V regulator so the board can be run from just the 12V input power supply. Remove that if, and only if, you want to supply 5V to the board separately from elsewhere.


message:
AW9523B I2C on Arduino Nano

I'm testing the AW9523B IO expander with an Arduino Nano. I can't get the device to be recognized.

Using I2C scanner to find all attached I2C devices.

I've connected AW9523B to the correct pins to the SDA/SCL pints of the Arduino, with 5K pullups. INTN is connected to GND.

An EEPROM is also connected on the bus. The EEPROM is recognized on the bus. I swapped the SDA/SCL pins just to make sure, and still AW9523B was not found on bus.

I've tried changing the AD0 and AD1 pins to no avail.

I have a 22uf capacitor on the VCC.

Changing the AD0 pin does change the default state of a connected LED, so I'm fairly confident the chip is not dead.

I've also tried the two example sketches from:

> https://github.com/mrmx/AW9523B

Curious if anyone has gotten their AW9523B to work.

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

**Updated Working Schematic**
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/AEPAM.png
  [2]: https://i.stack.imgur.com/s99xR.jpg

body:
Transcribing and adding to the answer from the comments.

The [AW9523B][1] has a reset (RSTN) pin 23 which is internally pulled low by a 100K ohm resistor (i.e., default = reset). @Majenko suggests attaching a pull-up 10K ohm resistor to +5V (i.e., not reset) to enable the chip.

The data sheet schematics and section describing the reset function (pg14) seem to anticipate the RSTN pin being connected to an MCU GPO pin used to dynamically control the reset function.

  [1]: https://cdn-shop.adafruit.com/product-files/4886/AW9523+English+Datasheet.pdf


message:
Programming ATTiny1614; Unexpected Signature

Trying to program an ATTTYIN1614 with jtag2updi.

    https://github.com/ElTangas/jtag2updi

I was able to use this tool to program an ATTINY1626-XFR and ATTINY807-MNR, but I'm getting an error with ATTINY1614-SSFR.

    avrdude: Expected signature for ATtiny1614 is 1E 94 22
             Double check chip, or use -F to override this check.

body:
I had the wrong ATTiny1614 selected. Needed to select the non-optiboot option.

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

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


message:
How do you get 2 PWM pins to inversely bitbang at 25 KHz on a Nano?

I need 2 PWM pins to oscillate at 25 KHz but they need to oscillate inverse to each other.  When one is high, the other must be low and vise-versa.

I want to do this with a Nano.

body:
There are various solutions. I suggest using two PWM channels driven by
a single timer. This way you do not have to worry about synchronizing
two timers. You can configure the channels identically, except that one
of them would be in “non-inverting” PWM mode, while the other one would
be in “inverting” mode.

Here is how I would do it: use Timer 1 to drive pins 9 (PB1, OC1A) and
10 (PB2, OC1B) in fast PWM.

```c++
void setup() {
    // Configure Timer 1 for complementary PWM @ 25 kHz.
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    DDRB  |= _BV(PB2);    // set pin 10 = PB2 = OC1B as output
    TCCR1A = 0;           // undo the Arduino timer initialization
    TCCR1B = 0;           // ditto
    ICR1   = 640 - 1;     // period = 640 CPU cycles = 40 us
    OCR1A  = 320 - 1;     // OC1A HIGH for 320 CPU cycles = 20 us
    OCR1B  = 320 - 1;     // OC1B LOW for 320 CPU cycles = 20 us
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock at F_CPU
}
```


message:
Using the touchscreen.getpoint causes program to instantly crash

this code runs fine until I add in the if statement surrounding the draw screen() method. upon clicking the screen, the program instantly crashes, turning the screen white. any help would be appreciated.

    "
    // IMPORTANT: Adafruit_TFTLCD LIBRARY MUST BE SPECIFICALLY
    // CONFIGURED FOR EITHER THE TFT SHIELD OR THE BREAKOUT BOARD.
    // SEE RELEVANT COMMENTS IN Adafruit_TFTLCD.h FOR SETUP.

    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_TFTLCD.h> // Hardware-specific library

    #include <stdint.h>
    #include "TouchScreen.h"
    #define YP A2  // must be an analog pin, use "An" notation!
    #define XM A3  // must be an analog pin, use "An" notation!
    #define YM 8   // can be a digital pin
    #define XP 9   // can be a digital pin

    // The control pins for the LCD can be assigned to any digital or
    // analog pins...but we'll use the analog pins as this allows us to
    // double up the pins with the touch screen (see the TFT paint example).
    #define LCD_CS A3 // Chip Select goes to Analog 3
    #define LCD_CD A2 // Command/Data goes to Analog 2
    #define LCD_WR A1 // LCD Write goes to Analog 1
    #define LCD_RD A0 // LCD Read goes to Analog 0

    #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin

    // When using the BREAKOUT BOARD only, use these 8 data lines to the LCD:
    // For the Arduino Uno, Duemilanove, Diecimila, etc.:
    //   D0 connects to digital pin 8  (Notice these are
    //   D1 connects to digital pin 9   NOT in order!)
    //   D2 connects to digital pin 2
    //   D3 connects to digital pin 3
    //   D4 connects to digital pin 4
    //   D5 connects to digital pin 5
    //   D6 connects to digital pin 6
    //   D7 connects to digital pin 7
    // For the Arduino Mega, use digital pins 22 through 29
    // (on the 2-row header at the end of the board).

    // Assign human-readable names to some common 16-bit color values:
    #define  BLACK   0x0000
    #define BLUE    0x001F
    #define RED     0xF800
    #define GREEN   0x07E0
    #define CYAN    0x07FF
    #define MAGENTA 0xF81F
    #define YELLOW  0xFFE0
    #define WHITE   0xFFFF

    Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
    // If using the shield, all control and data lines are fixed, and
    // a simpler declaration can optionally be used:
    // Adafruit_TFTLCD tft;
    int six;
    int hundred;
    int twenty;
    int ten;
    int four;
    int eight;
    int two;
    int twelve;
    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
    void setup()
    {
      Serial.begin(9600);
      Serial.println(F("TFT LCD test"));
      tft.reset();
      uint16_t identifier = tft.readID();

      tft.begin(identifier);
      tft.fillScreen(BLACK);

      six = random(1, 6);
      eight = random(1, 8);
      twenty = random(1, 20);
      hundred = random(1, 100);
      four = random(1, 4);
      ten = random(1, 10);
      two = random(1, 2);
      twelve = random(1, 12);

      tft.setTextColor(WHITE);  tft.setTextSize(4);
      drawNumbers();

    }

    void loop() {

      six = random(1, 6);
      eight = random(1, 8);
      twenty = random(1, 20);
      hundred = random(1, 100);
      four = random(1, 4);
      ten = random(1, 10);
      two = random(1, 2);
      twelve = random(1, 12);
      if (ts.getPoint().z != 0) {
        drawNumbers();
      }

    }

    void drawNumbers() {
      tft.setCursor(0, 0);
      tft.fillScreen(BLACK);
      tft.println("D2: " + String(two));
      tft.println("D4: " + String(four));
      tft.println("D6: " + String(six));
      tft.println("D8: " + String(eight));
      tft.println("D10: " + String(ten));
      tft.println("D12: " + String(twelve));
      tft.println("D20: " + String(twenty));
      tft.println("D100: " + String(hundred));

    }"

this library seems largely ill documented, but this seems egreigous if its not on my end.

body:
**Updated:**
* Provided info not revelant.

I would approach the problem like this. What if anything is returned by getPoint.

```c++
  if (ts.getPoint().z != 0) {
    drawNumbers();
  }
```
To
```c++
  auto pt = ts.getPoint().z;
  Serial.print("Point: ");
  Serial.println(pt);

  if (pt != 0) {
    drawNumbers();
  }
```

This would tell me if I am getting a value back or if it is a problem elsewhere.

Hope this helps.


body:
Figured it out

the TFT screen im using forces the sharing of pins being used for analog and digital together. By starting my draw method with pinMode() i set the pins to be treated as the touchscreen's

    void drawNumbers() {
        pinMode (XM, OUTPUT);
      pinMode (YP, OUTPUT);
      tft.setCursor(0, 0);
      tft.fillScreen(BLACK);
      tft.println("D2: " + String(two));
      tft.println("D4: " + String(four));
      tft.println("D6: " + String(six));
      tft.println("D8: " + String(eight));
      tft.println("D10: " + String(ten));
      tft.println("D12: " + String(twelve));
      tft.println("D20: " + String(twenty));
      tft.println("D100: " + String(hundred));

    }


message:
NodeMCU ESP32 as a replacement for my arduino project

I would just like to ask if this microcontroller can power or can manage 2 servos, 2 motors, and 2 hc-sr04 ultrasonic distance sensor combined? Also, does this board come with a bluetooth module?

body:
The ESP32 has more than enough free GPIOs to manage those peripherals. Also, the ESP32 does indeed come with a bluetooth module.

Your question about powering these peripherals very much depends on their power requirements. I would not count on being able to run motors or servos from the internal power supply of a NodeMCU board, so you would need an external supply.

Also, note that the ESP32 is a 3.3V device and might require logic level translation if you’re using 5V peripherals.


message:
MC33926 Brushed Motor Driver (Shield/Carrier)

How can I use a MC33926 Motor Driver like it is offered for Arduino to drive forwards, backwards with a PWM and a direction control.

**The problem is that the MC33926 has Inputs IN1 and IN2 and not PWM and DIR as usual. How can IN1 and IN2 be directly used with a Arduino. Such as it is done in the ArduMower project.**

I'm also wondering under which conditions this is controller is energy efficient? If the load has a flywheel effect (e.g. high RPM mower disk) reducing RPM would waste energy?

I know there are different shields that have logic to drive the inputs with PWM and DIR, but the ArduMower PCB 1.4 decided to hook it up directly. Here is a hardware solution by pololu (I wish i would understand these two NAND gates and the Q2, but that's another problem):

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

https://www.pololu.com/product/1213/pictures

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

body:
I have figured this so far:

 - If the PWM frequency is too low, the load-free power consumption (100% PWM 200mA) of the
   motors increases(!) rapidly when driving slowly, e.g. 33% to 1A.
 - From a certain PWM frequency (>2kHz), the power consumption normalizes and driving more slowly requires less power.
 - MC33936 has IN1 and IN2, which are normally connected with IN1 = LOW and
   IN2 = PWM or IN1 = PWM and IN2 = LOW (not good for most MCs)
 - Alternatively you can use IN1 = PWM and IN2 = LOW / HIGH **BUT you must INVERT the PWM SIGNAL when running reverse**, i.e. IN1 = PWM and IN2 = LOW or reverse IN1 = ~PWM (inverted PWM) and IN2 = HIGH. Otherwise you start driving at 0 PWM with 100% motor power. This is quite tricky, too.
 - MC33936 has no freewheel (except if ENABLE = LOW) and brakes the
   motor to 0 when IN1 = IN2
 - MC33936 is a braking motor controller that actively sets the output RPM.
   of the motor according to PWM.


message:
Printing the array using print and serial write function in Arduino Uno

I have, one program with only using printing array and other with serial write and print function for the array, while using serial write and print function I get these extra characters between the data as shown below, can anyone help me with this

Printing the array with print function

```c++
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    //Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}
```

[![Using Print Function][1]][1]

Using with serial write and print function for array

```c++
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}
```

[![Using Serial write and Print function for array][2]][2]

  [1]: https://i.stack.imgur.com/VFLIa.png
  [2]: https://i.stack.imgur.com/HUDLP.png

body:
To store a 2 character string you need a 3 byte array, not a 2 byte array. This is because in C a string consists of the actual string data *and* a zero ("NULL") byte at the end to indicate where the end of the string is.

So you would need:

    char Hex_Array[3];

so it can store, for the number 0x69: `69\0`. Otherwise you overrun the array and corrupt other data that follows in the stack, and changing that other data corrupts your string by changing the "end of string" marker to some other random ASCII character.


body:
`Serial.write(some_byte)` writes a byte on the serial output. The
Arduino serial monitor tries to interpret the bytes it receives as text:

- `0x11` is a control character, displayed as “□”
- `0x22` is the ASCII code for the double quote (")
- `0x33` is the ASCII code for the digit 3.
- `0x44` is the ASCII code for the uppercase letter “D”
- etc.


message:
Nikon IR remote trigger (ML-L3) emulator not working

I have tried to follow along/reproduce the results from several sources for emulating the Nikon infrared remote trigger:

 - [Adafruit Guide](https://learn.adafruit.com/ir-sensor/overview)
 - [DIY Nikon ML-L3 IR Wireless Remote Hack with Arduino UNO](https://youtu.be/lk3DIUwNq2Q)
 - [Teardown and Project: Clone Nikon ML-L3 IR Remote and Emulation](https://goughlui.com/2013/12/06/teardown-and-project-clone-nikon-ml-l3-ir-remote-and-emulation/)
 - [Teach you how to DIY Nikon ML-L3 infrared remote control](https://www.programmersought.com/article/56665017649/) *did not read yet*
 - [Arduino wireless remote for Nikon DSLR](https://youtu.be/198oRcCQdP8)
 - [Arduino Nikon Infrared command code](https://www.christidis.info/index.php/personal-projects/arduino-nikon-infrared-command-code)
 - [Arduino – IR remote/ intervalometer for Nikon D80 DSLR](https://duino4projects.com/arduino-ir-remote-intervalometer-nikon-d80-dslr/)

I can read the signal from my remote trigger, but I cannot reproduce it with my Arduino setup. The signal I can receive (w/ TSOP38238 receiver diode) matches all of the signals given by the links above (there is some expected variance in pulse durations).

**I don't think my hardware is at fault:**

 - TSOP38238 receives @ 950 nm
 - my [IR LED](https://www.robotshop.com/media/files/pdf/datasheet-com-09349.pdf) is 940-950 nm per datasheet
 - my IR LED works (I can see it emitting when I point it at my phone camera)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/xF00k.png)

<!-- End schematic -->

**My Code:**

I have tried the code given in the links above, most don't use [Port Manipulation](https://www.arduino.cc/en/Reference/PortManipulation) and instead trial-and-error the delay durations to account for the overhead in Arduino functions. I have experimented with different values of the ```wait``` variable (8-13 microseconds) but have not gotten it working so far. I prefer to have my code versatile like this (no hard coded durations) so I can use it with other remotes in the future.

```
uint16_t Signal[] = [2050, 27800, 430, 1650, 430, 3650, 430, 65000]; // ON & OFF pulse durations (microseconds)
uint8_t wait = 13; // duration (microseconds) between pin state changes

// the setup function runs once when you press reset or power the board
void setup() {
    DDRB = B00000001; // set digital pin 8 to output
    PORTB = B00000000; // set digital pin 8 LOW
    Serial.begin(9600); // start serial monitor
}

// the loop function runs over and over again forever
void loop() {
    delay(1500); // wait a bit between sending signal
    sendSignal();
    sendSignal();
    // send signal twice, this is what the actual remote does
    Serial.println("Signal sent"); // message saying signal was sent
}

// function that sends the signal
void sendSignal(void) {
    for (int i = 0; i < sizeof(Signal)/sizeof(Signal[0]); i++) { // for each element in Signal array
        if (i%2 > 0) { // odd numbered index, is an OFF pulse
            PORTB = B00000000; // set digital pin 8 LOW
            delayMicroseconds(Signal[i]); // delay for OFF pulse duration
        } else { // even numbered index (including i=0), is an ON pulse, 38 kHz (26.3 usec period), 50% duty cycle
            unsigned long currentTime = micros(); // get current time
            while (micros() - currentTime < (unsigned long)Signal[i]) { // while still in ON pulse duration
                PORTB = B00000001; // set digital pin 8 HIGH
                delayMicroseconds(wait); // leave ON for time
                PORTB = B00000000; // set digital pin 8 LOW
                delayMicroseconds(wait); // leave OFF for time
            }
        }
    }
}
```

I hold my camera in direct line of sight of the LED (not blocking the receiver on the camera) from distances of ~2in to ~3ft away without success.

Has anyone tried this before? Is there a mistake in my approach or code?

body:
Got it working. The problems were the ```delayMicroseconds``` input being too large (see comments) and the frequency mismatches.

I set up a script to time the code segments of interest and that allowed me to select the best wait duration. It looks like this:

```
while (i < 256) {
    /* your code to time here */
    i++;
}
i = 0;
unsigned long time = 10000000 + micros();
Serial.println(time);
```
Make sure to time the empty loop and subtract that from your readings w/ code. Take the difference between ```time``` read outs, subtract the printing statement overhead (which is dependent on how many digits it is printing, hence the ```10000000 + micros()``` to keep # of digits constant) and divide by 256.

I measured 4 different combinations to find the closest frequency match:

Command Type:|Wait duration (micro seconds):|Frequency (Hz):|% difference from 38 kHz
|:-:|:-:|:-:|:-:|
Port Manipulation|14|36990|-2.7 %
Port Manipulation|13|39960|5.2 %
digitalWrite|11|35980|-5.3 %
|**digitalWrite**|**10**|**38790**|**2.1 %**|

The final code ended up looking a lot like the one from [this link](https://www.christidis.info/index.php/personal-projects/arduino-nikon-infrared-command-code); counting off cycles of the on-off 38 kHz pulse.


message:
Error using `NtpClientLib.h`

Since Core of ESP8266 upgraded to v.3.0 (now it is 3.0.2), I encounter errors using this library.

First, the deprecation of `byte` to `uint8` (hoped that an upgrade of NTP lib to 3.0.2 beta will solve it ), but now even using library's built in example file fails, show the same message regarding `byte` error.

Is there a workaround ?

    In file included from /home/guy/Documents/git/Arduino/libraries/NtpClientLib/examples/NTPClientESP8266/NTPClientESP8266.ino:38:
    /home/guy/Documents/git/Arduino/libraries/NtpClientLib/src/NtpClientLib.h:501:32: error: reference to 'byte' is ambiguous
      501 |     bool summertime (int year, byte month, byte day, byte hour, byte weekday, byte tzHours);
          |                                ^~~~
    In file included from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/cmath:42,
                     from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/math.h:36,
                     from /home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/cores/esp8266/Arduino.h:34,
                     from sketch/NTPClientESP8266.ino.cpp:1:

EDIT 1 :: VERSIONS

[![pic1][1]][1]
[![pic2][2]][2]
[![IDE+Sketch file][3]][3]

  [1]: https://i.stack.imgur.com/05pVB.png
  [2]: https://i.stack.imgur.com/oXfH5.png
  [3]: https://i.stack.imgur.com/MrZ01.png

body:
The esp8266 Arduino 3 has breaking changes so library authors need to adjust their libraries to this changes. Check the repository of the library for the fixes.

The NtpClient library was marked as deprecated by the author. The reason was that there is a better way to work with NTP on ESP. Now the library was 'restarted' as an alternative to SDK functions because the author solved microseconds accuracy.

If you don't need microseconds accuracy, you don't need to use Arduino NtpClient library on esp8266 or esp32. The Espressif SDK have support to get the NTP time to internal RTC.

Both ESP Arduino cores have examples for NTP. For esp8266 it is the esp8266/NTP-TZ-DST example.

The NTP part should be in setup()
```
configTime(TIME_ZONE, "pool.ntp.org");
```
TIME_ZONE should be value from `TZ_` constants from `TZ.h`, for example I have
```
#include <TZ.h>
#define TIME_ZONE TZ_Europe_Bratislava
```

The SDK will keep the time with the internal RTC of the ESP and adjust it periodically from NTP server.

You can get the esp8266 RTC time time with
```
time_t t = time(nullptr); // epoch
struct tm *tm = localtime(&t);
uint8_t minute = tm->tm_min;
uint8_t hour = tm->tm_hour;
```

if you want to wait in setup() until the time is retrieved you can use
```
  time_t now = time(nullptr);
  while (now < SECS_YR_2000) {
    delay(100);
    now = time(nullptr);
  }
```


message:
What is the correct way to externally power a MKR 1010 WiFi

I'm a little confused by the powering arrangements of the MKR 1010 WiFi. I need to power it on a breadboard from an external power supply. I will not be using a LiPo battery and I need it to work when the USB is disconnected.

Assuming there is no battery or USB connected, I think I need to apply power on the `Vin` pin (the pinout diagram on `arduino.cc` shows this as an input pin and `5V` as an output pin). However, the `5V` pin has a resettable fuse inline whereas `Vin` does not, which to me is counterintuitive.

So my questions are twofold:

1. What is the correct pin for supplying external power, and
2. What is the correct voltage to apply

body:
> What is the correct pin for supplying external power, and

VIN

> What is the correct voltage to apply

The bq24195 can accept between 3.9V and 17V according to the datasheet. However the power LED on the board may blow if you apply more than about 12v since it only has a 330Ω resistor with it.

----

The polyfuse on 5V is there to protect the USB's power connection incase the user makes a mistake and short circuits it. It's more for the protection of your computer's USB port than the MKR board itself.


message:
Arduino voltage misunderstanding

For arduino nano.
I set digital pins 1,2,3,4,5 to HIGH (I do this using digitalWrite(pin,HIGH) for each pin). Does this mean that 5V is being sent through each of the pins so in total there is 25V going out from the arduino?
How is this possible?

body:
Every pin gives you 5V on HIGH, yes, but these voltages don't add up.

Voltages are always measured between two points. In electronics we are defining one point in our circuit, that we use for all measurements, and call it ground. This is normally the negative pin of the power source.

Each pin has 5V in reference to the same ground, so they cannot add up (because that would mean the second 5V would be in reference to the 5V of the other pin, not in reference to ground). In the end they are connected in parallel to Vcc (where the power for the microcontroller is connected, in this case the 5V pin) of the Arduino (through the output drivers of the respective pin).

In the end this boils down to kirchoff's laws (if you want to research more about it). At a junction of connections, the voltage stays the same, but the current will be divided up between the connections.


body:
Imagine that I have 5 flagpoles. I go to each of those flagpoles and raise a flag to a height of 2 meters. Since I have 5 flags, each at a height of 2 meters, does that mean that my flags have a total height of 10 meters?

Well, that question doesn't make a whole lot of sense, because "total height of the flags" isn't really a meaningful quantity. It's true that if you add up all the heights, you get 10 meters, but that number doesn't have any real meaning. Nothing in the system is 10 meters high.

Likewise, suppose you set 5 output pins all HIGH. Those output pins are just like flags on flagpoles, and you're raising each pin to a "height" of 5 volts. Nothing in the system is at a voltage of 25 volts; it doesn't make any sense to talk about a "total voltage."


body:
It's a fascinating question. The Nano has 22 pins, all potentially set to output. D0 to D13, and A0 to A7.

So we have a total of 22 outputs. Now if they **did** add up then we could connect up a 5V battery and get 110V out of it! That might kill you! So clearly something is amiss here.

It's like when an employee has "20 years experience". Do they really have 20 times the experience they had in the first year, or do they have the same experience 20 times over?

The fact is that all 22 pins are all referenced to the same ground pin, so we really have 22 x 5V but all from the same starting point. So we really have 5V but with maybe a bit more current.

If you look at the datasheet, you don't even have 22 x the current you might have from one pin. The Atmega328P is specified to have a total of 200 mA current output.

Don't worry, setting all pins to output won't kill you. :)


message:
Arduino ESPTelnet.h library read data from cmd screen

I am new to Arduino. I used Arduino IDE for upload code to ESP8266 module. I wrote an ATM application on the tiva-tm4c123 board. I am trying to connect to the application from the internet using telnet and ip address. I uploaded the example code of the ESPtelnet library to the ESP8266 module and connected the esp wifi module to the tm4c123 card by using uart. The ESP8266 module sends the data from the tiva card to the putty screen that I connect via telnet. But it does not transfer what I write from the putty screen to the tiva card. I couldn't find a function like telnet.read(). Is there a telnet function that will read the data from the Putty screen? I searched a lot but couldn't find it. If I find this function, I know that I can send the read data to the tiva card with Serial.write(telnet.read).ESP's RX and TX are connected to the tiva card. I created a wireless connection to the Putty screen.  When a char or string is entered on the telnet screen, it will send it to the tiva card with Serial write from the TX of the ESP8266.I want to write a code that will run in the following logic.

```
 if (telnet.available()) {
    Serial.print(telnet.read());
  }
```
Here is the example code
```/* ------------------------------------------------- */

#include "ESPTelnet.h"

/* ------------------------------------------------- */

#define SERIAL_SPEED    115200
#define WIFI_SSID       "****"
#define WIFI_PASSWORD   "****"

/* ------------------------------------------------- */

ESPTelnet telnet;
IPAddress ip;

/* ------------------------------------------------- */

void setupSerial(long speed, String msg = "") {
  Serial.begin(speed);
  while (!Serial) {
  }
  delay(200);
  Serial.println();
  Serial.println();
  if (msg != "") Serial.println(msg);
}

/* ------------------------------------------------- */

bool isConnected() {
  return (WiFi.status() == WL_CONNECTED);
}

/* ------------------------------------------------- */

bool connectToWiFi(const char* ssid, const char* password, int max_tries = 20, int pause = 500) {
  int i = 0;
  WiFi.mode(WIFI_STA);
  #if defined(ARDUINO_ARCH_ESP8266)
    WiFi.forceSleepWake();
    delay(200);
  #endif
  WiFi.begin(ssid, password);
  do {
    delay(pause);
    Serial.print(".");
  } while (!isConnected() || i++ < max_tries);
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
  return isConnected();
}

/* ------------------------------------------------- */

void errorMsg(String error, bool restart = true) {
  Serial.println(error);
  if (restart) {
    Serial.println("Rebooting now...");
    delay(2000);
    ESP.restart();
    delay(2000);
  }
}

/* ------------------------------------------------- */

void setupTelnet() {
  // passing on functions for various telnet events
  telnet.onConnect(onTelnetConnect);
  telnet.onConnectionAttempt(onTelnetConnectionAttempt);
  telnet.onReconnect(onTelnetReconnect);
  telnet.onDisconnect(onTelnetDisconnect);

  // passing a lambda function
  telnet.onInputReceived([](String str) {
    // checks for a certain command
    if (str == "ping") {
      telnet.println("> pong");
      Serial.println("- Telnet: pong");
    }
  });

  Serial.print("- Telnet: ");
  if (telnet.begin()) {
    Serial.println("running");
  } else {
    Serial.println("error.");
    errorMsg("Will reboot...");
  }
}

/* ------------------------------------------------- */

// (optional) callback functions for telnet events
void onTelnetConnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" connected");
}

void onTelnetDisconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" disconnected");
}

void onTelnetReconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" reconnected");
}

void onTelnetConnectionAttempt(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" tried to connected");
}

/* ------------------------------------------------- */

void setup() {
  setupSerial(SERIAL_SPEED, "Telnet Test");

  Serial.print("- Wifi: ");
  connectToWiFi(WIFI_SSID, WIFI_PASSWORD);

  if (isConnected()) {
    ip = WiFi.localIP();
    Serial.print(" ");
    Serial.println(ip);
    setupTelnet();
  } else {
    Serial.println();
    errorMsg("Error connecting to WiFi");
  }
}

/* ------------------------------------------------- */

void loop() {
  telnet.loop();

  // send serial input to telnet as output
  // this part read tiva and transmit to ESP
  if (Serial.available()) {
    telnet.print(Serial.read());
  }
}
//* ------------------------------------------------- */
```

body:
It appears to me that the library has been written to accept input terminated by a newline character.

```c++
    char c = client.read();
    if (c != '\n') {
      if (c >= 32) {
        input += c;
      }
    // EOL -> send input
    } else {
      if (on_input != NULL) on_input(input);
      input = "";
      }
```

It will keep adding characters to the input buffer until a newline character is detected, and then pass the contents to the `.onInputReceived` recieved handler.

If my understanding is correct, the best you can do without making alterations to the library itself is:-

```c++

  telnet.onInputReceived([](String str) {
      Serial.println(str);
  });

```

Again, if I'm right then the newline character will always need to be present to push the data through.

Hope this is useful.


message:
Arduino Uno won't connect when using USB-C to USB adapter

So I just got my first Arduino which is an Arduino Uno. I have a newer MacBook Air which doesn't have any USB ports so I thought I'd just use one of those USB-C to USB adapters.

I plugged it in and then searched for the Board in the Tools > Port menu. It was nowhere to be seen, only the `/dev/cu.Bluetooth-Incoming-Port` showed up.

To be clear, the Arduino did show signs of connectivity, it just didn't show up under the Port list. I'm also not 100% sure if it's an Arduino Uno since the company I bought it from said I should select Arduino/Genuino Uno in the Board menu which isn't an option anymore.

Is it a problem with my Arduino, my Laptop or my adapter?

body: Maybe it is not original, and it uses different usb-serial chip than the original one. Popular converters for Arduino Uno clones are CH340 and CP2104. You may try to install the driver for these 2 chips.


message:
How do you handle sensor drift?

I have a pair of potentiometers, on the Arduino, the output seems to drift, by one or 2 digits, back and forth. I would prefer they were read as one fixed value, without variation when their knobs are not turning. You can see in the image, the first and second values are shifting back and forth slightly. How should I address this?

I'm thinking of making a standard deviation function, but then I thought that might be unnecessarily complex.

[![wandering pots][1]][1]

My code is that the 2 sensor values are setting points in an SVG polyline. Variance means extra points will get plotted, while the device waits for valid input.

How should I deal with the variance in potentiometer readings to avoid outputting noise?

Here's my source:

```cpp
/**Fucntion Defs**/
void svgHeader();
void svgFooter();
void polyLineBegin();
void polyLineEnd();

int Reset = 4;     //programmatically reset the arduino
int potX = A0;
int potY = A1;

int sensorValX = 0;
int sensorValY = 0;
int oldX = 0;
int oldY = 0;

int del = 2;       //a button on pin 2 for deleting drawn content
int delbutton = 0;
void setup() {
  Serial.begin(9600);
  pinMode(del, INPUT);
  svgHeader();
  polyLineBegin();
  delay(1000);
}

void loop() {
  // close the svg and start over
  if (digitalRead(del) == LOW ) {
    delbutton = 1;
    polyLineEnd();
    svgFooter();
    delay(5000);
    digitalWrite(Reset, LOW);
    digitalWrite(Reset, HIGH);
    svgHeader();
    polyLineBegin();
  } else {
    delbutton = 0;
    //Serial.println(delbutton);

  }

  //dont draw if its not changing
  sensorValX = analogRead(potX);
  sensorValY = analogRead(potY);
  if (sensorValX == oldX && sensorValY == oldY) {
    ; //dont do shi.
  } else {
    Serial.print(sensorValX);
    Serial.print(",");
    Serial.print(sensorValY);
    Serial.print(",");
    oldX = sensorValX;
    oldY = sensorValY;
    // Serial.println(delbutton);
    delay(1000);
  }
}
/**Functions**/

void polyLineBegin() {
  Serial.println ("<polyline points=\""); //x,y points go here

}

void polyLineEnd() {
  Serial.println ("0, 0\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");  //a dirty hack to avoid dealing with 1 last trailing comma.

}

void svgHeader() {
  Serial.println("<svg width=\"1023\" height=\"1023\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">");
};

void svgFooter() {
  Serial.println ("</svg>");
};
```

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

body:
ok, once I got the idea I would need to do it in code, it became simpler to solve. In looking around the terms of quantization, the term thresh-holding came up, and I realized how to solve the problem.

I created a threshold value, and compared the difference between old and new variables.

    int threshold =3;
    int xVariance = abs(sensorValX-oldX);
    int yVariance = abs(sensorValY-oldY);
    if (xVariance >=threshold && yVariance >= threshold ||xVariance >=threshold || yVariance >=threshold){
      Serial.print(sensorValX);
      Serial.print(",");
      Serial.print(sensorValY);
      Serial.print(",");
     oldX=sensorValX;
     oldY=sensorValY;

    }else{
    ; //dont do shi.
     // Serial.println(delbutton);
    delay(1000);
        }

 now, when I turn either potentiometer, I get a response, and output I desire, but not while the device is just sitting there.


body:
Remove the analog component from your device.

Use a rotary encoder.

It will sense the knob rotation digitally.

One huge advantage is that you can easily select the sensitivity of the input. One click can advance the counter by .001 just as easily as advancing by a 1000.

https://duckduckgo.com/?q=rotary+encoder&iar=images&iax=images&ia=images

![enter image description here](https://cdn.hackaday.io/images/3405091516957678589.jpg)