gravity_y
Posts: 2
Joined: Wed May 01, 2019 12:12 am

How can I use a ultrasonic sensor to move a sprite up or down?

Wed May 01, 2019 12:16 am

I'm trying to make a similar game to flappy bird in python and using the ultrasonic sensor as the controller (it's all connected to a raspberry pi). if distance < 10, bird moves down, elif distance > 10 bird moves up. I am not too sure as to how I can connect the distance with the movement of the bird.

I've tried looking up various py game commands but I didn't have any luck so far.

Here's the code I have so far.

Code: Select all

import RPi.GPIO as GPIO
import time
import sys
import pygame                   
pygame.init()

GPIO.setmode(GPIO.BCM)

TRIG = 4
ECHO = 18

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

def get_distance():                      
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)

    while GPIO.input(ECHO) == False:
        start = time.time()

    while GPIO.input(ECHO) == True:
        end = time.time()

    sig_time = end-start            

    distance = sig_time / 0.000058 

    print ('Distance: {} cm'.format(distance))
    return distance


#   distance = get_distance()  ### stuck here
 #   if distance < 10:
       # bird1.

screenwidth = 600               #creating the world
screenheight = 400
speed = [4,4]
black = 0,0,0
skyblue = 0,231,252

screen = pygame.display.set_mode((600, 400))

bird1 = pygame.image.load("bird1.png")      
bird2 = pygame.image.load("bird2.png")
pipe = pygame.image.load("pipe1.png")
gameover = pygame.image.load("game-over.png")
gameover = pygame.transform.scale(gameover,(width,height))
gameoverrect = gameover.get_rect()

bird1height = bird1.get_height()      
bird1 = pygame.transform.scale(bird1,(int(bird1.get_height()*0.6),int(bird1.get_height()*0.6)))     #making the bird smaller to fit the screen better
bird2 = pygame.transform.scale(bird2,(int(bird2.get_height()*0.6),int(bird2.get_height()*0.6)))
bird1rect = bird1.get_rect()         
print ('bird1rect')                 #positioning 
bird1rect.x = 20
piperect = pipe.get_rect()
pipestartx = 600
pipestarty = 0
piperect.x, piperect.y = pipestartx, pipestarty
for x in range(0,600):
    screen.blit(bird1,(x,200))                                                                                                                                               


class pipe():                               #creating the pipe
    def __init__(self,startx,position = "top",pipeHeight = 200):
        self.sprite = pygame.image.load("pipe1.png")
        self.sprite = pygame.transform.scale(self.sprite,(50,pipeHeight))
        self.rect = self.sprite.get_rect()
        self.rect.x = startx

        if position == "top":
            self.rect.y = 0
        else:
            self.sprite = pygame.transform.rotate(self.sprite,180)
            self.rect.y = height - self.sprite.get_height()

pipelist = []                           #this creates the pipes in the world
pipelist.append(pipe(200,"top",220))
pipelist.append(pipe(200,"bottom",90))
pipelist.append(pipe(600,"top",140))
pipelist.append(pipe(600,"bottom",190))
pipelist.append(pipe(800,"bottom",100))
pipelist.append(pipe(800,"top",220))
pipelist.append(pipe(1000,"top",100))
pipelist.append(pipe(1000,"bottom",220))
pipelist.append(pipe(1200,"top",280))
pipelist.append(pipe(1200,"bottom",50))

fontObj = pygame.font.Font("C:\Windows\Fonts\Arial.ttf",40)       #creating a new font object
I expect to be able to move the bird using the ultrasonic sensor as a controller. Feel free to provide links to online sources that can help me out, I'd love to learn more.

scotty101
Posts: 3680
Joined: Fri Jun 08, 2012 6:03 pm

Re: How can I use a ultrasonic sensor to move a sprite up or down?

Wed May 01, 2019 8:57 am

You might find PyGame Zero easier if you are a beginner. https://pygame-zero.readthedocs.io/en/stable/

Your code at the moment doesn't have any thing in there to update the position of the objects, most PyGame programs have a "main loop" which periodically redraws/updates items. The code to change the position of the bird would be in there.

Basically you need to read the distance, limit it between a certain range (say 5 to 30 cm away from the sensor) and then convert that distance to a pixel value and move the bird to that position.
5cm for example might mean placing the bird at the Y coordinate 200 and 30cm might mean Y coordinate 0.

The equation for that would be y = -8*distance - 240.

One thing to be very aware of is that ultrasonic sensors aren't very accurate and one reading you might get 10cm, the next you might get 15cm so the bird might suddenly jump and fly in to a pipe.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

gravity_y
Posts: 2
Joined: Wed May 01, 2019 12:12 am

Re: How can I use a ultrasonic sensor to move a sprite up or down?

Wed May 01, 2019 7:10 pm

scotty101 wrote:
Wed May 01, 2019 8:57 am
You might find PyGame Zero easier if you are a beginner. https://pygame-zero.readthedocs.io/en/stable/

Your code at the moment doesn't have any thing in there to update the position of the objects, most PyGame programs have a "main loop" which periodically redraws/updates items. The code to change the position of the bird would be in there.

Basically you need to read the distance, limit it between a certain range (say 5 to 30 cm away from the sensor) and then convert that distance to a pixel value and move the bird to that position.
5cm for example might mean placing the bird at the Y coordinate 200 and 30cm might mean Y coordinate 0.

The equation for that would be y = -8*distance - 240.

One thing to be very aware of is that ultrasonic sensors aren't very accurate and one reading you might get 10cm, the next you might get 15cm so the bird might suddenly jump and fly in to a pipe.
Thank you so much Scotty, I will look into pygame zero after I get home from my class. I really hope that I can get it to work tonight.

Return to “Gaming”