2008 304

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

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

A simple Python script to test a "call & respond" session with the arduino:

import serial
ser = serial.Serial('/dev/ttyUSB0', 9600) # your serial port may be different
while 1:
	ser.write('x')			# call
	line = ser.readline()	# and read the response
	print line


And now combined with a simple PyGame program to visualize the sensor data received from Arduino:

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

import serial
ser = serial.Serial('/dev/ttyUSB0', 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))
	# 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)
		
		# draw to screen!
		pygame.display.update()
		# maintain frame rate
		clock.tick(30)

if __name__ == "__main__": main()