Python Module

#!/usr/bin/python
#    HAL userspace component to interface with Arduino board
#    by Colin Kingsbury (https://ckcnc.wordpress.com_)
#    Inspired by the earlier example from Jeff Epler
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
import serial
import hal
import sys
import time

#First we open the serial port. This should correspond to the port the Arduino
#is connected to. This can be found in the Arduino IDE in Tools->Serial Port
PORT = "/dev/ttyUSB0"
ser = serial.Serial(PORT, 9600, timeout=2)

#Now we create the HAL component and its pins
c = hal.component("arduino")
c.newpin("switch-on",hal.HAL_BIT,hal.HAL_IN)
c.newpin("switch-off",hal.HAL_BIT,hal.HAL_IN)
c.newpin("machine-state",hal.HAL_BIT,hal.HAL_IN)
c.ready()

#We save the machine state (i.e. whether it's off or on) so that we only
#send a message to the Arduino when it changes
machineState = c['machine-state']

#Check if the machine is on and set the LED accordingly
if(machineState != 1):
  ser.write("+R")

try:
  while 1:
    time.sleep(.001)
    #Check the machine State
    if(machineState != c['machine-state']):
      if(c['machine-state'] == 1):
        #The machine is on, so turn on the green LED and turn off the red one
        ser.write("+G")
        ser.write("-R")
      else:
        #opposite of above
        ser.write("-G")
        ser.write("+R")
      #update the machine state variable
      machineState = c['machine-state']
    #Check to see if we have a message waiting from the Arduino
    while ser.inWaiting():
      #This should be set to the length of whatever fixed-length message
      #you're sending from the arduino. It does not have to be the same length
      #as the outbound messages.
      key = ser.read(2)
      #The Arduino generates two different key events
      #One when the key is pressed down (+S) and another when it is released (-S)
      #In this case we are going to ignore the release
      if(key == "+S"):
        #If the machine is currently on, we turn it off, and vice-versa
        if(machineState == 1):
          c['switch-on'] = 0
          c['switch-off'] = 1
        else:
          c['switch-on'] = 1
          c['switch-off'] = 0

except KeyboardInterrupt:
    ser.write("-R-G");
    raise SystemExit

Leave a comment