Create a gist now

Instantly share code, notes, and snippets.

A simple class for reading values from the DG600F coin acceptor sold by SparkFun (https://www.sparkfun.com/products/11636)
#!/usr/bin/env ruby
# A simple class for reading values from the DG600F coin acceptor sold by
# SparkFun (https://www.sparkfun.com/products/11636)
#
# The coin acceptor must be configured to send three bytes per coin; see section
# 8.6 of the manual.
#
# You can configure the serial device and baud rate, e.g.:
#
# c = CoinAcceptor.new device: '/dev/ttyS0', baud: 2400
#
# By default it will use /dev/ttyUSB0 at 9600 baud.
#
# You must pass a block which will receive the credit value as configured
# on the coin acceptor:
#
# c.accept_coins do |credit|
# puts "You put in #{credit}s"
# end
#
# For testing at the command line, you can just run this file directly.
require 'serialport'
class CoinAcceptor
HEADER = 0xAA
IGNORE = 0xFF
attr_reader :serial_port
def initialize device: "/dev/ttyUSB0", baud: 9600
@serial_port = SerialPort.new device, baud, 8, 1, SerialPort::NONE
@serial_port.flush_input
end
def get_byte
byte = IGNORE
byte = @serial_port.read(1).unpack('C').first until byte != IGNORE
byte
end
def accept_coins
loop do
if get_byte == HEADER
credit = get_byte
check = get_byte
yield credit if check == HEADER ^ credit
end
end
end
end
if __FILE__ == $0
c = CoinAcceptor.new
c.accept_coins do |credit|
puts credit
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment