Hello all, Im pretty new to arduino but I am trying to get the hand of it. I have a small project (soap dispenser) I am working on. The ultrasonic sensor triggers a servo that dispenses soap and the LCD at the same time. The LCD should display to "wash hands for 30 secs" and initialize a timer. The first message works fine but when it gets to the counter the LCD displays very weird characters and does not clear to display the last message of"Thank you".
My questions are:
Do you see anything wrong with my code that is not allowing for the LCD to work properly and display the timer?
Should I use lcd.clear() to clear the lcd before a new message?
Hardware:
LCD 1602 Module
Servo Motor (SG90)
Ultrasoni Sensor (HC-SR04)
Potentiometer
Here is the code:
// defines pins numbers
const int servo = 9;
const int trigPin = 10;
const int echoPin = 11;
const int rs = 1, en = 2, d4 = 4, d5 = 5, d6 = 6, d7 = 7;
// defines variables
long duration;
int distance;
int StartTimer;
int Timing;
int TimeStart;
int Timer;
int TimeNow;
#include <Servo.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
Servo myservo; // servo object to control a servo
int pos = 0; // stores the servo position
char timeline[16];
void setup() {
lcd.begin(16, 2);
lcd.print("Stop The Spread");
lcd.setCursor(0, 1);
lcd.print("Wash Your Hands");
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
myservo.attach(servo); // attaches the servo on pin 9 to the servo object
myservo.write(0); // Sets Servo to initially 0 degrees
Serial.begin(9600); // Starts the serial communication
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Sets the trigPin on HIGH state for 10 micro seconds
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
distance = duration * 0.034 / 2; // Calculating the distance
Serial.print("Distance: "); // Prints the distance on the Serial Monitor
Serial.println(distance);
if (distance < 10) { //Check distance is less than 10cm
myservo.write(45);
delay(100);
myservo.write(90);
delay(100);
myservo.write(135);
delay(100);
myservo.write(180);
delay(100);
myservo.write(0); // Reset the servo to 0 Degrees
delay(2000);
StartTimer = 1;
Timing = 1;
//StartTimer
while (Timing == 1)
{
if (StartTimer)
{
TimeStart = millis(); // capture time at start of timer
StartTimer = 0;
}
else
{
TimeNow = millis();
Timer = (TimeNow - TimeStart) / 1000; // diff in start time and now is time for timer
lcd.setCursor(0, 0);
sprintf(timeline, "%0.2d Secs", Timer);
lcd.print(timeline);
}
if (Timer > 30.0) {
Timing = 0;
}
}
}
}