PIC12F508/509这款单片机比普通的51单片机还要简单,有51单片机基础的直接看数据手册就可直接深入。
至于入门安装IDE软件的教程可以参考另一个博主的系列教程,我觉得不错:https://blog.csdn.net/JYUNefe/article/details/80642999
其他教程:https://blog.csdn.net/qq_30209977/article/details/105775792
管脚分布
单片机存储空间大小
这款单片机内部资源有限,要省着点用,全局变量和静态变量不能太多,SRAM也少,所以写这款单片机程序时不能有太多的函数调用,尽量都写进main函数吧,如果发现烧进程序后跑不起来,可能就是你写了很多函数,资源不够用了,单片机已经死机,这款资源简单的单片机必定是应用在简单且功能不多的场景。
初始化配置位
关于初始化的配置位在这里
从上到下配置时钟来源、看门狗、代码保护、GP3管脚的功能选择(若选为MCLR则该管脚为普通的复位管脚,否则为输入脚,不可配置为输出管脚),配置好后点击输出,将输出生成的原代码复制到代码里。
寄存器
选项寄存器
这款单片机只有几个寄存器,首先看下图的选项寄存器
端口寄存器
第一条的"TRISGPIO"为I/O控制寄存器,当配置为1时为输入脚,配置为0时为输出脚。
下列的示例代码中I/O控制寄存器使用的是:TRIS,如果换成TRISGPIO也没问题。
状态寄存器
这个单片机没有中断,休眠后只能靠看门狗唤醒(实则是复位),但可以通过状态寄存器里的TO、PD、GPWUF这些位来判断是由什么原因导致复位的,如下图。
实例代码
定时器应用
// CONFIG
#pragma config OSC = IntRC // Oscillator Selection bits (internal RC oscillator)
#pragma config WDT = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config CP = OFF // Code Protection bit (Code protection off)
#pragma config MCLRE = OFF // GP3/MCLR Pin Function Select bit (GP3/MCLR pin function is digital input, MCLR internally tied to VDD)
#define uchar unsigned char
#define uint unsigned int
uchar count;
void main()
{
TRIS=~0x3F; //GP3输入,其它输出
OPTION=0xC5; //分频器给定时器 64 4MHz x=257-tJ/4F
TMR0=0x63; //10ms x=257-tJ/4F
while(1)
{
if(TMR0==0xFF)
{
TMR0=0x63; //
if(++count==50) //1s
{
count=0;
GP2=~GP2; //LED闪烁
}
}
}
}
看门狗和休眠模式
// CONFIG
#pragma config OSC = IntRC // Oscillator Selection bits (internal RC oscillator)
#pragma config WDT = ON // Watchdog Timer Enable bit (WDT Enable )
#pragma config CP = OFF // Code Protection bit (Code protection off)
#pragma config MCLRE = OFF // GP3/MCLR Pin Function Select bit (GP3/MCLR pin function is digital input, MCLR internally tied to VDD)
#define uchar unsigned char
#define uint unsigned int
uchar count;
void main()
{
TRIS = ~0x3F; //GP3输入,其它输出
OPTION = 0xCE; //定时器分配看门狗 时间是18Ms*64=1.152S
while(1)
{
if(nTO == 0) //看门狗引起的复位
{
GP2 = ~GP2;
}
SLEEP(); //进入休眠
}
}
看门狗 休眠唤醒与按键唤醒
// CONFIG
#pragma config OSC = IntRC // Oscillator Selection bits (internal RC oscillator)
#pragma config WDT = ON // Watchdog Timer Enable bit (WDT Enable )
#pragma config CP = OFF // Code Protection bit (Code protection off)
#pragma config MCLRE = OFF // GP3/MCLR Pin Function Select bit (GP3/MCLR pin function is digital input, MCLR internally tied to VDD)
#define uchar unsigned char
#define uint unsigned int
#define LED1 GP5
#define LED2 GP4
#define KEY GP3
bit KEY_F;
uchar count;
void main()
{
TRIS = ~0x3F; //GP3输入,其它输出
OPTION = 0x1E; //引脚中断唤醒使能 弱上拉使能 定时器分配看门狗时间是18Ms*64=1.152S
while(1)
{
if( (GPWUF == 1) && (KEY == 0) ) //引脚引起的中断唤醒
{
LED2 = ~LED2;
}
if(nTO == 0) //看门狗引起的复位
{
LED1 = ~LED1;
}
KEY_F = KEY; //读出休眠前的按键状态。
SLEEP();
}
}
延时函数
//延时函数,单位ms(大概时间)
void delay(uint16_t ms) {
uint32_t i;
i = ms * 30;
while (i--);
}