|
发表于 2010-5-25 09:21:02
|
显示全部楼层
this hopefully will get you on the right track.
============code===============
#include <htc.h>
#include <string.h>
#include "lcd_3wi.h"
#include "delay.h"
__CONFIG(MCLRDIS & WDTDIS & BORDIS & PWRTEN & INTIO);
#define LOOP_PIN (1<<5) //led indicator, on portC
#define KEY_PORT PORTA //leds on porta. needs to be able to cover the keypad.
#define KEY_DIR TRISA
#define KEY_SET(bits) KEY_PORT |= (bits) //set bits
#define KEY_CLR(bits) KEY_PORT &=~(bits) //clear bits
#define KEY_FLP(bits) KEY_PORT ^= (bits) //flip bits
#define KEY_IN(bits) KEY_DIR |= (bits) //bits as input
#define KEY_OUT(bits) KEY_DIR &=~(bits) //bits as output
#define KEY_COL 0b110000 //column connection bits
#define KEY_ROW 0b000111 //row connection bits
#define sleep() asm("sleep") //sleep macro
unsigned char vRAM[17]; //lcd buffer
const unsigned char str0[]="16F684 KeyScan 2";
const unsigned char str1[]="k= ";
void mcu_init(void ) { //reset the mcu
ANSEL=0x00; //all pins gpio
CMCON0=0x07; //analog comparators off
IRCF2=1, IRCF1=1, IRCF0=0; //running at 4mhz
LCD_DIR &=~LOOP_PIN; //LOOP_PIN as output
LCD_CLR(LOOP_PIN); //clear loop_pin
}
void uctoa(char *s, unsigned char ul, unsigned char length) { //convert unsigned long to a string, 3 dps
unsigned char i;
i=length;
do {
// if (i==(length-3)) s[i--]='.';
s[i--]=ul % 10 + '0';
ul = ul / 10;
} while (ul);
}
unsigned char key_read(unsigned char in_bits, unsigned char out_bits) { //output on out_bits and read in_bits
KEY_IN(in_bits); //set in_bits to be input
KEY_SET(out_bits); KEY_OUT(out_bits); //output 1 on out_bits
return KEY_PORT & in_bits;
}
unsigned char key_detect(void) { //return the cycle count
unsigned char tmp1, tmp2;
tmp2=key_read(KEY_ROW, KEY_COL); //read horizontal scan
tmp1=key_read(KEY_COL, KEY_ROW); //read vertical scan
return tmp1 | tmp2;
}
void
main(void)
{ unsigned char t1;
unsigned char i=0;
mcu_init(); //initialize the mcu
lcd_init(); //initialize the lcd
strcpy(vRAM, str0); lcd_display(LCD_Line0, vRAM);
while (1){
KEY_DIR &=~KEY_ROW; //row as output
KEY_PORT |=KEY_ROW; //set key_row
if (KEY_PORT & KEY_COL) { //see if a key is pressed
t1=key_detect(); //read the kaypad
strcpy(vRAM, str1);
uctoa(&vRAM[2], i++, 4);
uctoa(&vRAM[8], t1, 4);
lcd_display(LCD_Line1, vRAM);
// LED_EMIT(LED_A, LED_K); delay_us(t1>>4);
// simple_pwm(t1>>4, LED_A, LED_K);
}
LCD_FLP(LOOP_PIN);
//do something else
//delay_ms(100);
//TODO Auto-generated main function
}
}
============end of code=================
the code energies KEY_ROW, and then reads back KEY_COL to see if a key is pressed.
if a key is pressed, it goes into key_detect() to see which key is pressed and displays it on the lcd.
here is the sim.
(原文件名:16F684 keypad detect 3.PNG) |
|