0

I want to write a code that let’s a car drive if low light is detected and stop if a sonar sensor measures less than 20 cm. This has to be repeated. However, if the same low light is detected again while driving, the car has to stop completely and the code ends. Now I have the problem that if the LDR detects low light the first time, both the if-statements for low-light trigger immediately and the run comes to an end. How can I write it such that those two statements with essentialy the same requirements, don’t trigger both at the same time, but have like a short break between them (in which I can take my finger of the light sensor)? Because right now both statements trigger immediately after I put my finger on the LDR and the code just goes to state 'stop'.

while state != 'stop':
 pin14 = GetPinValue('14', 'analog')
 lightmeter = pin14.data
 sonar = GetDistanceLeft()
 distance = int(sonar.data)
 time.sleep(.2)
 if state == 'start':
 if lightmeter < 250:
 print('lightmeter < 250, transition from state "start" to "drive"')
 time.sleep(.5)
 state = 'drive' 
 SetRightSpeed(80)
 SetLeftSpeed(80)
 elif state == 'drive':
 if distance < 20:
 print('distance < 20 cm, transition from state "drive" to "start"')
 state = 'start'
 SetRightSpeed(0)
 SetLeftSpeed(0)
 
 elif state == 'drive':
 if lightmeter < 250:
 print('lightmeter < 250, transition from state "drive" to "stop"')
 state = 'stop'
 SetRightSpeed(0)
 SetLeftSpeed(0)
 
print('stopped')```

1 Answer 1

0

Your description is not very clear; from what I understand of it I would think you need another state: drive-after-light, to take not of the fact that you have already encountered the light, and stop if you encounter it again. You would use that to separate out your identical elif statements, depending on what already happened.

answered Mar 10, 2022 at 18:34
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.