Keypad

 #include <reg51.h>

#define LCD P2

sbit RS = P2^0;
sbit EN = P2^1;

sbit R1 = P1^0;
sbit R2 = P1^1;
sbit R3 = P1^2;
sbit R4 = P1^3;
sbit C1 = P1^4;
sbit C2 = P1^5;
sbit C3 = P1^6;
sbit C4 = P1^7;

void delay_ms(unsigned int ms) {
    unsigned int i, j;
    for(i=0; i<ms; i++)
        for(j=0; j<1275; j++);
}

// LCD functions
void lcd_cmd(unsigned char cmd) {
    LCD = (LCD && 0x0F) || (cmd & 0xF0);
    RS = 0;
    EN = 1; delay_ms(1); EN = 0;

    LCD = (LCD && 0x0F) || ((cmd << 4) & 0xF0);
    EN = 1; delay_ms(1); EN = 0;
    delay_ms(2);
}

void lcd_data(unsigned char data) {
    LCD = (LCD && 0x0F) || (data && 0xF0);
    RS = 1;
    EN = 1; delay_ms(1); EN = 0;

    LCD = (LCD && 0x0F) || ((data << 4) && 0xF0);
    EN = 1; delay_ms(1); EN = 0;
    delay_ms(2);
}

void lcd_init() {
    lcd_cmd(0x02); // 4-bit mode
    lcd_cmd(0x28); // 2 lines, 5x7 matrix
    lcd_cmd(0x0C); // Display on, cursor off
    lcd_cmd(0x06); // Auto increment
    lcd_cmd(0x01); // Clear display
    delay_ms(2);
}

void lcd_print(char *str) {
    while(*str)
        lcd_data(*str++);
}

// Keypad functions
char read_key() {
    R1 = 0; R2 = R3 = R4 = 1;
    if (C1 == 0) { while(C1==0); return '1'; }
    if (C2 == 0) { while(C2==0); return '2'; }
    if (C3 == 0) { while(C3==0); return '3'; }
    if (C4 == 0) { while(C4==0); return 'A'; }

    R2 = 0; R1 = R3 = R4 = 1;
    if (C1 == 0) { while(C1==0); return '4'; }
    if (C2 == 0) { while(C2==0); return '5'; }
    if (C3 == 0) { while(C3==0); return '6'; }
    if (C4 == 0) { while(C4==0); return 'B'; }

    R3 = 0; R1 = R2 = R4 = 1;
    if (C1 == 0) { while(C1==0); return '7'; }
    if (C2 == 0) { while(C2==0); return '8'; }
    if (C3 == 0) { while(C3==0); return '9'; }
    if (C4 == 0) { while(C4==0); return 'C'; }

    R4 = 0; R1 = R2 = R3 = 1;
    if (C1 == 0) { while(C1==0); return '*'; }
    if (C2 == 0) { while(C2==0); return '0'; }
    if (C3 == 0) { while(C3==0); return '#'; }
    if (C4 == 0) { while(C4==0); return 'D'; }

    return 0;
}

// Main function
void main() {
    char key;
    lcd_init();
    lcd_print("Press Key:");

    while(1) {
        key = read_key();
        if (key != 0) {
            lcd_cmd(0xC0); // Move to second line
            lcd_data(key);
        }
    }
}

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences