Atmega2560基础教程(3)——I/O口输入输出

Atmega2560基础教程(3)——I/O口输入输出

配置I/O,一般需要三个寄存器DDRx,PINx,PORTx,以I/O口A为例

1.I/O口输出

配置I/O口方向为输出时,方向寄存器DDRx将其相应位置高,输出的电平由PORTx决定


/*
	PA0输出引脚,10ms翻转一次电平
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
	DDRA|=_BV(DDA0);
	PORTA|=_BV(DDA0);
	_delay_ms(10);
	while (1)
	{
		PORTA&=~_BV(DDA0);
		_delay_ms(10);
		PORTA|=_BV(DDA0);
		_delay_ms(10);
	}
}

波形图如下:

2.I/O口输入

配置I/O口为输入时,方向寄存器DDRx将其相应位置低,输入的电平可以由PINx读出,PORTx决定无输入时的电平


/*
	PA0输入引脚,无输入时为高电平,PD0输出引脚,PA0输入低电平时PD0输出低电平,
	PA0输入高电平时PD0输出高电平
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/sfr_defs.h>
int main(void)
{
	DDRA&=~_BV(DDA0);
	PORTA|=_BV(PA0);
	DDRD|=_BV(DDD0);
	PORTD|=_BV(PD0);
	while (1)
	{
		if (bit_is_clear(PINA,PINA0))
		  {
			  PORTD&=~_BV(PD0);
		  }
		  else
		  {
			  PORTD|=_BV(PD0);
		  }
	}
}

发布了12 篇原创文章 · 获赞 2 · 访问量 4153

猜你喜欢

转载自blog.csdn.net/jiantoushi/article/details/104077882