#include <AFMotor.h>
#define ledPin1 22
#define ledPin2 23
AF_DCMotor leftMotor(4);
AF_DCMotor rightMotor(3);
AF_DCMotor conveyorMotor(2);
int rightSpeed, leftSpeed, sensorsSum, location, differenceTarget;
int sensors[] = {0, 0, 0, 1, 0};
long proportional, integral, derivative, lastProportional, errorValue, sensorsAverage;
unsigned const int maxSpeed = 255;
unsigned const int setPoint = 2000;
const float Kp = 0.097;
const float Ki = 0.004;
const float Kd = 0.097;
void pidCalculation(){
location = int(sensorsAverage/sensorsSum);
proportional = location - setPoint;
integral = integral + proportional;
derivative = proportional - lastProportional;
lastProportional = proportional;
errorValue = int(proportional*Kp + integral*Ki + derivative*Kd);
}
void speedCalculation(){
errorValue = (errorValue > 255) ? 255 : errorValue;
errorValue = (errorValue < -255) ? -255 : errorValue;
if(errorValue < 0){
rightSpeed = maxSpeed + errorValue;
leftSpeed = maxSpeed;
}
else{
rightSpeed = maxSpeed;
leftSpeed = maxSpeed - errorValue;
}
}
void setup() {
Serial.begin(9600);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
rightMotor.run(RELEASE);
leftMotor.run(RELEASE);
conveyorMotor.run(RELEASE);
}
void loop() {
sensorsAverage = 0;
sensorsSum = 0;
unsigned long currentMillis = millis();
long previousMillis,interval;
if((sensors[0] == 1)&&(sensors[1]==1)&&(sensors[2]==1)&&(sensors[3]==1)&&(sensors[4]==1)){
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
rightMotor.run(RELEASE);
leftMotor.run(RELEASE);
conveyorMotor.setSpeed(255);
conveyorMotor.run(FORWARD);
}
else{
for(int i=0; i<5; i++){
//sensors[i] = analogRead[i];
sensorsAverage += sensors[i] * i * 1000;
sensorsSum += int(sensors[i]);
}
location = int(sensorsAverage/sensorsSum);
Serial.print("Location = ");
Serial.print(location);
pidCalculation();
speedCalculation();
leftMotor.setSpeed(leftSpeed);
leftMotor.run(FORWARD);
rightMotor.setSpeed(rightSpeed);
rightMotor.run(FORWARD);
Serial.print(" | Error = ");
Serial.println(errorValue);
Serial.print("rightSpeed = ");
Serial.print(rightSpeed);
Serial.print(" | leftSpeed = ");
Serial.println(leftSpeed);
digitalWrite(ledPin1, !digitalRead(ledPin1));
digitalWrite(ledPin2, !digitalRead(ledPin1));
delay(500);
}
}
Hello, I'm doing a project where I need to make a line follower. I'm trying to implement a PID control method but that's not the problem. I'm utilizing the delay function to time the void loop, but I know that if I use a delay, the microprocessor does nothing. I'm using the atmega328p and I know the Arduino Mega has six timers. How can I use them to time the process? If there are other ways to optimize my code, feel free to correct and tell me.
I don't have all the components, so this is just a test program.