sudo|Xanthippe

But once I caught him when he was open like Silenus' statues, and I had a glimpse of the figures he keeps hidden within: they were so godlike — so bright and beautiful, so utterly amazing — that I no longer had a choice: I just had to do whatever he told me.

Tag: hardware

Transforming Raspberry Pi to a game console

Before yesterday I’ve never used Python. I was actually forced to do it because of the fact that it is now official language of Raspberry Pi. After spending one day with it I have to say that it’s amazing and I would recommend it for anyone who want to start programming (not advanced programmer here actually). Yesterday I modified already written Pong clone to use GPIO interface and move paddle when I push a button. Then I thought that it is rather senseless because keyboard can do it better. And then I come up with an idea that it would have sense if there were two players using custom controllers. I decided to write my own Pong clone which I called PiPong! At the end of that post you’ll find a source code. To run it you’ll need to images – for paddle and for ball. You can download package there: http://sourceforge.net/projects/pipong/files/. You can test it also on your computer. To do that, run keypong.py instead of pipong.py, which is made for Raspberry Pi. You’ll need also Pygame which can be downloaded there: http://www.pygame.org/download.shtml If you’re using a 64-bit version of Windows with Python 2.7 or 3.x, there is a binary for you: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

This is how it looks:

# www.sudoxanthippe.wordpress.com
# PiPong!

import pygame, random
from pygame.locals import *
import RPi.GPIO as GPIO
pygame.init()

def menu():
	    
    pygame.init()
    display = True
    
    # Setting resolution
    screen = pygame.display.set_mode((800,600), 0, 24)
    # Hiding mouse
    pygame.mouse.set_visible(False)
    # Setting window's caption
    pygame.display.set_caption("PiPong!")
    # Displaying starting label 
    label = pygame.font.SysFont("Tahoma", 25).render("Press ENTER to start!", 1, (185,0,0))
    # Checking size of the Surface
    background = pygame.Surface(screen.get_size())
    # Returning converted size
    background = background.convert()
    # Filling background with colour
    background.fill((45,45,45))
    
    while display:
        
        for event in pygame.event.get():
        # Checking if RETURN key was pressed    
            if pygame.key.get_pressed()[pygame.locals.K_RETURN]:
		# Go further
                    display = False
        
        # Dealing with the colours of the menu
        color = (200, 200, 200)
        rectangle = pygame.Surface((265, 50))
        rectangle = rectangle.convert()
        rectangle.fill(color)
        # Refreshing menu elements
        screen.blit(background, (0,0))
        screen.blit(rectangle, (264, 280))
        screen.blit(label, (280, 290))
        
        # Update the full display Surface to the screen
        pygame.display.flip()
        
