Hello dear forum users!
So I'm working on a robot car that has to follow a black line, the well known 'line follower'. However, I don't use DC motors, but stepper motors. I use two NEMA17 motors in conjunction with two DRV8825 stepper drivers. I also would like to be able to control the car manually via Bluetooth.
I'm aware that delay() should be avoided if possible, so I'm looking into other ways to control my steppers either manually or automatically by a triplet of digital IR-sensors.
This is a simple experimentation sketch that I've been using so far:
byte directionPin = 12;
byte stepPin = 11;
byte directionPin2 = 6;
byte stepPin2 = 5;
unsigned long curMillis;
unsigned long prevStepMillis = 0;
unsigned long millisBetweenSteps = 2; // milliseconds
void setup() {
Serial.begin(9600);
Serial3.begin(9600);
pinMode(directionPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(directionPin2, OUTPUT);
pinMode(stepPin2, OUTPUT);
}
void loop() {
StepForward();
curMillis = millis();
}
void StepForward() {
if (curMillis - prevStepMillis >= millisBetweenSteps) {
prevStepMillis = curMillis;
digitalWrite(directionPin, LOW);
digitalWrite(directionPin2, LOW);
digitalWrite(stepPin, HIGH);
digitalWrite(stepPin, LOW);
digitalWrite(stepPin2, HIGH);
digitalWrite(stepPin2, LOW);
}
}
This works. But I still can't control the steppers and their direction myself. So I've implemented a switch case control structure to be able to control the car over BT (or serial, for BT I'm using the hardware serial ports in the Arduino Mega).
That code looks like this:
byte directionPin = 12;
byte stepPin = 11;
byte directionPin2 = 6;
byte stepPin2 = 5;
unsigned long curMillis;
unsigned long prevStepMillis = 0;
unsigned long millisBetweenSteps = 2; // milliseconds
void setup() {
Serial.begin(9600);
Serial3.begin(9600);
pinMode(directionPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(directionPin2, OUTPUT);
pinMode(stepPin2, OUTPUT);
}
void loop() {
if (Serial3.available() > 0) {
char data = Serial3.read();
switch (data) {
case 'F':
StepForward();
break;
default:
break;
}
}
//StepForward();
curMillis = millis();
}
void StepForward() {
if (curMillis - prevStepMillis >= millisBetweenSteps) {
prevStepMillis = curMillis;
//digitalWrite(directionPin, LOW);
//digitalWrite(directionPin2, LOW);
digitalWrite(stepPin, HIGH);
digitalWrite(stepPin, LOW);
digitalWrite(stepPin2, HIGH);
digitalWrite(stepPin2, LOW);
}
}
"
This doesn't work, and it's probably something I'm missing in the code. The steppers step way slower that they did with the previous code. The Android app is sending the 'F' every 50ms.
I've also made other functions for going backwards, left, right and to stop. They all have the same issue.
How can I get the steppers to drive the same way they do by directly running 'StepForward()' in the first code?