// Pin configuration
#define RS 12 // Register Select pin (GP12)
#define RW 11 // Read/Write pin (GP11)
#define E 10 // Enable pin (GP10)
#define CONTRAST 15 // Contrast control pin (GP15)
#define DATA_PINS_START 0 // Data pins start at GP0-GP7
// Send a command to the LCD
void sendCommand(uint8_t command) {
digitalWrite(RS, LOW); // RS = 0 for command
digitalWrite(RW, LOW); // RW = 0 for write
sendByte(command);
}
// Send a data byte to the LCD
void sendData(uint8_t data) {
digitalWrite(RS, HIGH); // RS = 1 for data
digitalWrite(RW, LOW); // RW = 0 for write
sendByte(data);
}
// Send a byte to the LCD (for commands or data)
void sendByte(uint8_t value) {
// Set the data pins
for (int i = 0; i < 8; i++) {
digitalWrite(DATA_PINS_START + i, (value >> i) & 0x01);
}
// Toggle the enable pin to send the data/command
digitalWrite(E, HIGH);
delayMicroseconds(1); // Short delay
digitalWrite(E, LOW);
delayMicroseconds(100); // Allow time for the command to be processed
}
// Initialize the LCD
void lcdInit() {
pinMode(RS, OUTPUT);
pinMode(RW, OUTPUT);
pinMode(E, OUTPUT);
for (int i = 0; i < 8; i++) {
pinMode(DATA_PINS_START + i, OUTPUT);
}
pinMode(CONTRAST, OUTPUT);
analogWrite(CONTRAST, 128); // Set a default contrast level (0-255)
delay(50); // Wait for the LCD to power up
// Initialize LCD in 8-bit mode
sendCommand(0x38); // Function set: 8-bit, 2 lines, 5x8 dots
sendCommand(0x0C); // Display ON, Cursor OFF, Blink OFF
sendCommand(0x01); // Clear display
delay(2); // Wait for the clear command to complete
sendCommand(0x06); // Entry mode set: Increment cursor, no shift
}
// Write a string to the LCD
void lcdWriteString(const char *str) {
while (*str) {
sendData(*str++);
}
}
// Set the cursor to a specific position (col: 0-19, row: 0-1)
void lcdSetCursor(uint8_t col, uint8_t row) {
uint8_t rowOffsets[] = {0x00, 0x40};
sendCommand(0x80 | (col + rowOffsets[row])); // Set DDRAM address
}
void setup() {
lcdInit();
lcdSetCursor(0, 0); // Start at the beginning of the first line
lcdWriteString("Hello, 20x12 LCD!");
}
void loop() {
// In this example, the loop does nothing.
}