github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/machine/machine_stm32_iwdg.go (about)

     1  //go:build stm32
     2  
     3  package machine
     4  
     5  import "device/stm32"
     6  
     7  var (
     8  	Watchdog = &watchdogImpl{}
     9  )
    10  
    11  const (
    12  	// WatchdogMaxTimeout in milliseconds (32.768s)
    13  	//
    14  	// Timeout is based on 12-bit counter with /256 divider on
    15  	// 32.768kHz clock.  See 21.3.3 of RM0090 for table.
    16  	WatchdogMaxTimeout = ((0xfff + 1) * 256 * 1024) / 32768
    17  )
    18  
    19  const (
    20  	// Enable access to PR, RLR and WINR registers (0x5555)
    21  	iwdgKeyEnable = 0x5555
    22  	// Reset the watchdog value (0xAAAA)
    23  	iwdgKeyReset = 0xaaaa
    24  	// Start the watchdog (0xCCCC)
    25  	iwdgKeyStart = 0xcccc
    26  	// Divide by 256
    27  	iwdgDiv256 = 6
    28  )
    29  
    30  type watchdogImpl struct {
    31  }
    32  
    33  // Configure the watchdog.
    34  //
    35  // This method should not be called after the watchdog is started and on
    36  // some platforms attempting to reconfigure after starting the watchdog
    37  // is explicitly forbidden / will not work.
    38  func (wd *watchdogImpl) Configure(config WatchdogConfig) error {
    39  
    40  	// Enable configuration of IWDG
    41  	stm32.IWDG.KR.Set(iwdgKeyEnable)
    42  
    43  	// Unconditionally divide by /256 since we don't really need accuracy
    44  	// less than 8ms
    45  	stm32.IWDG.PR.Set(iwdgDiv256)
    46  
    47  	timeout := config.TimeoutMillis
    48  	if timeout > WatchdogMaxTimeout {
    49  		timeout = WatchdogMaxTimeout
    50  	}
    51  
    52  	// Set reload value based on /256 divider
    53  	stm32.IWDG.RLR.Set(((config.TimeoutMillis*32768 + (256 * 1024) - 1) / (256 * 1024)) - 1)
    54  	return nil
    55  }
    56  
    57  // Starts the watchdog.
    58  func (wd *watchdogImpl) Start() error {
    59  	stm32.IWDG.KR.Set(iwdgKeyStart)
    60  	return nil
    61  }
    62  
    63  // Update the watchdog, indicating that `source` is healthy.
    64  func (wd *watchdogImpl) Update() {
    65  	stm32.IWDG.KR.Set(iwdgKeyReset)
    66  }