I got L298 working with a Serial monitor for the train. I just add Hall Sensor at the end of the track. The loco has a small magnetic underneath by wheel. It is working when the loco goes over the hall sensor and it stops but I can't run the loco again to reverse unless I had to move it away from the hall sensor and hit 6 to reverse to run again. Here is my code for it. Can someone help me with this? Also, I would like to add two servos for turnout. I am not sure how to do this.
// Sensor
int SENSOR = 2 ; // define the Hall magnetic sensor
// Motor A connections
int enA = 9;
int in1 = 8;
int in2 = 7;
void setup() {
pinMode (SENSOR, INPUT) ; // define the Hall magnetic sensor line as input
// Set all the motor control pins to outputs for L298
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
// Start up serial connection
Serial.begin(9600);
// Turn off motors - Initial state
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
void loop()
{
while (digitalRead(SENSOR) == LOW){
Serial.println("Magnetic field detected");
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
if (Serial.available())
{
int state = Serial.parseInt();
if (state == 0){
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
if (state == 1){
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
analogWrite(enA, 120);
}
if (state == 6){
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
analogWrite(enA, 100);
}
}
}