tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/sx126x/radiocontrol_stm32wl.go (about)

     1  //go:build stm32wlx
     2  
     3  package sx126x
     4  
     5  import (
     6  	"device/stm32"
     7  
     8  	"runtime/interrupt"
     9  )
    10  
    11  // STM32RadioControl helps implement the RadioController interface
    12  type STM32RadioControl struct {
    13  	irqHandler func()
    14  }
    15  
    16  // SetNss sets the NSS line aka chip select for SPI.
    17  func (rc *STM32RadioControl) SetNss(state bool) error {
    18  	if state {
    19  		stm32.PWR.SUBGHZSPICR.SetBits(stm32.PWR_SUBGHZSPICR_NSS)
    20  	} else {
    21  		stm32.PWR.SUBGHZSPICR.ClearBits(stm32.PWR_SUBGHZSPICR_NSS)
    22  	}
    23  
    24  	return nil
    25  }
    26  
    27  // WaitWhileBusy wait until the radio is no longer busy
    28  func (rc *STM32RadioControl) WaitWhileBusy() error {
    29  	count := 100
    30  	var rfbusyms, rfbusys bool
    31  	for count > 0 {
    32  		rfbusyms = stm32.PWR.SR2.HasBits(stm32.PWR_SR2_RFBUSYMS)
    33  		rfbusys = stm32.PWR.SR2.HasBits(stm32.PWR_SR2_RFBUSYS)
    34  
    35  		if !(rfbusyms && rfbusys) {
    36  			return nil
    37  		}
    38  		count--
    39  	}
    40  	return errWaitWhileBusyTimeout
    41  }
    42  
    43  // init() configures whatever needed for sx126x radio control
    44  func init() {
    45  	// Enable APB3 Periph clock and delay
    46  	stm32.RCC.APB3ENR.SetBits(stm32.RCC_APB3ENR_SUBGHZSPIEN)
    47  	_ = stm32.RCC.APB3ENR.Get()
    48  
    49  	// Disable radio reset and wait it's ready
    50  	stm32.RCC.CSR.ClearBits(stm32.RCC_CSR_RFRST)
    51  	for stm32.RCC.CSR.HasBits(stm32.RCC_CSR_RFRSTF) {
    52  	}
    53  
    54  	// Set NSS line low
    55  	stm32.PWR.SUBGHZSPICR.SetBits(stm32.PWR_SUBGHZSPICR_NSS)
    56  
    57  	// Enable radio busy wakeup from Standby for CPU
    58  	stm32.PWR.CR3.SetBits(stm32.PWR_CR3_EWRFBUSY)
    59  
    60  	// Clear busy flag
    61  	stm32.PWR.SCR.Set(stm32.PWR_SCR_CWRFBUSYF)
    62  
    63  	// Enable SUBGHZ Spi
    64  	// - /8 Prescaler
    65  	// - Software Slave Management (NSS)
    66  	// - FIFO Threshold and 8bit size
    67  	stm32.SPI3.CR1.ClearBits(stm32.SPI_CR1_SPE)
    68  	stm32.SPI3.CR1.Set(stm32.SPI_CR1_MSTR | stm32.SPI_CR1_SSI | (0b010 << 3) | stm32.SPI_CR1_SSM)
    69  	stm32.SPI3.CR2.Set(stm32.SPI_CR2_FRXTH | (0b111 << 8))
    70  	stm32.SPI3.CR1.SetBits(stm32.SPI_CR1_SPE)
    71  }
    72  
    73  func (rc *STM32RadioControl) SetupInterrupts(handler func()) error {
    74  	irqHandler = handler
    75  	intr := interrupt.New(stm32.IRQ_Radio_IRQ_Busy, handleInterrupt)
    76  	intr.Enable()
    77  
    78  	return nil
    79  }
    80  
    81  var irqHandler func()
    82  
    83  func handleInterrupt(interrupt.Interrupt) {
    84  	irqHandler()
    85  }