51单片机 c语言看门狗程序怎么写
看门狗在51单片机电路里的作用是防止程序 “跑飞”、“死机”后,系统不动作,而采取复位的办法“唤醒”系统。
89S51、89S52系列单片机自带有看门狗功能,片内数据区A6H寄存器具有看门狗功能,使用很简单:
#include
sfr WDTRST = 0xA6; ...
void main() {
WDTRST=0x1E;;//初始化看门狗 WDTRST=0xE1;//初始化看门狗 for(;;) {
WDTRST=0x1E;;//喂狗指令
WDTRST=0xE1;//喂狗指令 } }
可见,你只要在程序的大循环体内加一条喂狗指令就行。但这种看门狗功能有限,不是很可靠的,它依靠晶振工作,一旦晶振不起振,就无效了。
实践中多采用外部看门狗的方法,可以选用的芯片很多:MAX708、MAX813 、X25045.....具体编程就要看芯片的参考资料了。
例如:X25045是SPI总线的看门狗芯片,复位端和单片机复位端连接,SPI数据输入你可以选择合适的IO接口。
WREN 0x06 设置写允许位 WRDI 0x04 复位写允许位 RDSR 0x05 读状态寄存器 WRSR 0x01 写状态寄存器
READ 0x03/0x0b 读操作时内部EEPROM页地址 WRITE 0x02/0x0a 写操作时内部EEPROM页地址
#include
#define WREN 0x06 // #define WRDI 0x04 // #define RDSR 0x05 // #define WRSR 0x01 // #define READ0 0x03 // #define READ1 0x0b // #define WRITE0 0x02 // #define WRITE1 0x0a // #define uchar unsigned char
uchar ReadByte() //read a byte from device {
bit bData;
uchar ucLoop; uchar ucData;
for(ucLoop=0;ucLoop<8;ucLoop++) {
SCK=1; SCK=0; bData=SO; ucData<<=1; if(bData)
{ ucData|=0x01; } }
return ucData; }
void WriteByte(uchar ucData)//write a byte to device {
uchar ucLoop;
for(ucLoop=0;ucLoop<8;ucLoop++) {
if((ucData&0x80)==0) //the MSB send first {SI=0;} else {SI=1;} SCK=0; SCK=1;
ucData<<=1; } }
uchar ReadReg() //read register {
uchar ucData; CS=0;
WriteByte(RDSR);
ucData=ReadByte(); CS=1;
return ucData; }
uchar WriteReg(uchar ucData) //write register {
uchar ucTemp;
ucTemp=ReadReg();
if((ucTemp&0x01)==1) //the device is busy return 0; CS=0;
WriteByte(WREN);//when write the WREN, the cs must have a high level CS=1; CS=0;
WriteByte(WRSR); WriteByte(ucData); CS=1; return 1; }
void WriteEpm(uchar cData,uchar cAddress,bit bRegion)
/* 写入一个字节,cData为写入的数,cAddress为写入地址,bRegion为页 */ {
while((ReadReg()&0x01)==1); //the device is busy CS=0;
WriteByte(WREN); //when write the wren , the cs must have a high level CS=1; CS=0;
if(bRegion==0)
{ WriteByte(WRITE0);} //write the page addr else
{WriteByte(WRITE1);} WriteByte(cAddress); WriteByte(cData); SCK=0; // CS=1; }
uchar ReadEpm(uchar cAddress,bit bRegion)
/* 读入一个字节,cAddress为读入地址,bRegion为页 */ {
uchar cData;
while((ReadReg()&0x01)==1);//the device is busy CS=0;
if(bRegion==0)
相关推荐: