📄 checksum.c
字号:
/*
This code shows implementation of a flash checksum for verifying integrity of
the data. In this example, a checksum is calculated at program start,
covering two flash segments. The checksum is stored in another segment of
flash. The device then goes to sleep. Two input signals can interrupt
the device. One initiates a verify of the checksum, and flashes the LED
several times if it's correct; if it's not correct, it disables interrupts
and lights the LED steadily. The other input signal deliberately corrupts
the flash block.
After the program is run, several transitions of the "check" input should
cause the LED to flash. After one transition of the "corrupt" input, the
next iteration of "check" will cause the LED to light steadily.
MSP430F1612
-----------------
/|\| XIN|-
| | |
--|RST XOUT|-
| |
*/
#include <msp430x16x.h>
#define flashStart 0xFA00
#define flashEnd 0xFDFF
#define flashChecksum 0x1080
int verifyFlash(void);
void storeChecksum(void);
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
FCTL2 = FWKEY + FSSEL0 + FN0; // MCLK/2 for flash timing generator
// .
// . Flash writes
// .
storeChecksum();
// Later in the program....
if (!verifyFlash())
{
// Handle the error
}
_BIS_SR(LPM3_bits+GIE); // Sleep until port interrupt
}
int verifyFlash(void)
{
unsigned int i, checksum=0, storedChecksum;
for (i=0;i<0x0200;i++) // Calculate checksum
checksum += ((unsigned int *)flashStart)[i];
storedChecksum = *(unsigned int *)flashChecksum; //Pull stored val from flash
if (checksum==storedChecksum) // Compare and return the result
return(1);
else
return(0);
}
void storeChecksum(void)
{
unsigned int i, checksum=0,*pFlashData;
for (i=0;i<0x0200;i++) // Calculate checksum
checksum += ((unsigned int *)flashStart)[i];
// Erase checksum storage location
pFlashData = (unsigned int *) flashChecksum; // Reset ptr to start of block
FCTL3 = FWKEY; // Unlock flash
FCTL1 = FWKEY + ERASE; // Set Erase bit
*pFlashData = 0x0000; // Dummy write to erase
// Store checksum
FCTL1 = FWKEY+WRT; // Enable flash write
*pFlashData = checksum; // Write checksum to flash
FCTL3 = FWKEY + LOCK; // Lock flash
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -