I have a LCD with a motor driver to make a simple line following robot
now the problem is that when I try to print the current state to the LCD it prints it but after some time it glitches and then comes back.
CODE:
#include <LiquidCrystal_I2C.h>
int enA = 8;
int in2 = 9;
// Motor B connections
int enB = 10;
int in4 = 11;
int L_I = A0;
int R_I = A1;
LiquidCrystal_I2C lcd(0x27, 16, 2);
String state = "Forward";
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("W");
delay(100);
lcd.print("E");
delay(100);
lcd.print("L");
delay(100);
lcd.print("C");
delay(100);
lcd.print("O");
delay(100);
lcd.print("M");
delay(100);
lcd.print("E");
delay(400);
lcd.clear();
lcd.print("Let's Go");
delay(500);
lcd.clear();
// Set all the motor control pins to outputs
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in4, OUTPUT);
// Turn off motors - Initial state
digitalWrite(in2, LOW);
digitalWrite(in4, LOW);
}
void loop() {
bool left_input = (bool)digitalRead(L_I);
bool right_input = (bool)digitalRead(R_I);
Serial.println(left_input);
Serial.println(right_input);
if (left_input == 1 && right_input == 0) {
turnLeft();
} else if (left_input == 0 && right_input == 1) {
turnRight();
} else {
forward();
}
}
void forward() {
if (state != "Forward") {
state = "Forward";
Serial.println(millis());
lcd.clear();
delay(40);
lcd.print(state);
}
digitalWrite(in2, HIGH);
digitalWrite(in4, HIGH);
digitalWrite(enA, HIGH);
digitalWrite(enB, HIGH);
}
void turnLeft() { //turnLeft
if (state != "Left") {
state = "Left";
Serial.println(millis());
delay(40);
lcd.clear();
delay(40);
lcd.print(state);
}
digitalWrite(in2, HIGH); //Right Motor backword Pin
analogWrite(in4, 100); //Left Motor forword Pin
digitalWrite(enA, HIGH);
digitalWrite(enB, LOW);
}
void turnRight() { //turnRight
if (state != "Right") {
state = "Right";
Serial.println(millis());
lcd.clear();
delay(40);
lcd.print(state);
}
analogWrite(in2, 100); //Right Motor backword Pin
digitalWrite(in4, HIGH); //Left Motor forword Pin
digitalWrite(enA, LOW);
digitalWrite(enB, HIGH);
}
// This function lets you control speed of the motors
void speedControl() {
// Turn on motors
digitalWrite(in2, HIGH);
digitalWrite(in4, HIGH);
// Accelerate from zero to maximum speed
for (int i = 0; i < 256; i++) {
analogWrite(enA, i);
analogWrite(enB, i);
delay(20);
}
// Decelerate from maximum speed to zero
for (int i = 255; i >= 0; --i) {
analogWrite(enA, i);
analogWrite(enB, i);
delay(20);
}
// Now turn off motors
digitalWrite(in2, LOW);
digitalWrite(in4, LOW);
}
now I think the issue is either voltage or EMF interference.