-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcd.c
More file actions
97 lines (84 loc) · 2.14 KB
/
lcd.c
File metadata and controls
97 lines (84 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/** Put this in the src folder **/
#include "lcd.h"
#define RS_BIT 0 // Register select bit
#define EN_BIT 2 // Enable bit
#define BL_BIT 3 // Backlight bit
#define D4_BIT 4 // Data 4 bit
#define D5_BIT 5 // Data 5 bit
#define D6_BIT 6 // Data 6 bit
#define D7_BIT 7 // Data 7 bit
#define LCD_ROWS 2 // Number of rows on the LCD
#define LCD_COLS 16 // Number of columns on the LCD
// Define global variable for backlight state
uint8_t backlight_state = 1;
void lcd_write_nibble(uint8_t nibble, uint8_t rs) {
uint8_t data = nibble << D4_BIT;
data |= rs << RS_BIT;//RS_BIT 0
data |= backlight_state << BL_BIT; // Include backlight state in data
data |= 1 << EN_BIT;
GPIOA->ODR=data;
HAL_Delay(1);
data &= ~(1 << EN_BIT);
GPIOA->ODR=data;
}
void lcd_send_cmd(uint8_t cmd) {
uint8_t upper_nibble = cmd >> 4;
uint8_t lower_nibble = cmd & 0x0F;
lcd_write_nibble(upper_nibble, 0);
lcd_write_nibble(lower_nibble, 0);
if (cmd == 0x01 || cmd == 0x02) {
HAL_Delay(2);
}
}
void lcd_send_data(uint8_t data) {
uint8_t upper_nibble = data >> 4;
uint8_t lower_nibble = data & 0x0F;
lcd_write_nibble(upper_nibble, 1);
lcd_write_nibble(lower_nibble, 1);
}
void lcd_init() {
HAL_Delay(50);
lcd_write_nibble(0x03, 0);
HAL_Delay(5);
lcd_write_nibble(0x03, 0);
HAL_Delay(1);
lcd_write_nibble(0x03, 0);
HAL_Delay(1);
lcd_write_nibble(0x02, 0);
lcd_send_cmd(0x28);
lcd_send_cmd(0x0C);
lcd_send_cmd(0x06);
lcd_send_cmd(0x01);
HAL_Delay(2);
}
void lcd_write_string(char *str) {
while (*str) {
lcd_send_data(*str++);
}
}
void lcd_set_cursor(uint8_t row, uint8_t column) {
uint8_t address;
switch (row) {
case 0:
address = 0x00;
break;
case 1:
address = 0x40;
break;
default:
address = 0x00;
}
address += column;
lcd_send_cmd(0x80 | address);
}
void lcd_clear(void) {
lcd_send_cmd(0x01);
HAL_Delay(2);
}
void lcd_backlight(uint8_t state) {
if (state) {
backlight_state = 1;
} else {
backlight_state = 0;
}
}