text:
Can someone help me solve a loop question and a couple others for my program?
I am currently working on the elegoo uno r3 smart car kit that uses arduino. I have written some code and it works for the most part but I could use some help. I am trying to figure out what i need to do to get my square program to loop and continue to until the stop button is pressed. Can anyone help me out please? Also, I have 2 programs in it. One is for obstacle avoidance which is controlled by button 2 and the square program which is controlled by button 3. The stop button will be used to stop either program. I will put the code below.
#include <Servo.h>

//#include <ArduinoJson.h>

//     Left motor truth table
//Here are some handy tables to show the various modes of operation.
//  ENB         IN1               IN2         Description
//  LOW   Not Applicable    Not Applicable    Motor is off
//  HIGH        LOW               LOW         Motor is stopped (brakes)
//  HIGH        HIGH              LOW         Motor is on and turning forwards
//  HIGH        LOW               HIGH        Motor is on and turning backwards
//  HIGH        HIGH              HIGH        Motor is stopped (brakes)
#include <IRremote.h>

//#include <Servo.h>
Servo myservo;      // create servo object to control servo
//Servo servo;             //  Create a DC motor drive object
//#include <stdio.h>

//#include "HardwareSerial.h"

int Echo = A4;
int Trig = A5;

//ir remote button values/ data sheet===========================
#define f 16736925    // FORWARD
#define b 16754775    // BACK
#define l 16720605    // LEFT
#define r 16761405    // RIGHT
#define s 16712445    // STOP
#define KEY2 16750695 //obstacle avoidance mode
#define KEY3 16756815 //square mode

#define KEY_STAR 16728765
#define KEY_HASH 16732845

// define IO pin
#define ENB 5
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define ENA 6
#define RECV_PIN 12
#define ECHO_PIN A4
#define TRIG_PIN A5
#define LED_Pin 13
#define carSpeed 250
int rightDistance = 0, leftDistance = 0, middleDistance = 0;

IRrecv irrecv(RECV_PIN);

decode_results results;

void forward(){

  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Forward");
}

void stop_r() {
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
   /* digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);*/
  Serial.println("Stop!");
}

void back() {
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Back");
}

void left() {
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Left");
}

void right() {
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  Serial.println("Right");
}

void stop_() {
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
   /* digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);*/
  Serial.println("Stop!");
}

//Ultrasonic distance measurement Sub function
int getDistance() {
    digitalWrite(Trig, LOW);
    delayMicroseconds(2);
    digitalWrite(Trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(Trig, LOW);
    return (int)pulseIn(Echo, HIGH) / 58;
}

//--------------------ZIG ZAG----------------------------------------------------

//init the car
void setup() {

  //pinMode(IN1, OUTPUT);     //set IO pin mode OUTPUT
  //pinMode(IN2, OUTPUT);
 // pinMode(ENB, OUTPUT);
 // digitalWrite(ENB, HIGH);  //Enable left motor

  myservo.attach(3);  // attach servo on pin 3 to servo object
  Serial.begin(9600);
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);

  pinMode(IN1, OUTPUT);     //set IO pin mode OUTPUT
  pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT);
  digitalWrite(ENB, HIGH);  //Enable left motor

  pinMode(ENB, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  digitalWrite(ENA, HIGH);//forward
  digitalWrite(ENB, HIGH);

  pinMode(IN3, OUTPUT);     //set IO pin mode OUTPUT
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  digitalWrite(ENA, HIGH);  //Enable right motor

  //attachInterrupt(0,CHECK_IR,CHANGE);

  irrecv.enableIRIn(); // Start the receiver

  stop_r();

  //pinMode(IN3, OUTPUT);     //set IO pin mode OUTPUT
  //pinMode(IN4, OUTPUT);
  //pinMode(ENA, OUTPUT);
  //digitalWrite(ENA, HIGH);  //Enable right motor
}

//main loop============================================================================================================================
void loop() {

  if(irrecv.decode(&results)){
    Serial.println(results.value);
    irrecv.resume();
  }
  delay(100);

  //square();

 if (results.value == KEY2){
     digitalWrite(ENA, HIGH);
     digitalWrite(ENB, HIGH);
    obstacleavoidance();
    //irrecv.resume();
  } else if (results.value == s){
    stop_r();
    results.value = 12;
    //irrecv.resume();
  }

  if(results.value == KEY3){
    digitalWrite(ENA, HIGH);
     digitalWrite(ENB, HIGH);
    square();
    //irrecv.resume();
  }else if (results.value == s){
    stop_r();
    results.value = 12;
    //irrecv.resume();
  }

 /* if(results.value == KEY3){
    square();
  } else if (results.value == s){
    stop_r();
  }*/

 /*if (key_pressed == KEY2){
    obstacleavoidance();
  }
  while (key_pressed == s){
    stop_r();
  }*/

}

void get_keys(){

}

void CHECK_IR(){
  if(irrecv.decode(&results)){
    Serial.println(results.value);
    //key_pressed = results.value;
    irrecv.resume();
  }
  delay(100);
}

void square (){
  Serial.println("square");
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);   //go forward
  delay(1000);

  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);   //stop
  delay(1000);

  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  delay(660);              //right wheel turning forward

  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);   //stop
  delay(1000);
}

void obstacleavoidance(){

  myservo.write(90);  //setservo position according to scaled value
    delay(500);
    middleDistance = getDistance();
    //delay(100);
    if(middleDistance <= 20) {
      stop_r();
      delay(500);
      myservo.write(10);
      delay(1000);
      rightDistance = getDistance();

      delay(500);
      myservo.write(90);
      delay(1000);
      myservo.write(180);
      delay(1000);
      leftDistance = getDistance();

      delay(500);
      myservo.write(90);
      delay(1000);
      if(rightDistance > leftDistance) {
        right();
        delay(360);
      }
      else if(rightDistance < leftDistance) {
        left();
        delay(360);
      }
      else if((rightDistance <= 20) || (leftDistance <= 20)) {
        back();
        delay(180);
      }
      else {
        forward();
      }
    }
    else {
        forward();
    }
}

you need to clean up your code before you do anything else ... there is no reason for repeated commands in setup() .... you define functions for left(), right(), forward(), etc. but you do not use the functions in square()

Your problem is, that you use blocking code for square() and obstacleavoidance(). Nothing else can happen during a delay() call, not even checking for a button (unless you use interrupts). You should rewrite your code without any delay() calls, so that the Arduino can do this, like changing outputs, when the time has come, and check the buttons inbetween. To do that look at the BlinkWithoutDelay example, that comes with the Arduino IDE. It explains how to use millis() as a time source.

Also you should look into Finite State Machines (FSM). That's a rather simple programming technique, that will help you odering the your code and giving it a good structure to work with. For both mentioned coding styles there are tutorials on the web.

@sempaiscuba Could you possibly help me rewrite the code in the way you are explaining? I am completely new to Arduino programming.

Start with learning how to use millis(). There are tons od tutorials for that on the web. After you understood that, you can search for FSM implementation. There should be enough material, that can be googled. I remember, that I already wrote answers about FSMs on this site.

Hannah, people that write software are inherently lazy, so because your code does the same thing over and over its quite alien to most people on here :)  As a rule of thumb if you copy and paste it more than once it should be a function.
You have functions at the top of the code to move the car, but you don't seem to use them.  Using them will make the code shorter, but also much more readable.
In your setup() function you are repeatedly setting the pinMode of pins.  Group all your pinMode() call and then use the pins.  Again this will make the code easier to read and less likely to break when you change it.
So back to your question, how to you make the bot run around in squares until you press a button?  Well it will be something like this:
void square ()
{
  while (condition)
  {
    for (int side = 0; side < 4 && condition; ++side)
    {
      forward ();
      delay (1000);
      stop ();
      right ();
      delay (660);
      stop();
    }
  }
}

You need to work out a way to tie make condition be updated by your stop button, I don't want to do everything for you.
Hope that helps, if not shout out.

As chrisl points out in their answer, if you use delay then you won't be able to detect button presses (or anything else) while the delay is running. The OPs code really need to be refactored using millis().


text:
How to display only specific data in the serial monitoring?
I got the following data as shown in the figure from imu razor which is connected to Arduino Mega 2560 in the serial monitoring and I want to get only the data that starts with "#A-R= "
Can any one provide me with code to do this?

This is my code:
#define BUFF_SIZE 40
char buffer[BUFF_SIZE];
String header ;
char Bufferheader[4] ;

void setup(){
Serial.begin(57600);
Serial2.begin(57600);
Serial2.write("#osct");
}

void loop() {

int i = 0;
while(Serial2.available()) {
buffer[i++] = Serial2.read();
if(i == BUFF_SIZE) break;
}

for(int j = 0; j < i; j++) {
Serial.print(buffer[j]);

}
}

Change your code so that it only prints the things you want it to print?

Or stop the serial monitor and type grep '#A-R=' /dev/ttyACM0

The method outlined by Majenko is the general way of dealing with this
kind of requirement, and also probably the “cleanest” way. If, however,
you are confident that the incoming data always follows the pattern you
are showing, then you can “cheat” and cut some corners.
Consider this: in the sample you show, the character 'A' only ever
appears as the second character in a line, and always as part of the
sequence "#A-R=". If you are confident that this is always the case,
then you can apply the following algorithm:

