#ifndef F_CPU #define F_CPU 16000000UL #endif #include #include #include #include #define LCD_RS (1U << 0) #define LCD_EN (1U << 2) #define LCD_BL (1U << 3) #define TWI_TIMEOUT 60000U static uint8_t lcd_address; static void i2c_init(void) { TWCR = 0; DDRC &= (uint8_t)~((1U << PC4) | (1U << PC5)); PORTC |= (1U << PC4) | (1U << PC5); TWSR = 0; TWBR = 72; TWCR = (1U << TWEN); } static uint8_t i2c_wait(void) { uint16_t remaining = TWI_TIMEOUT; while (!(TWCR & (1U << TWINT))) { if (--remaining == 0) { return 0; } } return 1; } static void i2c_stop(void) { uint16_t remaining = TWI_TIMEOUT; TWCR = (1U << TWINT) | (1U << TWEN) | (1U << TWSTO); while ((TWCR & (1U << TWSTO)) && --remaining) { } } static uint8_t i2c_start_write(uint8_t address) { uint8_t status; TWCR = (1U << TWINT) | (1U << TWSTA) | (1U << TWEN); if (!i2c_wait()) { return 0; } status = TW_STATUS; if (status != TW_START && status != TW_REP_START) { return 0; } TWDR = (uint8_t)(address << 1); TWCR = (1U << TWINT) | (1U << TWEN); return i2c_wait() && TW_STATUS == TW_MT_SLA_ACK; } static uint8_t i2c_write(uint8_t value) { TWDR = value; TWCR = (1U << TWINT) | (1U << TWEN); return i2c_wait() && TW_STATUS == TW_MT_DATA_ACK; } static uint8_t lcd_find(void) { const uint8_t bases[] = {0x20, 0x38}; for (uint8_t range = 0; range < 2; ++range) { for (uint8_t offset = 0; offset < 8; ++offset) { uint8_t address = bases[range] + offset; uint8_t found = i2c_start_write(address); i2c_stop(); if (found) { lcd_address = address; return 1; } } } return 0; } static uint8_t lcd_nibble(uint8_t nibble, uint8_t rs) { uint8_t data = (uint8_t)((nibble << 4) | LCD_BL | rs); uint8_t ok = i2c_start_write(lcd_address); if (ok) { ok = i2c_write(data); } if (ok) { ok = i2c_write(data | LCD_EN); } if (ok) { _delay_us(1); ok = i2c_write(data); } i2c_stop(); _delay_us(50); return ok; } static uint8_t lcd_byte(uint8_t value, uint8_t rs) { return lcd_nibble(value >> 4, rs) && lcd_nibble(value & 0x0F, rs); } static uint8_t lcd_command(uint8_t command) { uint8_t ok = lcd_byte(command, 0); if (command == 0x01 || command == 0x02) { _delay_ms(3); } return ok; } static uint8_t lcd_puts(const char *s) { while (*s) { if (!lcd_byte((uint8_t)*s++, LCD_RS)) { return 0; } } return 1; } static uint8_t lcd_init(void) { _delay_ms(50); if (!lcd_nibble(0x03, 0)) { return 0; } _delay_ms(5); if (!lcd_nibble(0x03, 0)) { return 0; } _delay_ms(1); if (!lcd_nibble(0x03, 0) || !lcd_nibble(0x02, 0)) { return 0; } return lcd_command(0x28) && lcd_command(0x08) && lcd_command(0x01) && lcd_command(0x06) && lcd_command(0x0C); } int main(void) { i2c_init(); _delay_ms(100); while (!(lcd_find() && lcd_init() && lcd_command(0x80) && lcd_puts("Hello, world!"))) { _delay_ms(1000); i2c_init(); } while (1) { } }