Skip to content

Instantly share code, notes, and snippets.

@c2h2
Created September 27, 2011 03:03
Show Gist options
  • Save c2h2/1244212 to your computer and use it in GitHub Desktop.
Save c2h2/1244212 to your computer and use it in GitHub Desktop.
serial printer by ruby
#!/usr/local/rvm/rubies/ruby-1.9.2-p180/bin/ruby
#encoding: utf-8
require "yaml"
require File.expand_path(File.join(File.dirname(__FILE__), "serialport.rb"))
require File.expand_path(File.join(File.dirname(__FILE__), "memq.rb"))
class String
def to_bin
[self].pack("H*")
end
def add_zero
self.length == 1 ? "0" + self : self
end
def to_hex
str=""
self.each_byte{|b| str << b.to_s(16).add_zero }
str
end
def reverse_printing length = 40
if self.length <= length
else
return chunk_intel(length).map{|l| l.center(length)}.reverse * ""
end
self
end
def chunk_string length = 40
strs = []
newstr = self
while newstr.length > length
strs << newstr[0..length-1]
newstr = newstr[length..-1]
end
strs << newstr
end
def chunk_intel length = 40
newstr=self
strs = []
elems = self.split(" ")
str_index=0
strs[str_index]=""
elems.each do |elem|
expected_len = (strs[str_index] +" "+ elem).length
if strs[str_index].length == 0 # empty line
if elem.length > length
elem_lines = elem.chunk_string
strs += elem_lines
str_index += elem_lines.length
else
strs[str_index] = elem
end
elsif expected_len > length # new line needed
str_index += 1
if elem.length > length
elem_lines = elem.chunk_string
strs += elem_lines
str_index += elem_lines.length
else
strs[str_index] = elem
end
elsif expected_len < length # within line
strs[str_index] += (" " + elem)
elsif expected_len == length # within line, no new space needed
strs[str_index] += (" " + elem)
end
end
strs
end
end
sp = SerialPort.new "/dev/ttyUSB0", 9600, 8, 1, SerialPort::NONE
str= ARGV[0].reverse_printing
sp.write("1b3800"+str.to_hex+"0d".to_bin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment