lcddriver.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import i2c_lib
  2. from time import *
  3. # LCD Address
  4. ADDRESS = 0x27
  5. # commands
  6. LCD_CLEARDISPLAY = 0x01
  7. LCD_RETURNHOME = 0x02
  8. LCD_ENTRYMODESET = 0x04
  9. LCD_DISPLAYCONTROL = 0x08
  10. LCD_CURSORSHIFT = 0x10
  11. LCD_FUNCTIONSET = 0x20
  12. LCD_SETCGRAMADDR = 0x40
  13. LCD_SETDDRAMADDR = 0x80
  14. # flags for display entry mode
  15. LCD_ENTRYRIGHT = 0x00
  16. LCD_ENTRYLEFT = 0x02
  17. LCD_ENTRYSHIFTINCREMENT = 0x01
  18. LCD_ENTRYSHIFTDECREMENT = 0x00
  19. # flags for display on/off control
  20. LCD_DISPLAYON = 0x04
  21. LCD_DISPLAYOFF = 0x00
  22. LCD_CURSORON = 0x02
  23. LCD_CURSOROFF = 0x00
  24. LCD_BLINKON = 0x01
  25. LCD_BLINKOFF = 0x00
  26. # flags for display/cursor shift
  27. LCD_DISPLAYMOVE = 0x08
  28. LCD_CURSORMOVE = 0x00
  29. LCD_MOVERIGHT = 0x04
  30. LCD_MOVELEFT = 0x00
  31. # flags for function set
  32. LCD_8BITMODE = 0x10
  33. LCD_4BITMODE = 0x00
  34. LCD_2LINE = 0x08
  35. LCD_1LINE = 0x00
  36. LCD_5x10DOTS = 0x04
  37. LCD_5x8DOTS = 0x00
  38. # flags for backlight control
  39. LCD_BACKLIGHT = 0x08
  40. LCD_NOBACKLIGHT = 0x00
  41. En = 0b00000100 # Enable bit
  42. Rw = 0b00000010 # Read/Write bit
  43. Rs = 0b00000001 # Register select bit
  44. class lcd:
  45. #initializes objects and lcd
  46. def __init__(self):
  47. self.lcd_device = i2c_lib.i2c_device(ADDRESS)
  48. self.lcd_write(0x03)
  49. self.lcd_write(0x03)
  50. self.lcd_write(0x03)
  51. self.lcd_write(0x02)
  52. self.lcd_write(LCD_FUNCTIONSET | LCD_2LINE | LCD_5x8DOTS | LCD_4BITMODE)
  53. self.lcd_write(LCD_DISPLAYCONTROL | LCD_DISPLAYON)
  54. self.lcd_write(LCD_CLEARDISPLAY)
  55. self.lcd_write(LCD_ENTRYMODESET | LCD_ENTRYLEFT)
  56. sleep(0.2)
  57. # clocks EN to latch command
  58. def lcd_strobe(self, data):
  59. self.lcd_device.write_cmd(data | En | LCD_BACKLIGHT)
  60. sleep(.0005)
  61. self.lcd_device.write_cmd(((data & ~En) | LCD_BACKLIGHT))
  62. sleep(.0001)
  63. def lcd_write_four_bits(self, data):
  64. self.lcd_device.write_cmd(data | LCD_BACKLIGHT)
  65. self.lcd_strobe(data)
  66. # write a command to lcd
  67. def lcd_write(self, cmd, mode=0):
  68. self.lcd_write_four_bits(mode | (cmd & 0xF0))
  69. self.lcd_write_four_bits(mode | ((cmd << 4) & 0xF0))
  70. # put string function
  71. def lcd_display_string(self, string, line):
  72. if line == 1:
  73. self.lcd_write(0x80)
  74. if line == 2:
  75. self.lcd_write(0xC0)
  76. if line == 3:
  77. self.lcd_write(0x94)
  78. if line == 4:
  79. self.lcd_write(0xD4)
  80. for char in string:
  81. self.lcd_write(ord(char), Rs)
  82. # clear lcd and set to home
  83. def lcd_clear(self):
  84. self.lcd_write(LCD_CLEARDISPLAY)
  85. self.lcd_write(LCD_RETURNHOME)