after uploading this code, the motor 1 is moving backwards only and nothing more than that is happening, here is the line follower code :
#include <QTRSensors.h>
QTRSensors qtr;
const uint8_t SensorCount = 8;
uint16_t sensorValues[SensorCount];
float Kp = 0.2;
float Ki = 0;
float Kd = 0.1;
int P;
int I;
int D;
int lastError = 0;
boolean onoff = false;
const uint8_t maxspeeda = 255; // Max speed for motor A (PWM range: 0-255)
const uint8_t maxspeedb = 255; // Max speed for motor B
const uint8_t basespeeda = 100; // Base speed for motor A
const uint8_t basespeedb = 100; // Base speed for motor B
// Define motor control pins
int aPhase = 9; // Motor A direction pin
int aEnable = 6; // Motor A PWM pin (Enable pin)
int bPhase = 5; // Motor B direction pin
int bEnable = 3; // Motor B PWM pin (Enable pin)
int buttonCalibrate = 17; // Calibration button pin
int buttonStart = 2; // Start button pin
void setup() {
Serial.begin(9600);
qtr.setTypeRC();
qtr.setSensorPins((const uint8_t[]){10, 11, 12, 14, 15, 16, 18, 19}, SensorCount);
qtr.setEmitterPin(7); // LEDON pin
// Set motor control pins as output
pinMode(aPhase, OUTPUT);
pinMode(aEnable, OUTPUT);
pinMode(bPhase, OUTPUT);
pinMode(bEnable, OUTPUT);
delay(500); // Delay for stability
boolean Ok = false;
while (!Ok) {
if (digitalRead(buttonCalibrate) == HIGH) {
calibration();
Ok = true;
}
}
forward_brake(0, 0); // Stop motors at the beginning
}
void calibration() {
digitalWrite(4, HIGH); // Pin 4 can be used to indicate calibration mode
for (uint16_t i = 0; i < 400; i++) {
qtr.calibrate(); // Calibrate the sensors
}
digitalWrite(4, LOW);
}
void loop() {
if (digitalRead(buttonStart) == HIGH) {
onoff = !onoff; // Toggle on/off state
delay(1000); // Debounce delay
}
if (onoff) {
PID_control(); // Execute PID control if on
} else {
forward_brake(0, 0); // Stop motors if off
}
}
void forward_brake(int speedA, int speedB) {
digitalWrite(aPhase, HIGH); // Set direction for Motor A
digitalWrite(bPhase, LOW); // Set direction for Motor B
// Set PWM speed for motors
analogWrite(aEnable, speedA);
analogWrite(bEnable, speedB);
}
void PID_control() {
uint16_t position = qtr.readLineBlack(sensorValues); // Read the line position
int error = 3500 - position; // Calculate error
P = error; // Proportional term
I += error; // Integral term
D = error - lastError; // Derivative term
lastError = error; // Update last error
int motorSpeed = P * Kp + I * Ki + D * Kd; // Calculate motor speed adjustment
int motorSpeedA = basespeeda + motorSpeed; // Speed for motor A
int motorSpeedB = basespeedb - motorSpeed; // Speed for motor B
// Constrain motor speeds within limits
motorSpeedA = constrain(motorSpeedA, 0, maxspeeda);
motorSpeedB = constrain(motorSpeedB, 0, maxspeedb);
forward_brake(motorSpeedA, motorSpeedB); // Set motor speeds
}
Using L298N, Arduino Nano and QTR-8RC
5 posts - 3 participants