How do I set a pause between if statements?

50 views Asked by At

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

There are 1 answers

0
Oliver Mason On

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.