I am trying to send the PWM values to the right and left motor from raspberry pi to Arduino. I noticed that the motors do not stop instantly as I stop sending data from pi.
I have double-checked this issue with the serial monitor too. Same problem.
The problem is if I send the PWM values just once, using a serial monitor, the motors do not for 2-3 seconds. Newbie here.
#define echoPin 3 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 2 //attach pin D3 Arduino to pin Trig of HC-SR04
// Motor A connections
int enA = 9;
int in1 = 8;
int in2 = 7;
// Motor B connections
int enB = 6;
int in3 = 5;
int in4 = 4;
int pwm_for_motor_A = 0;
int pwm_for_motor_B = 0;
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); //
// Set all the motor control pins to outputs
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
// Turn off motors - Initial state
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
}
void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
// Sets the trigPin HIGH (ACTIVE)
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
Serial.println(distance);
speedControl();
}
// This function lets you control speed of the motors
void speedControl() {
if(Serial.available() > 0)
{
pwm_for_motor_A = Serial.parseInt();
pwm_for_motor_B = Serial.parseInt();
}
else
{
pwm_for_motor_A = 0;
pwm_for_motor_B = 0;
}
analogWrite(enA, pwm_for_motor_A);
analogWrite(enB, pwm_for_motor_B);
}