4x4 keypad example using AVR-GCC C language

本文介绍了一种使用AVR-GCC语言从4x4键盘读取按键的简单方法。通过将键盘连接到AVR微控制器的B端口,并利用循环逐个检查按键状态来实现。介绍了具体的实现代码,包括初始化端口、设置内部上拉电阻及读取按键的具体过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is as simple routine how to read 4x4 keypad keys using AVR-GCC language. The keypad is connected to AVR microcontroller 8 bit port. In this example it is B port. You can change ports depending on your needs – this is only an example ant it is not the only way to this.

4x4 keypad AVR C 

Howt it works. Well very simply. PORTB is divided into two nibbles PINB0 – PINB3 as inputs (as rows) and PINB4-PINB7 as outputs (columns). The keys are checked in a loop in series. Lets say if we set first row output (PORTB bit 7) to 0 then when checking rows we are looking which bit is set to 0, because of key pressed with function bit_is_set(PINB, bitNo). This function gives non-zero if bit is clear.

10k resistors protect AVR from shortcuts.


#include <avr/io.h>
int main()
{
//high nibble for output(columns) low for input(rows);
DDRB=0xF0;
//enable internal pullups for PB0-PB3
PORTB=0x0F;
//Port D for indication only
DDRD=0xFF;
while (1) //loop key check forever
	{
		//first column
		PORTB =0b01111111;
		//check for rows and send key number to portD
		//instead sending key number to PORTD you can use
		// any function that serves pressed button
		if (bit_is_set(PINB, 3)) PORTD=1;
		if (bit_is_set(PINB, 2)) PORTD=2;
		if (bit_is_set(PINB, 1)) PORTD=3;
		if (bit_is_set(PINB, 0)) PORTD=4;
		//second column
		PORTB =0b10111111;
		if (bit_is_set(PINB, 3)) PORTD=5;
		if (bit_is_set(PINB, 2)) PORTD=6;
		if (bit_is_set(PINB, 1)) PORTD=7;
		if (bit_is_set(PINB, 0)) PORTD=8;
		//third column
		PORTB =0b11011111;
		if (bit_is_set(PINB, 3)) PORTD=9;
		if (bit_is_set(PINB, 2)) PORTD=10;
		if (bit_is_set(PINB, 1)) PORTD=11;
		if (bit_is_set(PINB, 0)) PORTD=12;
		//fourth column
		PORTB =0b11101111;
		if (bit_is_set(PINB, 3)) PORTD=13;
		if (bit_is_set(PINB, 2)) PORTD=14;
		if (bit_is_set(PINB, 1)) PORTD=15;
		if (bit_is_set(PINB, 0)) PORTD=16;
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值