def game():
	pygame.init()
	display = True
	
	# Setting resolution
	screen = pygame.display.set_mode((800,600))
	# Hiding mouse
	pygame.mouse.set_visible(False)
	# Setting window's caption
	pygame.display.set_caption("PiPong!")
	

	# Checking size of the Surface
	background = pygame.Surface(screen.get_size())
	# Returning converted size
	background = background.convert()
	# Filling background with colour
	background.fill((45,45,45))
	
	# Loading images
	sprite_pad = pygame.image.load("pad.png")
	sprite_pad_mirror = pygame.transform.flip(sprite_pad, True, False)
	sprite_ball = pygame.image.load("ball.png")
	
	# Converting images to sprites
	rect_pad1 = sprite_pad.get_rect()
	rect_pad2 = sprite_pad_mirror.get_rect()
	rect_ball = sprite_ball.get_rect()
	
	
	# Ball movement speed
	hspeed = 0
	vspeed = 0
	while hspeed == 0:
		hspeed = random.choice([-4, 4])
	while vspeed == 0:
		vspeed = random.choice([-4, 4])
	slower = 1
	
	score1 = 0
	score2 = 0
	
	pad_y = 300
	pad_y_2 = 300
	
	while display:

		# Ball movement
		slower -= 1
		if slower == 0:
			slower = 5
			
		# Pads movement for keyboard
		if pygame.key.get_pressed()[pygame.locals.K_s]:
			if (pad_y <= 500):
				pad_y = pad_y + 4
		if pygame.key.get_pressed()[pygame.locals.K_w]:
			if (pad_y >= 10):
				pad_y = pad_y - 4
		if pygame.key.get_pressed()[pygame.locals.K_DOWN]:
			if (pad_y_2 <= 500):
				pad_y_2 = pad_y_2 + 4
		if pygame.key.get_pressed()[pygame.locals.K_UP]:
			if (pad_y_2 >= 10):
				pad_y_2 = pad_y_2 - 4
		
		# Pads movement for GPIO		
		if GPIO.input(22):
			if (pad_y <= 500):
				pad_y = pad_y + 4
		if GPIO.input(24):
			if (pad_y >= 10):
				pad_y = pad_y - 4
		if GPIO.input(21):
			if (pad_y_2 <= 500):
				pad_y_2 = pad_y_2 + 4
		if GPIO.input(19):
			if (pad_y_2 >= 10):
				pad_y_2 = pad_y_2 - 4			
								
		# Setting sprites position
		rect_pad1.left = 25
		rect_pad1.top = pad_y
		rect_pad2.left = 750
		rect_pad2.top = pad_y_2
		
		# Score refreshment
		score1_str = str(score1)
		score2_str = str(score2)
		score = pygame.font.SysFont("Tahoma", 18).render(score1_str + ":" + score2_str, 1, (155,122,222))
				
		# Ball movement
		if hspeed < 0:
			if (rect_ball.left + hspeed > 5):
				rect_ball.left += hspeed
				GPIO.output(23, False)
			else:
				rect_ball.left = 400
				rect_ball.top = 300
				score1 = score1 + 1
				GPIO.output(23, True)
		else:
			if (rect_ball.left + hspeed < 750):
				rect_ball.left += hspeed
				GPIO.output(23, False)
			else:
				rect_ball.left = 400
				rect_ball.top = 300
				score2 = score2 + 1
				GPIO.output(23, True)
		if vspeed < 0:
			if (rect_ball.top + vspeed > 5):
				rect_ball.top += vspeed
			else:
				vspeed = -vspeed
		else:
			if (rect_ball.top + vspeed < 550):
				rect_ball.top += vspeed
			else:	
				vspeed = -vspeed

		# Collision detection
		hit = False
		# Pad1
		if ((rect_ball.left >= rect_pad1.left) and \
		(rect_ball.left <= rect_pad1.left + rect_pad1.width) and \
		(rect_ball.top >= rect_pad1.top) and \
		(rect_ball.top <= rect_pad1.top + rect_pad1.height)):
			hit = True
		# Pad2
		if (rect_ball.left >= rect_pad2.left-27) and \
		(rect_ball.top >= rect_pad2.top) and \
		(rect_ball.top <= rect_pad2.top + rect_pad2.height):
			hit = True
			
		# When collision is detected
		if (hit == True):
			if (rect_ball.left > 400):
				rect_ball.left = rect_ball.left - 5
			else:
				rect_ball.left = rect_ball.left + 5
			hspeed = -hspeed

		if pygame.key.get_pressed()[pygame.locals.K_ESCAPE]:
			display = False
		# Killing process
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				display = False
			if pygame.key.get_pressed()[pygame.locals.K_RETURN]:
			# Go further
				menu()
		
		# Dealing with the colours
		screen.blit(background, (0,0))
		screen.blit(sprite_pad, rect_pad1)
		screen.blit(sprite_ball, rect_ball)
		screen.blit(sprite_pad_mirror, rect_pad2)
		screen.blit(score, (375, 555))
		
		# Update the full display Surface to the screen
		pygame.display.flip()
		
		
def main():
	#GPIO initialize
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(22, GPIO.IN)
	GPIO.setup(24, GPIO.IN)
	GPIO.setup(21, GPIO.IN)
	GPIO.setup(19, GPIO.IN)
	GPIO.setup(23, GPIO.OUT)
	menu()
	game()

main()

Learning how to use GPIO

GPIO is very cool feature. When I managed to light a diode using it, I decided to check how input works. I made such configuration with switch, diode and resistors:

We’ve got now four wires connected to our RPi – one is ground (GND), one is power (VCC 3.3V), one is output (PIN23) and one is input(PIN24).  The only new thing, when we compare this to configuration from last post, is that now we have a switch connected to the input. Don’t forget to connect it from PIN24 side to GND with 10k resistor. This is how you should connect it to RPi:

Now it’s time to write a python program that will handle it.

Type in console:

cat > button.py

You will create a new file and start to edit its contents so type then:


import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.IN)
test = 0
while True:
           if GPIO.input(24):
                GPIO.output(23, True)
                if test == 0:
                             print 'You pushed the button!'
                             test = 1
            else:
                GPIO.output(23, False)
                test = 0

Then press ctrl + d. You can do that of course with any text editor you want (nano for example). Just make sure that file have such content.

Try to run it:

python button.py

Now if you press the button the led diode should light up and you should see on your screen a message.

Preparations for using GPIO on Raspberry Pi

While I’m waiting for the very last parts for my balloon project I decided to test GPIO interface on RPi. My objective was to light LED diode from a python console. I’ll show you how to that step by step.

There is webpage which really helped me, you can find schematics of GPIO pins there: LINK. There is my RPi with one of these schematics:

Carefully connect one wire to 3v3 output and one to GND. There is simple schematic for that:

Then you need to connect it to LED diode and 100Ω resistor if you are using red diode. Remember that longer leg is cathode (+) and shorter is anode (-). It should light up.

If you are using other type of LED diode you need to check it’s voltage and then do some calculations to select suitable resistor for your configuration.  You can use special calculator to do that or count that in old-fashioned way by using that formula:

R = (Vs – Vl) / I

r – resistance that you need

Vs – supply voltage (3.3V for us)

Vl – diode voltage (about 2V)

I – LED current (0.02A)

So let’s calculate this:

R = (3.3V – 2V) / 0.02A = 65 Ω

I used 100Ω for that so my diode is a bit subdued. It’s OK to use value that is higher than outcome of calculations.

If everything is working as described you can move to the next step.

Now we’re going to move one of the wires (this that is providing power do not move the grounding one) to pin 23 (GPIO11), there is schematic for that:

After you do that, your diode shouldn’t be lighting any more. Now we need to prepare Python.

At first we need to install python-dev package so type as root:

apt-get install python2.7-dev

Then download class which is able to control RPi’s GPIO. You can find it there: http://pypi.python.org/pypi/RPi.GPIO/0.3.1a#downloads. Unzip package:

gunzip FPi.GPIO-0.3.1.tar.gz
tar – xvf FPi.GPIO-0.3.1.tar

Then get into new catalogue:

cd FPi.GPIO-0.3.1

and type as root:

python setup.py install

GPIO class will be installed and you will be able to use it inside Python Shell. Let’s test if it is working!

Run Python 2 shell by simply typing:

python

 Be sure that you are using Python 2 not 3! It should be set do P2 on default. You can use for that also dedicated program when x server is started (you’ll find it under Programming section in LXDE menu).

After starting Python Shell your command prompt will change to:

>>>

Type there following commands:

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

GPIO.setup(23, GPIO.OUT)

Now observe your carefully diode and hold back the excitement! Type that command to light it up:

GPIO.output (23, True)

Congratulations! You just used your RPi to manage a low level peripheral! You are only one step from building a really advanced devices!

Raspberry Pi powering module (edit)

I noticed that there is a problem with my powering module when I’m connecting to Raspberry Pi devices that consume to much power. 7085 was limiting amperage to 1A so I decided to replace it with 78S05. You can do the same without modifying schematics I attached to last post which you can find HERE. I also installed small radiator which is leading away heat.

Raspberry Pi powering module

I’ve build a powering module for my balloon flight. This is how it looks:

Image

Image

To build the same you’ll need:

  • 1x LM7085
  • 1x 1000uF electrolytic capacitor
  • 2x 100nF ceramic capacitors

Schematics for that:

Image

Well, it could be build better, 7805 is wasting some power, that is just the simplest way of building such device. You could use 6 AA batteries as well. When I checked voltage on TP1 and TP2 on RPi board it showed me ~4.90V value. Keep in mind fact that my battery is drained a bit.

————————————————

EDIT 29-07-2012 19:47

Something about 10 minutes after connecting device I found out that 7805 is incredible hot, after next 5 minutes it stopped. To decrease temperature I mounted on it little radiator:

Now it’s good even when I’m putting it inside that box (these are outdated photos made before adding radiator):

As you probably noticed I’m powering device with 6xAA batteries instead of 1x9V battery. In this configuration I’m able to connect that Pentagram Wi-Fi modem and PS3 webcam, it’s working well.

Stationary balloon with Raspberry Pi (Part I)

Plan is simple. I’m going to mount RPi to a couple of balloons filled with hydrogen or helium (still not decided) and raise it 50 m above ground level. RPi will be connected to the Internet with 3g module and it will be streaming through it image from webcam. At this moment I’m gathering needed stuff.

I’ll need:

  • Raspberry Pi +
  • USB HUB powered by batteries –
  • Webcam +
  • 3g module – (I’ve got one but it’s not working on Raspbian, I’ll try on Arch)
  • Balloons –
  • Hydrogen (obtained in home way, I’ll show later how to do that) + / Helium –
  • 50 meters of thick fishing line

Photos of stuff I’ve already got:

Image

Some electronical parts.

Image

Mine Raspberry Pi with webcam that is working fine on it.

There’s a link to post with powering module: LINK.

Easiest and fastest way to get linux on Raspberry Pi

You are fledgling owner of Raspberry Pi? Well it was finally delivered to me, I really wasn’t interested in arduous configuring my operating system. I just wanted to test it out. RPi team gives us opportunity to have everything working in less than 10 minutes. On Raspberry Pi official page you can download Raspbian, dedicated distribution based on Debian.

Image

Inside zip archive you will find an img file. We still need to “burn it” on our SD card. Unix program called dd will do that for us. I’m using OS X for that so I’ll describe how to do it on mac, but dd is also available on Linux and it’ll work without changing anything.

1. Begin with checking how OS describes your SD card. Type in console:

ls /dev/ | grep disk

Last from that list will be probably the one you are looking for. This can be checked also with any   graphical tool that is used for disk management (for instance, gparted).

2. Unmount (but not eject!) selected disk by doing:

sudo diskutil umountDisk /dev/disk2

3. Now we are able to use dd. Type something like:

sudo dd if=~/Desktop/raspbian.img of=/dev/disk2

First parameter if must indicate img file location, second of location of SD card.

Whole process will last a few minutes. That’s all, now system is ready to boot. If your card is bigger that 2GB remember to expand / partition in gparted.

On Windows it is even simpler. You can use software that is called Win32 Disk Imager.