Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kantlivelong/e6161575d002ae9e81d0f0b42d451230 to your computer and use it in GitHub Desktop.
Save kantlivelong/e6161575d002ae9e81d0f0b42d451230 to your computer and use it in GitHub Desktop.
import logging
import logging.handlers
import logging.config
import threading
import time
import string
import serial
class SBLCD():
logger = logging.getLogger('SBLCD')
def __init__(self,port, baudrate, bytesize, parity, stopbits, backlight=True, brightness=100):
self.port=port
self.baudrate=int(baudrate)
self.bytesize=int(bytesize)
self.parity=parity
self.stopbits=int(stopbits)
self.backlight=backlight
self.brightness=brightness
self.ser_buffer=['']
self.writelock=False
try:
self.ser = serial.Serial(port, baudrate, bytesize, parity, stopbits)
except Exception as e:
self.ser = serial.Serial()
self.logger.warning('Unable to open serial connection to the LCD.')
self.setBrightness(brightness)
if(backlight):
self.backlightOn()
else:
self.backlightOff()
self.drawthread = threading.Thread(name='drawthread', target=self.draw)
self.drawthread.setDaemon(True)
def start(self):
if (not self.drawthread.isAlive()):
self.drawthread.start()
return True
else:
return False
def stop(self):
if (self.drawthread.isAlive()):
self.drawthread.stop()
self.ser.close()
return True
else:
return False
def draw (self):
while True:
if (len(self.ser_buffer) > 0):
tmp=self.ser_buffer[0]
self.ser_buffer.pop(0)
if (tmp == '\xFE\x58' and len(self.ser_buffer) > 0):
tmp+=self.ser_buffer[0]
self.ser_buffer.pop(0)
self.writeSerial(tmp)
time.sleep(0.1)
def isBacklightOn(self):
return self.backlight
def getBrightness(self):
return self.brightness
def backlightOn(self):
self.backlight = True
self.writeBuffer('\xFE\x42')
def backlightOff(self):
self.backlight = False
self.writeBuffer('\xFE\x46')
def setBrightness(self,percent):
self.brightness = percent
self.writeBuffer("\xFE\x99%c" % chr(int((float(percent)/100) * 255)))
def setWriteLock(self):
while self.writelock:
time.sleep(0.1)
self.writelock=True
def unsetWriteLock(self):
self.writelock=False
def writeBuffer(self,data):
self.ser_buffer.append(data)
def writeSerial(self,data):
self.setWriteLock()
if (not self.ser.isOpen()):
try:
self.ser.open()
except:
pass
try:
self.ser.write(data + '\r')
self.ser.flush()
except Exception as e:
pass
self.unsetWriteLock()
def clearScreen(self):
self.writeBuffer('\xFE\x58')
def getPositionCode(self,row,col):
return '\xFE\x47' + chr(col) + chr(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment