I want to make a self-guided car using the stored waypoints as reference for travel.
This is the simple logic:
a) Read GPS coordinates -> travel based on bearing and distance w.r.t next (stored) Waypoint
b) Read HC-SR04; if obstacle is too close, turn left and travel for x seconds. Then go to Step a (above)
It continuously reads GPS and HC-SR04 inputs and outputs/ controls 2 DC motors
I plan to use an INTERRUPT for avoiding obstacles as that is high priority task. For now, I have written a dummy code lighting Green LED in loop() and RED in interrupt when obstacles are met.
#include <NewPing.h> //library for UltraSonic Sensor
//============== HC-SR04 variables ===========
int TRIGGER_PIN_FRONT = 6;
int ECHO_PIN_FRONT = 2;
int MAX_DISTANCE = 200;
int thresholdDistance = 5;
int hurdleDistance = 0;
NewPing frontUSS(TRIGGER_PIN_FRONT, ECHO_PIN_FRONT, MAX_DISTANCE);
//============== TIMERS ================
int CYCLE_PERIOD = 500;
long lastCYCLE_TIME = 0;
//============== Indicator LEDs ======================
int greenLED = 5;
int redLED = 4;
bool resetLEDs = true;
void setup() {
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
attachInterrupt(digitalPinToInterrupt(2),subroutine_MeasureHurdleDistance, CHANGE); //
}
void loop() {
//In normal loop, blink GREEN LED - to be substitued with Motor Navigation code
if (resetLEDs) {
digitalWrite(redLED, LOW);
blinkLED(greenLED);
}
else {
digitalWrite(greenLED, LOW);
}
}
void blinkLED(int pinNo) {
digitalWrite(pinNo, LOW);
//using delayMicroseconds as it works inside interrupt (will be used to let car complete the turn)
delayMicroseconds(10000000);
digitalWrite(pinNo, HIGH);
delayMicroseconds(10000000);
}
void subroutine_MeasureHurdleDistance() {
if ((millis() - lastCYCLE_TIME) > CYCLE_PERIOD)
{
resetLEDs = false;
unsigned int uS = frontUSS.ping();
if ((uS / US_ROUNDTRIP_CM) <= thresholdDistance){
digitalWrite(greenLED, LOW);
blinkLED(redLED);
}
lastCYCLE_TIME = millis();
resetLEDs = false;
}
else {
resetLEDs = true;
}
}
Above code is not working for me - the GREEN LED stays HIGH and the RED led flickers continuously - as a function of CYCLE_PERIOD variable.
Also, the articles/ blogs I read seem to fire interrupt only when input on pin 2 changes from 0 to 1 or vice versa - which is not so in my pin 2's continuous input. It reads some voltage value as a function of obstacle distance
So, I request guidance on below questions:
1- Where am I going wrong in my current code
2- Is my Interrupt definition wrong? If so, how can I correct it
3- Is the thought process - inputs/ sensors - correct
Would appreciate your guidance.
Regards