Hey, so my Capstone group is working on our prototype and we're stuck on how to get the ultrasonic sensor to start a timer. We believe it's a coding issue so if anyone can help us troubleshoot our code it would be much appreciated.
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
long cm = 0;
String lightColor = "green";
int ledpinG= 8 ; // the number of the LED pin
int ledpinR= 10 ; // the number of the LED pin
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds *0.01723
return (pulseIn(echoPin, HIGH)*0.01723);
}
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.clear ();
// Print a message to the LCD.
lcd.print("Start");
// initialize the led pin as an output:
pinMode(ledpinR, OUTPUT);
pinMode(ledpinG, OUTPUT);
Serial.begin(9600);
}
double i = 0;
double a = millis ();
double c;
int min=0;
int hours=0;
void loop() {
cm =readUltrasonicDistance(12,11);
Serial.print(cm);
Serial.println("cm");
//reads the object detected distance. If detected, light green
if (cm <= 300) {
digitalWrite(ledpinR, LOW);
digitalWrite(ledpinG, HIGH);
lightColor = "green";
//Serial.print("green");
}
else if (cm>=30){
digitalWrite(ledpinR, LOW);
digitalWrite(ledpinG, HIGH);
lightColor = "green";
}
else if (cm>300){
digitalWrite(ledpinR, HIGH);
digitalWrite(ledpinG, LOW);
}
//no object detected - light red
else {
digitalWrite(ledpinR, HIGH);
digitalWrite(ledpinG, LOW);
lightColor = "red";
delay(1); // Wait for 100 millisecond(s)
lcd.clear ();
lcd.print ("Press start");
delay (10);
if (lightColor == "red")
{
lcd.clear ();
a = millis ();
while (lightColor == "red")
{
c = millis ();
i = (c - a)/1000;
if(i==60)
{
a = millis ();
c = millis ();
i=0;
min++;
if(min==60)
{
min=0;
}
}
lcd.print(min);
lcd.print(':');
lcd.print (i);
lcd.setCursor (10, 2);
lcd.print ("Sec's");
lcd.setCursor (0, 0);
//Serial.println (c);
//Serial.println (a);
//Serial.println (i);
//Serial.println ("......");
delay (1);
}
if (lightColor == "green")
{
lcd.setCursor (0, 0);
lcd.print (i);
lcd.setCursor (11, 0);
lcd.print ("");
lcd.setCursor (0, 0);
delay (1);
}
}
}
}