Hi DCloud,
To protect the code on your SAMD21G18A requires the setting of the security bit in the Non-Volatile Memory Controller (NVMCTRL).
However, while reading the security bit is just a case of checking the SB (Security Bit) in the NVMCTRL's STATUS register, writing to it requires you to call the Set Security Bit (SSB) command in the NVMCTRL's CTRLA reigster.
The only example code I could find was Atmel's ASF (Atmel's Software Framework) in the nvm_execute_command() function on Github, located here: asf/nvm.c at master · avrxml/asf · GitHub
The nvm_execute_command() function for setting the security bit essentially boils down to the following code, (although I haven't tested it, see warning below):
void setup() {
uint32_t ctrlb_bak = NVMCTRL->CTRLB.reg; // Turn off cache before issuing flash commands
NVMCTRL->CTRLB.reg = ctrlb_bak | NVMCTRL_CTRLB_CACHEDIS;
NVMCTRL->STATUS.reg = NVMCTRL_STATUS_MASK; // Clear error flags
if (!(NVMCTRL->INTFLAG.reg & NVMCTRL_INTFLAG_READY)) // Check if the module is busy
{
NVMCTRL->CTRLB.reg = ctrlb_bak; // Restore the setting
}
else
{
NVMCTRL->CTRLA.reg = NVMCTRL_CTRLA_CMD_SSB | // Set command
NVMCTRL_CTRLA_CMDEX_KEY;
while (!(NVMCTRL->INTFLAG.reg & NVMCTRL_INTFLAG_READY)) {} // Wait for the NVM controller to become ready
NVMCTRL->CTRLB.reg = ctrlb_bak; // Restore the setting
}
}
void loop() {}
Warning: Once the security bit has been set, it can only be reset by performing a full chip erase using an ICE programmer.