实验1:点亮LED
1.通用I/O端口相关寄存器
1)PxSEL(端口功能选择):用来设置端口的每个引脚为通用I/O或外设I/O。
0:表示通用,1:表示外设
2)PxDIR:用来设置端口为输入或输出
0:表示输入,1:表示输出
【注意】对于P2来说,其只有低五位表示该功能
2.电路图
3.程序代码
#include "iocc2530.h"
#define LED P1_0
void Init_Port()
{
P1SEL &=~0x01; //用来设置P1_0为通用I/O.事实上也可不写该句,其默认也是通用I/O.
P1DIR |=0x01; //用来设置P1_0为输出
}
void main()
{
Init_Port();
while(1)
{
LED=0; //当P1_0为低电平时,点亮LED
}
}
实验2:按键控制LED亮灭
1.相关寄存器
1)PxINP:用来在通用I/O端口用作输入时将其设置为上拉,下拉或三态操作模式。
默认时,复位后所有端口均设置为带上拉的输入。
2)通常设置步骤如下:
i)对PxINP进行设置:设置为1表示为上拉/下拉,设置为0表示三态
(【注意】当设置为1时表示上拉或下拉,仍需要进行具体的设置)
ii)对P2INP进行设置:
2.电路图
3.程序代码
//功能:按键控制LED亮灭
#include "iocc2530.h"
#define LED P1_0
#define KEY P0_4
void Delay(unsigned int t)
{
while(t--);
}
void Init_Port()
{
//对LED相关寄存器进行设置
P1SEL &=~0x01;
P1DIR |=0x01;
//对按键进行设置
P0SEL &=~0x10;
P0DIR &=~0x10; //按键是要设置为输入,所以P0_4要设置为低电平
P0INP &=~0x10; //将P0_4设置为低电平,表示上拉/下拉
P2INP &=~0x20; //将P2_5设置为低电平,表示端口0上拉选择
}
void Scan_Key()
{
if(KEY==0)
{
Delay(200);
if(KEY==0)
{
LED=!LED;
}
while(!KEY);
}
}
void main()
{
Init_Port();
while(1)
{
Scan_Key();
}
}
3.书上作业
1)在实验板上点亮LED1和LED2
//点亮LED1和LED2
#include "iocc2530.h"
#define LED1 P1_0
#define LED2 P1_1
void Init_Port()
{
P1SEL &=~0x03;
P1DIR |=0x03;
}
void main()
{
Init_Port();
while(1)
{
LED1=0;
LED2=0;
}
}
2)用按键Key2控制LED1和LED2交替闪烁
#include "iocc2530.h"
#define LED1 P1_0
#define LED2 P1_1
#define Key2 P0_5
void Delay(unsigned int t)
{
while(t--);
}
void Init_Port()
{
P1SEL &=~0x03;
P1DIR |=0x03;
P0SEL &=~0x20;
P0DIR &=~0x20;
P0INP &=~0x20;
P2INP &=~0x20;
LED1=0;
LED2=1;
}
void Scan_Key()
{
if(Key2==0)
{
Delay(200);
if(Key2==0)
{
LED1=!LED1;
LED2=!LED2;
}
while(!Key2);
}
}
void main()
{
Init_Port();
while(1)
{
Scan_Key();
}
}