/* Program 8-1: Display "HELLO" on the LCD using SPI with Edubase-V2 board * * The LCD controller is connected to a shift register via SPI. * The connections of the shift register output are: * Bit 0 - Register select (R/S) * Bit 1 - Enable (E) * Bit 7-4 - data D7-D4 * The read/write pin of the LCD is wired to ground for write only. */ #include "SPI.h" const int slaveSelect = 10; void setup() { LCD_init(); } void loop() { /* Write "HELLO" on LCD */ LCD_data('H'); LCD_data('E'); LCD_data('L'); LCD_data('L'); LCD_data('O'); delay(1000); /* clear LCD display */ LCD_command(1); delay(1000); } void LCD_init(void) { pinMode (slaveSelect, OUTPUT); /* set the slaveSelect pin as output */ SPI.begin(); /* initialize SPI */ SPI.setDataMode(SPI_MODE0); /* LCD controller reset sequence */ delay(20); LCD_nibble_write(0x30, 0); delay(5); LCD_nibble_write(0x30, 0); delay(1); LCD_nibble_write(0x30, 0); delay(1); LCD_nibble_write(0x20, 0); /* use 4-bit data mode */ delay(1); LCD_command(0x28); /* set 4-bit data, 2-line, 5x7 font */ LCD_command(0x06); /* move cursor right */ LCD_command(0x01); /* clear screen, move cursor to home */ LCD_command(0x0F); /* turn on display, cursor blinking */ } #define RS 1 /* BIT0 mask for reg select */ #define EN 2 /* BIT1 mask for E */ /* write 4 bits to LCD controller */ void LCD_nibble_write(char data, unsigned char control) { data &= 0xF0; /* clear lower nibble for control */ control &= 0x0F; /* clear upper nibble for data */ SPI_Write(data | control); /* RS = 0, R/W = 0 */ SPI_Write(data | control | EN); /* pulse E */ delay(0); SPI_Write(data); } /* write a command to LCD controller */ void LCD_command(unsigned char command) { LCD_nibble_write(command & 0xF0, 0); /* upper nibble first */ LCD_nibble_write(command << 4, 0); /* then lower nibble */ if (command < 4) delay(2); /* command 1 and 2 needs up to 1.64ms */ else delay(1); /* all others 40 us */ } /* write a byte of data to LCD controller */ /* since the connection is 4-bit, it takes two writes for a byte */ void LCD_data(char data) { LCD_nibble_write(data & 0xF0, RS); /* upper nibble first */ LCD_nibble_write(data << 4, RS); /* then lower nibble */ delay(1); } /* write a byte to the shift register of LCD through SPI */ void SPI_Write(unsigned char data) { digitalWrite(slaveSelect, LOW); /* assert SS low to shift register of LCD */ SPI.transfer(data); /* send a byte to the shift register */ digitalWrite(slaveSelect, HIGH); /* deassert SS */ }