the program processes one input character at a time, and decides
whether to print it to its output or not
it has two possible states: either it is printing every character it
reads (because it believes the character belongs to a “#A-R” line), or
it is not
if it is printing and it reads an end of line, it prints that end of
line, and then stops printing
if it is not printing and it reads an 'A', it outputs "#A", then
starts printing all its input.

In code:
void loop() {
    static bool printing = false;  // are we printing what we read?
    if (Serial2.available()) {
        char c = Serial2.read();
        if (printing) {
            Serial.write(c);
            if (c == '\n')  // on end of line, stop printing
                printing = false;
        } else if (c == 'A') {  // on 'A', start printing
            Serial.print("#A");
            printing = true;
        }
    }
}

This code assumes your device uses ASCII LF ('\n') as end-of-line
indicator. You will have to replace '\n' by '\r' if it uses ASCII CR
instead.

Your code is doing literally nothing except reading from one serial port and passing it to another.
You need to throw away pretty much all that code and do some actual processing of the data.
You need to:

Read the incoming data a line at a time (that is, read everything up to the line ending into a buffer)
Examine the start of that buffer
Output whatever data from the buffer your examinations deem appropriate.

I can't go into detail here about how to do it, but there are tutorials covering all those topics available on the web. For the serial reading I have a tutorial that you may find helpful.

source: Stack Exchange

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

sort: votes


text:
DHT11 temperature and humidity sensor Code
I’ve got a question about this code I’ve attached please- would it be correct to read it like this:
After defining the variable temperature and humidity and assigning measurement_timestamp to millis(), an if loop first checks if millis - measurement_timestamp < 3000 unsigned long (which doesn’t make sense to me) and then if a reading is read, it = true?
Is this correct please?
Code:
static bool measure_environment( float *temperature, float *humidity )
{
  static unsigned long measurement_timestamp = millis( );

  /* Measure once every four seconds. */
  if( millis( ) - measurement_timestamp > 3000ul )
  {
    if( dht_sensor.measure( temperature, humidity ) == true )
    {
      measurement_timestamp = millis( );
      return( true );
    }
  }

  return( false );
}

Please post code as text, not as images (and certainly not as screenshot-taken-with-a-cellphone)

Apologies, thought images were acceptable on site

code in an image cannot be copied and tested ... also, some people here cannot view images

That makes sense, apologies

The code makes sense to me.
The comment, "/* Measure once every four seconds. */" is inaccurate. It will measure when the time since last measurement is greater than 3 seconds.
Because of "static unsigned long measurement_timestamp = millis( );", measurement_timestamp will NOT be initialized to millis() every time the function is called - it will only be initialized once for lifetime of the run. Otherwise, it would never cause a measurement since "if( millis( ) - measurement_timestamp > 3000ul )" would never be true.
The first call sets measurement_timestamp= to millis() [the current timer value] and the function returns "false"
When called 3.001 sec later, "if( millis( ) - measurement_timestamp > 3000ul )" is true - a measurement is taken, "measurement_timestamp" is updated to the current millis() and the function returns "true".
It returns "false" for the next 3 seconds and then "true" and so on.
see https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c
and How can I handle the millis() rollover?
Hope it helps.

Hi, thank you for making things clearer- so I was wrong. What does the 3000ul mean please?

@Tom 3000ul is a literal constant and they have variable types just like other variables. In this case, the constant 3000 is designated as an unsigned long [ul] type, as is appropriate, see https://cplusplus.com/doc/tutorial/constants/ To put it simply, millis() measures in millisecond and when the difference between the last timestamp and the current millis() count is > 3000 milliseconds (3 seconds) go do your thing :)

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


text:
Send/receive data from/to Raspberry Pi to/from Arduino with HM-10 (Bluetooth LE module)
My goal is to send a string from an Arduino via an HM-10 bluetooth module to a Rasperry Pi. I do this today by connecting the HM-10 on the Arduino to another HM-10 module (master/slave) and then from that module to the Raspberry Pi via USB Serial adapter which gives me a /dev/ttyUSB0 that I can read. I would like to just have the Arduino's HM-10 connect up directly to the Bluetooth of the Raspberry Pi without any extra modules at all.
I found the app "Arduino Bluetooth Controller" (Android) that can connect to the module and serial communication is working.
I also have the HC-05 module and there I can solve it by using rfcomm bind 2 , but that doesn't work on the HM-10.
I'm open to any solution that can do this. Either bind the serial communication using rfcomm (or alternative) like on the HC-05, or try to build an app that is doing the same thing the Android app does, only on the Raspberry Pi.

HM-10 is a BLE device. You'll need to understand BLE programming, which is quite different than classic Bluetooth.
There is no standard BLE service for serial communication.
The best way on a Pi to use BLE is with the

noble and bleno modules for node.js.
Or start by playing with gatttool.

If you are fit in Phyton:
The HM-10 style device will send notifications that the Pi's BLE device can read. Basically you need to
attach a 'delegate' call-back function to the Peripheral object,
and then wait for notifications.
The call-back can then process the received data.
You'll have to install the bluepy lib on the PI. This sample code writes to an Arduino HC-10 device
import bluepy.btle as btle

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
s = p.getServiceByUUID("0000ffe0-0000-1000-8000-00805f9b34fb")
c = s.getCharacteristics()[0]

c.write(bytes("Hello world\n", "utf-8"))
p.disconnect()

Here is some code for reading from an Arduino HC-10 device
import bluepy.btle as btle

class ReadDelegate(btle.DefaultDelegate):
    def handleNotification(self, cHandle, data):
        print(data.decode("utf-8"))

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
p.withDelegate(ReadDelegate())

while True:
    while p.waitForNotifications(1):
        pass

p.disconnect()

I ended up using bluepy like in your example and with some chunking of the incoming data (seems to be a 20 byte limit) it all works great! Thank you!


text:
fingerprint sensor r307
am using fingerprint sensor r307 on my project and when l use connection from datasheet(My circuit connection is:
(Green) TX => Pin 0 [PWM]
(White) RX => Pin 1 [PWM]
//It doesn't respond when connected to 5V, it only heats up
(Red) VCC => 3.3v
(Black) GND => GND) the finger print is not light up and it starts to over heat but when l connect from left as ground , tx,rx and last vcc respectively the sensor lights up but it does not shown in the serial monitor it says did not find fingerprint sensor:
my code from Adafruit
#include <Adafruit_Fingerprint.h>

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
 #define mySerial Serial1

// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
// comment these two lines if using hardware serial
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(10, 11);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

uint8_t id;

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }
  }
}

uint8_t readnumber(void) {
  uint8_t num = 0;

  while (num == 0) {
    while (! Serial.available());
    num = Serial.parseInt();
  }
  return num;
}

void loop()                     // run over and over again
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
  id = readnumber();
  if (id == 0) {// ID #0 not allowed, try again!
     return;
  }
  Serial.print("Enrolling ID #");
  Serial.println(id);

  while (!  getFingerprintEnroll() );
}

uint8_t getFingerprintEnroll() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

the I/O connector has pin numbers, not colors ... referring to wires by color has no meaning because you have not defined which pin connects to which color

What is a "fingerprint sensor r307"? What datasheet do you refer to? Your code is a mess - format it properly. We aren't psychic. No links, no answer.


text:
Motor code for the "Pirate: 4WD Arduino Mobile Robot Kit with Bluetooth 4.0", will not work
The board is the RoMeo BLE V 1.0 and I have set the board to Arduino UNO on the board part of the arduino IDE, as I cannot find the RoMeo Board.
This is the code for the motors.
``int speedPin_M1 = 5;     //M1 Speed Control
int speedPin_M2 = 6;     //M2 Speed Control
int directionPin_M1 = 4;     //M1 Direction Control
int directionPin_M2 = 7;     //M1 Direction Control

void setup(){

}

void loop(){
    carAdvance(150,150);
    delay(1000);
    carBack(150,150);
    delay(1000);
    carTurnLeft(150,150);
    delay(1000);
    carTurnRight(150,150);
    delay(1000);
}

void carStop(){                 //  Motor Stop
  digitalWrite(speedPin_M2,0);
  digitalWrite(directionPin_M1,LOW);
  digitalWrite(speedPin_M1,0);
  digitalWrite(directionPin_M2,LOW);
}

void carTurnLeft(int leftSpeed,int rightSpeed){         //Turn Left
  analogWrite (speedPin_M2,leftSpeed);              //PWM Speed Control
  digitalWrite(directionPin_M1,LOW);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,HIGH);
}

void carTurnRight(int leftSpeed,int rightSpeed){        //Turn Right
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,HIGH);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,LOW);
}

void carBack(int leftSpeed,int rightSpeed){             //Move backward
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,LOW);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,LOW);
}
void carAdvance(int leftSpeed,int rightSpeed){          //Move forward
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,HIGH);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,HIGH);
}

After I upload the code, nothing happens. The boards light blinks and then after that nothing occurs. How do I get the Motors moving according to the code in the loop?

As I read the documentation I found this: "Please turn OFF the Motor Power Switch, when you debug the motor with USB port." Meaning, that the motors cannot run from USB, since it cannot provide enough current. Upload your code with the Motor Power switch in OFF state. Then take the board out of your USB port and connect the external power supply to Vin. Then turn on the Motor Power Switch.

Please try that, and if it is working, I will write a formal answer to your question

So these are the specific steps that I took. Plugged the usb in with the battery supply off. Uploaded the code, unplugged the usb then turned the battery supply for the motors on. After that, nothing occurs.

Okay, so I have got this code working which prints hello when pressing the "z" key BUT the motors do not respond when I send "w, a, s, d" keys through the serial monitor.

Your code does not read any data from serial, so it cannot react to anything. The motors should start running directly, since thats what your code says. 2. Have you used the motor power switch and the motor control jumper set to the right position, as described in the documentation, that I linked?

And in your code you don't set the pinmode for the direction pin. They have to been set to OUTPUT

So the power switch is on of the motor controls. 2. The wires from the motors are placed accordingly in the motor controls. 3. I have not at all utilised the motor control terminal jumpers as I don't know how to use them. Iam  a begginner so sorry for the confusion

The motor control terminal jumpers are marked on the image on the linked documentation with "Motor Control Terminal Jumpers". Please insert the jumper headers on all 4 jumper pin pairs, as shown in the image

thank you so much... The car now works, the problem was the the board on the instructions had the terminal jumpers already soldered together, and your comment saved the day. I am estatic... Thank you once again...

Thats great. I have formulated my comments as a proper answer. If you think, that it answers your question sufficiently, then please accept it. That you

To formulate my comments as answer:
Your board has some features involving the motors/servos:

Since the PCs USB port cannot provide enough current for the motors, they can be switched off wit the Motor Power Switch. It has to be set to OFF, when you connect the board to an USB port. For operating the motors the board needs it's own power supply (a battery in your case), which can provide enough current. So in this case, you have to switch the Motor Power Switch to ON, to enable the motor drivers. Attention: If you turn on the motors while being connected to the USB port, you can damage your board and also your USB port.
The motors are connected to the pins 4, 5, 6 and 7. If you don't need the motors, you can use these pins for other purposes. For this, the board let's you disconnect the motor driver from these pins. If the jumpers, that are marked with "Motor Control Terminal Jumpers" in the image on this documentation page, are inserted onto the jumper pin pairs (in the image they are already inserted), the motor drivers will be connected to the mentioned pins. If the jumpers are not inserted there, the motors will not work, since they are not connected to the controlling pins.

Note, that you need to use pinMode(pin_number, OUTPUT); in the setup() function for all pins, that you want to use digitalWrite() on, because only this way, the corresponding pin will be set to an output (can only then output a digital signal on digitalWrite()). analogWrite() will configure the corresponding pin for you, but it is a good practice to set it as OUTPUT in setup anyway, to make it clear for readers, that this pin is an output.


text:
Multitasking for music light sculpture
First of all, I'm new so please don't think this is dumb. I am creating a light culture with RGB LEDs that should play to programmed music. I have uploaded the following code to a spark fun redbird for now, but will later put it on a arduino mega. My circuit is working fine mostly except for the fact that the lights and music play separately and not next to each other. Note: this is just trial code, I will put my own music and light sequencing in later.
const int buzzerPin = 6;    // connect the buzzer to pin 6
const int RED_PIN = 11;
const int GREEN_PIN = 12;
const int BLUE_PIN = 13;
const int RED_PIN2 = 8;
const int GREEN_PIN2 = 9;
const int BLUE_PIN2 = 10;
const int songLength = 18;  // sets the number of notes of the song

const int DISPLAY_TIME = 100;
// Notes is an array of text characters corresponding to the notes
// in your song. A space represents a rest (no tone)

char notes[songLength] = {
  'c', 'd', 'f', 'd', 'a', ' ', 'a', 'g', ' ', 'c', 'd', 'f', 'd', 'g', ' ', 'g', 'f', ' '};

// beats[] is an array of values for each note. A "1" represents a quarter-note,
// "2" a half-note, and "4" a quarter-note.
// Don't forget that the rests (spaces) need a length as well.

int beats[songLength] = {
  1, 1, 1, 1, 1, 1, 4, 4, 2, 1, 1, 1, 1, 1, 1, 4, 4, 2};

int tempo = 113;  // The tempo is how fast to play the song (beats per second).

void setup()
{
  pinMode(buzzerPin, OUTPUT);  // sets the  buzzer pin as an OUTPUT
   pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
   pinMode(RED_PIN2, OUTPUT);
  pinMode(GREEN_PIN2, OUTPUT);
  pinMode(BLUE_PIN2, OUTPUT);
}

void loop()
{
  mainColors();        // Red, Green, Blue, Yellow, Cyan, Purple, White
  int i, duration; //

  for (i = 0; i < songLength; i++) // for loop is used to index through the arrays
  {
    duration = beats[i] * tempo;  // length of note/rest in ms

    if (notes[i] == ' ')          // is this a rest?
      delay(duration);            // then pause for a moment
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }

  // We only want to play the song once, so we pause forever
  }
  // If you'd like your song to play over and over, remove the while(true)
  // statement above

int frequency(char note)
{
  int i;
  const int numNotes = 8;  // number of notes we're storing
  char names[numNotes] = {
    'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'    };
  int frequencies[numNotes] = {
    262, 294, 330, 349, 392, 440, 494, 523    };

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency and exit function.
    }
  }
  return(0);  // We looked through everything and didn't find it,
  // but we still need to return a value, so return 0.
}

void mainColors()
{
  // Red
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, LOW);
   digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Green
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Blue
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
   digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Yellow (Red and Green)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);

  // Cyan (Green and Blue)
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Purple (Red and Blue)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);

  // White (turn all the LEDs on)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);
}

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


text:
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?
const int LED = 9;
const int BUTON = 2

void setup() {
  pinMode (LED, OUTPUT);
  pinMode (BUTON, INPUT);
}

void loop() {
  if (digitalRead(BUTON) == HIGH);
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}

This is actually not an Arduino related problem. Everybody that gets into physical computing should have some basic knowledge in C/C++ and the compiling of such code. Using an Arduino on top of that adds complexity and is more difficult to debug if something does not work as intended. So I hereby encourage you to take some tutorials in writing C/C++ to get a feeling of all the traps that lurk at you along your journey.

You are missing a semi-colon after const int BUTON = 2
Each expression should be terminated with a semi-colon.  Your code should look like this:
const int LED = 9;
const int BUTON = 2;

void setup() {
  pinMode (LED, OUTPUT);
  pinMode (BUTON, INPUT);
}

void loop() {
  if (digitalRead(BUTON) == HIGH)
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}


text:
My Arduino code is showing unidentified reference for 3 of my variables, I don't know how to fix it
Here's the code up to the error.
const int R = 12;
const int G = 10;
const int Y = 8;

const int PBR = 13;
const int PBG = 11;
const int PBY = 9;
const int pinNum = 3;
const int speaker = 2;

int LED = 0;
int gameStage = 0;

const int winNum = 2;
int gamePoint[winNum];
int rounding = 0;

unsigned long lastTime = 0;
unsigned long pause = 1000;

void ledState(int ledNum);
void clue(int rounding);
void begin_game();
void play();
void winning_sound();
void win();
void lose();
void lose_sound();
boolean inputWait(int buttonNum);

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

pinMode(R, OUTPUT);
pinMode(G, OUTPUT);
pinMode(Y, OUTPUT);
pinMode(PB1, INPUT);
pinMode(PB2, INPUT);
pinMode(PB3, INPUT);
pinMode(speaker, OUTPUT);

randomSeed(analogRead(0));
}

void loop() {

if (gameStage == 0)
{
int PBvalue1 = digitalRead(PB1);
int PBvalue2 = digitalRead(PB2);
int PBvalue3 = digitalRead(PB3);
  if (PBvalue1 && PBvalue2 && PBvalue3 == 0)
  {
    begin_game();
  }
  else
  {
    Serial.println("button Pressed");
    ledState(-1);
    rounding = 0;
    delay(1500);
    gameStage = 1;
  }
}
if (gameStage == 1)
{
  **play();** Error
}

if (gameStage == 2)
{
  delay(750);
  winning_sound();
  **win();
  win();
  win();
  win();** Error
  delay(1500);
  gameStage = 0;
}

if (gameStage = 3)
{
delay(750);
lose_sound();
**lose();
lose();
lose();** Error
delay(1500);
gameStage = 0;
}

}

which variables? .... please format your code

Lines 5,6,7 you use PBR, PBG and PBY,
Lines 39,40 and 41 you use PB1, PB2 and PB3
Again in your void loop() you reference PB1, PB2 and PB3

When I tried to compile it, I got (after editing **Error**):
 In function `loop':

/sketch_jan15b.ino:55: undefined reference to `begin_game()'

/sketch_jan15b.ino:60: undefined reference to `ledState(int)'

/sketch_jan15b.ino:68: undefined reference to `play()'

/sketch_jan15b.ino:74: undefined reference to `winning_sound()'

/sketch_jan15b.ino:75: undefined reference to `win()'

/sketch_jan15b.ino:76: undefined reference to `win()'

/sketch_jan15b.ino:77: undefined reference to `win()'

These are not variables, but functions which have been declared but not defined.
Changing these:
void ledState(int ledNum);
void clue(int rounding);
void begin_game();
void play();
void winning_sound();
void win();
void lose();
void lose_sound();
boolean inputWait(int buttonNum);

to read:
void ledState(int ledNum){}
void clue(int rounding){}
void begin_game(){}
void play(){}
void winning_sound(){}
void win(){}
void lose(){}
void lose_sound(){}
boolean inputWait(int buttonNum){}

Allowed the code to compile successfully.


text:
An error is shown as sendCommand was not declared in this scope.how to rectify it
#include <LiquidCrystal.h>
LiquidCrystal lcd(2,8,6,5,4,3);
#include <SoftwareSerial.h>
#define RX 9
#define TX 10
//ESP8266 CODE
String AP = "OPPO F11 PRO";       // AP NAME
String PASS = "bhargav123"; // AP PASSWORD
String API = "DWX3OYUU26GI5IJ7";   // Write API KEY
String HOST = "api.thingspeak.com";
String PORT = "80";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valSensor = 1;

SoftwareSerial esp8266(RX,TX);

void setup() {
  // put your setup code here, to run once:
 Serial.begin(9600);
 lcd.begin(16,2);
 lcd.setCursor(0,0);
 lcd.print("Cable");
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Fault Detection");
  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(A3,INPUT);
  pinMode(A4,INPUT);
  pinMode(A5,INPUT);

//ESP8266 CODE

  esp8266.begin(115200);
  sendCommand("AT",5,"OK");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");

}

void loop() {
//ESP8266 CODE
String getData = "GET /update?api_key="+ API +"&field1="+Insulation();
 sendCommand("AT+CIPMUX=1",5,"OK");
 sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
 sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
 esp8266.println(getData);delay(1500);countTrueCommand++;
 sendCommand("AT+CIPCLOSE=0",5,"OK");

String Insulation1(){
  if(value>=500 && value1<=700)
  int xoutput=0;
  else
  xoutput=1;
  return String(xoutput);
}

  int value1=analogRead(A0);
  delay(1000);
  lcd.clear();
  lcd.setCursor(0,0);
  Serial.println("value1");
  Serial.println(value1);
  if(value1>=500 && value1<=700)
  {
    Serial.println("Insulation at 1KM is good");
    lcd.print("Insul good 1KM");
    delay(3000);
    lcd.clear();
  }
else
   {
     Serial.println("Insulation at 1KM got damaged");
   lcd.print("Insul damage 1KM");
   delay(3000);
   lcd.clear();
   }
  int value2=analogRead(A1);
  Serial.println("value2 ");
  Serial.print(value2);
  delay(1000);
  if(value2>=500 && value2<=700)
  {
    Serial.println("Insulation at 2KM is good");
    lcd.print("Insul good 2KM");
    delay(3000);
    lcd.clear();

  }
else{
   Serial.println("Insulation at 2KM got damaged");
  lcd.print("Insul damage 2KM");
   delay(3000);
   lcd.clear();
}
    int value3=analogRead(A2);
    Serial.println("value3 ");
    Serial.print(value3);
    if(value3>=1000)
    {
      Serial.println("short circuit at 1KM ");
      lcd.print("Short at 1KM");
      delay(3000);
      lcd.clear();
    }
    int value4=analogRead(A3);
    Serial.println("value4 ");
    Serial.print(value4);
    if(value4<=1000)
    {
      Serial.println("Open circuit at 1KM");
      lcd.print("open at 1KM");
      delay(3000);
      lcd.clear();

    }
    int value5=analogRead(A4);
    Serial.println("value5 ");
    Serial.print(value5);
    if(value5>=1000)
    {
      Serial.println("short circuit at 2KM");
      lcd.print("short at 2KM");
      delay(3000);
      lcd.clear();

    }
    int value6=analogRead(A5);
    Serial.println("value6 ");
    Serial.print(value6);
    if(value6<=1000)
    {
      Serial.println("open circuit at 2KM");
      lcd.print("Open at 2KM");
      delay(3000);
      lcd.clear();
    }

//ESP8266 CODE
    void sendCommand(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while(countTimeCommand < (maxTime*1))
  {
    esp8266.println(command);//at+cipsend
    if(esp8266.find(readReplay))//ok
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if(found == true)
  {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if(found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
 }

 }

I am sure there are more error messages. read them

First thing: format your code properly. Statements that are at the same
nesting level should have the same amount of indenting. If you find this
rule too hard to follow, you can try the auto-format feature of the
Arduino IDE (Ctrl-T).
Once the code is properly indented, its whole structure should become
clear. Here is what it looks like:
// Preprocessor directives and declarations of variables...

// Definition of the function "setup":
void setup() {
  // Some code...

  sendCommand("AT",5,"OK");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}

// Definition of the function "loop":
void loop() {
  // Some code...

  // Nested function definition:
  String Insulation1() {
    // ...
  }

  // More code...

  // Nested function definition:
  void sendCommand(String command, int maxTime, char readReplay[]) {
    // ...
  }
}

The C++ language does not support nested function definitions. Even if
it did, using in setup() a function that is only defined within
loop() would not work. The solution is simple: move the definition of
sendCommand() out of loop(), into the global scope. Oh, and remove
the definition of Insulation1(): it is never used.


text:
Passing variable into catch() exception
I'm working with a try{} catch(){} exception right now and I want to change a Variable. For this my board has to connect to the Internet and with a try{} statement it will try to do so. If it fails I simply want to set the variables to 0.
  try {
    timeClient.update();
    ntp_seconds  = timeClient.getSeconds();
    ntp_minutes = timeClient.getMinutes();
    ntp_hours = timeClient.getHours();
  }
    catch () {
     ntp_seconds = 0;
     ntp_minutes = 0;
     ntp_hours = 0;
  }

I am getting this error: Compilation error: expected type-specifier before ')' token
I know that I somehow have to pass my variables into the catch() "function" but somehow I can't pass variables in like I would with normal functions.

This try/catch construct won't work with Arduino C++ :  https://forum.arduino.cc/t/try-catch/180063

OK. There is little more to say so I'll present that as the answer.

Besides that, why do you think that the NTP client is going to throw an exception?

You might want to refresh your knowledge about the try-catch statement by reading the respective chapter in your C++ book.
You need to declare an exception parameter in catch, which you can ignore:
  try {
    timeClient.update();
    ntp_seconds  = timeClient.getSeconds();
    ntp_minutes = timeClient.getMinutes();
    ntp_hours = timeClient.getHours();
  }
  catch (exception& ignored) {
    ntp_seconds = 0;
    ntp_minutes = 0;
    ntp_hours = 0;
  }

The Arduino IDE does not support the C++ try/catch exception handling construct and explicitly disables this feature.
See: https://forum.arduino.cc/t/try-catch/180063 for a fuller explanation.

how does IDE disable it? the build commands are in platform.txt of each platform. a forum post from 2013 is maybe outdated


text:
Rotate Robot head according to Sound level
I'm currently working on a robot using an Arduino and I'd like to control robot's head like this:
Imagine that it is on your desk and it can turn it's head through a range of 150 degrees like a human can do. So if I tap the desk in the the middle position, relative to his head rotation (in front of the robot), it should rotate his head by 75 degrees if he was looking at the left or right.
Likewise, I want to locate the desk tap or another sound source and make his head turn to that direction.
So in order to do that I have a solution, but I'm not confident enough to use it because I don't know whether is will give accurate results. This is what I thought:
I'll place two sound modules on the left and right sides of the robot. When a sound comes, I'll measure which microphone detects the higher sound level, and calculate an approximate angle to rotate the robot's head accordingly.
However, since I'm a newbie to Arduino, I've no real sense of whether that will work as I intend. Do people think this is a good method? If not, how can I improve it?
Also if you can, please suggest some good, Arduino compatible sound modules for this project. Thank you.

A couple of years ago, I completed a MOOC on FUN called Binaural Hearing for Robots (it doesn't seem to have run since, but it may be worth keeping an eye on it to see if they open registration again. At least some of the resources seem to be archived here). Interestingly, localising sound turns out to be easier with three microphones than with two.
You scan the three inputs in sequence, and when the sound is directed to record the time-difference between the three sensors. The technique you're looking at to localise the source is called trilateration.
Once you have a direction relative to the robot head, you can use a simple servo to turn the robot head to that direction.
I did play around with this a little bit, using three KY-038 microphone modules like this that I picked up cheap on eBay:

Connect them to your Arduino something like this:

I can't find my code (it was pretty untidy anyway since I was just playing around while I was working on the course), but a lot of Arduino sound-localisation projects have been published online with examples easy to find on Instructables, Hackaday, and many other sites.

Thank you very much. I have another question. Will that have high computational cost? I mean, that arduino mega microcontroller has a 16MHz processing power. Since I have to do them as well as lit EL panels using touch sensors, would that be possible? Will arduino be able to handle all of those stuffs?

@User9125 the Arduino Mega should be fine for that, but you could always distribute functions to multiple boards if it becomes a problem.

@sempaiscuba Where can I download the Fritzing KY-038 component that you used in your scheme?

@cespon I don't remember where I got the version I used. I just did a quick Google search and found one here on the Fritzing Forum.

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


text:
Trying to create a beats per minute monitor but having diffuctly with the coding? coding wont print any values
Any advice on what coding to adjust. New to Arduino.
const int sensorPin = A0;
float voltage=0.0;
int sensorVal=0;
int heartbeats=9;
float BPM=0.0;
const int led1=2;
const int led2=3;
int starttime = 0;
boolean counted = false;

void setup() {
pinMode(sensorPin, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
boolean counted = false;
}
void loop() {

starttime = millis();
while (millis()<starttime+10000)
{
  sensorVal = analogRead(sensorPin);
  if (sensorVal >550 && counted == false)
  {
    counted = true;
  }
  else if (sensorVal < 500)
  {
    counted = false;
  }
}

    BPM = heartbeats*6;
 Serial.println("Your BPM is");
 Serial.println(BPM);
BPM =0;
heartbeats =0;

}

Where are you actually counting the BPM? Also, starttime is too small to store time. Also your method of calculating time is wrong, since it won't cope with millis rollover.

Minor issues in your code could be fixed, but actual beat per minute measurement is a complex processing algorithm far beyond the scope of this site - and not something anyone would want to run on an ATmega based Arduino.  You'll have better luck picking a different project.

Depend on the way you're doing this, but the process of detecting pulse is very simple, as detecting the level of gaz in blood (confusion is often made with Oxymeter which in fact measure "gaz" and not O2 and can be fooled by CO intoxication). In order to get an exact count, I suggest to use interrupt or, maybe have a look at code like those about water flow rate which you must read at a specific velocity, a bit like in your case. Have a lokk here: https://www.sparkfun.com/products/11574 In the document tab of this product, you'll find code.

There's two basic methods of measuring a frequency, which is basically what you are trying to do.
There is Frequency Counting and Frequency Timing. The latter involves measuring the time between successive pulses and calculating the instantaneous frequency from that. Good for rapidly changing frequencies where you need to know the frequency right away.
Frequency counting is what you are attempting, and is basically counting the number of edges that occur within a certain timeframe.
However your method is slightly flawed: chiefly because you forgot to actually count the edges. You wrote some reasonable code for finding an edge, but failed to actually do anything with that edge.
Also your code is blocking for 10 seconds, which may be fine in this scenario, but is not a good habit to allow yourself to get into.
Instead you should consider something more like this:
void loop() {
    static int count = 0;
    static bool counted = false;
    static uint32_t ts = millis();

    int val = analogRead(sensorPin);

    if ((val > 550) && (counted == false)) {
        counted = true;
        count++;
    } else if (val < 500) {
        counted = false;
    }

    if (millis() - ts >= 10000) {
        ts += 10000; // You could assign ts the millis() value, but
                     // by adding 10 seconds it cancels any drift
                     // caused by other delays in your sketch.
        int BPM = count * 10;
        count = 0;
        Serial.print("BPM: ");
        Serial.println(BPM);
    }
}

Assuming the input waveform is a low frequency square wave. Multiple ways to do it.

Use the input to gate a counter on internal clock. It gives the most precise measurement, with a sub-us resolution.
Use external or pcint interrupts to time the start and beginning of an edge.
Wait in between edges.

...
Oversampling and algorithm will help smooth out the measurement.


text:
Changing Frequency of PWM Pin on Arduino Uno
I am trying to change the frequency of the PWM output from an Arduino Uno R3 (Been using Pin 9) to 200 Hz with a duty cycle of 20%. This is for an ESC that is connected to a 12V motor, and I know the ESC works as if I input a 200 HZ wave from a waveform generator the motor runs. However, I have been finding it difficult to do the same thing with an Arduino Uno and I believe it is due to the frequency being a default of 490 Hz, so I need a way to change that frequency to 200 Hz. Are there any libraries or specific ways to do so?
Thanks!

please add your code to the post ... format as "code"

Haven't used a library for this yet, but you can find promising results in a web search. Like this library

You can also use my newly-created AVR_PWM library to shield you from dealing with complex hardware registers
For example
#include "AVR_PWM.h"

#if ( PWM_USING_ATMEGA2560 )
  // Pins tested OK in Mega
  //#define pinToUse      12            // Timer1B on Mega
  //#define pinToUse      11            // Timer1A on Mega
  //#define pinToUse       9            // Timer2B on Mega
  //#define pinToUse       2            // Timer3B on Mega
  //#define pinToUse       3            // Timer3C on Mega
  //#define pinToUse       5            // Timer3A on Mega
  //#define pinToUse       6            // Timer4A on Mega
  //#define pinToUse       7            // Timer4B on Mega
  #define pinToUse       8            // Timer4C on Mega
  //#define pinToUse      46            // Timer5A on Mega
  //#define pinToUse      45            // Timer5B on Mega
  //#define pinToUse      44            // Timer5C on Mega

#elif ( PWM_USING_ATMEGA_32U4  )
  // Pins tested OK on 32u4
  //#define pinToUse      5            // Timer3A on 32u4
  #define pinToUse      9            // Timer1A on 32u4
  //#define pinToUse      10            // Timer1B on 32u4

#else

  // Pins tested OK on Nano / UNO
  #define pinToUse      9            // Timer1A on UNO, Nano, etc
  //#define pinToUse     10            // Timer1B on UNO, Nano, etc
  //#define pinToUse      5               // Timer0B on UNO, Nano, e
  //#define pinToUse       3            // Timer2B on UNO, Nano, etc
#endif

//creates pwm instance
AVR_PWM* PWM_Instance;

float frequency;
float dutyCycle;

void setup()
{
  Serial.print(F("\nStarting PWM_Basic on "));
  Serial.println(BOARD_NAME);
  Serial.println(AVR_PWM_VERSION);

  //assigns PWM frequency of 200 Hz and a duty cycle of 0%
  PWM_Instance = new AVR_PWM(pinToUse, 200, 0);
}

void loop()
{
  frequency = 200;
  dutyCycle = 20;

  PWM_Instance->setPWM(pinToUse, frequency, dutyCycle);

  delay(10000);
  dutyCycle = 90;

  PWM_Instance->setPWM(pinToUse, frequency, dutyCycle);

  delay(10000);
}

This works for me, thank you!

If you are prepared to use Timer 2 (Pin D3) this code will do it:
void setup()
 {
  pinMode (3, OUTPUT);

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2B on compare
  TCCR2B = bit (WGM22) | bit (CS20) | bit (CS21) | bit (CS22); // prescaler of 1024
  OCR2A =  77;    // zero relative
  OCR2B =  15;    // 20% duty cycle
  }  // end of setup

void loop()
  {
  // do other stuff here
  }

More information on the Atmega328P timers on my page about timers.
The figure 77 is obtained from:
16000000 / 1024 / 78 = 200.32

In other words, the prescaler of 1024 is divided into the clock of 16 MHz, and then we count up to 78, giving a result of just over 200. I actually use 77 because the timer is zero-relative (it counts from 0 to 77, giving 78 counts). This means the frequency is slightly out (it will be 200.32 Hz rather than 200 but that could be close enough).

You could also do it with Timer 1 (pin D10) to get slightly more accurate results, like this:
void setup()
 {
  pinMode (10, OUTPUT);

  // mode 15
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS11);   // fast PWM, prescaler of 8
  OCR1A = 10000 - 1;   // what to count to
  OCR1B = 2000 - 1;    // duty cycle
  }  // end of setup

void loop()
  {
  // do other stuff here
  }

In this case I have used a prescaler of 8 and a count-up value of 10000, as follows:
16000000 / 8 / 10000 = 200

In this case the answer is exactly 200, which will be more accurate than the 200.32 obtained from using Timer 2. That is because Timer 1 is a 16-bit timer and has higher resolution.


text:
Does ESP32 can support WIFIDirect
I would like to establish a simple P2P connection between an ESP32 and an Android device without the use of an access point. I should be able to send and receive data from the ESP32 through the established connection. Is this possible, and if not, are there any alternative solutions?

From my research i for to know that we can't use wifi direct for esp32 i found an alternative for my problem!!!!

can you maybe share your alternative ?

I do know that you can host a web page on an esp8266, sending and receiving data on that. You can from there connect the Android to that web page. I am not sure what you mean by access point, and I hope that this method is not using an access point.

Acccess point means router

so this approach should work?


text:
16 bit PWM on Nano Every
I need to drive a LED strip via MOSFET module. The module needs a high resolution PWM for very dim conditions. How can I set my pin to a 16 bit PWM resolution on an Arduino Nano Every?

It's possible for D5 (TCA0-WO2) + D9 (TCA0-WO0) + D10 (TCA0-WO1) all three of them will be 16bit if you change TCA0 top value, but you can't use analogWrite.
void setup() {
  // change period of TCA0 (already configured and started by arduino core)
  TCA0.SINGLE.PER = 0xFFFF; // change top value from 255 to 65535

  // set PWM value of D9 (channel 0)
  TCA0.SINGLE.CMP0 = 0; // initial value
  // enable PWM output (needed only once in setup)
  pinMode(9, OUTPUT); // setup pin as an output
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP0EN_bm; // enable pwm->pin

  // D5
  TCA0.SINGLE.CMP2 = 1; // initial value
  pinMode(5, OUTPUT);
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP2EN_bm;

  // D10
  TCA0.SINGLE.CMP1 = 65530; // initial value
  pinMode(10, OUTPUT);
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP1EN_bm;
}

and in the code you'll use only TCA0.SINGLE.CMPn = val; where n is 0..2
(untested, but should be working)
EDIT: I forgot the period will be 3.8Hz, so you'll need to change also TCA0 prescaller or use smaller precision like 10b or so. Changing prescaller will mess up the all the TCB counters periods along with the one used for millis counter so you'd need also change that
EDIT2: for classic UNO/nano it'll look like this:
TCCR1B = 0; // stop timer

ICR1  = 0xFFFF; // f = 16MHz / (2*N*ICR1) = 16MHz / (2*65536) => ~122Hz
OCR1A = 1;             // PB2 -> D9  (PWM value)
TCCR1A = _BV(COM1A1);  // enable PWM output on PB2
TCCR1B = _BV(WGM13) | _BV(CS10);  // mode=8 (phase and freq correct, ICR1 as top) and start timer with prescaller /1

Thanks for the detailed code. Will try these days. I used an analogWrite function on the Uno, which wrote uint16_t to OCR1A (pin9). Is this still the same?

No, classic uno/nano (with Atmega328) has different settings for timer1 - but on the other side it has independent prescaller, so you won't break anything.

@awado added changes for classic uno (pinMode omitted)

Thanks again for your help KIIV. I can confirm it works. This an example of a low light PWM for an LED on Pin 10. Maybe it helps others.
int brightness = 0;  // how bright the LED is
int fadeAmount = 1;  // how many points to fade the LED by

void setup() {
  TCA0.SINGLE.PER = 0x4000;
  TCA0.SINGLE.CTRLA = TCA_SINGLE_CLKSEL_DIV16_gc | 1 << TCA_SINGLE_ENABLE_bp
  TCA0.SINGLE.CMP1 = 65530; // initial value
  pinMode(10, OUTPUT);
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP1EN_bm;
}

void loop() {
  // set the brightness of LED pin:
  TCA0.SINGLE.CMP1 = brightness;

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

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 64) {
    fadeAmount = -fadeAmount;
  }
  // wait to see the dimming effect
  delay(50);
}


text:
WiFiNINA Reseting Arduino Nano IoT 33 When Powered Externally
This is puzzling me: if I power my Arduino IoT 33 Board from USB, everything runs smoothly. Now, if I power it with 5V on Vin, the board resets as soon as I call WiFiNINA's WiFi.begin(ssid, pass).
Of course, power is my first suspect as I'd imagine that wifi connections draw lots of current. But what's intriguing is that the main power source is a 5V (10A) DC source that is powered by a 24V (20A) AC/DC converter. The Arduino connects to 3 I2C components (an  128x128 monochrome OLED, an INA219, and an Adafruit PWM multiplexer). There are 2 servos connected to the multiplexer. Here's the wiring diagram:

With this setup, INA219 reads 4.8V and about 100mA when both servos are moving (85mA in rest).
An important remark: the PCA9685 multiplexer has a separate V+ just to drive the servos. I was assuming that my power source is enough to drive all of this, so I didn't bother supplying a separate power source for it (btw, there's an additional 680uF capacitor on soldered the board). Just for debugging purposes I did try a separate power source for it, but the problem persists.
Here some data sheets: 24V power source, DC-DC Converter (D24-S5), OLED, PWM Multiplexer, INA219.
Finally, here's the setup code:
void setup() {
  delay(250);
  Wire.begin();

  // Check for the screen module
  if (!display.begin(SCREEN_ADDRESS, true)) {
    // don't continue
    while (true)
      ;
  }

  // Check for the PWM module
  pwm.begin();
  pwm.setOscillatorFrequency(27000000);
  pwm.setPWMFreq(50);
  // Setting servos to midpoint
  pwm.setPWM(0, 0, SERVO_START);
  pwm.setPWM(1, 0, SERVO_START);
  display_line_2 = (String) "PWM... Ok";
  printDisplay(1);
  delay(10);

  // Check for the INA219 module
  if (!ina219.begin()) {
    display_line_3 = (String) "INA219... Fail";
    printDisplay(1);
    // don't continue
    while (true)
      ;
  }

  // Check for the internal LM module
  if (!IMU.begin()) {
    display_line_4 = (String) "IMU... Failed";
    printDisplay(1);
    // don't continue
    while (true)
      ;
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    display_line_5 = (String) "Wifi... Failed";
    printDisplay(1);
    // don't continue
    while (true)
      ;
  } else {
      while (status != WL_CONNECTED) {
      // Connect to WPA/WPA2 network:
      status = WiFi.begin(ssid, pass);
      // wait 10 seconds for connection:
      delay(5000);
    }
  }
}

As I said, if I comment the line status = WiFi.begin(ssid, pass), everything works just fine. So my question is: where the problem likely is? What would be the next step to troubleshoot it?

I'd try to move that 1000uF to Vin instead (or maybe even on 3V3 - but jumper must be shorted to be available on corresponding pin). If it doesn't help, use 9V/12V Vin or skip the INA219. Check Vin and 3V3 rails with the oscilloscope (MPM3610 has operation voltages between 4.5-21V).

Also DC-DC mentions minimal output current 0.5A, and who knows what is happening when you are taking less.

Interesting: moving the 1000uF to INA219's Vin didn't change the end result, but immediately gave me a less noisy power bus (I know it because the OLED doesn't flicker anymore), meaning that my wiring is indeed screwed up. I just bought a cheap oscilloscope and it should arrive tomorrow. But considering it's my first oscilloscope, I reckon I'll need some training.
With regards to the minimum of 0.5A, that's not a problem as there are other 5V devices being powered by it and it currently measures 2A.
Thanks!


text:
"if" condition problem / question
I'm new to Arduino and my question is rather theoretical. I have an Arduino Nano board (Atmega168 processor), a button, a display. I have written a button handler that does not stop code execution. My idea is: poll the button in "loop" cycle, and if it is pressed, perform k++. When k exceeds a specified value, perform cnt++ and print it on the display.
Code example №1 works correctly. I get 1 -> 2 -> 3 -> ...:
void loop() {
 if (digitalRead(button_pd) == LOW) {
    k = k + 1;
    if (k >= 20) {
      k = 0;
      cnt = cnt + 1;
    }
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(cnt);
  }
}

Code example №2 is incorrect. I get 16 -> 27 -> 40 -> ... Seems like not cnt is printed, but k.
void loop() {
  if (digitalRead(button_pd) == LOW) {
    k = k + 1;
    if (k >= 20) {
      k = 0;
      cnt = cnt + 1;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(cnt);
    }
  }
}

Here's my program:
#include <LiquidCrystal_I2C.h>

#define button_pd 6

LiquidCrystal_I2C lcd(0x27, 16, 2);

int k = 0;
int cnt = 0;

void setup() {

  pinMode(button_pd, INPUT_PULLUP);

  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(cnt);

}

void loop() {

  // button handler

}

My question is. Why examples №1 and №2 work differently?

The timings are different.
Every operation on the LCD takes time. This:
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(cnt);

involves some I2C communication, and thus takes orders of magnitude more
time than k++;.
On the first version of your loop(), these operations are performed on
each iteration, while the button is being pressed. On the second
version, they are performed only when k reaches 20, thus twenty times
less often. The second version thus runs twenty times faster... too fast
for the LCD to correctly refresh and show all the values it is being
asked to display.
I recommend you do not rely on loop counting for controlling timings.
Instead, use the Arduino function specifically designed for time
management. For example, if you want to increment the counter every
200 ms, you should record the time when the button is pressed (the
falling edge of the signal), and increment cnt 200 ms later:
uint8_t previous_state;  // previous state of the button
uint32_t press_timestamp;  // time when the button was pressed

void loop() {
    uint32_t now = millis();
    uint8_t state = digitalRead(button_pd);
    if (previous_state == HIGH && state == LOW)  // falling edge
        press_timestamp = now;
    previous_state = state;
    if (state == LOW && now - press_timestamp >= 200) {
        cnt = cnt + 1;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(cnt);
    }
}

Ah, understood... Thank you!

Unfortunately, result is still incorrect. Like 0 -> 10 -> 10 -> 10 -> 21...

I've modified your code a little. Modified version worked for me. Thank you for the idea!

Thanks. Somehow code example №3 works correctly. I have used a library for timer and simplified code from the answer above.
#include <LiquidCrystal_I2C.h>
#include <millisDelay.h>       // Timer

#define button_pd 6

LiquidCrystal_I2C lcd(0x27, 16, 2);

int k = 0;
int cnt = 0;

//uint8_t previous_state;  // previous state of the button

millisDelay d;

void setup() {
  pinMode(button_pd, INPUT_PULLUP);

  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(cnt);
}

void loop() {

    uint8_t state = digitalRead(button_pd);
    if (state == LOW)
        d.start(300);
    //previous_state = state;
    if (d.justFinished()) {
        cnt = cnt + 1;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(cnt);
    }

}


text:
I want the Arduino to be in sleep mode by default and have a button wake it up
I saw a library called LowPower_LowPowerLab that can set the Arduino in sleep mode. In their example they put the Arduino to sleep using an external button, is there anyway to invert this behavior? I want the Arduino to save battery power by being in sleep mode and then when I need it, hold a button down to keep the Arduino awake and then release the button to put it back to sleep. In their example below I have tried changing the attachInterrupt to HIGH/RISING/FALLING with no change. Also coul
LowPowerLab's Example:
#include "LowPower.h"

// Use pin 2 as wake up pin
const int wakeUpPin = 2;

void wakeUp()
{
    // Just a handler for the pin interrupt.
}

void setup()
{
    // Configure wake up pin as input.
    // This will consumes few uA of current.
    pinMode(wakeUpPin, INPUT);
}

void loop()
{
    // Allow wake up pin to trigger interrupt on low.
    attachInterrupt(0, wakeUp, LOW);

    // Enter power down state with ADC and BOD module disabled.
    // Wake up when wake up pin is low.
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

    // Disable external pin interrupt on wake up pin.
    detachInterrupt(0);

    // Do something here
    // Example: Read sensor, data logging, data transmission.
}

Looks like you're missing something after "Also coul".

In their example they put the Arduino to sleep using an external button, is there anyway to invert this behavior?

Of course. Put the Arduino to sleep in setup and make the button wake it up.
Some tips here.
Also, I wouldn't use LOW, I would use FALLING. LOW keeps interrupting the processor, so while you hold the button down it keeps entering the interrupt, which would make it unresponsive.


text:
inputs randomly turn on and off
I'm building the dactyl manuform, and I'm writing all of the code myself, but I've ran into a problem here's my code:
// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);

  for (int i=0;i<20;i++){
    pinMode(i, INPUT);
  }
}

// the loop routine runs over and over again forever:
void loop() {
  for (int i=0;i<20;i++){
    Serial.print(digitalRead(i));
  }
  Serial.print("\n");

  //delay(100); //uncomment if you want to
}

The problem is even when the inputs are not connected to 5V, the serial monitor sometimes gives a 1, and sometimes a 0. At first I was only using analog inputs, so I was suspecting that, but the same happens with digital inputs. I'm 99% sure it's not the switches, because I tested them with a multimeter. I feel like this is something obvious, and I'm just stupid (well I am, but you get the point).

What is connected to those inputs?

@EdgarBonet switches, but just to see if it works, I just bridge the connection with a cable.

INPUT means no internal pullup => super high input resistance == radio antenna. Read something about "floating inputs"

so should I do INPUT_PULLUP instead of just INPUT?

Yes, it means there is about 50k pull up resistor to the Vcc and you can use GND to change it's state to LOW

I changed it to INPUT_PULLUP, and now it's showing mostly 1s, and when I connect it to GND it turns to a 0. I'd rather it would do the opposite, show 0 until I connect it to 5V. INPUT_PULLDOWN said it was undeclared.

That is because not many MCUs have internal pull-downs. On Uno you'll need INPUT + external pull down

show 0 until I connect it to 5V. ... why do you want it that way?

There are several possible reasons random values are seen at micro controller inputs when connected to switches. Here are two:

Missing pull up or pull down resistor when using a SPST switch.

Micro controller inputs should not be allowed to float. This can lead to unexpected input states. Instead, inputs should be connected to ground or the micro controller's positive voltage supply usually either directly or though a resistor. It is common to use a pull up resistor when using a SPST switch connected to ground. Or a pull down resistor when using a SPST switch connected to the micro controller's positive voltage supply. Not all micro controllers have pull up or pull down resistors built internally. Some only have one or the other. In these cases an external resistor may be required. Some thought should be given to using micro controllers that do have built in pull up or pull down resistors. The actual resistance value of these built in resistors does vary (may not be carefully controlled). This is fine for the majority of cases. However, if a specific value is needed, it may be best if external resistors were used instead.

Long wires between the micro controller and the switch.

Longer wires are more likely to develop unexpected currents due external electrical noise. It is possible wires are long enough and the environment they are in electrically noisy enough to develop currents that will change the voltage across a pull up or pull down resistor. And, in turn, change the value of the micro controller's input. The higher the resistor value the more likely this will happen. However, the lower the resistor value chosen the more power needed when the SPST switch is closed. This is usually a concern when operating on batteries. There are many aspects to mitigating the effects of electrical noise. And will take us off subject. Instead, if long wires are necessary, consider using a "brake-before-make" SPDT switch which will connect the micro controller's input pin directly to ground or the micro controller's positive supply voltage. This will require running 3 rather than 2 wires to the switch.
Last words: Take care not to connect pull up resistors or switches to voltages higher than the micro controller's positive supply voltage! Some Arduino boards regulate higher voltages to lower voltage before supplying power to the micro controller. For instance, an Arduino board that runs from the 5 Volt USB power source may have a micro controller which actually runs at 3.3 Volt. In such a case, use the 3.3 Volts supplied to the micro controller when connecting a pull up resistor or switch.


text:
Fixing a pedestrian traffic light sequence pattern in a cycle using millis and without delay
I was emulating the pedestrian traffic light cyclic pattern (red, green, green flashing) in the next Arduino code. But when I run this code with my ESP8266 Wemos D1 mini controller, it appears the pattern (red, red and (green flashing) at the same time, green). I do not know why this strange pattern appeared and I was trying to fix it, but I did not get anything. How to fix this code to replicate the (red, green, green flashing) sequence pattern?
// Define pin assignments
const int redLED = D1;
const int greenLED = D2;
const int pedestrianButton = D3;
const int potentiometer = A0;

// Define variables
unsigned long lastStateChangeTime = 0;
unsigned long greenFlashingDuration = 3000; // 3 seconds
unsigned long redGreenDuration = 5000; // Initial duration
bool pedestrianRequest = false;

void setup() {
  // Initialize pins
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(pedestrianButton, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pedestrianButton), pedestrianInterrupt, FALLING);
}

void loop() {
  updateTiming(); // Read potentiometer/LDR and update timings
  manageTrafficLights(); // Manage traffic light states
}

void manageTrafficLights() {
  unsigned long currentTime = millis();

  if (pedestrianRequest==true) {
    // Pedestrian request prioritized
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);

    pedestrianRequest = false;
  }

  // Determine the state based on the timing

  if ( (currentTime-lastStateChangeTime) >= (2 * redGreenDuration) ) {
    lastStateChangeTime = currentTime; // Reset cycle
  }
  else {
    if ( (currentTime-lastStateChangeTime) < redGreenDuration ) {
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, HIGH); // Red state
    } else if ( (currentTime-lastStateChangeTime) < (2*redGreenDuration-greenFlashingDuration) ) {
      digitalWrite(redLED, LOW);
      digitalWrite(greenLED, HIGH); // Green state
    } else {
      digitalWrite(redLED, LOW);

      if ( ( (currentTime-lastStateChangeTime) >= (2*redGreenDuration-greenFlashingDuration) )
      && ( (currentTime-lastStateChangeTime) % (greenFlashingDuration/3) < (greenFlashingDuration/6) ) ){
        digitalWrite(greenLED, LOW);
      } else {
        digitalWrite(greenLED, HIGH);
      }

    }
  }

}

void updateTiming() {
  // Read potentiometer/LDR values and map to timings
  // Update redGreenDuration and greenFlashingDuration accordingly
  redGreenDuration = map(analogRead(potentiometer), 0, 1023, 5000, 10000);
}

void pedestrianInterrupt() {
  pedestrianRequest = true;
  // Quickly change to green if in red state
  if (digitalRead(redLED) == HIGH) {
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
    lastStateChangeTime = millis(); // Reset the cycle
  }

}

Here is some simplified example code that might be useful to you.
It keeps the logic and the LED control separated by the use of flags.
Simulation is at https://wokwi.com/projects/389132610627050497

// https://arduino.stackexchange.com/questions/95476/fixing-a-pedestrian-traffic-light-sequence-pattern-in-a-cycle-using-millis-and-w

// for simulation, see https://wokwi.com/projects/389127817478781953

const int redLED   = 2;
const int greenLED = 3;

unsigned int timeInterval  [4] = {  5,  3,  4,  0};             // timers reload with these values
unsigned int timeCounter   [4] = {  0,  0,  0,  0};             // these are the actual timers

//boolean    reloadable    [4] = {true, true, false, false};    // this determines if the timer will restart upon reaching end
                                                                // put value in <timeCounter> for oneshot event
                                                                // 3rd and 4th timers are not used in this example sketch

boolean       tick [4]  = {false, false, false, false};         // countdown timers flags
boolean       mainTick  = false;
boolean       subTick   = false;

boolean       red       = false;
boolean       green     = false;
boolean       blink     = false;

unsigned long previousMillis = 0;

void setup() {

  Serial.begin(115200);

//memcpy(timeCounter, timeInterval, 4 * sizeof(long));           // preload timers

  green = true;                                                  // start with green
  timeCounter[0] = 1;                                            // load the first counter

}

void loop() {

  unsigned long currentMillis = millis();

// -------------------------------------------------------------------

  if (currentMillis - previousMillis >= 500) {                    // 0.5 s tick
    previousMillis = currentMillis;
    subTick = !subTick;                                           // alternate the value

    if (subTick) {
      mainTick = true;                                            // 1 s tick

  //  Serial.println("tick");                                     // debugging code

      for (int i = 0; i < 4; i++) {                               // keep track of 4 time intervals

        timeCounter[i]-- ;                                        // decrement counter

        if (timeCounter[i] == 0) {
  //      if (reloadable[i])  timeCounter[i] = timeInterval[i];   // reached zero, reload counter if it is reloadable
          tick[i] = true;                                         // emit a "tick"
        }
      }
    }
  }

// -------------------------------------------------------------------

  if (mainTick) {                                         // 1 s tick
  }

// -------------------------------------------------------------------

  if (tick[0]) {                                          //
    tick[0] = false;
    timeCounter[1] = timeInterval[1];                     // setup the next tick

    red   = false;                                        // setup flags
    green = true;
    blink = false;
  }

// -------------------------------------------------------------------

  if (tick[1]) {                                          //
    tick[1] = false;                                      // clear flag so that code runs only once every tick
    timeCounter[2] = timeInterval[2];                     // setup the next tick

    red   = true;
    green = false;
    blink = false;
  }

// -------------------------------------------------------------------

  if (tick[2]) {                                          //
    tick[2] = false;                                      // clear flag so that code runs only once every tick
    timeCounter[0] = timeInterval[0];                     // setup the next tick

    red   = false;
    green = false;
    blink = true;
  }

// -------------------------------------------------------------------

  if (mainTick) {                                         // can have multiples of these
    mainTick = false;                                     // clear the flag in the last one
  }

// -------------------------------------------------------------------

  digitalWrite(redLED  , red             ? HIGH:LOW);     // C++ ternary operator
  digitalWrite(greenLED, green           ? HIGH:LOW);
  digitalWrite(redLED  , blink && subTick? HIGH:LOW);     // subTick changes every 500 ms
}

Your Wokwi link is broken.

@RussellMcMahon I tested the link on multiple devices, none of which were logged into Wokwi ... they all worked ... are you able to reach https://wokwi.com/ ?

It works for me now. I was able to access Wokwi. I tried accessing it only a few minutes after you posted the link. Mayhaps there was some setup time. || They need an NRF24L01 peripheral, or better still, a mesh of them :-). (That would be useful to me at present).

@RussellMcMahon they have a "custom chip" available ... it can be programmed with C++, Rust and Verilog ... perhaps it could be made to emulate an NRF24L01


text:
Problem adding IR receiver to smart car
I’m making a smart car using an arduino uno, sensor shield v5, motor control with a L298N and a servo motor + HC-SR04 ultrasound sensor. I want to add a IR receiver on the board so I can also control the car with a remote.
The problem is when I add in the code for the IR Receiver and make the 3 additional connections, the right motor doesn’t respond anymore, it only moves at the beginning, though slower than the left one during the initial setup, then only the left motor functions properly.
Here is the whole code with comments next to the IR-Receiver specific code:
#include <Servo.h>
#include <IRremote.h> //IR Receiver
Servo servo ;
const int trigPin = 13;
const int echoPin = 12;
const int servoPin = 11;
const int enAPin = 6;
const int in1Pin = 7;
const int in2Pin = 5;
const int in3Pin = 4;
const int in4Pin = 2;
const int enBPin = 3;
const int receiverPin = 9; //IR Receiver

IRrecv irrecv(receiverPin);  //IR Receiver
decode_results signals; //IR Receiver

enum Motor { LEFT, RIGHT };
void go(enum Motor m, int speed)
{
  digitalWrite (m == LEFT ? in1Pin : in3Pin , speed > 0 ? HIGH : LOW );
  digitalWrite (m == LEFT ? in2Pin : in4Pin , speed <= 0 ? HIGH : LOW );
  analogWrite(m == LEFT ? enAPin : enBPin, speed < 0 ? -speed : speed );
}

void testMotors ()
{
  static int speed[8] = { 128, 255, 128, 0 , -128, -255, -128, 0};
  go(RIGHT, 0);
  for (unsigned char i = 0 ; i < 8 ; i++)
    go(LEFT, -speed[i]), delay(200);

  for (unsigned char i = 0 ; i < 8 ; i++)
    go(RIGHT, speed[i]), delay(200);
}

unsigned int readDistance()
{
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  unsigned long period = pulseIn(echoPin, HIGH);
  return period * 343 / 2000;
}

#define NUM_ANGLES 7
unsigned char sensorAngle[NUM_ANGLES] = {60, 70, 80, 90, 100, 110, 120};
unsigned int distance [NUM_ANGLES];

void readNextDistance()
{
  static unsigned char angleIndex = 0;
  static signed char step = 1;
  distance[angleIndex] = readDistance();
  angleIndex += step ;
  if (angleIndex == NUM_ANGLES - 1) step = -1;
  else if (angleIndex == 0) step = 1;
  servo.write(sensorAngle[angleIndex]);
}

void setup () {
  Serial.begin(9600);  //IR Receiver
  irrecv.enableIRIn();  //IR Receiver

  pinMode(trigPin , OUTPUT);
  pinMode(echoPin, INPUT);
  digitalWrite(trigPin, LOW);
  pinMode(enAPin, OUTPUT);
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(in3Pin, OUTPUT);
  pinMode(in4Pin, OUTPUT);
  pinMode(enBPin, OUTPUT);
  servo.attach(servoPin);
  servo.write(90);
  go(LEFT, 0);
  go(RIGHT, 0);
  testMotors();
  servo.write(sensorAngle[0]);
  delay(200);
  for (unsigned char i = 0 ; i < NUM_ANGLES ; i ++)
    readNextDistance(), delay (200);
}

void loop () {

 //IR Receiver:
  if (irrecv.decode(&signals)) {
        Serial.println(signals.value);
        irrecv.resume();
        if (signals.value == 0xFFA25D) {
          Serial.println("yeees");
        }
  }

  readNextDistance ();

  unsigned char tooClose = 0;
  for (unsigned char i = 0 ; i < NUM_ANGLES ; i++)
    if (distance[i] < 200)
      tooClose = 1;

  if (tooClose) {
    go(LEFT, 180);
    go(RIGHT, -80);
  } else {
    go(LEFT, -180);
    go(RIGHT, 180);
  }
  delay (50);
}

Are you saying that the code that works correctly is only different because it is missing the lines commented with //IR Receiver? Maybe you should also post the working code (that doesn't have the IR receiver code included), so that we may compare the two versions ourselves?

@Greenonline Yes, exactly. If you remove the few lines commented with //IR Receiver, then you have the working code.

It seems to be the motors conflicting with the IRremote library, due to both usage of same timers. Need to find another library or find a way to make it use another timer

Please post that as an answer

Finally found the problem: it is due to the IRremote library using the same timers than the Servo.
Solutions are to change the specified timer that the IRremote library uses in the library files (didn't work for me though) or to not use a library for either the IR receiver or the Servo or to change the physical connection of the component plugged in a pin also used by a timer.
Link to an Arduino Forum post suggesting an alternative for controlling the Servo without a library


text:
What is the best (fastest and most robust) way to send messages back and forth between Python on a PC and an Arduino, over serial?
I am trying to communicate between a PC running Python using PySerial and an Arduino. The Arduino itself has a CAN shield, and is responsible for interfacing with a motor. My goal is for the PC to construct the desired CAN frame (8 bytes), send it over Serial to the Arduino, which then itself uses a CAN library to speak to the motor. The motor then send a return frame of the same size, which the Arduino copies to an array, and also prints it to serial.
This works in some cases, although I'm struggling to make it robust. As an example, I am driving the motor in torque control mode (Command 37 in this datasheet). For an arbitrary forward torque of '50', the sending frame should be:
[161, 0, 0, 0, 50, 0, 0, 0]

And for a command of '-50', the frame should be:
[161, 0, 0, 0, 206, 255, 255, 255]

I didn't appreciate this would be an issue, but my guess is that because this actually requires more characters, it takes longer to send. Positive torque commands are sent with no issues, while the negative ones cause the motor to skip or judder. I can see that the Arduino isn't actually receiving the correct command at times, see below (left is sent frame from Python, and right is what the Arduino receives printed straight back).

I have tried:

Flushing serial buffers before and after sending messages, on both devices
Adding delays to try and slow the communication down
Changing baudrates
Trying to use Serial.write() instead of Serial.print() as I assumed it might be faster (?)

I have attached my code below, but in general, what is the best way to communicate over serial between Python and Arduino, robustly and quickly? Even if my current application is ignored, what might ideal scripts for each look like?
Python:
    def serial_begin(self, baud, com):
        self.ser = serial.Serial(com, baud)
        self.ser.flushInput()
        self.ser.flushOutput()
        print("Connected to Serial Port " + com)
        t.sleep(1)

    def send_cam_frame(self, frame):

        self.send_frame = frame
        string_to_send = "<" + str(int(frame[0])) + "," + \
                         str(int(frame[1])) + "," + \
                         str(int(frame[2])) + "," + \
                         str(int(frame[3])) + "," + \
                         str(int(frame[4])) + "," + \
                         str(int(frame[5])) + "," + \
                         str(int(frame[6])) + "," + \
                         str(int(frame[7])) + ">"

        self.ser.write(string_to_send.encode('UTF-8'))
        self.receive_can_frame()

    def receive_can_frame(self):
        get_data = self.ser.readline().decode('UTF-8', errors='ignore')[0:][:-2]
        self.receive_frame = np.fromstring(get_data, dtype='int', count=8, sep=' ')

    def set_torque(self, torque):

        self.command = self.command_list["SET_TORQUE"]

        torque = int(self.constrain(torque * 2000 / 32, -2000, 2000))
        frame = [self.command, 0, 0, 0, torque & 0xFF, (torque >> 8) & 0xFF, (torque >> 16) & 0xFF,
                 (torque >> 24) & 0xFF]
        self.send_cam_frame(frame)

def main():

    arduino_port = "COM5"  # Default COM port
    baud_rate = 57600  # Default Baud Rate

    rmd = Motor()
    rmd.serial_begin(baud=baud_rate, com=arduino_port)

    set_torque = 0

    while True:
        try:

            if keyboard.is_pressed('w'):
                set_torque += 0.001
            if keyboard.is_pressed('s'):
                set_torque -= 0.001

            rmd.set_torque(set_torque)

        except KeyboardInterrupt:
            rmd.disable_motor()
            print("Keyboard Interrupt")

Arduino:

byte recvFrame[8] = {0, 0, 0, 0, 0, 0, 0, 0};
byte sendFrame[8] = {0, 0, 0, 0, 0, 0, 0, 0};

// Serial Read Parameters
const byte numChars = 32;  // Length of received char array from Serial
char receivedChars[numChars];  // Received char array from Serial
char tempChars[numChars];        // Temporary array for use when parsing
bool newData = false;  // Flag to check if newData has been received

void setup() {
  Serial.begin(57600);
  delay(1000);

}

void loop() {

  CANMessage frame;

  frame.id = 0x140 + 1;
  frame.len = 8;

  // Do not touch this section
  recvWithStartEndMarkers();  // Check Serial and receive data if there is newData
  if (newData == true) {
      strcpy(tempChars, receivedChars);  // Copy variables to prevent them being altered
      parseData();  // Parse data (split where there are commas)

      for (int i = 0; i  < 8; i++){
        frame.data[i] = sendFrame[i];
      }

      can.tryToSend(frame);

      newData = false;  // Set to false
  }

  if (can.available()){
    can.receive(frame);
  }

  for (int i = 0; i < 8; i++){
    recvFrame[i] = frame.data[i];
  }

  printFrame();

}

// Do not touch this function
void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

// Only touch this function if more data is being sent from Python code
void parseData() {      // split the data into its parts

    char * strtokIndx; // this is used by strtok() as an index

    strtokIndx = strtok(tempChars,",");
    sendFrame[0] = atoi(strtokIndx);

    strtokIndx = strtok(NULL,",");
    sendFrame[1] = atoi(strtokIndx);

    strtokIndx = strtok(NULL,",");
    sendFrame[2] = atoi(strtokIndx);

    strtokIndx = strtok(NULL,",");
    sendFrame[3] = atoi(strtokIndx);

    strtokIndx = strtok(NULL,",");
    sendFrame[4] = atoi(strtokIndx);

    strtokIndx = strtok(NULL,",");
    sendFrame[5] = atoi(strtokIndx);

    strtokIndx = strtok(NULL,",");
    sendFrame[6] = atoi(strtokIndx);

    strtokIndx = strtok(NULL, ",");
    sendFrame[7] = atoi(strtokIndx);

    // How to add a new variable
    // Currently, data is sent as <0, 0, 0, 0>
    // If a fourth parameter was to be sent (<0, 0, 0, 0, 1>), the following lines need to be added

    // strtokIndx = strtok(NULL, ", "); This reads the string, from where it was previously cut, up until the next comma
    // newVariableName = atoi(strtokIndx); atoi is 'to integer'. If newVariable is a float, atof is needed etc

}

void printFrame(){

  for (int i = 0; i < 8; i++){
    Serial.print(sendFrame[i]);
    Serial.print(" ");
  }
  Serial.println();
  //Serial.write(sendFrame, 8);
  //delay(3);

}

N.B: I have removed some of the unnecessary functions from both scripts (e.g: the rest of the Motor class for the Python, and the CAN Shield setup from the Arduino) for clarity.

questions about a robust serial protocol are not Arduino specific

Asking for the "best" solution is a poor design approach. Clearly state what your requirements are and someone might have a solution that is good enough.

Have you checked the data transmission without any CAN and motor code and without anything else connected? And currently you are sending back the already parsed frame. Please try sending the char buffer instead and report the results back. And I don't see, where you were printing the send and received data in the python code. Please include the actual code that created that output. This can be relevant to debug the code

You might like https://github.com/nanopb/nanopb

There is no best way, but there is a better way (and more efficient way).

For an arbitrary forward torque of '50', the sending frame should be:
[161, 0, 0, 0, 50, 0, 0, 0]
And for a command of '-50', the frame should be:
[161, 0, 0, 0, 206, 255, 255, 255]

Most of the programmers who are new to embedded program, prepare their data to be send via communication as string instead of sending raw binary data, the problem is that

to send a value of 215, you are sending 3 bytes of ASCII('2', '1', '5') while the data can actually sent by one single byte.
both integer 256 (0x0100) and 32766 (0x7FFE) only took up two bytes, but when you encode it as ASCII, you are dealing with various length from 3 chars to 5 chars. This not only take more bytes to send the data but also make parsing of the data more difficult unless you had some delimiter to separate the data, e.g. ("256,32766" separated by comma).

Looking at your data set and datasheet, it is clear that the each data point is represented by a 4-byte signed data with small endian (i.e. the lower byte get send first), so decimal 50 is 0x00000032, it is store in memory as 0x32, 0x00, 0x00, 0x00 with small endian.
A negative value is represented in two's compliment of the positive value, so -50 in decimal is 0xFFFFFFCE and stored as 0xCE, 0xFF, 0xFF, 0xFF.
In python, the struct library allows you to converts between Python values and C structs represented as Python bytes objects.
form struct import *

torque = -50

data = pack('<i', torque) # pack torque as a 4-byte integer with little endian
ser.write(torque)         # send over serial as bytes

On the Arduino side, read the data from Serial as byte(i.e. uint8_t) and store it in an array. You can then convert it back to a int32.
// assuming you had read these 4 bytes of data from Serial and add them into an array
uint8_t data[4]{0xCE, 0xFF, 0xFF, 0xFF};

// Convert received data bytes to int32_t
int32_t torque = static_cast<int32_t> (data[3]<< 24 | data[2] << 16 | data[1] << 8 | data[0]);

// This will return result of -50
Serial.println(torque);

This should reduce the code and improve the efficiency of the sending the data significantly.
The code along however does not improve the reliability, one advantage of sending data as string is that you could determine the end of data stream by detecting the \0 terminator at end of the string. When sending raw binary, ideally you need to have the mechanism to signify the number of bytes the data of bytes that you are going to send over.