I just started coding and I'm trying to make a sketch which will tell my robot to reverse when it hits a wall and either turn left or right depending on which switch is hit. The code I currently have allows the robot to go forward,backward,right,left, but the limit switch just causes the LED on the UNO to light up, no change in state is seen in the serial monitor and no order is executed.
Controlable_motor_limit.ino (3.38 KB)
In your drawing, is the 9v battery positive lead connected by link 20 to the Uno Ground, that also has the battery negative attaced at the top line?
That's wire is not actually connected I was trying to mess around with stuff in thinkercad and forgot to delete that when sharing the photos
Anyone? I'm lost as what is wrong.
if (digitalRead(Lstate == HIGH))
That makes no sense. Lstate is already the result of a digitalRead():
.... so you probably mean that to be:
if (Lstate == HIGH))
However, with all those delay()s in the code, and that linear flow, it's only ever going to do that read right at the bottom of loop() so it's not going to register the limit switch as pressed except in exceptional co-incidental circumstances.
To make switches responsive, you really need to ditch all those delay()s for a millis()-based approach which is pretty much a re-thnk of the whole sketch. With millis() (and the thinking embodied in blink without delay) it's possible for many things to get a decent share of the processor. That's impossible with delay(), since during a delay() nothing else happens. So the vehicle might be cruising towards a wall under a delay() but the limit switch won't get read until the damage is done.
I see the limit switches are pinMode()-ed as INPUT, and it seems from the above that HIGH means a hit? So have you got pull down resistors on the switches to ensure they read LOW until they switch to HIGH?