bjucha
Posts: 7
Joined: Thu Aug 02, 2018 5:01 am

Distance sensor does not work after introducing the keypress function

Wed May 08, 2019 6:11 pm

Need help to figure out why since introducing a function to detect keypress the if statement for distance sensor does not work anymore on my robot
I have tried moving it around and changing it but without luck.
The forward function does work so goes into the while True statement

happy for any help:

Code: Select all

#!/usr/bin/python3

import RPi.GPIO as GPIO
from datetime import datetime
from picamera import PiCamera
import time
#import keyboard
import random
import termios
import tty
import sys
import os

os.system("sudo service motion stop")





kamera = PiCamera()
namn = datetime.now().strftime('%c')

def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
             
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch


try:

    while True:
        GPIO.setmode(GPIO.BOARD)
        
        #forward()
        PIN_TRIGGER = 7
        PIN_ECHO = 11
        
          
            
        def init():
            GPIO.setup(31, GPIO.OUT)
            GPIO.setup(33, GPIO.OUT)
            GPIO.setup(35, GPIO.OUT)
            GPIO.setup(37, GPIO.OUT)
        
        def forward():
            init()
            GPIO.output(31, True)
            GPIO.output(33, False)
            GPIO.output(35, True)
            GPIO.output(37, False)


        def reverse():
            init()
            GPIO.output(31, False)
            GPIO.output(33, True)
            GPIO.output(35, False)
            GPIO.output(37, True)

        def back_left():
            init()
            GPIO.output(31, False)
            GPIO.output(33, True)
            GPIO.output(35, False)
            GPIO.output(37, False)
            
        def back_right():
            init()
            GPIO.output(31, False)
            GPIO.output(33, False)
            GPIO.output(35, False)
            GPIO.output(37, True)

        def stopit():
            init()
            GPIO.output(31, False)
            GPIO.output(33, False)
            GPIO.output(35, False)
            GPIO.output(37, False)
        
        
        
        GPIO.setup(PIN_TRIGGER, GPIO.OUT)
        GPIO.setup(PIN_ECHO, GPIO.IN)

        GPIO.output(PIN_TRIGGER, GPIO.LOW)

       

        time.sleep(0.2)

        

        GPIO.output(PIN_TRIGGER, GPIO.HIGH)

        time.sleep(0.00001)

        GPIO.output(PIN_TRIGGER, GPIO.LOW)

        while GPIO.input(PIN_ECHO)==0:
            pulse_start_time = time.time()
        while GPIO.input(PIN_ECHO)==1:
            pulse_end_time = time.time()

        pulse_duration = pulse_end_time - pulse_start_time
        distance = round(pulse_duration * 17150, 2)
       # print ("Distance:",distance,"cm")
       
      
            
        
            
        if distance < 30:  // This part has stopped working
           
            stopit()
            kamera.capture('/home/pi/robot/bilder/'+namn+'.jpeg')
            os.system("/home/pi/robot/send_mail.py")
	    #print("Distance:",distance,"cm")
            #back_right()
            r = random.randint(0,11)
            if r > 5:
                
                back_right()
                time.sleep(0.5)
               
               
                
            else:
                
                back_left()
                time.sleep(0.5)
                
        
            
        
            
                
        else:
            forward()


            
                
                    
            char = getch() 


            if (char == "s"):
                print("Turning")
                back_left()
                time.sleep(0.2)

            elif (char == 'a'):
                print("Turning")
                back_right()
                time.sleep(0.2)    

except KeyboardInterrupt:
    print("Robot stopping")
    stopit()

    GPIO.cleanup()


User avatar
MrYsLab
Posts: 312
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: Distance sensor does not work after introducing the keypress function

Wed May 08, 2019 9:11 pm

Please don't take this the wrong way, but your code is a bit of a mess.

You are initializing the GPIO within a while loop as well as defining functions within that loop. You probably want to do all the GPIO initialization in your init function and just break out all the defs out of the loop. You should probably place setting of the echo and trigger GPIO modes in init as well.

Perhaps you should create a separate function to measure distance.

Also for this code:

Code: Select all

    else:
        forward()

        char = getch()

        if (char == "s"):
            print("Turning")
            back_left()
            time.sleep(0.2)

        elif (char == 'a'):
            print("Turning")
            back_right()
            time.sleep(0.2)
I am not sure if you only want to call getch when the distance >= 30 and the robot is going forward. I believe that is what your code is currently doing.

bjucha
Posts: 7
Joined: Thu Aug 02, 2018 5:01 am

Re: Distance sensor does not work after introducing the keypress function

Thu May 09, 2019 6:25 am

Thanks fore the info, Im not very good at coding, I have learned from tutorials, and got it to work
But, I re-write it better after your instructions.

Return to “Python”