Hello,
It would seem the primary problem with your code is that it will be resident in flash, and the flash memory becomes inaccessible during erase or programming operations. This is why the function code must be transferred to RAM, and run from there. You may use either a dedicated block of RAM for this purpose, or alternatively run the code from the stack. The previously referenced code attempts to do the latter.
Incidentally, even though this referenced code uses assembler, it is a relatively simple matter to interface with your C code. In this case, the assembly code should remain in a separate .ASM file, and within your C code you would provide functions that call the assembly routines.
/* Assembly sub-routines */
extern void *FlashProg1( void);
extern void *FlashErase1( void);
/* Program flash byte */
byte FlashProg( byte *pntr, byte val)
{
byte err;
__asm {
ldhx pntr
lda val
jsr FlashProg1
sta err
}
return err;
}
/* Erase flash page */
byte FlashErase( byte *pntr)
{
byte err;
__asm {
ldhx pntr
jsr FlashErase1
sta err
}
return err;
}
The flash frequency divider may only be written once out of reset. Are you attempting to set the value multiple times? The following function should flag this situation.
byte Flash_init( byte value)
{
if (FCDIV & 0x80)
return 1; /* Error return */
FCDIV = value & 0x7F;
return 0; /* No error */
}
Regards,
Mac