在β版中与上课内容有偏差,开发板是高电平点亮,慕课中讲的是低电平点亮LED
首先设计功能为RGB三色循环亮色
代码为
#include "derivative.h" /* include peripheral declarations */
void delay()
{
unsigned int i,j;
for(i=0;i<5000;i++)
{
for(j=0;j<100;j++) //嵌套的循环体,延时
asm("nop");
}
}
int main()
{
SIM_SCGC5=SIM_SCGC5|((1<<10)+(1<<11)); //通过逻辑”或”置1,单独使能PORTC时钟
PORTB_PCR16=0x0100;
PORTB_PCR17=0x0100;
PORTB_PCR18=0x0100;
PORTB_PCR19=0x0100;
PORTC_PCR0=0x0100;
PORTC_PCR2=0x0100;//设置PTC0为GPIO
PORTC_PCR3=0x0100;
PORTC_PCR4=0x0100;
PORTC_PCR5=0x0100;//设置PTC4为GPIO
GPIOB_PDDR =0x0f0000;
GPIOC_PDDR =0x003d;//配置PTC0、PTC4为输出
for(;;)
{
GPIOB_PDOR=0x090000;
GPIOC_PDOR=0x0008; //输出PTC0、PTC4为1,小灯点亮
delay();
GPIOB_PDOR=0x020000;
GPIOC_PDOR=0x0011; //输出PTC0、PTC4为1,小灯点亮
delay();
GPIOB_PDOR=0x040000;
GPIOC_PDOR=0x0024; //输出PTC0、PTC4为1,小灯点亮
delay();
//GPIOC_PDOR = ~ GPIOC_PDOR;
//GPIOB_PDOR = ~ GPIOB_PDOR;
// ~为逻辑取反,也可用GPIOC_PTOR寄存器反转端口
}
}
逐条分析
1 延时
#include "derivative.h" /* include peripheral declarations */
void delay()
{
unsigned int i,j;
for(i=0;i<5000;i++)
{
for(j=0;j<100;j++) //嵌套的循环体,延时
asm("nop");
}
}
其中asm(“nop”);为空指令,起延时效果。
2时钟模块
SIM_SCGC5=SIM_SCGC5|((1<<10)+(1<<11)); //通过逻辑”或”置1,单独使能PORTC时钟
我们要让led等交替闪烁,可以发现在原理图中三个灯RGB都由PTB和PTC控制。第一步要打开这两个的时钟。查阅芯片说明书
首先查看system intergration module(系统集成模块) system clocking gate control的主页面
查看说明书207页12.2 Memory map and register definition
经了解,ptc ptb由SIM_SCGC5控制,我们打开后面蓝字,在222页,由此可以知道,把这个寄存器的10位和11位置1可以打开PORTB和PORTC的时钟模块
3 将pin设置为IO口
PORTB_PCR16=0x0100;
PORTB_PCR17=0x0100;
PORTB_PCR18=0x0100;
PORTB_PCR19=0x0100;
PORTC_PCR0=0x0100;
PORTC_PCR2=0x0100;//设置PTC0为GPIO
PORTC_PCR3=0x0100;
PORTC_PCR4=0x0100;
PORTC_PCR5=0x0100;//设置PTC4为GPIO
查看11章Port control and interrupt (PORT)的11.5 Memory map and register definition在193页
点开后面蓝字
其中8 9 10三个比特来确定引脚是什么功能
001时为gpio,则上述代码都设置PTC为GPIO
4配置PTC为输出
GPIOB_PDDR =0x0f0000;
GPIOC_PDDR =0x003d;//配置PTC0、PTC4为输出
查看42章General-purpose input/output (GPIO)
在842页找到寄存器表点开蓝字
其中B为16 17 18 19,换到16位表达式为0x0f0000,0f前面0省略
GPIOC_PDDR用到的口为0,2,3,4,5,其中(0,2,3)为12为d,(4,5)为3所以为0x003d
5PDOR output 0 and1
for(;;)
{
GPIOB_PDOR=0x090000;
GPIOC_PDOR=0x0008; //输出PTC0、PTC4为1,小灯点亮
delay();
GPIOB_PDOR=0x020000;
GPIOC_PDOR=0x0011; //输出PTC0、PTC4为1,小灯点亮
delay();
GPIOB_PDOR=0x040000;
GPIOC_PDOR=0x0024; //输出PTC0、PTC4为1,小灯点亮
delay();
//GPIOC_PDOR = ~ GPIOC_PDOR;
//GPIOB_PDOR = ~ GPIOB_PDOR;
// ~为逻辑取反,也可用GPIOC_PTOR寄存器反转端口
}
在这里逐条分析
GPIOB_PDOR=0x090000;9在第5位所以从15开始的1001即是16和19号口输出LED2和3的R被点亮
GPIOC_PDOR=0x0008为c的3号口输出LED1的R被点亮
即三个红灯亮起
GPIOB_PDOR=0x020000; 17点亮LED3的G
GPIOC_PDOR=0x0011; //输出PTC0、PTC4为1,小灯点亮 0号和4号点亮,led 2和4的G