text:
Connecting multiple ultrasonic sensors(hc-sr04) to a single arduino board.(mega)
I am currently working on an alarm system using multiple sensors and one arduino board and I am getting readings from 2 of the sensors but one gives a constant zero and a constant buzzer sound even without sensing the distance...I have followed the schematics of the original project but nothing works. Here is the code

int ledred1 = 2;
int ledgreen1 = 3;
int ledorange1 = 4;
int ledred2 = 5;
int ledgreen2 = 6;
int ledorange2 = 7;
int ledred3 = 8;
int ledgreen3 = 9;
int ledorange3 = 10;

int sound = 250;

int trigPin1 = 11;
int echoPin1 = 12;

int trigPin2 = 13;
int echoPin2 = 30;

int trigPin3 = 31;
int echoPin3 = 32;

#define buzzer1 33
#define buzzer2 34
#define buzzer3 35

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);

  pinMode(ledred1, OUTPUT);
  pinMode(ledred2, OUTPUT);
  pinMode(ledorange1, OUTPUT);
  pinMode(ledgreen1, OUTPUT);
  pinMode(ledgreen2, OUTPUT);
  pinMode(ledred3, OUTPUT);
  pinMode(ledgreen3, OUTPUT);
  pinMode(ledorange2, OUTPUT);
  pinMode(ledorange3, OUTPUT);

}
void firstsensor(){ // This function is for first sensor.
  int duration1, distance1;
  digitalWrite (trigPin1, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin1, LOW);
  duration1 = pulseIn (echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

      Serial.print("1st Sensor: ");
      Serial.print(distance1);
      Serial.print("cm    ");

  if (distance1 <=200 && distance1>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,HIGH);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance1 <100&& distance1>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,HIGH);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance1 <50&& distance1>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, HIGH);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance1>200 || distance1<0){
    Serial.println("Out of Range");
    noTone(buzzer1);
  }
  else{
    Serial.print(distance1);
    Serial.println("cm");
    tone(buzzer1,sound);

  }
}
void secondsensor(){ // This function is for second sensor.
    int duration2, distance2;
    digitalWrite (trigPin2, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin2, LOW);
    duration2 = pulseIn (echoPin2, HIGH);
    distance2 = (duration2/2) / 29.1;

      Serial.print("2nd Sensor: ");
      Serial.print(distance2);
      Serial.print("cm    ");

     if (distance2 <=200&& distance2>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, HIGH);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance2 <100&& distance2>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,HIGH);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance2 <50&& distance2>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, HIGH);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance2>200 || distance2<0){
    Serial.println("Out of Range");
    noTone(buzzer2);
  }
  else{
    Serial.print(distance2);
    Serial.println("cm");
    tone(buzzer2,sound);

  }
}
void thirdsensor(){ // This function is for third sensor.
    int duration3, distance3;
    digitalWrite (trigPin3, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin3, LOW);
    duration3 = pulseIn (echoPin3, HIGH);
    distance3 = (duration3/2) / 29.1;

      Serial.print("3rd Sensor: ");
      Serial.print(distance3);
      Serial.print("cm");

     if (distance3 <=200&& distance3>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, HIGH);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance3 <100&& distance3>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,HIGH);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance3 <50&& distance3>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance3>200 || distance3<0){
    Serial.println("Out of Range");
    noTone(buzzer3);
  }
  else{
    Serial.print(distance3);
    Serial.println("cm");
    tone(buzzer3,sound);

  }
}

void loop() {
Serial.println("\n");
firstsensor();
delay(100);
secondsensor();
delay(100);
thirdsensor();
delay(100);
}

This is what I get in the serial monitor
This is the snapshot of the pin configuration

Did you try exchanging the first module with one of the others? Tripple-check all your connections? Test it out with a simple example sketch all on its own?

I would suggest that you want to really simplify your program by making a single function that can take parameters to work with different pin combinations rather than duplicating code like that.

please review your code line by line and learn what each line does .... it appears that you have not thought about program flow at all .... i am saying this because your sensor1 code manipulates led2 and led3 ... same with sensor2 and sensor3 ... also the distance checking code turns off leds that were previously turned on .... you cannot just copy and paste code without being aware of what it does

@Mat I have rebuilt the connections and tested using a simple sketch..It works.. I guess the problem is with the code

@Majenko I am currently trying to simplify the code

@jsotola Rookie mistake:( I am kindly requesting for your help in going through the lines with me since I am new to all this

This is NOT an answer to the question, but I did some (major) refactoring which make it much more clear what is happening.
I think you made some mistake within the (refactored) method Sensor::UpdateState.
File <.ino>:
#include "Sensors.h"

Sensors _sensors;

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

void loop()
{
  _sensors.Process();
}

File Sensors.h:
#ifndef SENSORS_H
#define SENSORS_H

#include "Arduino.h"
#include "Sensor.h"

class Sensors
{
  public:
    Sensors();

    void Init();
    void Process();

  private:
    static const int NR_OF_SENSORS = 3;

    Sensor _sensors[NR_OF_SENSORS];
};

#endif // SENSORS_H

File Sensors.cpp:
#include "Sensors.h"

Sensors::Sensors()
:
  //              index trigPin echoPin redLed orangeLed greenLed buzzer)
  _sensors( { Sensor(1 ,  11   ,  12   ,  2       3     ,   4    ,  33),
              Sensor(2 ,  13   ,  30   ,  5       6     ,   7    ,  34),
              Sensor(3 ,  31   ,  32   ,  8       9     ,   10   ,  35) })
{
}

void Sensors::Init()
{
  for (uint8_t index = 0; index < NR_OF_SENSORS; index++)
  {
    _sensors[index].Init();
  }
}

void Sensors::Process()
{
  for (uint8_t index = 0; index < NR_OF_SENSORS; index++)
  {
    _sensors[index].Process();
  }
}

File Sensor.h:
#ifndef SENSOR_H
#define SENSOR_H

#include "Arduino.h"

class Sensor
{
  public:
    enum EState
    {
      LOW_OUT_OF_RANGE,
      WAY_TOO_CLOSE,
      TOO_CLOSE,
      OK,
      HIGH_OUT_OF_RANGE
    };

    Sensor(uint8_t index, uint8_t trigPin, uint8_t echoPin, uint8_t redLed, uint8_t orangeLed, uint8_t greenLed, uint8_t buzzer);

    uint8_t Index    (void) { return _index;     };
    uint8_t TrigPin  (void) { return _trigPin;   };
    uint8_t EchoPin  (void) { return _echoPin;   };
    uint8_t RedLed   (void) { return _redLed;    };
    uint8_t OrangeLed(void) { return _orangeLed; };
    uint8_t GreenLed (void) { return _greenLed;  };
    uint8_t Buzzer   (void) { return _buzzer;    };

    void Init();
    void Process();

  private:
    uint8_t _index;
    uint8_t _trigPin;
    uint8_t _echoPin;
    uint8_t _redLed;
    uint8_t _orangeLed;
    uint8_t _greenLed;
    uint8_t _buzzer;
    EState _state;
    uint8_t _distance;

    void Measure();
    void UpdateState();
    void ProcessState();
    void Show(uint16_t sound, uint8_t led);
    void PrintDistance(void);
};

#endif // SENSOR_H

File Sensor.cpp:
#include "Sensor.h"

Sensor::Sensor(uint8_t index, uint8_t trigPin, uint8_t echoPin, uint8_t redLed, uint8_t orangeLed, uint8_t greenLed, uint8_t buzzer)
:
  _index(index),
  _trigPin(trigPin),
  _echoPin(echoPin),
  _redLed(redLed),
  _orangeLed(orangeLed),
  _greenLed(greenLed),
  _buzzer(buzzer),
  _state(OK),
  _distance(0)
{
}

void Sensor::Init()
{
  pinMode(TrigPin()  , OUTPUT);
  pinMode(EchoPin()  , INPUT);
  pinMode(RedLed()   , OUTPUT);
  pinMode(OrangeLed(), OUTPUT);
  pinMode(GreenLed() , OUTPUT);
}

void Sensor::Process()
{
  Measure();
  UpdateState();
  ProcessState();
  PrintDistance();
  delay(100);
}

void Sensor::Measure()
{
  digitalWrite(TrigPin(), HIGH);
  delayMicroseconds (10);
  digitalWrite(TrigPin(), LOW);
  uint16_t duration = pulseIn (EchoPin(), HIGH);
  _distance = (duration / 2) / 29.1;
}

void Sensor::UpdateState()
{
  if (_distance < 0)
  {
    _state = LOW_OUT_OF_RANGE;
  }
  else if (_distance <= 50)
  {
    _state = WAY_TOO_CLOSE;
  }
  else if (_distance <= 100)
  {
    _state = TOO_CLOSE;
  }
  else if (_distance <= 200)
  {
    _state = OK;
  }
  else
  {
    _state = HIGH_OUT_OF_RANGE;
  }
}

void Sensor::ProcessState()
{
  digitalWrite(RedLed(), LOW);
  digitalWrite(OrangeLed(), LOW);
  digitalWrite(GreenLed(), LOW);

  switch (_state)
  {
  case LOW_OUT_OF_RANGE:
    noTone(Buzzer());
    break;

  case WAY_TOO_CLOSE:
    Show(300, RedLed());
    break;

  case TOO_CLOSE:
    Show(275, OrangeLed());
    break;

  case OK:
    Show(250, GreenLed());
    break;

  case HIGH_OUT_OF_RANGE:
    noTone(Buzzer());    break;
    break;

  default:
    // Error
    break;
  }
}

void Sensor::Show(uint16_t sound, uint8_t led)
{
  tone(Buzzer(), sound);
  digitalWrite(led, HIGH);
}

void Sensor::PrintDistance()
{
  Serial.print("Sensor ");
  Serial.print(Index());
  Serial.print(": ");
  Serial.print(_distance);
  Serial.print("cm    ");

  if ((_state == LOW_OUT_OF_RANGE) || (_state == HIGH_OUT_OF_RANGE))
  {
    Serial.print(" (Out of range)");
  }

  Serial.println("");
}

Thank you for this..i am going through it to see how I can model the code to suit the one I have written


text:
Error compiling for board NodeMCU 1.0 (ESP-12E Module)
I am trying to connect MFRC522 using nodeMCU and send a simple code to scan the tags but the IDE brings the following error:
Multiple libraries were found for "MFRC522.h"
 Used: /home/georgewayne/snap/arduino/current/Arduino/libraries/MFRC522
 Not used: /home/georgewayne/snap/arduino/current/Arduino/libraries/rfid-master
 Not used: /home/georgewayne/snap/arduino/current/Arduino/libraries/MFRC522-spi-i2c-uart-async
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

What do I do to rectify this error?

This mate over here seems to fix his bug by just reviewing his code: https://forum.arduino.cc/index.php?topic=660724.0
But, apparently there is a bug in the ArduinoIDE. Try to use Platform.IO(platformio.org/), it has a "better" debugger, (it's a little bit hard to install tho), this may help you.

More complete output may help.  If you haven't already, turn on verbose for compiling in File/Preferences.   In and of itself, the Multiple libraries were found thing is not an error.  It's just warning you that it found multiple and telling you which one it chose.  If it chose the wrong one, then that might result in an actual compiler error that isn't shown.

source: Stack Exchange

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

sort: votes


text:
Stepper motor driver not working properly
I have a problem. I am following this guide about controlling a NEMA 17 stepper motor: https://www.makerguides.com/a4988-stepper-motor-driver-arduino-tutorial/
I uploaded the code to my arduino uno and powered on everything, but the stepper motor doesn't rotate, except when I put my finger on the metal screw of the a4988 driver. The arduino is powered by a 5v 1A adapter and the a4988 driver is powered with a 12v 2amp adapter.
What is causing this?

have you connected all the grounds?

The "metal screw" is a "trim potentiometer" that is used to set the current used to drive the motor. It sounds like you may be altering the current when you push against it. Try turning it to different angles to see what effect that has on the motor.
Alternatively if it only ever works when you push on it then it could be that you have a faulty potentiometer on your board.

Despite not being able to take it out of the circuit, it is probably safe for you to put a meter across the pot while the board is unpowered.  Certainly worth a try if you get the point of feeling that you need to throw one out.  You can fiddle with it and see if you can notice what Majenko mentions, understanding the results may be skewed by being in circuit. Admittedly, it may be game of twister to get your probes in the right place and manipulate the trimpot the way you want.

Could also be a cracked solder joint connecting the pot to the board. If that's what it is, it could be fixed by heating up the bad solder joint(s) and applying more rosin-core electronics solder to them.

The stepper driver is broken. Bought a new one and everything is working now! But I had to trim the potentiometer indeed!

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


text:
Set acceleration for stepper motor with no ending
I have a problem. I am using a stepper motor with 2 buttons. In my code I am trying to rotate the stepper motor clockwise while holding button1 and counter-clockwise while holding button2. To do that, I had the following code:
#include <AccelStepper.h>

// Define button pins
#define btnLowerPin 5
#define btnRaisePin 6

// Define stepper motor connections and motor interface type.
#define dirPin 2
#define stepPin 3

int btnLowerState = 0;
int btnRaiseState = 0;

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(AccelStepper::DRIVER, stepPin, dirPin);

void setup() {
  // initialize the button pins as an input:
  pinMode(btnLowerPin, INPUT);
  pinMode(btnRaisePin, INPUT);

  // Set the maximum speed in steps per second:
  stepper.setMaxSpeed(1000);
}
void loop() {
  // read the state of the button values:
  btnLowerState = digitalRead(btnLowerPin);
  btnRaiseState = digitalRead(btnRaisePin);

  if (btnLowerState == LOW) {
    stepper.setSpeed(-1000);
    stepper.runSpeed();
  }
  else if (btnRaiseState == LOW) {
    stepper.setSpeed(1000);
    stepper.runSpeed();
  }
  else {
    stepper.setSpeed(0);
    stepper.runSpeed();
  }
}

This code worked, but I have to accelerate the motor to the speed of 1000. I found this article that explains how to do that: https://www.makerguides.com/28byj-48-stepper-motor-arduino-tutorial/. In code #3 they use the following code:
void setup() {
  // Set the maximum steps per second:
  stepper.setMaxSpeed(1000);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(200);
}
void loop() {
  stepper.moveTo(8192);
  stepper.runToPosition();

  delay(1000);

  stepper.moveTo(0);
  stepper.runToPosition();

  delay(1000);
}

Now I tried combining it, but the problem is that I don't know how far the motor has to rotate, because its While holding the button. Here was my code:
void loop() {
  // read the state of the button values:
  btnLowerState = digitalRead(btnLowerPin);
  btnRaiseState = digitalRead(btnRaisePin);

  if (btnLowerState == LOW) {
    stepper.moveTo(8000);
    stepper.runToPosition();
  }
  else if (btnRaiseState == LOW) {
    stepper.moveTo(0);
    stepper.runToPosition();
  }
  else {
    stepper.setSpeed(0);
    stepper.runSpeed();
  }
}

But this code stops when the loop is over and restarts the acceleration. How can I fix this?
So in short:

The motor needs to accelerate when you start holding the button.
The acceleration has to be 300 and max speed 1000.
When you release the button it decelerates to 0.

I think you should be able to use move() instead of moveTo()


text:
Ultrasonic Sensor(HC-SR04) recording random distance
I am am trying to make a code which automatically controls relay on basis of ultrasonic sensor measurements. I am using a nodeMCU as a microcontroller rather than an arduino. The relay and the ultrasonic sensor is being powered from a 5V source and nodemcu from a 3.3V Source. I don't think none of the sensors are interfering with each other as all the sensors are kept at a distance. Due to the random values my relay is being latched without any reason.
Can someone please help me out with the problem. I don't want these values(above 3000) being shown in the serial monitor.
#define TRIGGER 5
#define ECHO    4
#define RELAY   0

void setup() {
  Serial.begin(9600);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  pinMode(RELAY, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  }else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

Please no text as image. You can copy and paste the text from the serial monitor and format it as code.

First thing: disconnect the relay, and try to just measure the distance. If it's still as bad, then either your target is not providing a strong enough echo, or some other object is giving too strong an echo.

These random values could be nothing but noise as your receiver may be sensing other source of ultra sound. In your case, the circuit is especially sensitive as the output powers a relay and any noise in the input side will cause the relay to "chatter". There are many approaches to filtering and smoothing out the signal. One method would be to implement a basic averaging algorithm where you take several readings and then average out the result. Compare this result with the threshold and the output should be smoother.
EDIT
Here is a rudimentry example, where I take multiple readings (nb_measurements measurements) and then take the average over it:
long getDuration() {
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  return pulseIn(ECHO, HIGH);
}

void loop() {
  float duration = 0, distance = 0;
  int nb_measurements = 10;
  for (int i = 0; i < nb_measurements; i++) {
    duration += getDuration();
  }
  duration = duration/nb_measurements;
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  } else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

Due to the extra processing, this will be in theory slower than your previous code but in practice, you wouldn't perceive it as long as you keep nb_measurements at a reasonable value. There are more complex digital signal filtering algorithms, search around and you can find good documentation and libraries online.

Could you help me with that please

@ShubhamBajaj, Sure have a look at the edited answer

Look at the OP's data: averaging won't help. The bad values are about 50 times larger than the good ones. A single bad value within your 10 samples will put the average completely off. And these bad values are about 50% of the samples.

Is there a way to decrease noise in hardware level instead of software level?

@YaMin Some high frequency noise can be eleminated using a small value decoupling capacitor


text:
ESP8266 - How to recieve UDP multicast packet?
how can I recieve udp multicast packets in ESP8266? I have this piece of code:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "my_wifi_ssid";
const char* password = "my_wifi_password";

WiFiUDP Udp;
unsigned int multicastPort = 5683;  // local port to listen on
IPAddress multicastIP(224,0,1,187);

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

    Serial.printf("Connecting to %s ", ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }
    Serial.println("connected");

    Udp.beginMulticast(WiFi.localIP(), multicastIP, multicastPort);
    Serial.printf("Now listening at IP %s and %s, UDP port %d\n", WiFi.localIP().toString().c_str(), multicastIP.toString().c_str(), multicastPort);
}

void loop(){
    int packetSize = Udp.parsePacket();
    if (packetSize){
    Serial.println("RECEIVED!");
    }
}

I wrote it according to this documentation and this addition to that about adding multicast.
It just set server listening on port 5683.
It prints something like:
Now listening at IP 192.168.1.6 and 224.0.1.187, UDP port 5683
But if I send UDP packet to 224.0.1.187:5683 (eg. via Packet sender app), it doesn't print message "RECEIVED!" (which should, look in loop function). Why ESP8266 is not receiving anything? Strange is, that when I send packet to 192.168.1.6:5683 (its local IP), it prints that message ("RECEIVED!").
Why it works only for local message but not for multicast??
Thanks for every help! :)
PS: this advice didn't help me...

I think you need to call
Udp.begin(multicastPort);

right before calling
Udp.beginMulticast(WiFi.localIP(), multicastIP, multicastPort);

At least that's what did the trick for me.


text:
help with error: cant open device "\\.\COM6":Access is denied
I built a new pc which I use as a flight simulator. On my old PC I had ArduinoIDE for programming a pro micro as well as a teensy 4.1 using the teensyduino library. I installed all the necessary libraries and can make revisions to the code for the Teensy and successfully upload them. However when I try to upload anything to the arduino I get the above mentioned error.  The old pc could program the arduino without a problem.
The arduino is showing up in device manager and it disappears when the usb cable is unplugged. The correct port is chosen in the tools menu and I can get the board info. I just can upload it to the board. Still using  windows 10 pro, the same OS as on the previous pc.
Running the arduino IDE (v2.1.0) as admin does not help.

Are you sure the port number is correct and not open by another program?

using usbtreeview.exe shows me the same info as device manager. The arduino is seen on com 6. I could post the output of usbtreeview but it exceeds what I can do in a comment and it is ugly. I just freshly booted this pc with only the arduino a keyboard and mouse as well as a hub connected.

Can you open the console window? Or does that print the same error?

Please take the [tour] and read "[ask]" to learn how this site works. This is not a forum. Therefore, you do not add new information or clarification in a comment. Instead, [edit] your question, and you have all features available, space and formatting.

Installing Arduino 1.8.19 solved the problem. I guess v2.1.0 has some  code that trips over itself.


text:
Arduino +CCLK at command parsing
I have arduino leonardo and sim800h module. I don't seem to find the problem in my program, this is probably the 5th time I'm rewriting it. Please someone tell me what should I change to work normally. I decodes the answers, but some chars seem to disappear and sometimes appear again. With time only +CCLK stays everything else is gone. Also the time should update all the time, but the seconds stay the same for 5-10 seconds.
This is the code:
const long interval = 200;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

byte pointingfinger = 0;

char enabledtime = 0;

char readenabl = 0;

char foundchar[6];

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    Serial1.print("AT+CCLK?\r");

    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
  if (Serial1.available () > 0) {
    if (foundchar[0] == '\n') {
      /*for (byte a = 0; a < 255; a = a + 1 ) {
        serialdata[a] = 0;
        }*/
        readenabl = 0;
      //pointingfinger = 0;
      enabledtime = 0;
      rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[searchcharpos + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[searchcharpos + 11];
    rtcm1[1] = serialdata[searchcharpos + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[searchcharpos + 14];
    rtcd1[1] = serialdata[searchcharpos + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[searchcharpos + 17];
    rtch1[1] = serialdata[searchcharpos + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[searchcharpos + 20];
    rtcmm1[1] = serialdata[searchcharpos + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[searchcharpos + 23];
    rtcs1[1] = serialdata[searchcharpos + 24];
    rtcs1[2] = '\0';
    }

    if (foundchar[0] == '\r') {
      readenabl = 0;
      //pointingfinger = 0;
      enabledtime = 0;
      rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[searchcharpos + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[searchcharpos + 11];
    rtcm1[1] = serialdata[searchcharpos + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[searchcharpos + 14];
    rtcd1[1] = serialdata[searchcharpos + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[searchcharpos + 17];
    rtch1[1] = serialdata[searchcharpos + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[searchcharpos + 20];
    rtcmm1[1] = serialdata[searchcharpos + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[searchcharpos + 23];
    rtcs1[1] = serialdata[searchcharpos + 24];
    rtcs1[2] = '\0';
    }
    foundchar[0] = foundchar[1];
    foundchar[1] = foundchar[2];
    foundchar[2] = foundchar[3];
    foundchar[3] = foundchar[4];
    foundchar[4] = foundchar[5];
    foundchar[5] = Serial1.read();

    if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K') {
      readenabl = 1;
      pointingfinger = 0;
    }
    if (readenabl == 1) {
      serialdata[pointingfinger] = foundchar[0];
      serialdata[pointingfinger + 1] = 0;
      pointingfinger++;
    }
  }
  }
}

This is the output:

Thanks!

Try to reduce it to an absolute minimalistic example. Trigger the request once, then read all available characters repedeately. Try this sketch: https://pastebin.com/sRJy63Dt Do you get the full response?

Oh, I do see a fatal problem: The baud rate for Serial is the same as those of Serial1. Printing a debug stuff or whatever is extremely slow on Serial. Increase to at least 115200 baud on Serial so you can eliminate the possibility of waiting too long for serial writes.

I get full response, even if interval = 200. Now I need to search the + and copy with offsets all the parameters. But how? Increasing speed seemed logical, but in this case it didn't change much.

I think you should change your approach to reading and processing the serial data. After sending a request over Serial, you should spin in a loop until the end of the answer is received (double \r\n I think?). In that loop, just dump the received data into a buffer. After it was received completely, analyze the received response (split into year, month, day, et cetera). I think you are loosing to much time in your combined "read and process" method with a billion variable assignments before each read.

Can you give an example of a full response string? You might be able to just sscanf the integers out of there.

this is the output your program gives: `Sending request
+CCLK: "04/01/01,06:33:06+00"
OK` I was actually able to use the idea for the loop in my program and so far it's working fine now

If it's working you can maybe write up a full answer on the code and techniques used to get it working.

This is the final working program that requests the time and parses the answer:
const long interval = 1000;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

byte pointingfinger = 0; //index of the array

char enabledtime = 0; //this variable is set to 1 every second and set to 0 after parsing is done

char readenabl = 0; //this is set to 1 when is finished reading from serial

char foundchar[6]; //small buffer that works as a shift register to hold only the command for comparison

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    Serial1.print("AT+CCLK?\r");

    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
    if (Serial1.available () > 0) {
      /*
        if (foundchar[0] == '\n') {
          readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }
        if (foundchar[0] == '\r') {
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }

        if (foundchar[0] == '\r') {
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }
      */
      foundchar[0] = foundchar[1];
      foundchar[1] = foundchar[2];
      foundchar[2] = foundchar[3];
      foundchar[3] = foundchar[4];
      foundchar[4] = foundchar[5];
      foundchar[5] = Serial1.read();

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K' && foundchar[5] == ':') {
        readenabl = 1;
        pointingfinger = 0;
      }
      if (readenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
      }
    }
  }
}


text:
analogRead Function AC Voltage Reading Capabilities
Usually when you sense AC voltage, you get a sinusoidal waveform. However, for AC voltage sources, Arduino analogRead ( ) only presents positive voltage values. So what's basically happening? Is it skipping half the cycle where the voltage is negative. If so, how can I account for that when I try to use the voltage values to calculate for total electrical energy generated by the source (piezoelectric film) and avg. power?

I guess that you are showing the voltages there directly calculated from analogRead() and that you connected the AC voltage directly to the analog input (and it's ground with the Arduino's ground).
The reference for every communication/voltage measurement/digital input is ground. Naturally the Arduino can only measure voltages inside of it's own supplied voltage range, meaning 0 to 5V for the Uno. If you apply a negative voltage (relative to ground), you will measure a voltage of 0V. You can even damage the microcontroller, if the negative voltage is too high.
If you have negative and positive voltages, you should offset the signal at the analog input pin, so that the resulting signal stays in the range from 0 to 5V. You can do this with a simple voltage divider. Use two resistors with the same value (for example 5kOhm), so that you will get a new zero point at 2.5V. The AC signal will then variate around that value.

For what is happening inside the microcontroller:
The ADC is responsible for measuring the voltage. For this the voltage on the analog input pin will first be sampled (loaded onto an internal condensator) and then step by step compared to the voltages, that the ADC generates by dividing the supply voltage range into 1024 distinct values (10 bit). Again the reference, to which the voltage is measured/compared, is ground. It cannot generate negative voltages, thus cannot compare them.


text:
How to send multiple data over serial in one byte?
I'm currently reading 3 limit switches and sending those data over Serial.write using the following code.
#include <SPI.h>
#include <Wire.h>
#include <arduino-timer.h>

//Define limit switch pins
#define LEFT_SWITCH_PIN 5
#define RIGHT_SWITCH_PIN 6
#define REAR_SWITCH_PIN 7

bool left_switch_state;
bool right_switch_state;
bool rear_switch_state;
bool switch_state_array[3] = {left_switch_state,right_switch_state,rear_switch_state};
int switch_pin_array[3] = {LEFT_SWITCH_PIN,RIGHT_SWITCH_PIN,REAR_SWITCH_PIN};

int send_status_state = 0;

void setup() {
    Wire.begin();
    Serial.begin(115200);
    status_timer.every(200, sendStatus);
}

void sendStatus() {
  if (send_status_state == 0) {
    getLimitSwitch();

    unsigned char buf[5];
    buf[0] = 'S';
    buf[1] = switch_state_array[0];
    buf[2] = switch_state_array[1];
    buf[3] = switch_state_array[2];
    buf[4] = '|';
    Serial.write(buf,5);
    send_status_state = 1;

  }
}

void loop() {
    status_timer.tick();
  }

void getLimitSwitch()
{
  for (int i=0; i<3; i++)
  {
    switch_state_array[i] = digitalRead(switch_pin_array[i]);
  }
}
/*********************************************************************************************************
    END FILE
*********************************************************************************************************/

as you can see I'm currently using 3 bytes to send the states of each limit switch separately.
    buf[1] = switch_state_array[0];
    buf[2] = switch_state_array[1];
    buf[3] = switch_state_array[2];

How can I send all limit switch data in one byte?

You should learn how to use bitwise operators. These are needed to do what you want.
We can save the state of each switch in one bit each. For this we first define our global variable that will hold the switch states:
byte switch_states = 0;

Then in getLimitSwitch() we loop through our pins. The result of digitalRead() is always one of 0 and 1. So we can take this value and bit shift it to the left. Then we do bitwise OR operations to put the value into our switch_states variable:
void getLimitSwitch()
{
  for (int i=0; i<3; i++)
  {
    switch_states |= ( digitalRead(switch_pin_array[i]) << i );
  }
}

Then you can send that byte over Serial. It can hold up to 8 states.
Serial.write(switch_states);

The most interesting line here is
switch_states |= ( digitalRead(switch_pin_array[i]) << i );

Lets follow here with an example: Lets assume we look at the pin with index 2 and it is HIGH. So we have switch_states |= ( 1 << 2 ). This equates to the following representation in binary switch_states |= ( 0b00000001 << 2 ). << shifts the bit pattern to the left; by 2 digits in this case. So we get switch_states |= 0b00000100;. That is equal to switch_states = switch_states | 0b00000100;. The bitwise OR operator | return a value where each bit is set to 1, if the corresponding bit in at least one of the two operants is 1. Here we use this to put the bits together.
If the pins have the states HIGH,LOW,HIGH the resulting value will be 0b00000101, aka. 5 in decimal.

On the other side you might want to decode this value. How it is done depends on the architecture (using a PC, a microcontroller, ...). But on an Arduino you can test for a pin to be HIGH with this:
if(received_states_variable & (1 << pin_index))

Note: Doing this
bool left_switch_state;
bool right_switch_state;
bool rear_switch_state;
bool switch_state_array[3] = {left_switch_state,right_switch_state,rear_switch_state};

doesn't make much sense. You initialize the array elements just with the implicitly to false initialized variables. You just don't need the normal bool variables. You can just simply define your bool array. If you want to initialize it explicitly, just use true or false directly:
bool switch_state_array[3] = {false, false, false};

or even
bool switch_state_array[3] = {false};

"These are needed to do what you want." Well, there are also bit field structs. I like to use them extensively in C and then in Rust I get told that transmutation is bad and I should feel bad.

I don't know Rust and I don't know why this should be so bad. But you are right. You can also ise bitfield structs. Maybe you want to add another answer with a short explanation how to use them. I personally use bitshifting but for the OP and others knowing all the options can help further


text:
Millis() does not back to zero after woke up from deep sleep mode
I am going to make a project that needs four boards of Arduino which synchronization in time is needed. The project is about capturing the timestamp (in ms resolution) whenever something is crossing ultrasonic proximity sensor. The following are the modules I am going to use:

Arduino Uno R3 4 units
Ultrasonic Proximity sensor 4 units
DS1302 RTC modules 4 units
Micro SD Card modules 4 units

The boards will be placed in 4 different places which it is quite far from each other that makes it is hard to make wired connection. The detecting object will move back and forth during a certain interval of time, so that is why the time synchronization is needed.
My idea is, by using the timestamp from RTC modules, I turn all the boards together into deep sleep mode at the time I have set in the code and wake them up together after 10 seconds. I don't have any problem with RTC modules, but my problem lies in the millis() function which did not back to zero after woke up from deep sleep mode. I need this function since the DS1302 RTC does not provide ms resolution, yet I can not achieve sync if the millis() function does not back to zero.
I tried the code (edited with millis() added in the loop) from here:
https://www.youtube.com/watch?v=8fiYvnBDsDE
Do you have any solutions? Or another RTC module which provides ms resolution instead. Thank you

why are not able to treat the millis() value, at wake time, as the zero reference point?

I don't actually think that millis() is supposed to be reset on a wakeup...

This looks like an XY problem. X: you need to synchronize the times, Y: you want to reset millis().

I can not achieve sync if the millis() function does not back to zero ... change your code so that it does not require millis() to be reset

You should read edgar's reference to the XY problem. Although it sounds like it might relate to tracking an object in two dimensions. It is actually talking about something else.

You should also read jsotola's comment again. Here is an additional clue... zeroTime = millis();  time goes by, stuff happens, sampleTime = millis(); and elapsedTime = sampleTime - zeroTime. In this clue, does it really matter what the value of start time is? Make sure you use unsigned values for your. Variables.

Store millis() at boot, and if (resetCause == "Deep-Sleep Wake") zero out the stored copy of millis().

I do not understand how you will get them to sync with each other. The RTC modules work great but there is no communications to set or update them and they do drift. With the RTC it will be easy to generate a timestamp using Unix time. There is a lot of information posted on how to do this.  syncing (making all the clocks the same) is where I believe your problem is. Consider adding WiFi to each and use NTP to sync everything, it would be automatic.


text:
I've gotten an error telling me, "expected initializer before 'digitalWrite'"
I should mention that I didn't write this code but got it from HERE.
#include<Servo.h>
Servo myservo; // create a servo object
int redled=13; // declare the pins
int greenled=12;

int servopin=9;
int trigpin=6;
int echopin=5;
float distance;
float duration;
int datapin=7;
int clockpin=8;
int latchpin=3;

void setup(){
  Serial.begin(9600);
  pinMode(redled,OUTPUT); // declare the pinmode
  pinMode(greenled,OUTPUT);

  pinMode(servopin,OUTPUT);
  pinMode(trigpin,OUTPUT);
  pinMode(echopin,INPUT);
  pinMode(datapin,OUTPUT);
  pinMode(clockpin,OUTPUT);
  pinMode(latchpin,OUTPUT);
  myservo.attach(servopin); // declare servo object is connected to servo pin

}

int ping() // create a function {
  digitalWrite(trigpin,LOW);
  delayMicroseconds(10);

  digitalWrite(trigpin,HIGH);
  delayMicroseconds(20);
  digitalWrite(trigpin,LOW);

  duration= pulseIn(echopin,HIGH);
  distance= duration*0.034/2; // distance is in cm
  return(distance);
  }

void loop() {
  myservo.write(90); // set servo at 90 degree angle
  float value;
  value=ping(); // call the ping function
  Serial.println(value);
  delay(100);
  if(value>20) {
      digitalWrite(redled,LOW);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000); // move the car in forward direction
      digitalWrite(latchpin,HIGH);
  }
  if(value<20&& value>15) {
      digitalWrite(redled,HIGH);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000);
      digitalWrite(latchpin,HIGH);
  }
    if(value<15) {
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // stop the car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // then again stop
      digitalWrite(latchpin,HIGH);
      delay(100);

      go(); // call go function
      delay(2000);
  }

  myservo.write(90);

}

void go() {
  int a;
  int b;
  myservo.write(0);
  delay(1000);
  a=ping();
  myservo.write(180);
  delay(1000);
  b=ping();

  if(a>b) {
   digitalWrite(redled,HIGH);
   digitalWrite(greenled,LOW);

   digitalWrite(latchpin,LOW);
   shiftOut(datapin,clockpin,LSBFIRST,B00010000); // move to the right side
   digitalWrite(latchpin,HIGH);
} else if(a<b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // move to the left side
    digitalWrite(latchpin,HIGH);
} else if(a=b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
    digitalWrite(latchpin,HIGH);
    delay(4000); // wait for 4 seconds
    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // then move to right direction
    digitalWrite(latchpin,HIGH);
    delay(2000);
  }
}

The error in full is:
sketch_may02a:31:3: error: expected initializer before 'digitalWrite'

   digitalWrite(trigpin,LOW);

   ^

sketch_may02a:32:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(10);

                    ^

sketch_may02a:34:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,HIGH);

               ^

sketch_may02a:35:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(20);

                    ^

sketch_may02a:36:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,LOW);

               ^

sketch_may02a:38:3: error: 'duration' does not name a type

   duration= pulseIn(echopin,HIGH);

   ^

sketch_may02a:39:3: error: 'distance' does not name a type

   distance= duration*0.034/2; // distance is in cm

   ^

sketch_may02a:40:3: error: expected unqualified-id before 'return'

   return(distance);

   ^

sketch_may02a:41:3: error: expected declaration before '}' token

   }

   ^

exit status 1
expected initializer before 'digitalWrite'

In addition to that, why is your ping function declared with int return type? It looks like you intended to return float value. Although in your code you are constantly going back and forth on that.

note: you have repeating code in the if blocks in the go() function ..... the first three lines of each if block are same .... move the three lines to before the first if statement and delete them  from inside the three if blocks

Your function definition starts:
int ping() // create a function {

Notice that the comment is inserted before the open curly brace. That means the curly brace is commented out. Move the comment to the end of the line, or move the curly brace to a line on it's own.

Good catch. I looked at that code and saw what I expected to see, not what's there. (voted)


text:
No headers (.h) found in Documents\Arduino\libraries\arduino_144469 with demo code
I followed this tutorial for a demo code for the SR04 ultrasonic distance sensor (without the LCD display). I've installed the Arduino IDE and wrote the code in it and saved it in some location. Compilation of the code is successful. However when I try to upload the code, I get the message:
Invalid library found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469: no headers files (.h) found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469

There are no header files in the directory and I'm wondering if I need to download additional header files or if I should configure something else.

Is there anything in that folder?

No. It is empty.

Then delete it. The Arduino IDE tries to find a library there, because it is a folder in the library folder.

It worked. Thanks. I can't believe all it took was deleting. I looked all over the internet for a solution.

Yes! Exactly the answer I was looking for. Worked perfectly. Thanks Guys. :)

If the folder is not needed then delete it.
The Arduino IDE uses the folders in the library folder to search for library header files (ie. .h files). It expects one library in each folder. When it see's a folder without any header files in it, it will count this as an invalid library.

i had similar problem and I Fix it by changing in preferences field Sketchbook location to different drive (from c:\ to d:).
This problem can ocure on system windows 10 (probably also 8) where you have sequred drive with system installed to protect you data (or system files) against some unwanted changes. Probably there is missing in Arduino some rights to make directory and save files in temporary directories, but i'm not an expert.


text:
rst cause:2, boot mode:(3,6) caused by pointer reference
I am experiencing an unusual issue with my code.
I have a LOLIN WEMOS D1 mini Lite and I am using the Arduino IDE to upload the sketch.
The version of the board is 3.0.2 for ESP8266.
The problem is with the following line of code:
unsigned long n = (this->configuration)->getOffset();

There is a class Aggregator which has a private member variable named configuration which is a pointer to another object of class Configuration which is initialized as a global instance. The above line of code is contained in one of the methods of Aggregator. Basically, it is trying to access a member getter method of a Configuration object and the pointer to this object is set in one of the private members of the Aggregator class. This pointer is initialized in the constructor of the Aggregator class.
When the code is uploaded, the Serial prints out some garbage values and when the Serial Monitor of the Arduino IDE is set to 115200 Baud then the output is:
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 3460, room 16
tail 4
chksum 0xcc
load 0x3fff20b8, len 40, room 4
tail 4
chksum 0xc9
csum 0xc9
v00052b80
~ld

Whenever this line is commented out, the code works fine and the Serial console displays the actual messages and expected lines. It seems that with the above line of code, the board seems to restart in a loop.

Print out the addresses of this->configuration and your global configuration object and see if they match...


text:
Can't find exact Part type of Stepper Motor Driver
I have searched everywhere and can't seem to find the exact model/part number for this Stepper Motor Driver.

Neither can we. We can't read the number on the chip. Can you?

It may be an ULN2003, but thats pure speculation

@chrisl Looking at the pinout and wiring (what can be seen of it), you may be spot on there. Ground and + are in the right location, certainly.


text:
Receive Signal from different circuit
I am an mid experienced Programmer but I have no clue about electronic circuits. I want my Arduino to do sth if he gets a signal from an external source. The external source has 5V and is 0V or 5V and when it has 5V I want my Arduino to send me a Message, the Code for the Message is no problem, but please help me with the circuit:
The external source is independent and runs on battery and the device has a 2.5mm jack, normally there is an LED attached that lights up, but I want my Arduino to receive the signal. Are there any opportunities for realising this?
Thank you for your help

its ground to the uno's ground, it's 5v to one of the uno's GPIO pin.

You may need an optocoupler if for whatever reason you cannot safely share grounds.

https://majenko.co.uk/blog/importance-sharing-grounds

what is "the external source"?

the external source is an indicator that sends a 5V signal via a 2.5mm mono jack, I think this just has +&- so no ground. But I only need to measure if it is on or of, not the intensity

Unless there are exceptional circumstances you can just connect the two ground connections together. Then the 5V of your other circuit will be the same voltage as the 5V of the Arduino and you can just connect your signal direct to an input.
However, if there are exceptional circumstances (ground isn't really ground, for example) then you can use an opto-coupler to act like an optically-controlled button:

simulate this circuit – Schematic created using CircuitLab
R1 can be replaced by the internal pullup resistor of the Arduino by setting the pinMode to INPUT_PULLUP.
Note that this inverts the logic of the input: a HIGH input signal is detected on the Arduino as a LOW logic level, and vice versa.

the external source is an indicator that sends a 5V signal via a 2.5mm mono jack, I think this just has +&- so no ground. But I only need to measure if it is on or off, not the intensity


text:
How to stop the screeching noise that comes from buzzer?

I use sfm-27 dc 3-24v Buzzer. It sounds fine if i close the buzzer using my palm but if i doesn't close it, it will make a screeching noise. I play melody using the buzzer so the sound is important. This is the code that i use.

    const int buzzer = 4; //Define pin 13, can use other PWM pins  (5,6 or 9)
                       //Note pins 3 and 11 can't be used when using the tone function in Arduino Uno
const int songspeed = 1.5; //Change to 2 for a slower version of the song, the bigger the number the slower the song
//*****************************************
#define NOTE_C4  262   //Defining note frequency
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_G5  784
#define NOTE_A5  880
#define NOTE_B5  988
//*****************************************
int notes[] = {       //Note of the song, 0 is a rest/pulse
   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
   NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
   NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_D5, NOTE_E5, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
   NOTE_C5, NOTE_A4, NOTE_B4, 0,

   NOTE_A4, NOTE_A4,
   //Repeat of first part
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
   NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
   NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_D5, NOTE_E5, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
   NOTE_C5, NOTE_A4, NOTE_B4, 0,
   //End of Repeat

   NOTE_E5, 0, 0, NOTE_F5, 0, 0,
   NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
   NOTE_D5, 0, 0, NOTE_C5, 0, 0,
   NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4,

   NOTE_E5, 0, 0, NOTE_F5, 0, 0,
   NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
   NOTE_D5, 0, 0, NOTE_C5, 0, 0,
   NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4
};
//*****************************************
int duration[] = {         //duration of each note (in ms) Quarter Note is set to 250 ms
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 125, 250, 125,

  125, 125, 250, 125, 125,
  250, 125, 250, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 375,

  250, 125,
  //Rpeat of First Part
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 125, 250, 125,

  125, 125, 250, 125, 125,
  250, 125, 250, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 375,
  //End of Repeat

  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 125, 125, 125, 375,
  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 500,

  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 125, 125, 125, 375,
  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 500
};

void setup() {
  for (int i=0;i<203;i++){              //203 is the total number of music notes in the song
  int wait = duration[i] * songspeed;
  tone(buzzer,notes[i],wait);          //tone(pin,frequency,duration)
  delay(wait);}                        //delay is used so it doesn't go to the next loop before tone is finished playing
  //You can click reset on Arduino to replay the song
}

void loop() {

}

you probaby cannot ... most likely the buzzer is not for playing music ... apply DC voltage and it buzzes ... apply AC voltage and you hear rhe buzz modulated at the frequency of the voltage

ok thank you so much.


text:
Pushbutton firing somewhat randomly
I have a circuit which consists of a pushbutton and 2 relays.
The power supply is driven either over USB, where the circuit seems to work fine, or powered by a linear regulator board I've knocked together consisting of an LM78XX (see the next paragraph for detail), where the circuit exhibits the behaviour.
Detail of power supply:
The LM7808 was used to drive the main voltage into the Nano, via the VIN pin. It is supported by a 330n and 100n capacitor, as per the standard circuit diagrams for LM78XX chips. The LM7805 was also used to drive the nano via the 5v pin, as well as the Pico via its 5v pin. Using LM7805, I drove the 5v relay boards directly from the power supply, not utilising the onboard 5v regulator. Using the LM7808, I used the onboard 5v regulator to power the relay boards since they required 5v, not 8v. I have tried each of these configurations with no success.
I have 2 relay boards, each has 5v, GND, and IN. These take their 5v and GND directly from the same power supply driving the Arduino where possible, or from the regulator on the board where necessary (when powered by 8v).
On power up, the relays go to opposing states (one switches on, the other stays off).
I also have essentially a pushbutton, which currently consists of a choc block that I short out with a piece of wire by hand. I have had it pulled up by the Arduino, and shorting it to ground with the pushbutton. I have also had it pulled up manually, with a 10k resistor as per the circuit diagram below. In all configurations, note that it was a choc block and a piece of wire.

Now, for the unexpected behaviour. When I power this circuit over USB, the pushbutton works almost entirely. I may have seen it fail once or twice, I can't be sure. It seems to behave as expected 99% of the time. When I power it from a 12v power supply (into the LM78XX regulator) however, I only need to wave my hand near the choc block of the "pushbutton" and it will fire. Sometimes it will fire for seemingly no reason at all, other times I will need to connect a small length of wire only to the GPIO side of the choc block and it will fire the switch.
My current code is as below:
const int signal_1 = 10;
const int relay_1 = 11;
const int relay_2 = 12;
bool state = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(relay_1, OUTPUT);
  pinMode(relay_2, OUTPUT);
  pinMode(signal_1, INPUT_PULLUP);

  digitalWrite(relay_1, LOW);
  digitalWrite(relay_2, HIGH);
}

void toggleRelays() {
  digitalWrite(relay_1, !state);
  delay(5000);
  digitalWrite(relay_2, state);
  state = !state;
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensor_1_val = digitalRead(signal_1);

  if (sensor_1_val == LOW) {
    toggleRelays();
  }
}

I have simplified this as much as possible, and tried it in as many variations as I can think of. I still suffer from this interference issue.
Can anyone explain what might be happening here? Is it possible that I'm suffering from a brownout, and need to add an additional capacitor on the power supply? Is there something I'm obviously missing about the switch circuit?

add debugging code ... then start troubleshooting by removing relay activation in setup()

Does the problem persist when you remove the relays and just use simple LEDs to indicate the state of the output pins?

@chrisl I only got my box of LEDs out late last night and haven't tried this yet, so far as I can expect though it will. I'll find out today & update the question as/when.

"other times I will need to connect a small length of wire only to the GPIO side of the choc block" -- this does sound like your "pushbutton wire" acts as an antenna picking up some EMF emitted by some oscillation in your power supply chain.

@orithena that's exactly my thought, for some reason the microcontroller is over-sensitive to EMF. Waving a hand nearby occasionally works, other times I have to make contact with the GPIO pin, but I virtually never get to actually close the "pushbutton" because before I do, it fires. I'm starting to wonder if maybe I should edit the code to take the average high/low value of 20 GPIO reads, or maybe look for a rising edge and if possible measure the duration of the rise... Ultimately my 12v is a switching supply but I believe it to be rather clean, and it's plentifully filtered on the LM78XX.

@XtrmJosh Sounds like you'd need an oscilloscope to make sure that e.g. your LM78XX does not throw the feedback loop of your switching power supply into some resonating oscillation. (I'm a bit clueless about whether that could happen, I'm just clutching at straws here.)


text:
SIM800l doesn't respond on arduino micro
I want my Arduino Micro to interact with my SIM 800 L module. But unfortunately nothing happens, may you can help me figure out where I made a mistake. Here's my wiring:

Summary of my wiring:

External Battery ---> 800L
plus ---> 5VIN
minus ---> GND (both in POWER and UART TTL-Section)

Arduino ---> 800L
RX ---> RXD
TX ---> TXD

With that setup I'm using the following code:
#include <SoftwareSerial.h>
#include<Arduino.h>

//Arduino Micro
//SIM 800l

SoftwareSerial mySerial(1, 0); // RX, TX

void setup()
{
  // Open serial communication
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  Serial.println("Setup finished");

}

void loop() // run over and over
{
  Serial.println("Sending AT command");
  mySerial.write("AT"); //OK should be returned
  delay(1000);
  //read sim-module response
  Serial.println("Response: ");
  while( mySerial.available() )
  {
    char c = mySerial.read();
    Serial.print(c);
  }

  mySerial.write("at+cmee=2"); //set sim-module into debug mode

  delay(1000);

  mySerial.write("at+cpin?"); //check if pin is necessary

  //read sim-module response
  while( mySerial.available() )
  {
    char c = mySerial.read();
    Serial.print(c);
  }

}

But it gives me the following output as a loop:
 Sending AT command
 Response:
 Sending AT command
 Response:
 Sending AT command
 Response:

And I've noticed that a yellow LED is blinking on the Arduino while running the program so I assume there has to be some input from the SIM800 but I can't read the data at the moment. On the 800L-board itself is also an LED that blinks in an interval of about one second, wich tells you that it has no connection (I live in a relatively remote area) but even if there's no connection shouldn't it still return OK when sending AT?
If you need any further information feel free to ask. I would appreciate every idea you come up with :)
Edit: On the photo the wire goes from the Arduino directly to the 800L but I've changed it so the 800L-power comes from a battery now.

Here is some edit in your code
#include <SoftwareSerial.h>
#include<Arduino.h>

//Arduino Micro
//SIM 800l

SoftwareSerial mySerial(9,10); // RX, TX

void setup()
{
  // Open serial communication
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  Serial.println("Setup finished");

}

void loop() // run over and over
{
  Serial.println("Sending AT command");
  mySerial.write("AT\r\n"); //OK should be returned
  delay(1000);
  //read sim-module response
  Serial.println("Response: ");
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

  mySerial.write("at+cmee=2\r\n"); //set sim-module into debug mode

  delay(1000);

  mySerial.write("at+cpin?\r\n"); //check if pin is necessary

  //read sim-module response
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

}

Change UART pins to 9,10 as 0,1 are already used in normal serial. Secondly change Seria.read() to Serial.readString() because as far as i know the response is string.

Thank you for your advice but I still get nothing returned. Only the RX led on my arduino is blinking but nothing arrives on tx. I tried mapping rxd to txd, put it to port 9,10 then back to the RX,TX ports but nothing gets me a response :/

sorry I missed on thing. Carriage Return and EOD character are most important part of AT commands. I just see that those are missing.

Thank you very very much, retrying some wiring positions and the carriage return did the job its woking now :)


text:
ESP32 proper DS18B20 wiring
I want to connect a DS18B20 to my newly bought Heltec ESP32 LoRa (V2). For initial testing I have used some standard code:
#include "heltec.h"
#include <OneWire.h>
#include <DallasTemperature.h>

OneWire ds(14);
DallasTemperature sensors(&ds);

void getDS18B20values()
{
  Serial.print(" Requesting therms...");
  sensors.requestTemperatures();
  Serial.println("DONE");

  uint8_t count = sensors.getDeviceCount();
  for (int i = 0; i < count; i++)
  {
    Serial.print("Temperature " + String(i) + "is: " + String(sensors.getTempCByIndex(i)));
  }

  delay(1000);
}

void setup()
{

  //WIFI Kit series V1 not support Vext control
  Heltec.begin(
      true /*DisplayEnable Enable*/,
      true /*Heltec.LoRa Disable*/,
      true /*Serial Enable*/,
      true /*PABOOST Enable*/,
      868E6/*long BAND*/);

  sensors.begin(); // initialize therm-sensors
}

void loop()
{
  getDS18B20values();

  delay(1500);
}

Here's a quick schematic I designed with the designer provided by stackexchange. Not all parts were available so I had to improvise a litte. I hope it is accurate enough.

simulate this circuit – Schematic created using CircuitLab
Another weird thing is that if I wire it all up I can start the ESP but I can't flash any new software to it because it doesn't react. So I assume it's a wiring issue the code should be fine but I posted it anyway. I had tested it with multiple DS18B20 sensors. A while ago on an Arduino they were all still working. I am more experienced with Arduinos than with ESPs. Are there any differences in regard to the wiring I have to be careful of?
Edit: I already have some sensored wired to the ESP, a BH1750, DHT11, an analog soil moisture sensor and an analog light dependent resistor.

Please just use a blank rectangle if you can't find the proper schematic symbols instead of random components.

You should become sceptical when connecting two pins of a device together :) if that was correct, the manufacturer hinself could have connected those pins inside the device and one of the pins wouldn't be there

I have not checked your code, but you certainly have a wiring issue.
There are two main problems.

Your Vcc is connected to the data output of the DS18B20. This means you will never read anything except logic "high" from the data output.
The 4k7 resistor should not be connected this way. See the schematic below on how it should be connected. You could also set up a data pin with an internal pullup so you don't need an external pullup.

This is roughly how it should look.

simulate this circuit – Schematic created using CircuitLab


text:
Erasing 1 byte of external Flash memory (winbond)
i'm trying to use an external flash memory Winbond 25q64jvsiq for my Arduino Nano based project for audio recording purposes, to have extra memory for recording 1 byte audio samples, since Arduino nano SRAM memory is too small (8kb), to store at least 1 second of 8 kHz 8 bit samples audio. I'm trying to understand the basics of  bytes storing in my external memory. I'm using SPIMemory library for that, and i can't find a function to erase 1 byte, there is only sectorErase() function. So i wonder is it even possible to erase a single byte of external memory?
Here is a part of code where i try to rewrite (erase one byte and write a new one) a next byte when the button pressed, but when it erase a sector it erases not the one byte but all bytes behind it, and i want to manipulate it more accurate, and erase only one byte:
if(!digitalRead(5)){      //button pressed
     if(e<3){
      e++;
      flash.eraseSector(count);    //erasing a byte
      flash.writeByte(count,e,NOERRCHK); // write a new value
      }  else {
        e=0;
        flash.eraseSector(count);
        flash.writeByte(count,e,NOERRCHK);
        }
     }

For a flash chip, no it's not possible to erase a single byte.
The closest you can do is to read an entire sector into memory, erase that sector, modify your in-memory copy, then write the sector back.
You would be better using an SPI SRAM or PSRAM chip instead of a flash chip.


text:
Maximum sampling rate of Arduino Mega2560
I'd like to know what is the maximum sampling rate achievable while using ADC on Arduino Mega2560.
Thanks

The beginning of section 26 of the datasheet for the ATMega2560 gives the following data:

• 13µs - 260µs Conversion Time
  • Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)


text:
Interfacing optical mouse with arduino
I have a USB mouse which I am using to measure distance travelled by my bot for a project. I followed this blog to get the optical sensor from the mouse from the arduino and interface it with the arduino. In that blog, the USB wire has been removed and the 4 pins (VCC,GND and 2 data) are connected to the arduino
However,I found the code to not be very robust as the mouse doesn't always establish Serial communication with the arduino.
I have a USB host shield for the arduino. Is there any library which will let me get the x and y coordinates of the mouse using the USB protocol?
And if not, then is there a more stable library which will be more robust than the one used in thr blog linked above?

Serial communication with an USB mouse? Really? A mouse is normally a HID device. I know no mouse, that implements a serial interface. Please show us your code

Are you sure that mouse you are using in your project is PS2/2 compatible?

@chrisl yes..I followed https://www.instructables.com/id/Optical-Mouse-Odometer-for-Arduino-Robot/ this

Yes it is PS2/2 compatible

https://github.com/felis/USB_Host_Shield_2.0 is the library for the USB host shield.


text:
Check if a set of events occur in a limited time period
I am making a project in which I am using 4 Infrared sensors to take an input. The way I want it to work is such that when one of the sensors is triggered, the code listens for input from the other sensors for a fixed amount of time (say 2 seconds). Based on this data, further functions are executed.
I am assigning a number to each of the sensors, and the sequence in which they are triggered is stored in an array like:
// All relevant pins of the IR sensors are set to input with names ir1,ir2,ir3,ir4
int sequence[] = {0,0,0,0}
int s1 = digitalRead(ir1); //and similarly for all other pins
int counter = 0;

if(s1==1){
  sequence[counter] = 1; //similarly 2 for s2 and so on
  counter ++;
}

What I am attempting to do is something like this:
if(s1 == 1 || s2==1 || s3 == 1 || s4 == 1){
   if(s1 == 1){
      sequence[counter] = 1;
      counter ++;

   //Start listening for other sensors
   } // similarly check which sensor is triggered first

   //Allow 2 seconds for input from all sensors (no input from either one of them is also allowed)
   // After 2 seconds execute some code based on the sequence array which got updated from inputs by different sensors
}

How do I accomplish this?

Definitely look at the timing principle shown in the BlinkWithoutDelay example, that comes with the Arduino IDE

Here's some pseudocode that might help:
   if millis() - start time >= 2000
         time is up, do what you want with the sequence so far
         maybe a boolean flag here so you only do it once
   if any button is pressed
      if counter == 0
          set start time = millis() // start the timer
          set first in sequence
      else
          add the button to the sequence

Thanks this worked. I put the code to check inputs from the sensors inside a while loop and used the millis() function as the while condition. Something like int a = millis(); int b= millis(); while(a-b <=200){...  a=millis() // updates a at the end of every loop}


text:
Follow black and white line simultaneously
I have a line following bot which uses IR sensors (LSA08, more specifically) to detect the white line on black surface and stay on track. For the project however, there is a trick in the track. At a certain point, the line changes from white to black and the bot is expected to follow the black line on the white surface.
My question is, how would I design the algorithm which will make the bot recognise that the track and conditions have changed.

How many IR sensors do you use for detecting the line?

The LSA08 has 8 IR sensors

Assume the "road" line is narrower than the bot's width. Sense light/dark across the road-width by enough more that it can see both edges plus enough to regain the roadway at a sharp bend.
Now pretend we don't know what color the roadway is - which is in fact, true! But we do know that the sensors should see either:
[W, W, W, ... W, B, B, ..., B, W, ..., W] (black stripe), or
[B, B, B, ... B, W, W, ..., W, B, ..., B] (white stripe).
Call W(hite) a 1 and B(lack) a zero. The above conditions, stored in an unsigned int, might look (in binary) like:
1111110000111111, or
0000001111000000.
One is just an inversion of the other, right? So read your sensors (and I'm going to assume perfect robo-vision for a moment: no noisy signals and we know we're on the roadway), and if necessary, invert the result so it look like my second case, 0000001111000000, a group of ones surrounded by a group of zeros shows we're (somewhat) centered on the track. You no longer need to know what color the roadway is!
We assumed perfect signals - in reality you'll need some smarts to detect and correct an odd 1 in the midst of a bunch (technical term here) of 0s, or vice versa.
We assumed your bot is kind of centered on the track; able to see both roadway edges. In reality, sometimes you may be losing it - 111000000000000, or drifting to the right. If you can't ensure this won't happen, you'll need to be able to recognize it and correct it. And, here is where we need to know something about the roadway color. We knew what color it was recently, just before we started to drift off, so we'll just continue inverting (or not inverting) our stored sensor data - IF the color doesn't change until the bot re-centers itself (nasty track designers)! If your design criteria can include that the bot doesn't lose either edge of the track, you can always recover, even during a color change. Otherwise you'll have to recognize and respond to a color change even when you can only see one edge. Use the recent road-color to keep track of this.
Hope that helps.

It depends a bit on your precise requirements. Currently you are following the black line (meaning sensing black in the middle and white on the sides). Instead you could follow the border of that line. To do this you would have to control the motors in a way, so that in at the middle of the sensors there is a high contrast (black at the right, white at the left, or vice versa). It will not follow the exact same path as before, but a bit to the side.


text:
Best Data model/Concept to Store Multi-Day Alarm for clock?
I'm writing a multiday day alarm program for a project.
I'm not sure how I want to store the format of each of 10 alarms....I need to store it...in SPIFFS retrieve it(at boot) and then compare it to the current day of the week and time so as to fire off the alarm..I was thinking of storing it in a 10 member array.
First alarm would be every day at 2PM and the second is turned off but would be Mon tues Thursday at 10AM. was going to use strtok_r to extract all of the pieces and compare them every minutte to see if an alarm is needed.
Every minute
{"1|M|T|W|T|F|S|S|14|00","0|M|T||T|||S|10|00"}

maybe use something similar to linux cron ... https://linuxhandbook.com/crontab/

Are you asking about the best format for your file, or the best way of storing the data in memory?

Well I'mm going to go SPIFFS on alarm change and just in memory while the clock is running.

I would suggest a bit field for storing the days of the week when the
alarm is supposed to fire:

bit 0: fire on Sundays
bit 1: fire on Mondays
...

This numbering is meant to match the one of DateTime::dayOfTheWeek().
Pack this, together with the hour and minute of the alarm, in a struct
(or a class if you prefer). Maybe add a boolean to tell whether the
alarm is active. For example:
struct Alarm {
    bool is_on;
    uint8_t days;  // bitfield: 0 = Sunday
    uint8_t hour;
    uint8_t minute;
    bool matches(DateTime) const;
};

bool Alarm::matches(DateTime t) const {
    bool day_matches = days & (1 << t.dayOfTheWeek());
    return day_matches && t.hour() == hour && t.minute() == minute;
}

Then if (alarm.is_on && alarm.matches(rtc.now())), the alarm fires.

That would work. Though I feel like your solution isn't easily readable by humans, and also not easily readable by machines.
Removing the |s, making the data a fixed length, and putting each alarm on separate line, would help with both. You'd get something like
ON  MTWTFSS 14:00
OFF MT T  S 10:00

Because the data-string is of a fixed length, you know where the data you want is inside the string. So your code can, for example, check the 7th character, to see if it needs to turn on/off on Wednesday. Or check the 13th and 14th character to get the hour. And so on.
But you'd have to decide what's important to you. Human readability, machine parseability, compactness (storing it as binary data, like Edgar said), standardized format (Cron-style), Extensibility (for example the option to add seconds, somewhere in the future), ease of implementing.

thansk that is a good way too look at it..


text:
Communication between two nrf24l01
i can't figure this out, i have a task to get data from RX module that led has turned on.
The Idea. I press push button on TX part, and led diode turn on, on RX part. Then RX send's data to TX that led have been turn'd on and print "LED HAVE BEEN TURNED ON".
I have made turn on part, but i struggle with sending from rx to tx. When i add this part code just stops
 while (!radio.available()); {
   radio.read(&buttonState, sizeof(buttonState));
   if (buttonState == 0) {
     Serial.print("LED HAS BEEN TURNED ON");
     Serial.print("\n");

//RX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define led1 6
#define mot 5

int buttonState = 0;

bool ledbutton = 0;

RF24 radio(9, 8);
const byte address[][6] = {"00001", "00002"};

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

  pinMode(led1, OUTPUT);
  digitalWrite(led1, HIGH);

  pinMode(mot, OUTPUT);
  analogWrite(mot, HIGH);

  radio.begin();
  radio.setChannel(80);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);

  radio.openWritingPipe(address[0]); // 00001
  radio.openReadingPipe(1, address[1]); // 00002

  radio.setPALevel(RF24_PA_MIN);

}
void loop() {
  radio.startListening();
  if ( radio.available()) {
    while (!radio.available()); {
      radio.read(&buttonState, sizeof(buttonState));

      ledON();
      motON();
    }
    radio.stopListening();
    ledbutton = digitalRead(led1);
    radio.write(&ledbutton, sizeof(ledbutton));
  }
}

void ledON() {
  if (buttonState == 1) {
    digitalWrite(led1, LOW);
  }
  else  if (buttonState == 0) {
    digitalWrite(led1, HIGH);
    Serial.print("LED ON");
    Serial.print("\n");
  }

}

void motON() {
  if (buttonState == 3) {
    analogWrite(mot, 0);
  }
  else  if (buttonState == 2) {
    analogWrite(mot, 255);
    Serial.print("MOTOR ON");
    Serial.print("\n");
  }

}

//TX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define buttonPin1 7
#define buttonPin2 4

int buttonState1 = 0;
int buttonState2 = 0;

int ledbutton = 0;

RF24 radio(9, 8);
const byte address[][6] = {"00001", "00002"};

void setup() {
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);

  Serial.begin(9600);

  radio.begin();
  radio.setChannel(80);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);

  radio.openWritingPipe(address[1]); // 00002
  radio.openReadingPipe(1, address[0]); // 00001

}
void loop() {
  radio.stopListening();
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  LedControl();
  MotorControl();

  radio.write(&buttonState1, sizeof(buttonState1));
  radio.write(&buttonState2, sizeof(buttonState2));

  delay(5);
  radio.startListening();
  while (!radio.available()); {
    radio.read(&ledbutton, sizeof(ledbutton));
    if (ledbutton = 0) {
      Serial.print("LED HAS BEEN TURNED ON");
      Serial.print("\n");
    }
  }
}

void LedControl() {
  if (buttonState1 == 1) {
    buttonState1 = 1;
  }
  else  if (buttonState1 == 0) {
    buttonState1 = 0;
  }
  Serial.print(buttonState1);
  Serial.print("\n");
}
void MotorControl() {
  if (buttonState2 == 1) {
    buttonState2 = 3;
  }
  else  if (buttonState2 == 0) {
    buttonState2 = 2;
  }
  Serial.print(buttonState2);
  Serial.print("\n");
}

while (!radio.available()); {. Why do a while loop, when you just checked that there is radio-data available? Also, using a semi-colon and following that with a curly-bracket is terrible. I'm not sure what it is you want to do here. I think you could remove that line entirely (including the closing bracket 3 lines below).


text:
How do I transform data for a column to data for a row, for a led matrix
I have a 8x8 led matrix. I'm using LedControl.h library to control the matrix, which has 3 ways to light up the leds: setLed, setRow and setColumn. I've found that setColumn it's really slow, it's using setLed to print columns. With all my code, I can only print 3 times a second with setColumn. The function setRow is way faster, I'm guessing that the design of the matrix is allowing to print the rows directly. I can print more than 10 times a second with setRow, so I have to use it, since speed is crucial to my project. In my code, the data i have to print is stored in an array of 8 bytes. This is how it looks like when I use setColumn
for(int i = 7; i >= 0; i--)
    lc.setColumn(0, i, vector[i]);

i is the row to be printed, and vector[i] is a byte value, indicating which leds to be on or off. Column 0 is the left-most one, while column 7 is the right-most one, so i go from 7 to 0 to print from right to left, because that's what I have to do. My goal is to transform somehow to data in vector[i], to data that I can use it using setRow. So that's what I've done so far.
byte mask = 128, x;
for (int j = 0; j < 8; j++){
  x = 0;
  for(int p = 0; p < 8; p++){
    x = x | (valueVector[p] & mask);
    if (p != 7)
      x = x >> 1;
  }
  if (j != 7)
  mask = mask >> 1;
  lc.setRow(0, j, x);
}

Now i print the rows from row 0 to row 7, from top to bottom. Since I'm printing from top to bottom, this means I have to take the last bit of every column (last bit of every element in vector), and put it in a byte variable. I was thinking to make a byte mask = 128 (b1000000, do a AND logic between to mask and the vector value in order to take the bit I'm looking for, and then making a OR to put the bit in the x byte. After every mask operation, I shift the x variable to the right, in order to make space for the next bit. After i'm done with a row, I shift the mask to the right, in order to take the second bit from the value in the vector. The result I get, is quite odd, I can't explain it, it's not good at all. What I'm i doing wrong with the mask and shifts? I hope I explained well what I'm trying to do. If necessary, I can provide more information. Thanks.

please post the entire code

why can't you physically rotate the square matrix?

You use a mask 10000000. With each iteration of the outer loop the 1 in the mask is shifted to the right. 01000000 -> 00100000 -> 00010000. Let's say we are in the 2nd iteration the mask is 01000000. x = x | (valueVector[p] & mask); takes the 2nd bit (counted from left) and sets it at the 2nd position in the x value. But this position contains the bit from the last iteration (as you shifted it to this position).
Possible solution: (I have no compiler at hand. So hopefully it is correct. ;-)
byte x;

for ( int j=0; j<8; j++ )
{
   x = 0;

   for ( int p=0; p<8; p++ )
     x = x | ((valueVector[p] & (1 << p)) >> p);

   lc.setRow(0, j, x);
}


text:
'scale' was not declared in this scope
I am currently doing a robotic arm project. I used load cell with HX711 amplifier to detect and monitor of the objects. If the objects is less than 3kg, then the servomotor in gripper can rotate and the gripper can hold the objects. But there is an error in my coding.

please, no pictures of text ... post the actual code

#include <HX711.h>
#include <Servo.h>
// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 3;
const int LOADCELL_SCK_PIN = 2;
//Define servos
Servo servo1;//servo located at gripper
int joy1X = 0;
//variable to read analog pins
int joyVal;
void setup() {
Serial.begin(9600);
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
//declare servo connection
servo1.attach(3);//connection of servo at gripper to PWM pin arduino
}

Edit your question and post the code there. You can see, can't you, that in the comment it looks pretty unreadable.

You forgot 'at least' to declare the global variable:
HX711 scale;

See documentation: https://github.com/bogde/HX711/blob/master/src/HX711.h
See GitHub example: https://github.com/bogde/HX711/blob/master/examples/HX711_basic_example/HX711_basic_example.ino

oh yesss got it THANK YOUUUUUU

@Nuradlin Athirah, please also thank him by marking this answer as correct, and also upvoting it if you haven't. Thank you.