#include<Arduino.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
#define RS 1
#define RW 2
#define E 3
const char C[3] = {RS,RW,E};
const char D[8] = {5,6,7,8,9,10,11,12};
unsigned int dem = 128;
void lcd_init();
void lcd_print(char *str);
void lcd_data(uint8_t data);
void lcd_command(uint8_t command);
void lcd_gotoxy(uint8_t hang, uint8_t cot);
void xuat_gia_tri_1(uint16_t value);
void xuat_gia_tri_2(uint16_t value);
void xuat_gia_tri_thuc(float value);
void setup(){
Serial.begin(115200);
for(int i = 0 ; i < 3;i++){
pinMode(C[i], OUTPUT);
}
for(int i = 0; i < 8; i++){
pinMode(D[i], OUTPUT);
}
lcd_init();
}
void loop(){
lcd_gotoxy(1,3);
lcd_print("Gia tri ");
lcd_gotoxy(2,3);
xuat_gia_tri_thuc(39.25);
delay(1000);
lcd_command(0x01);
}
void lcd_init(){
lcd_command(0x38); // 2-line, 5x8 character matrix setupLCD
lcd_command(0x08); // display off
lcd_command(0x01); // clear display
lcd_command(0x06); // cursor move direction - right
lcd_command(0x0C); // display on, cursor off, blink off
}
void lcd_print(const char *str){
//dung ky thuat gan bien dem
while(*str){
lcd_data(*(str++));
dem++;
lcd_command(0x06);
if(dem > 143 && dem < 192 ){
lcd_command(0xC0);
dem = 0xC0;
}
if(dem > 208 ){
lcd_command(0x80);
dem = 0x80;
}
}
}
void lcd_data(uint8_t data){
digitalWrite(RS, HIGH);
digitalWrite(RW, LOW);
for(int i = 0; i < 8; i++){
digitalWrite(D[i], (data & (0x01 << i)) >> i);
// xuat 8 bit ra 8 pin tu pin 5 ung voi lsb
}
digitalWrite(E, HIGH);
delay(10);
digitalWrite(E, LOW);
}
void lcd_command(uint8_t command){
digitalWrite(RS, LOW);
digitalWrite(RW, LOW);
for(int i = 0; i < 8; i++){
digitalWrite(D[i], (command & (0x01 << i)) >> i);
// xuat 8 bit ra 8 pin tu pin 5 ung voi lsb
}
digitalWrite(E, HIGH);
delay(10);
digitalWrite(E, LOW);
}
void lcd_gotoxy(uint8_t hang, uint8_t cot){
switch(hang){
case 1: lcd_command(dem = (128 + cot)); break;
case 2:
lcd_command(dem = (192+ cot));
}
}
// lap de xuat 1 gia tri float
void xuat_gia_tri_1(uint16_t value){
//tao 1 vong lap de kiem tra gia tri nay co may so
char check, i;
uint16_t tam = value;
for( i = 0 ; tam != 0 ; i++)
{
tam = tam/ 10;
}
//lay duoc i luc nay se la gia tri cac so cua value
//lam 1 ham de xuat tung gia tri
for(int j = 0; value != 0 ; j++){
tam = value / pow(10,i -1);
lcd_data(0x30+tam);
value = value % (int) (pow(10,i -1));
i--;
}
}
void xuat_gia_tri_2(uint16_t value){
char mang[100] , i = 0;
for(i = 0; value != 0; i++){
mang[i] = value % 10;
value = value /10;
}
i = i - 1;
// for(i=i; i >=0; i--){
// lcd_data(0x30+ mang[i]);
// } // ranh thi tim ra cai loi nay
for(int j = i ; j >= 0; j--){
lcd_data(0x30 + mang[j]);
}
}
void xuat_gia_tri_thuc(float value){
char i = 0; dem = 0;
for( i = 0; value - (int)value != 0; i++){
value = value * 10;
}
xuat_gia_tri_2(value);
// 1 la phai biet duoc ban chat cua no trong pham vi nao
}
// gio la lam sao check dau cham :hoan thien ve viec tim dau cham