Skip to content

Instantly share code, notes, and snippets.

@pocketkk
Created January 27, 2013 17:02
Show Gist options
  • Save pocketkk/4649238 to your computer and use it in GitHub Desktop.
Save pocketkk/4649238 to your computer and use it in GitHub Desktop.
Ruby Serial Library for 4x20 LCD (NHD-0420D3Z-NSW-BBW)
# RUBY LIBRARY FOR SERIAL COMM RS-323 TO 4X20
# LCD COMPATIBLE WITH THE NEW HAVEN DISPLAY COMMANDS
#
# LCD MODEL# NHD-0420D3Z-NSW-BBW
#
# SPEC SHEET LOCATED:
# http://www.newhavendisplay.com/specs/NHD-0420D3Z-NSW-BBW.pdf
#
# HOOK UP PIN 1 TO TX ON RASBERRY PI
# PIN 2 TO GND
# PIN 3 TO 5V
#
# *********************EXAMPLE USAGE***************************
#
# lcd=Display.new(path_to_serial, baudrate) #initializes lcd
# lcd.print("Hello World", 1) #Prints hello world on line 1
#
# *************************************************************
require 'serialport'
class Display
CMD = 254.chr
CMD_POS = 69.chr
ROW_1=0.chr
ROW_2=64.chr
ROW_3=20.chr
ROW_4=84.chr
HOME = 70.chr
OFF = 66.chr
ON = 65.chr
BLINK_OFF = 76.chr
LEFT = 73.chr
RIGHT = 74.chr
CLEAR = 81.chr
def initialize (serial_path='/dev/ttyAMA0', baudrate=9600)
serial_path, baudrate = serial_path.to_s, baudrate.to_i
#OPEN UP SERIAL PORT
@display = SerialPort.new serial_path, baudrate
sleep(0.1)
#TURN OFF CURSOR
cmd(BLINK_OFF)
sleep(0.01)
end
def cmd(command)
@display.write(CMD)
@display.write(command)
sleep(0.01)
end
def clear
cmd(CLEAR)
end
def off
cmd(CLEAR)
cmd(OFF)
end
def on
cmd(ON)
end
def write(command)
@display.write(command)
end
# ALIGN OPTIONS 1=CENTER, 2= LEFT, 3=RIGHT
def print(text, line=1, align=1)
clear_line(line)
text=text.to_s
posLine(line)
if text.length >= 21
extra_text=text.length-20
text_array=*(0..extra_text)
@display.write(text[0,20])
text_array.each do |it|
posLine(line)
@display.write(text[it, 20])
sleep(0.15)
end
sleep(0.5)
text_array.reverse.each do |it|
posLine(line)
@display.write(text[it, 20])
sleep(0.1)
end
else
padding=20-text.length
case align
when 1 #CENTER ALIGN
padding = padding/2
while padding >= 1
text=" " << text
padding-=1
end
# DON'T NEED TO MAKE CHANGES FOR LEFT ALIGN
when 3 #RIGHT ALIGN
while padding >= 1
text=" " << text
padding -= 1
end
end
@display.write(text)
end
end
def posLine(line)
cmd(CMD_POS)
case line
when 1
@display.write(ROW_1)
when 2
@display.write(ROW_2)
when 3
@display.write(ROW_3)
when 4
@display.write(ROW_4)
end
sleep(0.01)
end
def posCursor(pos)
pos=pos.chr
cmd(pos)
end
def clear_line(line)
posLine(line)
@display.write(" ")
posLine(line)
end
LINE_1 = *(0..19)
LINE_2 = *(64..83)
LINE_3 = *(20..39)
LINE_4 = *(84..103)
LINE_1_R = LINE_1.reverse
LINE_2_R = LINE_2.reverse
LINE_3_R = LINE_3.reverse
LINE_4_R = LINE_4.reverse
#TO-DO ADD SCROLLING TEXT
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment