body: When I send data to an Arduino Uno via the serial monitor, the serial data goes down the same USB cable used to program the Arduino.  So there must be a device on the Arduino board like a FTDI or USB-capable AVR that drives the `RXD` pin of the Arduino.  So my question is: When I want two Arduino boards to communicate with each other over serial, many tutorials say just connect RX and TX on one Arduino to TX to RX on the other.  So how come the device on the board that normally drives the `RXD` pin doesn't "fight" the other Arduino that is also now driving the `RXD` line?

title: Arduino to Arduino communication

Answers: 3

body:
If we take a look at this portion of the Arduino Uno schematic ([whole schematic is located here][1]):

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

... we see there are two 1K Ohm (1,000 Ohms) resistors (labeled RN4A and RN4B) between the USB to serial conversion chip on the left to the Atmel processor at center right.  These allow the Rx (Receive) and Tx (Transmit) pins to be back driven by an externally connected device.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: https://i.stack.imgur.com/lma1U.jpg

body:
The Atmega16U2 that does the USB communications is connected to Rx and Tx via 1k resistors, so when communicating with another Arduino it "overpowers" the USB interface. See image:

[![Arduino Uno USB interface][1]][1]

---

By the way, note that the Tx and Rx LEDs are connected to the Atmega16U2, not the Atmega328P, so they do *not* light when doing Arduino-to-Arduino communications.

---

Measuring with an empty sketch on my Uno, the current between Tx and Gnd was 0.14 mA, not 5 mA. So that suggests that the Atmega16U2 sets the pins to high-impedance when not actually receiving data from the USB interface.

It's logical it would do that, because the 5 mA you mention (in a comment) could be a nuisance if you wanted to use that pin for something else.

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

body:
Another  way to do serial communication between Arduinos is to use the SoftwareSerial library using (digital) pins of your choosing for serial communication between the Arduinos. Incidentally, it avoids interference from your computer under simple serial communication,

>The SoftwareSerial library allows serial communication on other digital pins of an Arduino board, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

https://docs.arduino.cc/learn/built-in-libraries/software-serial

It takes just a little preparation and understanding, but not much.
```
#include <SoftwareSerial.h>

#define rxPin 10
#define txPin 11

// Set up a new SoftwareSerial object
SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

void setup()  {
    // Define pin modes for TX and RX
    pinMode(rxPin, INPUT);
    pinMode(txPin, OUTPUT);

    // Set the baud rate for the SoftwareSerial object
    mySerial.begin(9600);
}

void loop() {
    if (mySerial.available() > 0) {
        mySerial.read();
    }
}
```

In this example (copied from the above/linked article), you would use the `mySerial` variable to do your Arduino to Arduino communication in the same way as you use the standard serial connection. You would also need to wire the `RX` and `TX` pins of one Arduino to the `TX` and `RX` pin of the other Arduino, respectively.

One of the benefits of learning how to use the SoftwareSerial library is that there are many communication devices that use serial connection, such as Bluetooth modules (HC-05, HC-06, and HM-10 for example), that you can now use with ease. In this case, you can replace the wires I had you add with a Bluetooth module and communication between the 2 Arduinos wirelessly. Or you can instead communicate with a mobile device with the Bluetooth module.

https://www.instructables.com/Tutorial-Using-HC06-Bluetooth-to-Serial-Wireless-U-1/

Or you could access the internet with a WiFi module over SoftwareSerial.

https://www.taintedbits.com/2017/07/21/arduino-uno-esp8266-software-serial/


body:
I want to control the LEDs with my hand, for this I used the repository https://github.com/paveldat/finger_counter/tree/main. I want to control the LEDs with my hand, for this I used the repository. To connect to the arduino mega serial port, I use the pyserial library, here is the code to which I pass variables.
```
arduinoData = serial.Serial("com9", 9600)
arduinoData.write(bytes(str(variable), "utf-8"))
```
to control the LEDs and process data from the serial port, I wrote the following code in the Arduino IDE:
```
void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop() {
/*
  if (Serial.available() > 0){
    serialData = Serial.read();

    for (int i = 3; i<serialData; i++){
      digitalWrite(i, HIGH);
    }
    }
*/
  if (Serial.available() > 0){
    char serialData = Serial.read();
    if (serialData == '3'){
      digitalWrite(3, HIGH);
      }
    else if (serialData == '4'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      }
    else if (serialData == '5'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      }
    else if (serialData == '6'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
      }
    else if (serialData == '7'){
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
      digitalWrite(7, HIGH);
      }
    else if (serialData == '0'){
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      }

    //Serial.println(serialData);
    //digitalWrite(serialData, HIGH);
    //delay(1000);
  }
}
```
when I run this code without connecting the camera and just pass the values to the serial port, then everything works. However, when I try to run this code together with the camera, the following error occurs:
```
serial.serialutil.SerialException: could not open port 'com9': PermissionError(13, 'Access denied.', None, 5)
```
The camera is a laptop webcam, I have not tested the code with the USB camera, the assumption is that the USB camera will not occupy all serial ports.

title: Python script cannot connect to serial port

Answers: 1

body:
The problem with accessing the port is solved, it was busy since I tried to open it every time in a loop that receives an image and displays it on the screen. I took out the code for a cycle, but the LEDs did not start.
here is the updated code:
```
import cv2
import time
import os
import serial
import HandTrackingModule as htm

wCam, hCam = 640, 480

cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)

folderPath = "fingers" # name of the folder, where there are images of fingers
fingerList = os.listdir(folderPath) # list of image titles in 'fingers' folder
overlayList = []
for imgPath in fingerList:
    image = cv2.imread(f'{folderPath}/{imgPath}')
    overlayList.append(image)

pTime = 0

detector = htm.handDetector(detectionCon=0.75)
totalFingers = 0

def arduino_write(totalFingers):
    arduinoData = serial.Serial("com9", 9600)
    arduinoData.write(bytes(str(totalFingers+2)+"\n", "utf-8"))
    arduinoData.close()

while True:
    sucess, img = cap.read()
    img = cv2.flip(img, 1)

    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img, draw=False)

    if lmList:
        fingersUp = detector.fingersUp()
        totalFingers = fingersUp.count(1)

    h, w, c = overlayList[totalFingers].shape
    img[0:h, 0:w] = overlayList[totalFingers]

    cTime = time.time()
    fps = 1/ (cTime-pTime)
    pTime = cTime

    cv2.putText(img, f'FPS: {int(fps)}', (400, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
    cv2.rectangle(img, (20, 225), (170, 425), (0, 255, 0), cv2.FILLED)
    cv2.putText(img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN, 10, (255, 0, 0), 25)

    arduino_write(totalFingers)

    cv2.imshow("Image", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
```


body: When I connect the Arduino to the computer, the L LED is constantly on and com is not detected. However, when I press the reset button, the L LED starts blinking for about 10 seconds and com appears. But then he leaves.

title: L LED on Arduino is constantly on and com is not detected

Answers: 1

body: Hold the Reset button down with one hand and start uploading the sketch (like, an empty sketch or the Blink sketch) with the other. Once you see "uploading" release the Reset button.


body:
I am getting a compilation error: expected unqualified-id before 'if' .  Btu I have check all the semicolons . Please help finding my error.
 The rest of the message error reads
```
C:\Users\jecalderon\Documents\Arduino\Codigo_AS7262_Investigacion_V2\Codigo_AS7262_Investigacion_V2.ino:35:1: error: expected unqualified-id before 'if'
 if (currentMillis - previousMillis >= interval) {
 ^~
C:........\Codigo_AS7262_Investigacion_V2.ino:40:1: error: expected unqualified-id before 'if'
 if (send) {
 ^~

exit status 1

Compilation error: expected unqualified-id before 'if'
```

    #include <Wire.h>
    #include "Adafruit_AS726x.h"
    //create the object
    Adafruit_AS726x ams;
    //buffer para leer valores en bruto
    uint16_t sensorValues[AS726x_NUM_CHANNELS];
    //buffer para  guardar los valores calibrados( no esta siendo utilizado en este codigo)
    //float calibratedValues[AS726x_NUM_CHANNELS];
    unsigned long previousMillis = 0;
    const long interval = 250;
    bool send = false;
    void setup() {
      Serial.begin(115200);
      while (!Serial) {
        // inicializa el pin digital LED_BUILTIN como un output.
        pinMode(LED_BUILTIN, OUTPUT);

        //inicia y permite la comunicacion con el sensor
        if (!ams.begin()) {
          Serial.println("could not connect to sensor! Please check your wiring.");

        }
      }
    }
    void loop() {
      //lee la temperatura del sensor
      //uint8_t temp = ams.readTemperature();
      //ams.drvOn(); // descomentar esto si quieres usar el led del sensor para hacer medidas
      ams.startMeasurement();  //begin a measurement
      //permite que el sensor lea la data cuando este disponible
      unsigned long currentMillis = millis();
    };
    //ams.drvOff(); //descomentar esto si quieres usar el led del sensor para hacer medidas
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      send = true;
    }

    if (send) {
      //lee los valores!
      ams.readRawValues(sensorValues);
      //ams.readCalibratedValues(calibratedValues);

      //Serial.print("{");
      //Serial.print("Temp: ");
      //Serial.print(temp);
      //Serial.print(",");
      //Serial.print(" Violet: ");
      Serial.print(sensorValues[AS726x_VIOLET]);
      Serial.print(",");
      //Serial.print(" Blue: ");
      Serial.print(sensorValues[AS726x_BLUE]);
      Serial.print(",");
      //Serial.print(" Green: ");
      Serial.print(sensorValues[AS726x_GREEN]);
      Serial.print(",");
      //Serial.print(" Yellow: ");
      Serial.print(sensorValues[AS726x_YELLOW]);
      Serial.print(",");
      //Serial.print(" Orange: ");
      Serial.print(sensorValues[AS726x_ORANGE]);
      Serial.print(",");
      //Serial.print(" Red: ");
      Serial.print(sensorValues[AS726x_RED]);
      //Serial.print("}");

      Serial.println();

      send = false;
    }

title: error: expected unqualified-id before 'if' if (send) { but all semicolons are available

Answers: 1

body:
Check your braces.  Use Control-T to autoformat your code and the error will become apparent.

This is your entire loop function.  Everything after this is is outside of the function.

    void loop() {
      //lee la temperatura del sensor
      //uint8_t temp = ams.readTemperature();
      //ams.drvOn(); // descomentar esto si quieres usar el led del sensor para hacer medidas
      ams.startMeasurement();  //begin a measurement
      //permite que el sensor lea la data cuando este disponible
      unsigned long currentMillis = millis();
    };


body:
I'm encountering persistent errors with the sample code provided for my smart home kit project. Despite conducting extensive research and troubleshooting efforts, I haven't been able to find a solution. It's becoming increasingly frustrating as each problem I fix seems to be replaced by another. I'd greatly appreciate any assistance in resolving this ongoing issue.

```lang-cpp
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiClient.h>
#include <Adafruit_NeoPixel.h>
#define LED_PIN    26
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 4
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

String item = "0";
const char* ssid = "Temp_Wifi"; //Wifi Name
const char* password = "Temp4"; //Wifif Password
WiFiServer server(80);

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C mylcd(0x27,16,2);
#include <analogWrite.h>
#include "xht11.h"
xht11 xht(17);
//#include <ESP32_Servo.h>
//Servo Wservo;
//Servo Dservo;
#include <ESP32Tone.h>
#define buzzer_pin 25
//#define windowServo 5
//#define doorServo 13
#define waterPin 34
#define fanPin1 19
#define fanPin2 18
#define led_y 12  //Define the yellow led pin to 12

#define waterPin 34
#define gasPin 23
#define pyroelectric 14

unsigned char dht[4] = {0, 0, 0, 0};//Only the first 32 bits of data are received, not the parity bits

//Servo channel
int channel_PWM = 13;
int channel_PWM2 = 10;
int freq_PWM = 50;
int resolution_PWM = 10;
const int PWM_Pin1 = 5;
const int PWM_Pin2 = 13;

void setup() {
  Serial.begin(115200);
  mylcd.init();
  mylcd.backlight();
  pinMode(led_y, OUTPUT);
  pinMode(fanPin1, OUTPUT);
  pinMode(fanPin2, OUTPUT);
  ledcSetup(5, 1200, 8);//Set the frequency of LEDC channel 1 to 1200 and PWM resolution to 8, that is duty cycle to 256.
  ledcAttachPin(fanPin2, 5);  //Bind the LEDC channel 1 to the specified left motor pin GPIO26 for output.
  pinMode(waterPin, INPUT);
  pinMode(buzzer_pin, OUTPUT);
  pinMode(gasPin, INPUT);
  pinMode(pyroelectric, INPUT);
  ledcSetup(channel_PWM, freq_PWM, resolution_PWM); //Set servo channel and frequency as well as PWM resolution.
  ledcSetup(channel_PWM2, freq_PWM, resolution_PWM);
  ledcAttachPin(PWM_Pin1, channel_PWM);  //Binds the LEDC channel to the specified IO port for output
  ledcAttachPin(PWM_Pin2, channel_PWM2);  //Binds the LEDC channel to the specified IO port for output
//  Wservo.attach(windowServo);
//  Dservo.attach(doorServo);
//  #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
//    clock_prescale_set(clock_div_1);
//  #endif
//    // END of Trinket-specific code.
//  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
//  strip.show();            // Turn OFF all pixels ASAP
//  strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
  Serial.println("TCP server started");
  MDNS.addService("http", "tcp", 80);
  mylcd.setCursor(0, 0);
  mylcd.print("ip:");
  mylcd.setCursor(0, 1);
  mylcd.print(WiFi.localIP());  //LCD displays ip adress
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
      return;
  }
  while(client.connected() && !client.available()){
      delay(1);
  }
  String req = client.readStringUntil('\r');
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
      Serial.print("Invalid request: ");
      Serial.println(req);
      return;
  }
  req = req.substring(addr_start + 1, addr_end);
  item=req;
  Serial.println(item);
  String s;
  if (req == "/")  //Browser accesses address can read the information sent by the client.println(s);
  {
      IPAddress ip = WiFi.localIP();
      String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
      s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>ESP32 ip:";
      s += ipStr;
      s += "</html>\r\n\r\n";
      Serial.println("Sending 200");
      client.println(s);  //Send the string S, then you can read the information when visiting the address of E smart home using the browser.
  }
  if(req == "/led/on") //Browser accesses address ip address/led/on
  {
    client.println("turn on the LED");
    digitalWrite(led_y, HIGH);
  }
  if(req == "/led/off") //Browser accesses address ip address/led/off
  {
    client.println("turn off the LED");
    digitalWrite(led_y, LOW);
  }
  if(req == "/window/on")
  {
    client.println("open the window");
    ledcWrite(channel_PWM, 100);  //The high level of 20ms is about 2.5ms, that is, 2.5/20*1024, at this time, the servo angle is 180°.
    //Wservo.write(175);
  }
  if(req == "/window/off")
  {
    client.println("close the window");
    ledcWrite(channel_PWM, 60);  //The high level of 20ms is about 0.5ms，that is, 0.5/20*1024，at this time, the servo angle is 0°.
    //Wservo.write(0);
  }
  if(req == "/music/on")
  {
    //client.println("play music");
  }
  if(req == "/music/off")
  {
    client.println("play music");
    birthday();
    noTone(buzzer_pin,0);
  }
  if(req == "/buz/on")
  {
    client.println("buzzer");
    tone(buzzer_pin,392,250,0);
    Serial.println("1");
  }
  if(req == "/buz/off")
  {
    client.println("off");
    noTone(buzzer_pin,0);
  }
  if(req == "/door/on")
  {
    client.println("open the door");
    ledcWrite(channel_PWM2, 120);
//    Dservo.write(180);
  }
  if(req == "/door/off")
  {
    client.println("close the door");
     ledcWrite(channel_PWM2, 20);
//    Dservo.write(0);
  }
  if(req == "/fan/on")
  {
    client.println("turn on the fan");
    digitalWrite(fanPin1, LOW); //pwm = 0
    ledcWrite(5, 100); //The LEDC channel 1 is bound to the specified left motor output PWM value of 100.
  }
  if(req == "/fan/off")
  {
    client.println("turn off the fan");
    digitalWrite(fanPin1, LOW); //pwm = 0
    ledcWrite(5, 0); //The LEDC channel 1 is bound to the specified left motor output PWM value of 0.
  }
  if(req == "/red/on")
  {
    client.println("red on");
    colorWipe(strip.Color(255,   0,   0), 50);
  }
  if(req == "/red/off")
  {
    client.println("red off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/oringe/on")
  {
    client.println("oringe on");
    colorWipe(strip.Color(200,   100,   0), 50);
  }
  if(req == "/oringe/off")
  {
    client.println("oringe off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/yellow/on")
  {
    client.println("yellow on");
    colorWipe(strip.Color(200,   200,   0), 50);
  }
  if(req == "/yellow/off")
  {
    client.println("yellow off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/green/on")
  {
    client.println("green on");
    colorWipe(strip.Color(0,   255,   0), 50);
  }
  if(req == "/green/off")
  {
    client.println("green off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/cyan/on")
  {
    client.println("cyan on");
    colorWipe(strip.Color(0,   100,   255), 50);
  }
  if(req == "/cyan/off")
  {
    client.println("cyan off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/blue/on")
  {
    client.println("blue on");
    colorWipe(strip.Color(0,   0,   255), 50);
  }
  if(req == "/blue/off")
  {
    client.println("blue off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/purple/on")
  {
    client.println("purple on");
    colorWipe(strip.Color(100,   0,   255), 50);
  }
  if(req == "/purple/off")
  {
    client.println("purple off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/white/on")
  {
    client.println("white on");
    colorWipe(strip.Color(255,   255,   255), 50);
  }
  if(req == "/white/off")
  {
    client.println("white off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/sfx1/on")
  {
    client.println("sfx1 on");
    rainbow(10);
  }
  if(req == "/sfx1/off")
  {
    client.println("sfx1 off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }
  if(req == "/sfx2/on")
  {
    client.println("sfx2 on");
    theaterChaseRainbow(50);
  }
  if(req == "/sfx2/off")
  {
    client.println("sfx2 off");
    colorWipe(strip.Color(0,   0,   0), 50);
  }

  if(req == "/rain/on")
  {
    int rainVal = analogRead(waterPin);
    client.println(rainVal);
  }
  if(req == "/rain/off")
  {
    client.println("off");
  }
  if(req == "/gas/on")
  {
    boolean gasVal = analogRead(gasPin);
    if(gasVal == 0)
    {
      client.println("safety");
    }
    else
    {
      client.println("dangerous");
    }
  }
  if(req == "/gas/off")
  {
    client.println("off");
  }
  if(req == "/body/on")
  {
    boolean pyroelectric_val = digitalRead(pyroelectric);
    if(pyroelectric_val == 1)
    {
      client.println("someone");
    }
    else
    {
      client.println("no one");
    }
  }
  if(req == "/body/off")
  {
    client.println("off");
  }
  if(req == "/temp/on")
  {
    if (xht.receive(dht)) { //Returns true when checked correctly
      Serial.print("Temp:");
      Serial.print(dht[2]); //The integral part of temperature, DHT [3] is the fractional part
      Serial.println("C");
      delay(200);
    } else {    //Read error
      Serial.println("sensor error");
    }
    client.println(dht[2]);
    delay(1000);  //It takes 1000ms to wait for the device to read
  }
  if(req == "/temp/off")
  {
    client.println("off");
  }
  if(req == "/humidity/on")
  {
    if (xht.receive(dht)) { //Returns true when checked correctly
      Serial.print("Temp:");
      Serial.print(dht[0]); //The integral part of temperature, DHT [3] is the fractional part
      Serial.println("%");
      delay(200);
    } else {    //Read error
      Serial.println("sensor error");
    }
    client.println(dht[0]);
    delay(1000);  //It takes 1000ms to wait for the device to read
  }
  if(req == "/humidity/off")
  {
    client.println("off");
  }

  //client.stop();
}

void birthday()
{
  tone(buzzer_pin,294,250,0);  //The four parameters are pin, frequency, delay and channel
  tone(buzzer_pin,440,250,0);
  tone(buzzer_pin,392,250,0);
  tone(buzzer_pin,532,250,0);
  tone(buzzer_pin,494,250,0);
  tone(buzzer_pin,392,250,0);
  tone(buzzer_pin,440,250,0);
  tone(buzzer_pin,392,250,0);
  tone(buzzer_pin,587,250,0);
  tone(buzzer_pin,532,250,0);
  tone(buzzer_pin,392,250,0);
  tone(buzzer_pin,784,250,0);
  tone(buzzer_pin,659,250,0);
  tone(buzzer_pin,532,250,0);
  tone(buzzer_pin,494,250,0);
  tone(buzzer_pin,440,250,0);
  tone(buzzer_pin,698,250,0);
  tone(buzzer_pin,659,250,0);
  tone(buzzer_pin,532,250,0);
  tone(buzzer_pin,587,250,0);
  tone(buzzer_pin,532,500,0);
  noTone(buzzer_pin,0);  //关闭
}

void colorWipe(uint32_t color, int wait) {
  for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);         //  Set pixel's color (in RAM)
    strip.show();                          //  Update strip to match
    delay(wait);                           //  Pause for a moment
  }
}

// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait) {
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait) {
  int firstPixelHue = 0;     // First pixel starts at red (hue 0)
  for(int a=0; a<30; a++) {  // Repeat 30 times...
    for(int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();         //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in increments of 3...
      for(int c=b; c<strip.numPixels(); c += 3) {
        int      hue   = firstPixelHue + c * 65536L / strip.numPixels();
        uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show();                // Update strip with new contents
      delay(wait);                 // Pause for a moment
      firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
    }
  }
}
```
The current error code I'm encountering during compilation is as follows:
```
WARNING: library LiquidCrystal_I2C claims to run on avr architecture(s) and may be incompatible with your current board which runs on esp32 architecture(s).
In file included from C:\Users\temp\Downloads\KS5009 Keyestudio Smart Home Kit for ESP32\3. Arduino Tutorials\arduino Code\pj13_2_IoT_smart_home\pj13_2_IoT_smart_home.ino:16:
c:\Users\temp\OneDrive\Documents\Arduino\libraries\Wire\src/Wire.h:44:5: error: 'i2c_t' does not name a type; did you mean 'ino_t'?
     i2c_t * i2c;
     ^~~~~
     ino_t
c:\Users\temp\OneDrive\Documents\Arduino\libraries\Wire\src/Wire.h:64:5: error: 'i2c_err_t' does not name a type; did you mean 'esp_err_t'?
     i2c_err_t last_error; // @stickBreaker from esp32-hal-i2c.h
     ^~~~~~~~~
     esp_err_t
c:\Users\temp\OneDrive\Documents\Arduino\libraries\Wire\src/Wire.h:87:5: error: 'i2c_err_t' does not name a type; did you mean 'esp_err_t'?
     i2c_err_t writeTransmission(uint16_t address, uint8_t* buff, uint16_t size, bool sendStop=true);
     ^~~~~~~~~
     esp_err_t
c:\Users\temp\OneDrive\Documents\Arduino\libraries\Wire\src/Wire.h:88:5: error: 'i2c_err_t' does not name a type; did you mean 'esp_err_t'?
     i2c_err_t readTransmission(uint16_t address, uint8_t* buff, uint16_t size, bool sendStop=true, uint32_t *readCount=NULL);
     ^~~~~~~~~
     esp_err_t
Multiple libraries were found for "Wire.h"
  Used: C:\Users\temp\OneDrive\Documents\Arduino\libraries\Wire
  Not used: C:\Users\temp\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.13\libraries\Wire
exit status 1

Compilation error: exit status 1
```

title: Keyestudio KS5009 ESP32WROOM32 Smart Home

Answers: 0


body:
# What was my problem
I had a big problem with my esp8266. I couldn't upload anything to it using the Arduino IDE 2.2.1, the ttyUSB port couldn't be found.

When I plug my esp8266 into the USB Port, it shows up in the port selection in the Arduino IDE but then disappears imminently.

## dmesg | grep ch34
```bash
[    7.286317] usbcore: registered new interface driver ch341
[    7.286328] usbserial: USB Serial support registered for ch341-uart
[    7.286342] ch341 1-3:1.0: ch341-uart converter detected
[    7.304530] usb 1-3: ch341-uart converter now attached to ttyUSB0
[    7.804730] usb 1-3: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1
[    7.811803] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
[    7.811814] ch341 1-3:1.0: device disconnected
```
As shown above, the esp8266 is connecting, but then disconnects.

title: Can't connect esp8266 via USB to Linux Mint 21.1

Answers: 1

body:
# The solution

https://www.linux.org/threads/ch340-driver-on-linux-mint.44961/post-204493

`sudo apt-get remove -y brltty`

Just remove the brltty package.

## What is brltty?
https://brltty.app/ <br>
"BRLTTY is a background process (daemon) which provides access to the Linux/Unix console (when in text mode) for a blind person using a refreshable braille display. It drives the braille display, and provides complete screen review functionality. Some speech capability has also been incorporated."

So as long as you don't need the abilty for displaying something on a braille display, you'll good to go wit that solution.

I hope, that this will help anyone :D I posted this here, because I was searching for that very long, so it might be useful to have short solution for that.


body:
I have a question regarding serial buffer readout.

At program start, I send a serial command to a sensor that 1. activates him and 2. let him send data - that works.
When I unplug the sensor, the serial buffer remains empty and the program goes into the else condition of void loop.
But if I connect the sensor again, the serial buffer should be filled again and the program should jump into the if condition of the void loop. But it does not.

I added the variable i because the serial buffer becomes empty too quickly and the program then sends the start command of the else condition again, even though the sensor is connected and still works. Then the readout gets mixed up...that works too.

Why doesn't the program jumps back in the if condition of void loop when the sensor gets connected again after it was disconnected some time? Then serial.available() should be bigger 0 and it should readout data?

    #include <SoftwareSerial.h>
    int i = 0;

    void setup()  {
        Serial.begin(9600);
        Serial1.begin(9600);
        Serial1.write(Send Start Sequence);
        Serial1.write(Start continuously read out sensor data);
    }

    void loop() {
      if (Serial1.available() > 0) {
        char incomingByte = Serial1.read();
        Serial.write(incomingByte);
      i = 0;
      }
      else {
        i++;
        if (i > 5) {
          Serial1.write(Send Start Sequence);
          Serial1.write(Start continuously read out sensor data);
        }
      }
    }

title: Serial Buffer stays empty as soon as it becomes empty once

Answers: 2

body:
Your loop going to 5 is going to happen extremely quickly. Instead I would do a delay, say of one second (1000 ms), maybe less. Constantly sending the start sequence my be misinterpreted if the sensor comes online in the middle of the sequence. Plus your (counting) delay would only happen once. Putting a delay in the loop would make it happen every time.

---

I suggest a different way of recovering from an unplugged sensor:

<!-- language: c++ -->

    #include <SoftwareSerial.h>

    void setup()  {
        Serial.begin(9600);
        Serial1.begin(9600);
        Serial1.write("Send Start Sequence");
        Serial1.write("Start continuously read out sensor data");
    }

    unsigned long lastDataReceived;

    void loop() {
      if (Serial1.available() > 0) {
        char incomingByte = Serial1.read();
        Serial.write(incomingByte);
        lastDataReceived = millis ();
      }
      else {
        if ((millis() - lastDataReceived) > 5000) {
          Serial1.write("Send Start Sequence");
          Serial1.write("Start continuously read out sensor data");
          lastDataReceived = millis ();
        }
      }
    }

What this will do is wait 5 seconds before sending out the new start sequence. At 9600 baud your loop will be a lot faster than incoming bytes. This will be more reliable.

body:
I second Nick Gammon in recommending a time-based condition, rather than
counting the loop iterations. You can do it in a non-blocking fashion
though:

* keep track of when was the last time you communicated with the sensor
* if this was too long ago, resend the “start sequence” command

Note that sending the command counts as a communication event, which
rearms the timer. Otherwise you would be repeatedly sending the command
too fast.

```c++
// After this delay, assume we lost the sensor.
const unsigned long timeout = 200;

// Last time we communicated with the sensor.
unsigned long last_comm_time;

void loop() {
    // Check the clock.
    unsigned long now = millis();

    // Process incoming data.
    if (Serial1.available() > 0) {
        last_comm_time = now;
        char incomingByte = Serial1.read();
        Serial.write(incomingByte);
    }

    // Try to wake up the sensor if we lost it.
    if (now - last_comm_time >= timeout) {
        last_comm_time = now;  // count this as a communication event
        Serial1.write(start_sequence);
        Serial1.write(continuously_read_out_sensor_data);
    }
}
```

You could potentially have separate timeouts for “the sensor just
stopped sending data” and “the sensor should be processing the start
command we just sent”. This would be a bit more complex though,
requiring some sort of state machine. If you can use a single timeout
value, things are simpler.


body:
I am working on a project where I need to get the RGB light value from surrounding ambient light.

For that I am using an ESP32 with a Sparkfun ISL29125 breakout board. I have tried to scan available/connected I2C devices addresses. I'm getting the 0x44 address in the output, which is the address of the ISL29125.

But when running the following code, I am not getting any output. I have added the library to the Arduino IDE.

I have checked all wire connections. 2 other sensors are connected to the I2C bus.

I have connected the pins as follows:

GPIO21 (ESP32) -> SDA (ISL29125)
GPIO22(ESP32) -> SCL (ISL29125).

I'm supplying 3.3v and GND from ESP32.

I have scanned the I2C bus and getting the addresses of all connected sensors including the ISL29125.

- 0X38
- 0X44 (Address of the ISL29125)
- 0X47

Following is the source code.

```c
#include <Wire.h>
#include <SparkFunISL29125.h>
SFE_ISL29125 RGB_sensor;
void setup() {
  // Initialize serial communication
  Serial.begin(115200);
  Serial.println("Hello123");
  // Initialize the ISL29125 with simple configuration so it starts sampling
  if (!RGB_sensor.init()) {
    Serial.println("Sensor Initialization Problem\n\r");
  }
}

void loop() {
  Serial.println("Hello");
  // Read sensor values (16 bit integers)
  unsigned int red = RGB_sensor.readRed();
  unsigned int green = RGB_sensor.readGreen();
  unsigned int blue = RGB_sensor.readBlue();

  // Print out readings, change HEX to DEC if you prefer decimal output
  Serial.print("Red: "); Serial.println(red,HEX);
  Serial.print("Green: "); Serial.println(green,HEX);
  Serial.print("Blue: "); Serial.println(blue,HEX);
  Serial.println();
  delay(2000);
}
```

This is the output I am getting

```
[     4][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
Hello123
[    21][I][esp32-hal-i2c.c:75] i2cInit(): Initialising I2C Master: sda=21 scl=22 freq=100000
```

I am not getting any RGB value or the code is getting stuck in the `init()` method.
Can anyone guide me? What can be the problem? What is my mistake?

title: Sparkfun ISL29125 breakout board issue with Arduino IDE with ESP32

Answers: 1

body:
The library file "SparkFunISL29125.cpp" contains this: `Wire.begin();` and I guess you want it to contain `Wire.begin(21,22)` from what you have said in a later comment.  Best would be to comment out `Wire.begin();` in the library and put the corrected version in your sketch.
In such a situation I'd suggest  copying the .cpp and .h files of the library into the sketch folder. You also have to change this in the sketch: `#include <SparkFunISL29125.h>` to `#include "SparkFunISL29125.h"` to address the local copy.

Further, the schematic of the SparkFun ILS29125 breakout board shows that the on board I2C pullup resistors are connected via a solder jumper which by default is not bridged.
You appear to have done the I2C scan test with two other devices connected and may have "benefitted" from their I2C pullup resistors. If you did the live test with the ILS29125 alone, there may have been no I2C pullup resistors in the circuit.

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

[![schematic][2]][2]

  [1]: https://i.stack.imgur.com/jiQ4M.png
  [2]: https://i.stack.imgur.com/dxHuR.png


body: I want to make an arduino code on the arduino leonardo that detects when keys are being pressed and to print them to the serial monitor so I can control the arduino with the computer keyboard. I need to know how to detect keyboard presses.

title: Arduino Leonardo Key Detector

Answers: 1

body:
If the keyboard is plugged to the computer, there is no way the Arduino
can detect the key presses. You can, however, run a program on the
computer that detects those key presses and forwards that information to
the Arduino.

That being said, if you goal is simply to “control the Arduino with the
computer keyboard”, I suggest you run a [terminal emulator][] on the
computer. This is a program that emulates an old school computer
terminal, like the classic [VT100][] series. You won't get individual key
events this way: only characters. For example, if you press and hold
Shift, then press A, then release both, the
Arduino will receive a single `'A'` character through the serial port,
instead of four individual key events.

On Windows, you can try [Putty][]. On macOS and Linux, you already have
a terminal emulator: you just need a communication program such as
[picocom][] to connect it to the serial port.

You could also use the Arduino serial monitor. This is, however, not a
proper terminal emulator. Specifically, it doesn't send the characters
you type immediately: you have to click on “Send” for that.

[terminal emulator]: https://en.wikipedia.org/wiki/Terminal_emulator
[VT100]: https://en.wikipedia.org/wiki/VT100
[Putty]: https://www.chiark.greenend.org.uk/~sgtatham/putty/
[picocom]: https://github.com/npat-efault/picocom


body:
I want print data from a DHT11 (temperature and humidity) on a MAX7219 LED display but it only shows 0. Serial monitor, on the other hand, shows both humidity and temperature which means that my circuit works just fine and there's something wrong with code.
Could anyone please point out what needs to be fixed to make it work? Thanks. [![enter image description here][1]][1]
[![enter image description here][2]][2]
Here is the code

```
#include <WiFi.h>
#include <NTPClient.h>
#include <DHT.h>
#include <WiFiUdp.h>
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
//#define HARDWARE_TYPE MD_MAX72XX::GENERIC_H
#define MAX_DEVICES 4
#define CLK_PIN   5
#define DATA_PIN  7
#define CS_PIN    6
MD_Parola Display = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
const char* ssid     = "6666";
const char* password = "6666";
String Time, hour, minute;
String Formatted_date;
long currentMillis = 0;
long previousMillis = 0;
int interval = 1000;
#define DHTPIN  A2         /*Signal pin for DHT11 Sensor*/
#define DHTTYPE    DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("Connecting.");
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  timeClient.begin();
  timeClient.setTimeOffset(0);

  Display.begin();
  Display.setIntensity(0);
  Display.displayClear();

   dht.begin();
   Serial.println("Status\tHumidity (%)\tTemperature (C)");
}
void loop()
 {
   obtainTime();
}
void obtainTime() {
  while(!timeClient.update()) {
    timeClient.forceUpdate();
  }
  currentMillis = millis();
  if (currentMillis - previousMillis > interval)  {
previousMillis = millis();
Formatted_date = timeClient.getFormattedDate();
Serial.println(Formatted_date);
hour = Formatted_date.substring(11, 13);
minute = Formatted_date.substring(14, 16);

Time = hour + ":" + minute;
Serial.println(Time);
Display.setTextAlignment(PA_CENTER);
Display.print(Time);

delay(3000);
// The DHT11 returns at most one measurement every 3s
  float h = dht.readHumidity();
  //Read the moisture content in %.
  float t = dht.readTemperature();
  //Read the temperature in degrees Celsius

Serial.println(t);
Serial.println(h);
Display.setTextAlignment(PA_CENTER);
Display.print(t);
delay(5000);
Display.displayClear();

}

}
```

  [1]: https://i.stack.imgur.com/PfiGw.jpg
  [2]: https://i.stack.imgur.com/uC5YK.jpg

title: DHT11's data on MAX7219 reads 0

Answers: 1

body:
It turned out that MD_Parola can't handle floats directly. I fixed the problem by converting the floats t and h into strings using dtostrf()

```
 float h = dht.readHumidity();
 float t = dht.readTemperature();

char temp_result[6];
dtostrf(t,2,1,temp_result);

char hum_result[6];
dtostrf(h,2,0,hum_result);
Serial.println(t);
Serial.println(h);
Display.setTextAlignment(PA_CENTER);
//Display.print(temp_result);
Display.print((String)temp_result+" "+"C");
delay(5000);
//Display.print(hum_result);
Display.print((String)hum_result+" "+"%");
delay(5000);

```


body:
I have recently created a sketch for an ATTiny85.

My project consists of:

  - 1x ATTiny85 IC only
  - 1x 433MHz RF module => using data pin `2`
  - 2x input digital pins => using pin `3` and pin `4`

Running at 16MHz using the ATTiny85 board core from https://github.com/damellis/attiny

All running on a 5v 1A 7805 only using `24.4mA` idle `29.5mA` when TXing.

I have optimized my code a bit and the sketch works as intended.
 However sometimes the RF 433 module just keeps sending data for a few seconds instead of sending a burst then waiting for my 7 second timeout.

I do use the internal pullup resistors on pin 3 and 4.

This happens intermittently.. I would like to know if anyone has had a similar problem and knows how to prevent this "*runaway transmission*".. Or suggestions code improvements etc.

Strangely enough I can get 450m+- line of sight (farm land) distance accurate pings on my sensitive receiver using this cheap module.

**RF 433 Module**

I have the one with the SMD coil I have also soldered a 17.3cm LAN wire as antenna.

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

**SDR Waterfall**

I expect a constant burst every 7s.

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

**Code**

The code starts by looping a switch statement over states when an input is H/L or a timer runs out a state is changed.

When a trigger state is initiated a for loop copies and concatinates a condenses hex string then the next for loop sends these signals over pin 2.

After the signal is sent the state then changes to a timeout to wait before sending a pulse again.

*This is where the problem is.*

Sometimes the signal keeps sending as if the state is stuck for a few seconds but then the timer starts working as expected...

The longer 15min timer works fine, it's only the 7s and 9s loops that seem to have this issue.

---

**Pictures of testing PCB**

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

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

---

**Full sketch**
[*updated with suggestions*]

<!-- language-all: lang-arduino -->
```
#include <stdint.h>
#include <avr/io.h>
#include <util/delay.h>

#define DATA_PIN PB2// digital pin 2
#define ALARM_TRIGGER_PIN PB3// digital pin 3
#define LEARN_PIN PB4// digital pin 4

//15min= 900000 ms
//16min = 960000 ms
//20min= 500000 ms
const unsigned long DELAY_TIME_ZONE_HEARTBEAT = 900000;//15min
const unsigned long DELAY_TIME_CHECKALARM_TIMEOUT = 7000;//7sec
const unsigned long DELAY_TIME_CHECKLEARN_TIMEOUT = 9000;//9sec

unsigned long Delay_Start_Check_Alarm = 0;
unsigned long Delay_Start_Heartbeat = 0;
unsigned long Delay_Start_Learn = 0;

char LEARN[] ="269369a6924d36da6c800";//condensed hexadecimal signal; learnState/tamper same signal
char ALARM[] = "da4da69a4934db69b200";//condensed hexadecimal signal
char HEARTBEAT[] ="1269b4d349269b6d36400";//condensed hexadecimal signal
uint16_t pulse = 1100;//Attiny85 chip needs more of delay time
uint8_t i;

//custom states
enum State
{
  ALARMTIMEOUT,
  CHECKING,
  HEARTBEATTIMEOUT,
  HEARTBEATSEND,
  LEARNTIMEOUT,
  LEARNSEND,
  ALARMSEND
};

enum State state;

void setup()
{
  DDRB |= (1 << DATA_PIN);//replaces pinMode(DATA_PIN, OUTPUT);
  DDRB &= ~(1 << ALARM_TRIGGER_PIN); //replaces pinMode(ALARM_TRIGGER_PIN, INPUT);
  DDRB &= ~(1 << LEARN_PIN); //replaces pinMode(LEARN_PIN, INPUT);

  PORTB |= (1 << ALARM_TRIGGER_PIN);//initiate alarm pin pullup
  PORTB |= (1 << LEARN_PIN);//initiate learn pin pullup

  ADCSRA &= ~(1 << ADEN); //Disable ADC, saves ~230uA

  Delay_Start_Check_Alarm = Delay_Start_Heartbeat = Delay_Start_Learn  = millis();//set to start millis
  state = CHECKING;//initial state
}

void Check_Alarm_And_Heartbeat()
{
  unsigned long Mill = millis();//set to current time

  uint8_t alarmState = PINB&8;//read alarm pin 3
  uint8_t learnState = PINB&16;//read learn pin 4

  //main switch loop
    switch (state)
    {
    case CHECKING:
         //constant checking here
         if((alarmState) && (!learnState))
          {
           state = ALARMSEND;//set state
           Delay_Start_Check_Alarm = Mill;//keep time
          }
         //learn loop
         if((learnState) && (!alarmState))
         {
           state = LEARNSEND;//set state
           Delay_Start_Learn = Mill;//keep time
         }
         //continue heartbeat
         if((!alarmState) && (!learnState))
         {
           state = HEARTBEATTIMEOUT;//set state
         }
         //if both are high prioratize learnState/tamper signal
         if((alarmState) && (learnState))
         {
           state = LEARNSEND;//set state; learnState/tamper same signal
           Delay_Start_Learn = Mill;//keep time
         }
        break;
    case LEARNSEND:
         {
           state = LEARNTIMEOUT;//set state
           char LEARNFINAL[168];//make LEARNFINAL var and define length
           strcpy(LEARNFINAL, LEARN);//copy LEARN to new LEARNFINAL var
           for (uint8_t i = 0; i < 7; i++)
           {
             strcat(LEARNFINAL, LEARN);// append/concatenate LEARN 7 times to LEARNFINAL
           }
             for (i = 0; i < sizeof(LEARNFINAL); i++)
             {
               Send_Hex_Digit(DATA_PIN, LEARNFINAL[i], pulse);//send finished LEARNFINAL var
             }
             //PORTB &= ~(1 << DATA_PIN);//write low
         }
        break;
    case ALARMSEND:
         {
           state = ALARMTIMEOUT;//set state
           char ALARMFINAL[168];//make ALARMFINAL var and define length
           strcpy(ALARMFINAL, ALARM);//copy ALARM to new ALARMFINAL var
            for (uint8_t i = 0; i < 7; i++)
            {
               strcat(ALARMFINAL, ALARM);// append/concatenate ALARM 7 times to ALARMFINAL
            }
             for (i = 0; i < sizeof(ALARMFINAL); i++)
             {
               Send_Hex_Digit(DATA_PIN, ALARMFINAL[i], pulse);//send finished ALARMFINAL var
             }
             //PORTB &= ~(1 << DATA_PIN);//write low
         }
        break;
    case HEARTBEATSEND:
         {
             state = CHECKING;//change state
             char HEARTBEATPREFINAL[160];//make HEARTBEATPREFINAL var and define length
             strcpy(HEARTBEATPREFINAL, HEARTBEAT);//copy HEARTBEAT to new HEARTBEATPREFINAL var
              for (uint8_t i = 0; i < 7; i++)
              {
                 strcat(HEARTBEATPREFINAL, HEARTBEAT);// append/concatenate HEARTBEAT 7 times to HEARTBEATPREFINAL
              }
             for (i = 0; i < sizeof(HEARTBEATPREFINAL); i++)
             {
               Send_Hex_Digit(DATA_PIN, HEARTBEATPREFINAL[i], pulse);//send finished HEARTBEATPREFINAL var
             }
         }
        break;
    case HEARTBEATTIMEOUT:
             state = CHECKING;//change state
             if ((Mill - Delay_Start_Heartbeat) >= DELAY_TIME_ZONE_HEARTBEAT)
             {
                 Delay_Start_Heartbeat += DELAY_TIME_ZONE_HEARTBEAT;//prevents drift
                 state = HEARTBEATSEND;//change state when time ends
             }
        break;
    case ALARMTIMEOUT:
             state = ALARMTIMEOUT;//change state
             if ((Mill - Delay_Start_Check_Alarm) >= DELAY_TIME_CHECKALARM_TIMEOUT)
             {
                 state = CHECKING;//change state when time ends
             }
        break;
    case LEARNTIMEOUT:
             state = LEARNTIMEOUT;//change state
             if ((Mill - Delay_Start_Learn) >= DELAY_TIME_CHECKLEARN_TIMEOUT)
             {
                 state = CHECKING;//change state when time ends
             }
        break;
    default:
        //do nothing
        break;
    }
}

void Send_Hex_Digit(uint8_t pin, char c, uint16_t pulse)
{
  byte bc = c - 48 ; // convert c to number 0 to 15
  for (int i = 3; i >= 0; i--)
  {
    bitWrite(PORTB, pin, bitRead(bc, i));
    delayMicroseconds(pulse);
  }
}

void loop()
{
  Check_Alarm_And_Heartbeat();
}
```

  [1]: https://i.stack.imgur.com/sa8EZ.jpg
  [2]: https://i.stack.imgur.com/q8min.jpg
  [3]: https://i.stack.imgur.com/oNXEj.jpg
  [4]: https://i.stack.imgur.com/RdPnA.jpg

title: 433MHz RF run away TX burst with ATTiny85 IC

Answers: 1

body:
After implementing the suggestions I was able to make the sketch smaller and also solve the unwanted transmitting for the 2 timeouts (`pin3`, `pin4`).

The main issue was a 7s timeout before the sketch checks the High/Low.

This was solved by setting `Delay_Start_Check_Alarm` and `Delay_Start_Learn` in my switch statement, if the alarm was triggered.

```C++
    Delay_Start_Check_Alarm = Mill;//Setting this solved the issue
```

The heartbeat did not need this change since it gets set every time `HEARTBEATTIMEOUT` is called so it works ok.

The code in the question is also updated.

Big thanks to *@chrisl*, *@6v6gt* and *@timemage*.


body:
according to the official documentation of the Arduino, the SRAM memory (which is allocated for the local variables) should be automatically released after calling any function. For example, I have a function `memory_allocate_test2`, which declares a large char array and this function is called in the loop(). I expect, that every time, after the function `memory_allocate_test2` is executed, the SRAM memory that I allocated for the local variables within that function should be freed or released. However, it is not working like that. When I call that function in a loop() the microcontroller hangs and stops working because it runs out of the available SRAM memory. Let me provide an example code:

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);

      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only - development mode. It has to be removed when releasing to live!!!
      }
    }

    void loop() {
      delay(2000);
      memory_allocate_test2();
    }

    void memory_allocate_test2() {
      Serial.println("memory_allocate_test2 STARTING ");
      display_freeram();
      Serial.println("------------------------------------------------------------");
      Serial.println("Allocating the memory for the MKR: ");
      char* memory_usage_test = new char[2000];
      Serial.println("Allocated memory!");
      display_freeram();
      Serial.println("------------------------------------------------------------");
    }

    extern "C" char* sbrk(int incr);

    void display_freeram(){
      Serial.print(F("- SRAM left: "));
      Serial.println(freeRam());
    }

    int freeRam() {
      char top;
      return &top - reinterpret_cast<char*>(sbrk(0));
    }

why it doesn't work as it states in the documentation? what I'm doing wrong? why the SRAM memory is not released each time after the `memory_allocate_test2` function execution?

https://www.seeedstudio.com/blog/2021/04/26/managing-arduino-memory-flash-sram-eeprom/

when I execute that program, here is what happens:

memory_allocate_test2 STARTING
- SRAM left: 7163
------------------------------------------------------------
Allocating the memory for the MKR:
Allocated memory!
- SRAM left: 5155
------------------------------------------------------------
memory_allocate_test2 STARTING
- SRAM left: 5155
------------------------------------------------------------
Allocating the memory for the MKR:
Allocated memory!
- SRAM left: 3147
------------------------------------------------------------
memory_allocate_test2 STARTING
- SRAM left: 3147
------------------------------------------------------------
Allocating the memory for the MKR:
Allocated memory!
- SRAM left: 1139
------------------------------------------------------------
memory_allocate_test2 STARTING
- SRAM left: 1139
------------------------------------------------------------
Allocating the memory for the MKR:
Allocated memory!
- SRAM left: -869
------------------------------------------------------------
memory_allocate_test2 STARTING
- SRAM left: -869
------------------------------------------------------------
Allocating the memory for the MKR:

at that point the device just hangs and stops working. That's not what I expect!

since the functionality differs for each board and microcontroller, here are my specs:
the board name is "**Arduino® MKR WiFi 1010**", the microcontroller name is "**SAMD21 Cortex®-M0+ 32bit low power ARM MCU**"

title: Arduino MKR WiFi 1010 memory management

Answers: 1

body:
You are mixing two different ways of memory allocation.

The automatic memory allocation and release you cite works with defined local variables. These variables are allocated on the stack. At the end of their scope, their memory is released. To mimic your example:

```c++
void memory_allocate_test3() {
  Serial.println("memory_allocate_test3 STARTING ");
  display_freeram();
  Serial.println("------------------------------------------------------------");
  Serial.println("Allocating the memory for the MKR: ");
  char memory_usage_test[2000] = "Some content...";
  Serial.println("Allocated memory!");
  display_freeram();
  Serial.println("------------------------------------------------------------");
}
```

But what you use is heap-allocated memory because of the `new` operator. This kind of allocation is under complete responsibility of the programmer, this is you. Since you only allocate and never release, each loop reduces the remaining RAM. Use `delete` (actually `delete[]`) to release:

```c++
void memory_allocate_test2() {
  Serial.println("memory_allocate_test2 STARTING ");
  display_freeram();
  Serial.println("------------------------------------------------------------");
  Serial.println("Allocating the memory for the MKR: ");
  char* memory_usage_test = new char[2000];
  Serial.println("Allocated memory!");
  display_freeram();
  Serial.println("------------------------------------------------------------");
  delete[] memory_usage_test;
}
```

---

**Beware:** There are different allocation methods, `malloc`/`calloc`/`alloca`/`free` and `new`/`delete`. The former method uses functions of the C standard library, the latter method uses keywords of C++.

The pointers returned by the different methods are not compatible. You cannot release memory by `free` that you allocated by `new`. The same holds true for `delete`/`malloc`.

However, you can use both methods in the same program.

Please learn about memory allocation before attempting to use it. C and C++ are error-prone to the unsuspecting user.

As a side note, C and C++ are different languages, even though you can build a mixed program.


body:
    #include<avr/io.h>
    float x, y, z, baf = 0, j, i = 0, k, angle, a, b, c, d;
    unsigned long current_time = 0;
    unsigned long previous_time = 0;
    unsigned long time_interval = 0;
    float gyro_offset_x = 0.0;
    float gyro_offset_y = 0.0;
    float gyro_offset_z = 0.0;

    void i2cinit(void)
    {
      TWSR = 0x00;
      TWBR = 0x14;
      TWCR = (1 << TWEN);
    }

    void i2cstart(void)
    {
      TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
      while (!(TWCR & (1 << TWINT)));
    }

    void i2cwrite( unsigned char data)
    {
      TWDR = data;
      TWCR = (1 << TWINT) | (1 << TWEN);
      while (!(TWCR & (1 << TWINT)));
    }

    unsigned int i2c_receive(unsigned char isLast) {
      if (isLast == 0)
      {
        TWCR |= (1 << TWINT) | (1 << TWEA) | (1 << TWEN);
      }
      else
      {
        TWCR = (1 << TWINT) | (1 << TWEN);
      }
      while (!(TWCR & (1 << TWINT)));
      return TWDR;
    }

    void i2cstop(void)
    {
      TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);

    }

    void mpu6050_init(void) {
      i2cstart();
      i2cwrite(0xD0);
      i2cwrite(0x6B); // PWR_MGMT_1 register
      i2cwrite(0);
      i2cstop();
    }
    void mpu6050f()
    {
      i2cstart();
      i2cwrite(0xD0);
      i2cwrite(0x1B);
      i2cwrite(0x00);// changed here
      i2cstop();
    }
    float mpu6050rbyte(int gyro) {
      i2cstart();
      i2cwrite(0xD0);
      i2cwrite(gyro);
      i2cstart();
      i2cwrite(0xD0 | 0x01);
      float i = i2c_receive(1);
      i2cstop();
      return i;
    }
    float mpu6050_whole_data(int a, int b) {
      int msb = mpu6050rbyte(a);
      int lsb = mpu6050rbyte(b);
      float x_gyro = (msb << 8) | lsb;

      return x_gyro;
    }

    void calibrateGyroOffset() {
      const int numSamples = 100;
      for (k = 0; k < numSamples; k++) {
        gyro_offset_x += mpu6050_whole_data(0x43, 0x44);
        gyro_offset_y += mpu6050_whole_data(0x45, 0x46);
        gyro_offset_z += mpu6050_whole_data(0x47, 0x48);
      }

      gyro_offset_x /= numSamples;
      gyro_offset_y /= numSamples;
      gyro_offset_z /= numSamples;
    }

    float mpu6050angle(float woho, float gyro) {
      float angular_velocity = (woho - gyro) / 131.0;
      previous_time = current_time;
      current_time = millis();
      time_interval = (current_time - previous_time);
      float filter = (0.98 * angular_velocity) + (0.04 * angular_velocity);
      float angle = baf + (filter * time_interval) / 1000.0;
      baf = angle;
      return angle;
    }

    void setup()
    {
      Serial.begin(9600);
      i2cinit();
      mpu6050_init();
      mpu6050f();
      calibrateGyroOffset();
    }
    void loop()
    {
      x = mpu6050_whole_data(0x43, 0x44);
      y = mpu6050_whole_data(0x45, 0x46);
      z = mpu6050_whole_data(0x47, 0x48);
      //  a = mpu6050angle(y, gyro_offset_msb);
      //  b = mpu6050angle(z, gyro_offset_lsb);
      j = mpu6050angle(x, gyro_offset_x);
      c = mpu6050angle(y, gyro_offset_y);
      d = mpu6050angle(z, gyro_offset_z);
      //  mpu6050r(0x43, &x, &y, &z);
      // mpu6050_init();
      //  Serial.print("Offset x");
      //    Serial.print(gyro_offset_x) ;
      //    Serial.print("      ");
      //  Serial.print("Offset y");
      //  Serial.print(y) ;
      //  Serial.print("      ");
      //  //  Serial.print("Offset z");
      //  Serial.print(z) ;
      //  Serial.print("      ");
      Serial.print("Angle x: ");
      Serial.print(j);
      Serial.print("      ");
      Serial.print("Angle y: ");
      Serial.print(c);
      Serial.print("      ");
      Serial.print("Angle z: ");
      Serial.println(d);
    }

title: The code is showing same angles for all three axis in the mpu gyro. can anyone solve it so that it works

Answers: 1

body:
*There may be a number of problems with this code.  I will try to edit this answer as you provide feed back.  The goal is a workable answer.  To be clear, some here may, but it is up to you to fix your code.*

* Dead Reckoning is difficult.  Any errors accumulate over time.  A gyroscope is usually used as part of a sensor fusion with an Accelerometer or Magnetometer. This allows the gyroscope absolute reading to be corrected or reset to mitigate accumulated error. If sensor fusion is not available, then the gyroscope calibration will be very important in mitigating as much drift as possible.

* Constrain the problem to make it simple.  Initially, constrain the gyroscope movements such that only the X axis is rotated.  For example, only rotate the gyroscope on a stable table top. This way, only the X data need be considered / shared as this problem is discussed.

* Consider finding the gyroscope offset as the first step.  The calibration function does not appear to have a time delay as does the normal sampling code. If the calibration function samples the gyroscope as fast as possible, the offsets may be too small or even zero and little use later when applying them to the gyroscope samples.


body:
Totally newbie here. I need to burn 50 blank Attiny13 chips with the following code:

https://github.com/mstratman/relay-bypass/blob/main/relay-bypass/relay-bypass.ino

