Hardware Hacking en
Ruby: Arduino y RAD
Esti Álvarez y Svet Ivantchev
http://www.efaber.net
Conferencia Rails 2008
Sistemas integrados
Physical Computing
¿Qué es Arduino?
http://www.arduino.cc
¿Por qué Arduino?
• Es Open Source
• Es multiplataforma (Linux, Mac, Windows)
• Se puede programar con cable USB
• Pensado para hacer prototipos
• El hardware es barato (30€)
La familia Arduino
El Hardware
El Hardware
• 14 pins IO digitales
• 6 pins Input analógicos
• 6 pins Output analógicos (PWM)
• 16Kb memoria Flash (Apollo 11: 74 Kb)
• 1Kbyte RAM (Apollo 11: 4Kb)
• Microcontrolador ATMega168 a 16MHz
• Alimentación por USB o pila de 9V
Otras piezas
• Sensores “binarios”: interruptores,
termostatos, switches magnéticos, de
posición, de luz, etc
• Sensores “analógicos”: termistores,
accelerómetros.
• “Actuadores”: leds, motores, servos, LCDs
El Software
http://arduino.cc/en/Main/Software
Hello World: Hardware
Pin 13
Arduino
Hello World: Software
/* Blink
* The basic Arduino example.Turns on an LED on for one second,
* http://www.arduino.cc/en/Tutorial/Blink */
int ledPin = 13; // LED connected to digital pin 13
void setup() { // run once, when sketch starts
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() { // run over and over again
digitalWrite(ledPin, HIGH);// sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}
/* Code for cross-fading 3 LEDs, RGB, or one tri-color LED */
int redPin = 9; int greenPin = 10; int bluePin = 11;
int redVal = 255; int greenVal = 1; int blueVal = 1;
int i = 0; // Loop counter
void setup() {
pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
i += 1; // Increment counter
if (i < 255) {
redVal -= 1; greenVal += 1; blueVal = 1;
} else if (i < 509) {
redVal = 1; greenVal -= 1; blueVal += 1;
} else if (i < 763) {
redVal += 1; greenVal = 1; blueVal -= 1;
} else {
i = 1;
}
analogWrite(redPin, redVal); analogWrite(greenPin, greenVal);
analogWrite(bluePin, blueVal);
delay(10); // Pause for 10 milliseconds before resuming the loop
}
RAD: Ruby Arduino
Development
• Añadir a Arduino las ventajas de programar
en Ruby
• Convenciones y helpers inspirados en Rails
• Testing Framework aprovechando el
dinamismo de Ruby
• Entorno de simulación gráfica usando “Shoes
GUI”
RAD: Ruby Arduino
Development
$ sudo gem install rad
$ rad hello_world
Successfully created your sketch directory.
...
Added hello_world/hello_world2.rb
Added hello_world/Rakefile
Added hello_world/config
Added hello_world/config/hardware.yml
Added hello_world/config/software.yml
RAD: Ruby Arduino
Development
$ ls -l hello_world
-rw-r--r-- 1 esti esti 31 Rakefile
drwxr-xr-x 4 esti esti 136 config
drwxr-xr-x 42 esti esti 1428 examples
drwxr-xr-x 7 esti esti 238 hello_world
-rw-r--r--@ 1 esti esti 106 hello_world.rb
drwxr-xr-x 5 esti esti 170 vendor
Hello World
class HelloWorld < ArduinoSketch
output_pin 7, :as => :led
def loop
led.blink 500
end
end
Compilar y transferir
$ rake make:upload
Demo
Twitter Lámpara
Twitter Lámpara
Twitter Lámpara
Twitter Lámpara
Twitter Lámpara
TwitAmbiLight
• Comunicación por puerto serie
• Datos del REST API de Twitter
• Los colores de nuestra lámpara dependerán
del humor de nuestros followers en Twitter.
TwitAmbiLight: Ingredientes
• 1 Arduino y 1 breadboard
• 1 LED RGB y 3 resistencias de 220 ohms
• 1 Cable USB y unos cuantos de conexión
$ gem install toholio-serialport
$ gem install twitter
$ gem install mbbx6spp-twitter4r
TwitAmbiLight: Hardware
TwitAmbiLight: Hardware
+5 V +5 V +5 V
pin 11
USB
pin 10
Arduino
pin 9
PWM
Internet
TwitterAmbiLight: Software Ordenador
# Se conecta al API de Twitter y busca colores en formato RGB
# Hexadecimal entre los replies a @raduino
# Ejemplo: @raduino #FF0000
%w(rubygems twitter serialport).each {|g| require g}
gem 'mbbx6spp-twitter4r'
# params para puerto serie
port_str = \"/dev/tty.usbserial-A4001lmt\" # puede cambiar para ti
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits,
parity)
...
def get_color_from_twitter
client = Twitter::Client.new(:login => 'raduino',
:password => 'mypass')
last_status = client.status(:replies).first
color = last_status.text.gsub('@raduino', '').strip || ''
end
5.times do
puts \"Cojo el color\"
color = get_color_from_twitter
puts \"Devuelve #{color}\"
if color.match(/#[A-F0-9]{6}$/i)
puts \"Envio en color al puerto serie\"
sp.write color
end
puts \"-------------\"
sleep(10)
end
sp.close
TwitterAmbiLight: Software Arduino
class TwitAmbiLight < ArduinoSketch
output_pin 9, :as => :red_led
output_pin 10, :as => :green_led
output_pin 11, :as => :blue_led
r = 255; g = 255; b = 255
@first_byte = byte;
@byte1 = byte; @byte2 = byte; @byte3 = byte
@byte4 = byte; @byte5 = byte; @byte6 = byte
serial_begin
def setup
red_led.digitalWrite HIGH
green_led.digitalWrite HIGH
blue_led.digitalWrite HIGH
end
...
...
def loop
if serial_available
# Si el primer byte es #, leer los 6 siguientes
@first_byte = serial_read
if @first_byte == '#'
@byte1=serial_read; serial_print \"Primer caracter:\";serial_println @byte1
@byte2 = serial_read; serial_print \"2 caracter:\"; serial_println @byte2
@byte3 = serial_read; serial_print \"3 caracter:\"; serial_println @byte3
@byte4 = serial_read; serial_print \"4 caracter:\"; serial_println @byte4
@byte5 = serial_read; serial_print \"5 caracter:\"; serial_println @byte5
@byte6 = serial_read; serial_print \"6 caracter:\"; serial_println @byte6
r = 255 - h2d(@byte1) * 16 + h2d(@byte2)
g = 255 - h2d(@byte3) * 16 + h2d(@byte4)
b = 255 - h2d(@byte5) * 16 + h2d(@byte6)
end
serial_print \"Rojo: \"; serial_println r
serial_print \"Verde: \"; serial_println g
serial_print \"Azul:\"; serial_println b
red_led.analogWrite(r); green_led.analogWrite(g); blue_led.analogWrite(b)
delay(100)
end
end
...
...
def h2d(c)
if c >= 48 && c <= 57
# c esta entre 0 y 9
return c - '0'
elsif c >= 'A' && c <= 'F'
# c esta entre A y F
return c - 65 + 10
end
end
end
Demo
Opciones Wireless
Zigbee
GSM/GPRS 802. 11 Bluetooth
802.15.4
Moritorizado y Conectividad
Aplicación Voz y datos Internet rápido
control entre dispositivos
Duración ~ semanas ~ días ~ horas ~ horas
batería
Ancho de
250 kbps Hasta 2 Mbps Hasta 54 Mbps 720 kbps
banda
Alcance típico 100-1000 metros Kilómetros 150-300 metros 10-100 metros
Infraestructura
Ventajas Bajo consumo Velocidad Comodidad
existente
XBee XBee Arduino Shield
WiTwitAmbiLight: Hardware
+5 V +5 V +5 V
pin 11
serie
Xbee pin 10
Arduino
pin 9
802.15.4
Xbee
serie
Internet
Demo
Nunchuck como sensor
• Interfaz I2C standard
• Accelerómetro de 3 ejes
• Joystick analógico de 2 ejes
• 2 botones
Ejemplo Nunchuck
+5 V
pin 11
serie
Xbee pin 10
Arduino
pin 9
PWM
802.15.4
i2c
serie
Xbee Arduino
Demo
Referencias
• Getting Started with Arduino. Make Magazine
• http://www.arduino.cc/
• http://rad.rubyforge.org/
• http://github.com/atduskgreg/rad/tree/master
• http://todbot.com/blog/bionicarduino/
0 comments
Post a comment