hello,
I'm trying to get my project working by tomorrow evening so a timely response would be greatly appreciated (fingers crossed). Anyway, the goal of this project is to have a car drive down a track as fast as possible, then slow down at 8.5m and stop at 12m. I wrote up my code and so far it will only get as far as spinning up the motor and counting wheel turns using the optical shaft encoder. Can anyone please explain where the code is getting "stuck" and possibly offer some solutions?
This is my first time coding anything and I am here to learn so dont hold back, drop some knowledge on me!!
any reply would be greatly helpful.
thanks in advance,
Patrick
heres my sketch:
/* pins:
* optical shaft encoder = 3,5
* button = 11
* esc = 9
* led = 13
*/
#include <Servo.h>
Servo motor;
//IMPORTANT PART HERE
const int trackDist = 12000; //in MILLIMETERS ex. (11500cm = 11.50m)
const int wheelDi = 725; //in MILLIMETERS
const int countTurn = 30; //check that (shaft encoder count per turn)
//IMPORTANT PART HERE
int val;
const int encoderPinA = 3;
const int encoderPinB = 5;
int encoderPos = 0;
int encoderPinALast = LOW;
int n = LOW;
int final = 0;
int wheelTurn;
int distTrav;
unsigned long startMillis = 0;
const int buttonPin = 11;
int buttonState;
int start = LOW;
const int ledPin = 13;
void setup() {
Serial.begin (9600);
pinMode (encoderPinA,INPUT);
pinMode (encoderPinB,INPUT);
pinMode (buttonPin, INPUT);
pinMode (ledPin, OUTPUT);
motor.attach(9);
motor.writeMicroseconds(1500);
}
void loop() {
wheelTurn = encoderPos / countTurn;
distTrav = wheelTurn * wheelDi * 314 / 1000;
n = digitalRead(encoderPinA);
if ((encoderPinALast == LOW) && (n == HIGH)) {
if (digitalRead(encoderPinB) == LOW) {
encoderPos--;
} else {
encoderPos++;
}
Serial.print (encoderPos);
Serial.print ("/");
}
encoderPinALast = n;
buttonState = digitalRead(buttonPin);
unsigned long currentMillis = millis();
digitalWrite(ledPin, HIGH);
if (buttonState == HIGH) {
encoderPos = 0;
start = HIGH;
}
if (start == HIGH && distTrav < 8500) {
startMillis = currentMillis;
motor.writeMicroseconds(2000);
}
if (distTrav >= 8500 && distTrav < trackDist) { //optional braking before cruise stage
motor.writeMicroseconds(1400);
delay(200);
motor.writeMicroseconds(1600);
}
if (distTrav >= trackDist) { //optional relax on motor after stop stage
motor.writeMicroseconds(1400);
delay(2000);
motor.writeMicroseconds(1500);
}
/* if (currentMillis - startMillis >= 8000) { //failsafe
motor.writeMicroseconds(1500);
digitalWrite(ledPin, HIGH);
} */
}