AFAIK the code can be used by anyone since its license is MIT (https://mas-effects.com/relay.pdf)

What do you think is the easiest and quickest way to burn that code to my chips?

I have a Windows PC, an Arduino Uno, and USBASP, a chip socket, and the 50 chips. Never used arduino before. I do have a MiniPro TL866 programmer which is very easy to use, just upload the bin file, select the chip and click burn... Not sure if it would work with Attiny chips. If there is any hardware that would be easier/quicker to do the job I would buy it though.

Thank you!

title: Burn code to Attiny13/85 the easy way

Answers: 0


body:
In `pgmspace.h`, `PROGMEM` is defined as `__ATTR_PROGMEM__`, which is defined as `__attribute__((__progmem__))`. AFAIK, `__attribute__` is GNU only. Since C++ 11, we have the [attribute specifier sequence](https://en.cppreference.com/w/cpp/language/attributes).

I can't use `[[__progmem__]]` instead of `PROGMEM`. The error is

> warning: '\_\_progmem\_\_' attribute directive ignored [-Wattributes]

Shouldn't that work equally?

Why would I want to do that?

1. **Clarity**: When I first read code that used PROGMEM, I thought that this is the variable name (being a constant, we have a conding guideline that it should be upper case, which matched). Reading on, I found the real variable name, which confused me. Putting it into square brackets would immediately have made clear that it's an attribute and not a name.
2. **Portability**: `[[ ]]` is Standard C++, whereas `__attribute__` is not.

title: Can I use [[__progmem__]] instead of PROGMEM?

Answers: 1

body:
Maybe I should just read the complete documentation...

Under [Standard Attributes](https://en.cppreference.com/w/cpp/language/attributes#Standard_attributes), we see the attributes that come with the C++ Standard. `__progmem__` isn't one of them.

Following the example for syntax 2, I tried `[[gnu::__progmem__]]`, which compiles. So this helps with *Clarity*, but since it now has the `gnu` namespace, it doesn't help with *Portability*.


body:
I want to connect two MPU6050 sensor on Esp32 using the I2C protocol.

ESP32 to MPU6050 connection, I'm using -
```
VCC(ESP32) - VCC(MPU6050_1) - VCC(MPU6050_2)
GND(ESP32) - GND(MPU6050_1) - GND(MPU6050_2)
G21(ESP32) - SDA(MPU6050_1) - SDA(MPU6050_2)
G22(ESP32) - SCL(MPU6050_1) - SCL(MPU6050_2)

3V (ESP32) - AD0 (MPU6050_2)
```
and both the MPU6050 device are also detected by the I2C scanner program
0x68 , 0x69

but when the basic reading program to read for MPU6050 data , one MPU6050 is giving zero value for all accelerate axis and gyro axis.

// Basic demo for accelerometer readings from Adafruit MPU6050

    #include <Adafruit_MPU6050.h>
    #include <Adafruit_Sensor.h>
    #include <Wire.h>

    Adafruit_MPU6050 mpu1;
    Adafruit_MPU6050 mpu2;

    void setup(void) {
      Serial.begin(115200);
      while (!Serial)
        delay(10); // will pause Zero, Leonardo, etc until serial console opens

      Serial.println("Adafruit MPU6050 test!");

      // Try to initialize!
      if (!mpu1.begin(0x68)) {
        Serial.println("Failed to find MPU6050 chip1");
        while (1) {
          delay(10);
        }
      }

      if (!mpu2.begin(0x69)) {
        Serial.println("Failed to find MPU6050 chip2");
        while (1) {
          delay(10);
        }
      }
      Serial.println("MPU6050 Found!");

      mpu1.setAccelerometerRange(MPU6050_RANGE_8_G);

      mpu1.setGyroRange(MPU6050_RANGE_500_DEG);

      mpu1.setFilterBandwidth(MPU6050_BAND_21_HZ);

      mpu2.setAccelerometerRange(MPU6050_RANGE_8_G);

      mpu2.setGyroRange(MPU6050_RANGE_500_DEG);

      mpu2.setFilterBandwidth(MPU6050_BAND_21_HZ);

      Serial.println("");
      delay(100);
    }

    void first() {

      /* Get new sensor events with the readings */
      sensors_event_t a, g, temp;
      mpu1.getEvent(&a, &g, &temp);

      Serial.println("Sensor 1");

      /* Print out the values */
      Serial.print("Acceleration X: ");
      Serial.print(a.acceleration.x);
      Serial.print(", Y: ");
      Serial.print(a.acceleration.y);
      Serial.print(", Z: ");
      Serial.print(a.acceleration.z);
      Serial.println(" m/s^2");

      Serial.print("Rotation X: ");
      Serial.print(g.gyro.x);
      Serial.print(", Y: ");
      Serial.print(g.gyro.y);
      Serial.print(", Z: ");
      Serial.print(g.gyro.z);
      Serial.println(" rad/s");

      Serial.print("Temperature: ");
      Serial.print(temp.temperature);
      Serial.println(" degC");

      Serial.println("");
      delay(500);
    }

    void second() {

      /* Get new sensor events with the readings */
      sensors_event_t a, g, temp;
      mpu2.getEvent(&a, &g, &temp);

      Serial.println("Sensor 2");

      /* Print out the values */
      Serial.print("Acceleration X: ");
      Serial.print(a.acceleration.x);
      Serial.print(", Y: ");
      Serial.print(a.acceleration.y);
      Serial.print(", Z: ");
      Serial.print(a.acceleration.z);
      Serial.println(" m/s^2");

      Serial.print("Rotation X: ");
      Serial.print(g.gyro.x);
      Serial.print(", Y: ");
      Serial.print(g.gyro.y);
      Serial.print(", Z: ");
      Serial.print(g.gyro.z);
      Serial.println(" rad/s");

      Serial.print("Temperature: ");
      Serial.print(temp.temperature);
      Serial.println(" degC");

      Serial.println("");
      delay(500);
    }

    void loop(){

      first();

      delay(1000);

      second();

    }

All connection and config are correct both still MPU6050 sensor two not giving the correct data.

I request you to please check and see, what wrong I'm doing in it.

Serial Monitor -
```
Adafruit MPU6050 test!
MPU6050 Found!

Sensor 1
Acceleration X: -2.18, Y: 1.27, Z: 9.20 m/s^2
Rotation X: 0.23, Y: 8.34, Z: 2.97 rad/s
Temperature: 31.69 degC

Sensor 2
Acceleration X: 0.00, Y: 0.00, Z: 0.00 m/s^2
Rotation X: 0.00, Y: 0.00, Z: 0.00 rad/s
Temperature: 36.53 degC

Sensor 1
Acceleration X: -2.21, Y: 1.29, Z: 9.17 m/s^2
Rotation X: 0.06, Y: 8.29, Z: 2.96 rad/s
Temperature: 31.70 degC

Sensor 2
Acceleration X: 0.00, Y: 0.00, Z: 0.00 m/s^2
Rotation X: 0.00, Y: 0.00, Z: 0.00 rad/s
Temperature: 36.53 degC
```

title: Connecting Multi MPU6050 using I2C on ESP32 Wroom 32D

Answers: 0


body:
We are new to ESP32 and Camera. We are facing issue in getting VSYNC event. We observed that if we change fb_count (frame buffer count) value the VSYNC behavior is changing.
Our understanding is, VSYNC event is received when capture is completed and captured data is available in DMA for processing.
We observed that:
1. If fb_count = 1, it is taking 2 VSYNC events  to raise DMA event.
2. If fb_count = 2, it is taking 1 VSYNC event to raise the DMA event.

We observed same behavior with ESP32 Wrover and ESP32-S3 Wroom.
We  observed this on Oscilloscope.

two queries are there:
1. Can you please help us to understand this behavior?
2. why 2 VSYNC events are required to get DMA interrupt?

title: ESP32 Camera driver VSYNC query

Answers: 0


body:
Please help!

I purchased a [3-inch e-Paper Display from Waveshare](https://www.waveshare.com/product/displays/e-paper/3inch-e-paper-module-g.htm), which appeared to suit my project well. The exemplary little code to show an image was easy to set up and to demonstrate functionality:

```
#include <SPI.h>
#include "epd3in0g.h"
#include "imagedata.h"

Epd epd;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.print("e-Paper init ");
  if (epd.Init() != 0) {
      Serial.print("e-Paper init failed");
      return;
  }

  Serial.print("White \r\n");
  epd.Clear(white);
  delay(2000);

  epd.Init();
  Serial.print("Image \r\n");
  epd.Display(IMAGE_DATA);
  delay(2000);

  epd.Init();
  Serial.print("Small Image \r\n");
  epd.Display_part(IMAGE_DATA, 0 ,0, 168, 400);
  delay(2000);

  epd.Init();
  Serial.print("Clear...\r\n");
  epd.Clear(white);
  delay(2000);

  Serial.print("Goto Sleep...\r\n");
  epd.Sleep();
}

void loop() {

}
```

I will not just have images displayed, I aim for strings with text and numbers and those partial refreshed. Wild guesses if a

```
epd.Display_Text('''Hello World''');
```
might work is pointless. Thus, the existence and usage of possible commands for the *epd.* appears to me not well documented (or I was unable to find something even after a thoroughly search).

I had a look at other examples using GxEPD libraries and it seemed as a good starting point for me.

Within the [GxEPD2 Library](https://github.com/ZinggJM/GxEPD2) it seems a class for 3-inch EPD is missing as it is nowhere declared (I assume there should be something like a *GxEPD_300* to set display dimensions etc.).

So, I reckon I need to wrap up something to meet the specs of the 400x168 pixel display but I don't know where to start.

I tried around with the [GxEPD_MinimumExample.ino](https://github.com/ZinggJM/GxEPD/blob/master/examples/GxEPD_MinimumExample/GxEPD_MinimumExample.ino), like
* replacing the display specific lib with the *epd3in0g.h* from the example
* adjusted the right pins according to the [Waveshare Wiki](https://www.waveshare.com/wiki/3inch_e-Paper_Module_(G)_Manual#Working_With_Arduino)

```
// GxEPD_MinimumExample by Jean-Marc Zingg

#include <GxEPD.h>

// select the display class to use, only one, copy from GxEPD_Example
//#include <GxGDEH0154D67/GxGDEH0154D67.h>  // 1.54" b/w -> from org. example.
#include "epd3in0g.h" //my 3-inch display

#include <GxIO/GxIO_SPI/GxIO_SPI.h>
#include <GxIO/GxIO.h>

// constructor for AVR Arduino, copy from GxEPD_Example else
GxIO_Class io(SPI, /*CS=*/ 10, /*DC=*/ 9, /*RST=*/ 8); // arbitrary selection of 8, 9 selected for default of GxEPD_Class
GxEPD_Class display(io, /*RST=*/ 8, /*BUSY=*/ 7); // default selection of (9), 7

void setup()
{
  display.init();
  display.eraseDisplay();
  // comment out next line to have no or minimal Adafruit_GFX code
  display.drawPaged(drawHelloWorld); // version for AVR using paged drawing, works also on other processors
}

void drawHelloWorld()
{
  display.setTextColor(GxEPD_BLACK);
  display.print("Hello World!");
}

void loop() {};
```

During the verification prior the upload I get errors pointing back to the libs:

```
error: 'GxEPD_Class' does not name a type; did you mean 'GxIO_Class'?*
```
I assume this is because the call to initiate the display is not working.

Thank you for any advice!

title: Get 3-inch e-Paper working on a Nano

Answers: 1

body:
Waveshare examples, by and large, suck. They're usually a bunch of register writes, undocumented. I had to write a [library for an EPD][1] once - OEM version, which later popped up on Waveshare's website as their own - and the OEM's documentation and code were good enough (just...) to produce a functional library.

Looking at the example for your specific screen, I see it is indeed the usual `SendCommand()` crap. Although it seems slightly more evolved, with an `Epd` class. But still, useless.

EPD code is HARD, and requires a lot of information from the manufacturer. And producing a library that handles text is also a little harder to get right.

I don't think trying to transplant their crappy code onto an existing library is going to work. I figure you have two solutions:

 - Rewrite a library for this epaper from scratch.
 - Half-ass something by adding text handling to their code by converting text to pixels in the buffer, and push that.

In both cases, painful.

  [1]: https://github.com/Kongduino/SE0352NQ01_Library


body:
My code is taking values from a remote and transmitting the state of it. Right now the states are just 1 and 0, on or off, and is writing over the serial monitor on the transmitting Arduino. On the receiving RF module I can't seem to get my if statements working right

Transmitter code:

    const char a[] = "1";
    const char b[] = "0";
    void loop() {
    if (Serial.available ( ) > 0)
    {
    char state = Serial.read(); // reading the value from the remote

    if (state >= 0)
    {
    digitalWrite (7, HIGH); //turning LED on transmitting breadboard on to compare to recieving breadboard
    radio.write(&a, sizeof(a)); //tell the other arduino that the value is 1
    }
    if (state < 0)
    {
    digitalWrite(7,LOW);
    radio.write(&b,sizeof(b)); //tell other arduino value is 0
    }
    }

reciever code:

    void loop()
    {
    if (radio.available())
    {
    char state[32] = {0};

    radio.read(&state, sizeof(state));
    Serial.println(state);
    int a = state;
    if (a = 1);
    {
      digitalWrite(7,HIGH);
      Serial.println("do something");
    }
    if (a = 0);
    {
    digitalWrite(7,LOW);
    Serial.println("do nothing");
    }
    }

receiving serial monitor

    1
    do something
    do nothing
    0
    do something
    do nothing
    0
    do something
    do nothing

 and my light stays off on the receiving Arduino, why does it print both statements? A is 1, but it prints the value that's supposed to be printed when a is 0 also, i'm so confused

title: RF24 if statements are not reading properly, even if an "if" value is wrong, it still follows the associated code

Answers: 1

body:
    if (a = 1);
    {
      digitalWrite(7,HIGH);
      Serial.println("do something");
    }

Two major problems here. In C++ you test for equality for `==`, not `=`.

Second, putting the semicolon after the `if` terminates the scope of the `if`.

That should read:

    if (a == 1)
    {
      digitalWrite(7,HIGH);
      Serial.println("do something");
    }

---

    char state[32] = {0};

    radio.read(&state, sizeof(state));
    Serial.println(state);
    int a = state;

`state` is an array. If you assign that to `a` you will get the same array, in another variable. That array will not be zero or one.

Maybe you mean:

    int a = state [0];


body:
When trying to upload my firmware to an ESP8266 board using Arduino IDE 2.2.1 I get
```
A fatal esptool.py error occurred: Cannot configure port, something went wrong. Original message: PermissionError(13, 'A device attached to the system is not functioning.', None, 31)
```
All of my research says that this is a CH340 driver problem, this is not the case. I did try reinstalling the driver. I use Termite as a Serial Monitor which communicates with my ESP8266 just fine. I can use the Arduino Web Editor and upload to the serial port through the Arduino Create with no issue, this has to be an Arduino specific issue are there any fixes for this?

title: esptool.py error Cannot configure port, something went wrong. PermissionError(13, 'A device attached to the system is not functioning.', None, 31)

Answers: 0


body:
I made a simple music program using an arduino Uno and the `tone()` function. It works fine.

I decided to build my own circuit using a barebones AVR and upload that program.
I did not know exactly what frequency was being used by the arduino, so I used a Murata resonator, with a frequency of 8 MHz.

When I put my circuit to the test, the music that I had generated was played an octave lower, and its duration was doubled (taking twice the time to finish played a note).

I figured out that I used the wrong resonator frequency. Indeed, I found out that the Arduino Uno used a 16 MHz resonator.
Since I had half that frequency in my clock, the tone would be lower frequency, and it would take twice the time to finish a note. This made sense.

So I went ahead and rebuilt the circuit with a 16 MHz resonator frequency.
However, now I have the opposite effect!

All the notes are one octave higher compared to my original Arduino Uno design, and the note duration finished in hald the time compared to the original Arduino Uno design...
This suggests that I now have doubled the frequency compared to the original design (and four times the frequency compared to my first custum circuit attempt).

I cannot seem to understand why this is happening, because right now I have the frequency that the original Arduino uses....

title: Frequency problems with DIY arduino and resonator

Answers: 1

body:
If the code runs at twice at the expected speed when clocked at
16 MHz, this can only be because either:

* you fixed the program to run correctly when clocked at 8 MHz
* you told the IDE that you are using a 8 MHz clock.

The IDE comes with a few configurations that are suitable for an
8 MHz clock. If you select as a board “Arduino Pro or Pro Mini”,
you have something equivalent to an Arduino Uno, except that you can
choose between an 8 MHz clock and a 16 MHz clock (and also
between an ATmega168 and a 328P).


body:
I try to upload Adafruit's example sketch (Wemos mini 8266 + Lolin TFT-2.4" touch screen).
When complied and uploaded via Arduino IDE v1.8.19, sketch runs OK (including TFT), but when uploading via platformIO, exact same sketch (with no compilation errors), screen stays "white" (uninitialized). Placing a `Serial.println(millis());` in `loop` shows that MCU is running OK.

I even verified and took the same Arduino's IDE lib's version and updated `platformIO.ini` file.

EXAMPLE CODE:

    /***************************************************

    1. !!!Make sure you using lastest ESP8266 core for Arduino, otherwise it may not work properly.
      https://github.com/esp8266/Arduino

      (The pin D0(GPIO16) will be not work when you use older version ESP8266 core for Arduino,
      because the older version ESP8266 core for Arduino's digitalPinToBitMask(), portOutputRegister(),
      portInputRegister() and portModeRegister() fuction have some bugs which Adafruit_ILI9341 Library will use.
      This bug was fixed after commit:  https://github.com/esp8266/Arduino/commit/799193888a553de8876052019842538396f92194 )

    2. Setup latest Adafruit_GFX, Adafruit_ILI9341 and XPT2046_Touchscreen Library first:

        https://github.com/adafruit/Adafruit-GFX-Library

        https://github.com/adafruit/Adafruit_ILI9341

        https://github.com/PaulStoffregen/XPT2046_Touchscreen

    ****************************************************/
    #include <Arduino.h>
    #include <SPI.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_ILI9341.h>
    #include <XPT2046_Touchscreen.h>

    #define TFT_CS D0  //for D1 mini or TFT I2C Connector Shield (V1.1.0 or later)
    #define TFT_DC D8  //for D1 mini or TFT I2C Connector Shield (V1.1.0 or later)
    #define TFT_RST -1 //for D1 mini or TFT I2C Connector Shield (V1.1.0 or later)
    #define TS_CS D3   //for D1 mini or TFT I2C Connector Shield (V1.1.0 or later)

    // #define TFT_CS 14  //for D32 Pro
    // #define TFT_DC 27  //for D32 Pro
    // #define TFT_RST 33 //for D32 Pro
    // #define TS_CS  12 //for D32 Pro

    Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
    XPT2046_Touchscreen ts(TS_CS);

    void setup()
    {
      Serial.begin(115200);
      ts.begin();
      ts.setRotation(1);

      tft.begin();
      tft.setRotation(3);
      tft.fillScreen(ILI9341_BLACK);
      tft.setTextColor(ILI9341_WHITE);
      tft.setTextSize(3);
      tft.println("Touch Test");

      while (!Serial && (millis() <= 1000))
        ;
    }

    void loop()
    {
      if (ts.touched())
      {
        TS_Point p = ts.getPoint();

        tft.fillScreen(ILI9341_BLACK);
        tft.setCursor(0, 0);

        tft.print("Pressure = ");
        tft.println(p.z);
        tft.print("X = ");
        tft.println(p.x);
        tft.print("Y = ");
        tft.println(p.y);
      }
    }

`platformIO.ini`:

    ; PlatformIO Project Configuration File
    ;
    ;   Build options: build flags, source filter
    ;   Upload options: custom upload port, speed and extra flags
    ;   Library options: dependencies, extra library storages
    ;   Advanced options: extra scripting
    ;
    ; Please visit documentation for the other options and examples
    ; https://docs.platformio.org/page/projectconf.html

    [env:d1]
    platform = espressif8266
    board = d1
    framework = arduino
    lib_deps =
     adafruit/Adafruit GFX Library@1.11.5
     adafruit/Adafruit ILI9341@1.5.12
     paulstoffregen/XPT2046_Touchscreen

title: Sketch does not run right when uploaded via Arduino IDE vs PlatfomIO

Answers: 0


body:
**The Project:**

I want to measure orientation of the MPU-6050 in z-axis for a mobile robot powered with the Arduino Mega 2560, so I need an accurate and reliable rotation measurement for the robot's movement.

I decided to use the gyroscope feature of the MPU-6050 sensor to measure orientation of its z-axis, by using its rotational velocity measurements.

I got the readings from Adafruit's MPU6050 library because it measures gyroscope using rad/s instead of raw data, so I can use the readings easily.

**The Implementation:**

I would really like to provide the source code with this question, but unfortunately while i'm writing this, I cannot get acces to the source code, and I will provide it as soon as I get access to it.

My implementation is, I used the z-axis velocity by dividing the current reading by 100 to get velocity per 10ms, then run a 10ms delay, and after that I add and assign the value to a variable (the += operator). And I run that in a loop.

The code might look something like this:

    float currentReading;
    float orientation = 0;

    void loop() {

        g = doMpuReadings();
        currentReading = g.gyro.z / 100;

        delay(10);

        orientation += currentReading;
     }

For those who might wonder why I delayed the code by 10ms is to wait the sensor to travel a distance before defining its orientation.

The code worked quite like how I expected it to work. When I rotate it at some point, the orientation value adds, and when I rotate it back to its initial value, the orientation value goes back to near zero, and the values are pretty consistent.

**The Issue:**

But if I hold the sensor and rotate it by its center, it doesn't read 2 Pi or 6.28 rad, but it reads around 2 rad instead regardless of how fast or slow I rotate the sensor. When it is attached to the robot in which it doesn't rotate by its center, it reads around 5 rad. So like, the bigger circle it travels means more radians and vice versa?

Is that how it supposed to work?

Any possibilities to consistently measure 6.28 rad in a full rotation regardless of the pivot point?

title: Measuring 2 Pi radians in a full rotation of MPU-6050, regardless of the pivot point

Answers: 0


body:
I have designed a test board to understand ESP32-S3 working pins. I am using USB interface D+, D- for programing so Serial0 is free to use.

This is my test circuit for testing an RS485 converter. For the test, I am using an MD02 temperature and humidity sensor. Also for the converter I am using [this module][1]

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

This code is not working on Serial0 despite Rx and Tx LEDs are blinking on the RS485 converter.

    #include <HardwareSerial.h>

    void setup() {
      // put your setup code here, to run once:
      Serial0.begin(9600, SERIAL_8N2, 44, 43);
      Serial.begin(115200);
    }

    void loop() {
      Serial0.write("READ");
      delay(3000);
      Serial.print("Temp ve NEM: ");
      while (Serial0.available() > 0) {
        Serial.print(char(Serial0.read()));
      }
      Serial.println(".");
    }

This is working

    #include <HardwareSerial.h>

    void setup() {
      // put your setup code here, to run once:
      Serial1.begin(9600, SERIAL_8N2, 18, 17);
      Serial.begin(115200);
    }

    void loop() {
      Serial1.write("READ");
      delay(3000);
      Serial.print("Temp ve NEM: ");
      while (Serial1.available() > 0) {
        Serial.print(char(Serial1.read()));
      }
      Serial.println(".");
    }

**What should I do differently for Serial0 and RS485?,** because the 6M NEO GPS module is working properly on Serial0.

  [1]: https://www.robotistan.com/rs485-ttl-uart-donusturucu-1
  [2]: https://i.stack.imgur.com/Fp8iQ.jpg

title: ESP32 S3 Same code works on Serial1 but NOT on Serial0 for RS485 module

Answers: 0


body:
Glenn from Sweden here. I was wondering if some kind soul could help me out here.

My partner bought a cheap chinese knock-off automatic chicken coop door that operates based on sunlight. [Link to the actual chicken coop door][1] In the morning the door opens and at the evening the door closes. It does this (from my humble understanding) with a  LDR, a 5v dc motor and a small circuit board. The main problem is that the door opens way to early (about 07:00 am) with the risk that predators may snatch the chickens and there is no way to regulate the opening/closing times.

What I would like is the following:
I would like the door to open at 10:00am and close at 21:00pm every day of the week using the existing 5v motor. I do have some 28BYJ-48 step motors and A3967 driver boards I bought 10+ years ago, but then I would have to start modify physical things to get it to fit. I rather not do that if it’s possible to use the original parts.

Now, coding is way over my head. Some people can draw beautiful things with paints and brushes, others can not. I can get some LED's to flash but I just can’t wrap my head around ”advanced” coding like this project. That is why I, out of desperation, tried to get Bing A.I. to write the code for me. **I can compile the code without any errors, but it doesn’t work IRL. The motor does not start at the specified time, and sometimes the motor starts to spin out of the blue but doesn’t stop spinning.** I have installed ”Time (1.6.1) by Michael Margolis” in the Arduino Library Manager to get the timer function to work. Is that the problem?

I must mention here that the three leads from the SN754410 originally was routed to pins 7,8,9 on the Arduino, but since it didn't work I tried switching them to 3,5,6 in case it had something to do with the analog output?

With the original electronics the door opens and closes mechanical fine, but I don’t understand how the ”brain” knows when to stop the motor so it doesn’t start to crunch the gear on the motor. There are no microswitches at the end points or anything…

I added the red and green LED's (got Bing to include them in the code) just to be able to see when the door opens/closes if dark outside).

I understand a Fritzing layout is preferable so I did my best to create one. Its my first time so please bear that in mind.

[![ritzing circuit layout][2]][2]

[![Chicken coop door][3]][3]

```

    // Include the Time library
#include <TimeLib.h>

// Define the pins for the motor controller
#define ENA 6
#define IN1 5
#define IN2 3

// Define the pins for the LEDs
#define GREEN_LED 10
#define RED_LED 11

// Define the times for the motor actions
#define START_TIME 1825 // 10:25 AM in 24-hour format
#define END_TIME 1925 // 21:25 PM in 24-hour format
#define DURATION 20 // 20 seconds

// Define a variable to store the current time
int currentTime;

// Define a variable to store the motor state
int motorState;

// Define the motor states
#define STOPPED 0
#define CLOCKWISE 1
#define COUNTERCLOCKWISE 2

void setup() {

  setSyncProvider(getTime);

  // Set the motor pins as outputs
  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);

  // Set the LED pins as outputs
  pinMode(GREEN_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);

  // Stop the motor and turn off the LEDs initially
  stopMotor();
  turnOffLEDs();

  // Set the time to sync with the computer's time
  setTime(17,27,10,7,10,2023); // hour,minute,second,day,month,year
}

void loop() {
  // Get the current time in HHMM format
  currentTime = hour() * 100 + minute();

  // Check if the current time matches the start time or the end time
  if (currentTime == START_TIME || currentTime == END_TIME) {
    // Check the motor state and switch it accordingly
    switch (motorState) {
      case STOPPED:
        // Start the motor clockwise and turn on the green LED
        startMotor(CLOCKWISE);
        turnOnLED(GREEN_LED);
        break;
      case CLOCKWISE:
        // Stop the motor and start it counterclockwise after DURATION seconds and switch the LEDs accordingly
        stopMotor();
        turnOffLED(GREEN_LED);
        delay(DURATION * 1000);
        startMotor(COUNTERCLOCKWISE);
        turnOnLED(RED_LED);
        break;
      case COUNTERCLOCKWISE:
        // Stop the motor and start it clockwise after DURATION seconds and switch the LEDs accordingly
        stopMotor();
        turnOffLED(RED_LED);
        delay(DURATION * 1000);
        startMotor(CLOCKWISE);
        turnOnLED(GREEN_LED);
        break;
    }
  }
}

// A function to stop the motor
void stopMotor() {
  // Set the enable pin to low
  digitalWrite(ENA, LOW);

  // Set the motor state to stopped
  motorState = STOPPED;
}

// A function to start the motor in a given direction
void startMotor(int direction) {
  // Set the enable pin to high
  digitalWrite(ENA, HIGH);

  // Set the input pins according to the direction
  if (direction == CLOCKWISE) {
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    motorState = CLOCKWISE;
  }
  else if (direction == COUNTERCLOCKWISE) {
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    motorState = COUNTERCLOCKWISE;
  }
}

// A function to turn on a given LED pin
void turnOnLED(int ledPin) {
  // Set the LED pin to high
  digitalWrite(ledPin, HIGH);
}

// A function to turn off a given LED pin
void turnOffLED(int ledPin) {
  // Set the LED pin to low
  digitalWrite(ledPin, LOW);
}

// A function to turn off both LEDs
void turnOffLEDs() {
  // Turn off both LED pins
  turnOffLED(GREEN_LED);
  turnOffLED(RED_LED);
}
  // A function that gets the time from the computer
time_t getTime() {
  // Check if there is serial data available
  if (Serial.available()) {
    // Read the serial data and convert it to a time_t value
    time_t t = Serial.parseInt();
    // Return the time value if it is valid
    if (t >= 946684800) { // Check if the value is after 1 Jan 2000
      return t;
    }
  }
  // Return a zero value if there is no valid time
  return 0;
}

```

  [1]: https://www.amazon.se/dp/B0C18STKD6?psc=1&ref=ppx_yo2ov_dt_b_product_details
  [2]: https://i.stack.imgur.com/05Acn.jpg
  [3]: https://i.stack.imgur.com/mJeM9.jpg

title: Problem with Bing generated code for automated chicken coop door

Answers: 1

body:
Using generative AI is only really helpful, if you have enough knowledge to work further with the generated code. Current LLMs are not as plug and play as many believe them to be.

Timemages idea of covering the LDR with an LED in your control seems very reasonable. Then you don't need to hassle with the motors. Try taping one if your LEDs to the sensor and use a blink code to test that. You might need a brighter LED, depending on the LDR. Just make sure to use a transistor in low side switch configuration, if the needed current for the LED is greater than 20mA, which is the maximum continous current for a digital output pin (small bipolar transistors are very cheap; you will find much information online when searching for something like arduino transistor low side switch).

Then about the time keeping: The Arduino itself is not good at keeping time accurately over a longer span. Due to manufacturing differences and temperature clock drift your time will be very much off after some days. For this you need a RTC (Real Time Clock). It has a very precise internal clock, so it can keep time accurately over long timestamps. You can buy ready to use RTC modules which also include a battery backup, so that the clock doesn't loose time on powerloss. Often these modules are build with the DS3231. There are also libraries for this RTC, for example [this one][1]. Look at the provided alarm example, because that is what you want (code triggering on specific times of the day). Use that example as starting point and make the LED turn on and off at these alarms. That are only small changes to the existing example code.

  [1]: https://github.com/jarzebski/Arduino-DS3231/tree/dev


body:
I have this pressure transducer:
https://www.amazon.co.uk/dp/B07YZL6TYD?psc=1&ref=ppx_yo2ov_dt_b_product_details

The transducer has a range of 0.5v to 4.5v which translates to 0 psi to 100 psi.

When I hook the transducer up to a Arduino boards analog pin, whose range is between 0 to 1024, it returns about 520 at 0 psi.

When I measure with a meter, it reads 2.4v which i think should not measure that much.

What am I doing wrong?

title: Pressure transducer returns 2.4v at 0 psi when working with a 0.5v to 4.5v pressure transducer

Answers: 2

body:
Is the pressure sensor measuring relative pressure or absolute pressure?

Assuming the pressure sensor is measuring absolute pressure:

 - 1 atmosphere is about 14 pounds per square inch (PSI).
 - Altitude and weather change that so it is unreliable / not-constant.
   But for many uses it is close enough.
 - (14/100 PSI * (4.5V - 0.4V)) + 0.4V = 0.546V + 0.4V = 0.946V

The expected voltage given the parameters in the question, assuming this is an absolute pressure sensor and that it has a linear response, should be near 1 Volt.  But it is over double that.  Consider checking the supply voltage to the sensor.  Also consider disconnecting the output of the sensor from the Arduino board and repeating the voltage measurement. Finally, make sure the above assumptions are accurate.

body:
I would expect your pressure transducer has an initial offset voltage, typically 0.5V, it states Output: 0.5 - 4.5 V / 0 - 5 V. I would also expect the output to be about 4.5V at full pressure but this is only a SWAG as there is no data sheet available. It might have been a good price but was it worth all of the time it is taking you to determine if it is OK? Are the meter readings correct, I cannot determine that unless I know what type of output the transducer has. Is it actually analog, does it need a pull up resistor, output loading requirement, ???

If you cannot get the information from the vendor I think the only way you will really know is to connect several up and test them. There are several types of pressure transducers in this package, they are absolute (atmospheric pressure) and Gauge (PSIG) (Pounds Per Square Inch). The nice looking advertisement on your link does not give this or much other needed information such as what media is it compatible with other then a few.


body:
I am working with STM32G491RE.I am giving pulse to GPIO pin from function generator. That pulse will be 2 msec on time and 8msec off time.I need to make flag high if the signal from function generator lost.
Can anyone suggest me how to do this?

    void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
    {
    if(GPIO_Pin==detect_Pin){
    if(HAL_GPIO_ReadPin(detect_GPIO_Port,detect_Pin)==GPIO_PIN_SET){
     HAL_UART_Transmit(&huart2, (uint8_t *)"rising:",7, HAL_MAX_DELAY);
     }
    else if(HAL_GPIO_ReadPin(detect_GPIO_Port,detect_Pin)==GPIO_PIN_RESET){
     HAL_UART_Transmit(&huart2, (uint8_t *)"falling:",8, HAL_MAX_DELAY);
     }
    else
    {
     HAL_GPIO_WritePin(led_GPIO_Port,led_Pin,GPIO_PIN_SET);
    }

 I tried with EXTI interrupt but If input is there from generator its detecting both rising and falling edge and if there is no signal from generator I am not getting  in to else condition.

[![img: pulse input from function generator.][1]][1]

1.If I want to make flag high for no signal from function generator,above image offtime also it considering as no signal.

can anyone suggest how to do?

Thanks

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

title: Rising and falling edge on GPIO_STM32G4

Answers: 1

body:
I do not know how to use the HAL API you are using. I will instead
suggest an approach based on the Arduino API, which is more suitable for
this site.

Take note of the current time on every transition you detect. When the
time since the last detected transition is longer than a predefined
timeout, you know the pulse train has stopped:

```c++
const uint8_t pulse_pin = 2;
const uint32_t pulse_timeout = 10;  // milliseconds

volatile uint32_t last_input_change;  // last time we detected a change

void on_input_change()
{
    last_input_change = millis();
}

void setup() {
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(pulse_pin),
            on_input_change, CHANGE);
}

void loop() {
    // Avoid a data race while reading last_input_change.
    noInterrupts();
    uint32_t last_input_change_copy = last_input_change;
    interrupts();

    if (millis() - last_input_change_copy >= pulse_timeout)
        Serial.println("The pulse train stopped.");
}
```

Note that, for this to work, your whole code should be non-blocking,
which is a good practice in any case.