The code for the firmata. I make a global variable called pin for my short hand… But you can name it anything. I do recommend making it global however.
require ‘arduino_firmata’
$pin = ArduinoFirmata.connect # this binds a global variable to connect and communicate with the Arduino.
def firmata_ver
puts "Firmata version: #{$pin.version}
end
making a method will keep you from having to retype the puts string for the firmata version.
#simple on/off commands for io pins.
def led_on
a = proc[ $pin.digital_write 5, true]
a.call
end
#the code method_name(this case $pin).digital_write pin_number, true/false tells the pi to connect with the Arduino and access the io pin and turn it on or off. I used 5 in this example. Setting it to true will turn the pin on.
def led_off
a = proc[ $pin.digital_write 5, false]
a.call
end
digital_write makes the pin a output pin. The next attr_accessor I will show you is digital_read. This pulls information about a pin. Let’s make a new method for a new led.
def blue_led_on
a = proc[ $pin.digital write 6, true]
a.call
b = proc[puts “blue led is #{$pin.digital_read 6}”)
b.call
end
#input pins. These can be trigger pins like buttons. Where output pins sends voltage out, input pins act like a ground pin. It takes the voltage in and uses It for data measurements.
Connect your button to the 3.5v aux of the Arduino. NOT THE 5V PIN! IO pins can only take 3.5 volts and cannot exceed 30ma(milliamps). If it draws more than a led, don’t use the io pins to power it. These are our signal pins.
3.5v pin to button, button to pin #(we will use 7)
button = $pin.pin_mode 7, ArduinoFirmata::INPUT ;
While button == true
if led_off == true
puts. $pin.digital_read 7
led_on
puts $pin.digital_read 7
end
If led_on == true
puts $pin.digital_read 7
led_off
puts $pin.digital read 7
end
end
#pwm (pulse width modulation). Makes a output pin produce a square wave.
This is used to control fan speeds, motors, servos, etc.
https://shokai.github.io/arduino_firmata/