2008 304: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
(No difference)

Revision as of 12:01, 21 May 2008

Some websites:

Hardware hacking with arduino


Example Programs

Arduino:

int a1_port = 0;                // LED connected to digital pin 13
int a1_value = 0;
int resetButton = 2;
int serveButton = 3;
int reset = 0;
int serve = 0;

void setup()                    // run once, when the sketch starts
{
: Serial.begin(9600);
: pinMode(resetButton, INPUT);      // sets the digital pin as output
: pinMode(serveButton, INPUT);      // sets the digital pin as output
}

void loop()                     // run over and over again
{
: if (Serial.available() > 0) {
: int inByte = Serial.read();
: 
: a1_value = analogRead(a1_port);
: reset = digitalRead(resetButton);
: serve = digitalRead(serveButton);
: 
: Serial.print(a1_value);
: Serial.print(",");
: Serial.print(reset);
: Serial.print(",");
: Serial.println(serve);
: }
}


Python / PyGame

import pygame
from pygame.locals import *
SCREENRECT = Rect(0, 0, 640, 480)

import serial
ser = serial.Serial('/dev/ttyUSB1', 9600)


def main():
	(min_analog, max_analog) = (None, None)
	avalue = 0
	
	pygame.init()
	screen = pygame.display.set_mode(SCREENRECT.size, 0)
	
	# make background
	background = pygame.Surface(SCREENRECT.size).convert()
	background.fill((0, 255, 0))
	screen.blit(background, (0,0))
	pygame.display.update()
	
	# keep track of sprites
	all = pygame.sprite.[[RenderUpdates]]()
	
	# keep track of time
	clock = pygame.time.Clock()
	
	# game loop
	while 1:
		
		# get input
		for event in pygame.event.get():
			if event.type == QUIT or \
				(event.type == KEYDOWN and \
				event.key == K_ESCAPE):
				return
		
		ser.write("x")
		arduino_data = ser.readline()
		# print arduino_data
		
		try:
			(analog, s1, s2) = arduino_data.split(",")
			analog = int(analog)
			s1 = int(s1)
			s2 = int(s2)
		except [[ValueError]]:
			pass
		
		# print analog
		
		if min_analog == None or analog < min_analog:
			min_analog = analog
		
		if max_analog == None or analog > max_analog:
			max_analog = analog
		
		if (max_analog != min_analog):
			avalue = float(analog - min_analog) / (max_analog - min_analog)
				
		
		bgcolor = (0, 0, 0)
		if s1: bgcolor=(255, 255, 0)
		background.fill(bgcolor)
		screen.blit(background, (0,0))
		
		r = avalue * SCREENRECT[3] / 2
		pos = (SCREENRECT[2] / 2, SCREENRECT[3]/2)
		# print r, pos
		pygame.draw.circle(screen, (255, 255, 0), pos, r)
		
		
		pygame.display.update()
		
		# maintain frame rate
		clock.tick(30)

if __name__ == "__main__": main()