Hi! Just wanted to try PID with my little robot car. The robot car is based on an UNO, two dc motors, a L293D and three HC-SR04. It´s also possible to connect a HC-06 to control it by Bluetooth. So, the car has been remotely controlled, a wall follower and a maze solver and so on. I haven´t been using PID in any of these projects but now wanted to try that in a simple way by just reading distance from the right HC-SR04 and see if the car could follow a left wall at a desired distance.
I´ve tried to implement the PID library basic example into parts of my previous code just to achieve the left wall following. The distance is measured in inches. The pwm values pwmSpeedRight = 100 and pwmSpeedLeft = 132 makes the car go straight forward, well almost.
Since I don´t have the car where I am right now I can´t try the code in real. So I just thought posting it here and see if someone have a comment maybe could be a good thing?! It´s not unlikely that I´m far out from understanding how to use this library - I´m just guessing ?!
#include <PID_v1.h>
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
const int leftForward = 2;
const int leftBackward = 3;
const int rightForward = 4;
const int rightBackward = 5;
const int rightPWM = 10;
const int leftPWM = 6;
int pwmSpeedRight = 100;
int pwmSpeedLeft = 132;
const int trigPin2 = A2;
const int echoPin2 = A1;
long duration2;
int distance2;
void setup()
{
pinMode(leftForward , OUTPUT);
pinMode(leftBackward , OUTPUT);
pinMode(rightForward , OUTPUT);
pinMode(rightBackward , OUTPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(rightPWM, OUTPUT);
pinMode(leftPWM, OUTPUT);
//initialize the variables we're linked to
Input = distance2;
Setpoint = 8;
//turn the PID on
myPID.SetMode(AUTOMATIC);
}
void loop()
{
distance2Left();
LeftRightForwardHigh();
Input = distance2;
myPID.Compute();
analogWrite(rightPWM,Output);
analogWrite(leftPWM, pwmSpeedLeft);
//delay(50);
} //to void loop
void distance2Left()
{
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration2 = pulseIn(echoPin2, HIGH);
distance2 = duration2*0.034/2;
}
void LeftRightForwardHigh()
{
digitalWrite(leftForward , HIGH);
digitalWrite(leftBackward , LOW);
digitalWrite(rightForward , HIGH);
digitalWrite(rightBackward , LOW);
}