MC9S12DP512单片机使用EEPROM模块记录开机次数代码
时间: 2023-12-08 11:05:06 浏览: 136
#include <hidef.h> /* necessary for EnableInterrupts macro */
#include "derivative.h" /* contains declarations of the peripheral registers */
#include <stdio.h>
#define EEPROM_START_ADDRESS 0x4000
#define EEPROM_END_ADDRESS 0x4FFF
void write_eeprom(unsigned int address, unsigned char data);
unsigned char read_eeprom(unsigned int address);
void delay(unsigned int time);
void main(void) {
unsigned int count;
unsigned char data;
EnableInterrupts;
/* include your code here */
count = read_eeprom(EEPROM_START_ADDRESS);
count++; // Increase count by 1
write_eeprom(EEPROM_START_ADDRESS, count);
data = read_eeprom(EEPROM_START_ADDRESS);
printf("The number of times the system has been powered on is %d\n", data);
for(;;) {
__RESET_WATCHDOG(); /* feeds the dog */
} /* loop forever */
}
void write_eeprom(unsigned int address, unsigned char data) {
if (address >= EEPROM_START_ADDRESS && address <= EEPROM_END_ADDRESS) {
/* Enable EEPROM programming */
ECLKDIV = 0x08; // EEPROM clock divider, 8 MHz
ESTAT = 0x30; // EEPROM enable programming, erase, and write
/* Write to EEPROM */
EADDR = address;
EDATA = data;
ECTL |= 0x08; // EEPROM write
while (ESTAT_CBEIF == 0); // Wait for EEPROM write completion
/* Disable EEPROM programming */
ESTAT = 0x00; // EEPROM disable programming, erase, and write
}
}
unsigned char read_eeprom(unsigned int address) {
unsigned char data = 0;
if (address >= EEPROM_START_ADDRESS && address <= EEPROM_END_ADDRESS) {
/* Read from EEPROM */
EADDR = address;
ECTL |= 0x04; // EEPROM read
while (ESTAT_CCIF == 0); // Wait for EEPROM read completion
data = EDATA;
}
return data;
}
void delay(unsigned int time) {
unsigned int i;
for (i = 0; i < time; i++);
}
阅读全文