github.com/aykevl/tinygo@v0.5.0/src/machine/machine_stm32f103xx.go (about)

     1  // +build stm32,stm32f103xx
     2  
     3  package machine
     4  
     5  // Peripheral abstraction layer for the stm32.
     6  
     7  import (
     8  	"device/arm"
     9  	"device/stm32"
    10  	"errors"
    11  )
    12  
    13  const CPU_FREQUENCY = 72000000
    14  
    15  const (
    16  	GPIO_INPUT        = 0 // Input mode
    17  	GPIO_OUTPUT_10MHz = 1 // Output mode, max speed 10MHz
    18  	GPIO_OUTPUT_2MHz  = 2 // Output mode, max speed 2MHz
    19  	GPIO_OUTPUT_50MHz = 3 // Output mode, max speed 50MHz
    20  	GPIO_OUTPUT       = GPIO_OUTPUT_2MHz
    21  
    22  	GPIO_INPUT_MODE_ANALOG       = 0  // Input analog mode
    23  	GPIO_INPUT_MODE_FLOATING     = 4  // Input floating mode
    24  	GPIO_INPUT_MODE_PULL_UP_DOWN = 8  // Input pull up/down mode
    25  	GPIO_INPUT_MODE_RESERVED     = 12 // Input mode (reserved)
    26  
    27  	GPIO_OUTPUT_MODE_GP_PUSH_PULL   = 0  // Output mode general purpose push/pull
    28  	GPIO_OUTPUT_MODE_GP_OPEN_DRAIN  = 4  // Output mode general purpose open drain
    29  	GPIO_OUTPUT_MODE_ALT_PUSH_PULL  = 8  // Output mode alt. purpose push/pull
    30  	GPIO_OUTPUT_MODE_ALT_OPEN_DRAIN = 12 // Output mode alt. purpose open drain
    31  )
    32  
    33  func (p GPIO) getPort() *stm32.GPIO_Type {
    34  	switch p.Pin / 16 {
    35  	case 0:
    36  		return stm32.GPIOA
    37  	case 1:
    38  		return stm32.GPIOB
    39  	case 2:
    40  		return stm32.GPIOC
    41  	case 3:
    42  		return stm32.GPIOD
    43  	case 4:
    44  		return stm32.GPIOE
    45  	case 5:
    46  		return stm32.GPIOF
    47  	case 6:
    48  		return stm32.GPIOG
    49  	default:
    50  		panic("machine: unknown port")
    51  	}
    52  }
    53  
    54  // enableClock enables the clock for this desired GPIO port.
    55  func (p GPIO) enableClock() {
    56  	switch p.Pin / 16 {
    57  	case 0:
    58  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_IOPAEN
    59  	case 1:
    60  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_IOPBEN
    61  	case 2:
    62  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_IOPCEN
    63  	case 3:
    64  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_IOPDEN
    65  	case 4:
    66  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_IOPEEN
    67  	case 5:
    68  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_IOPFEN
    69  	case 6:
    70  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_IOPGEN
    71  	default:
    72  		panic("machine: unknown port")
    73  	}
    74  }
    75  
    76  // Configure this pin with the given configuration.
    77  func (p GPIO) Configure(config GPIOConfig) {
    78  	// Configure the GPIO pin.
    79  	p.enableClock()
    80  	port := p.getPort()
    81  	pin := p.Pin % 16
    82  	pos := p.Pin % 8 * 4
    83  	if pin < 8 {
    84  		port.CRL = stm32.RegValue((uint32(port.CRL) &^ (0xf << pos)) | (uint32(config.Mode) << pos))
    85  	} else {
    86  		port.CRH = stm32.RegValue((uint32(port.CRH) &^ (0xf << pos)) | (uint32(config.Mode) << pos))
    87  	}
    88  }
    89  
    90  // Set the pin to high or low.
    91  // Warning: only use this on an output pin!
    92  func (p GPIO) Set(high bool) {
    93  	port := p.getPort()
    94  	pin := p.Pin % 16
    95  	if high {
    96  		port.BSRR = 1 << pin
    97  	} else {
    98  		port.BSRR = 1 << (pin + 16)
    99  	}
   100  }
   101  
   102  // UART
   103  type UART struct {
   104  	Buffer *RingBuffer
   105  }
   106  
   107  var (
   108  	// USART1 is the first hardware serial port on the STM32.
   109  	// Both UART0 and UART1 refer to USART1.
   110  	UART0 = UART{Buffer: NewRingBuffer()}
   111  	UART1 = &UART0
   112  )
   113  
   114  // Configure the UART.
   115  func (uart UART) Configure(config UARTConfig) {
   116  	// Default baud rate to 115200.
   117  	if config.BaudRate == 0 {
   118  		config.BaudRate = 115200
   119  	}
   120  
   121  	// pins
   122  	switch config.TX {
   123  	case PB6:
   124  		// use alternate TX/RX pins PB6/PB7 via AFIO mapping
   125  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_AFIOEN
   126  		stm32.AFIO.MAPR |= stm32.AFIO_MAPR_USART1_REMAP
   127  		GPIO{PB6}.Configure(GPIOConfig{Mode: GPIO_OUTPUT_50MHz + GPIO_OUTPUT_MODE_ALT_PUSH_PULL})
   128  		GPIO{PB7}.Configure(GPIOConfig{Mode: GPIO_INPUT_MODE_FLOATING})
   129  	default:
   130  		// use standard TX/RX pins PA9 and PA10
   131  		GPIO{UART_TX_PIN}.Configure(GPIOConfig{Mode: GPIO_OUTPUT_50MHz + GPIO_OUTPUT_MODE_ALT_PUSH_PULL})
   132  		GPIO{UART_RX_PIN}.Configure(GPIOConfig{Mode: GPIO_INPUT_MODE_FLOATING})
   133  	}
   134  
   135  	// Enable USART1 clock
   136  	stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_USART1EN
   137  
   138  	// Set baud rate
   139  	uart.SetBaudRate(config.BaudRate)
   140  
   141  	// Enable USART1 port.
   142  	stm32.USART1.CR1 = stm32.USART_CR1_TE | stm32.USART_CR1_RE | stm32.USART_CR1_RXNEIE | stm32.USART_CR1_UE
   143  
   144  	// Enable RX IRQ.
   145  	arm.SetPriority(stm32.IRQ_USART1, 0xc0)
   146  	arm.EnableIRQ(stm32.IRQ_USART1)
   147  }
   148  
   149  // SetBaudRate sets the communication speed for the UART.
   150  func (uart UART) SetBaudRate(br uint32) {
   151  	// first divide by PCLK2 prescaler (div 1) and then desired baudrate
   152  	divider := CPU_FREQUENCY / br
   153  	stm32.USART1.BRR = stm32.RegValue(divider)
   154  }
   155  
   156  // WriteByte writes a byte of data to the UART.
   157  func (uart UART) WriteByte(c byte) error {
   158  	stm32.USART1.DR = stm32.RegValue(c)
   159  
   160  	for (stm32.USART1.SR & stm32.USART_SR_TXE) == 0 {
   161  	}
   162  	return nil
   163  }
   164  
   165  //go:export USART1_IRQHandler
   166  func handleUART1() {
   167  	UART1.Receive(byte((stm32.USART1.DR & 0xFF)))
   168  }
   169  
   170  // SPI on the STM32.
   171  type SPI struct {
   172  	Bus *stm32.SPI_Type
   173  }
   174  
   175  // There are 3 SPI interfaces on the STM32F103xx.
   176  // Since the first interface is named SPI1, both SPI0 and SPI1 refer to SPI1.
   177  // TODO: implement SPI2 and SPI3.
   178  var (
   179  	SPI1 = SPI{Bus: stm32.SPI1}
   180  	SPI0 = SPI1
   181  )
   182  
   183  // SPIConfig is used to store config info for SPI.
   184  type SPIConfig struct {
   185  	Frequency uint32
   186  	SCK       uint8
   187  	MOSI      uint8
   188  	MISO      uint8
   189  	LSBFirst  bool
   190  	Mode      uint8
   191  }
   192  
   193  // Configure is intended to setup the STM32 SPI1 interface.
   194  // Features still TODO:
   195  // - support SPI2 and SPI3
   196  // - allow setting data size to 16 bits?
   197  // - allow setting direction in HW for additional optimization?
   198  // - hardware SS pin?
   199  func (spi SPI) Configure(config SPIConfig) {
   200  	// enable clock for SPI
   201  	stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_SPI1EN
   202  
   203  	var conf uint16
   204  
   205  	// set frequency
   206  	switch config.Frequency {
   207  	case 125000:
   208  		conf |= stm32.SPI_BaudRatePrescaler_128
   209  	case 250000:
   210  		conf |= stm32.SPI_BaudRatePrescaler_64
   211  	case 500000:
   212  		conf |= stm32.SPI_BaudRatePrescaler_32
   213  	case 1000000:
   214  		conf |= stm32.SPI_BaudRatePrescaler_16
   215  	case 2000000:
   216  		conf |= stm32.SPI_BaudRatePrescaler_8
   217  	case 4000000:
   218  		conf |= stm32.SPI_BaudRatePrescaler_4
   219  	case 8000000:
   220  		conf |= stm32.SPI_BaudRatePrescaler_2
   221  	default:
   222  		conf |= stm32.SPI_BaudRatePrescaler_128
   223  	}
   224  
   225  	// set bit transfer order
   226  	if config.LSBFirst {
   227  		conf |= stm32.SPI_FirstBit_LSB
   228  	}
   229  
   230  	// set mode
   231  	switch config.Mode {
   232  	case 0:
   233  		conf &^= (1 << stm32.SPI_CR1_CPOL_Pos)
   234  		conf &^= (1 << stm32.SPI_CR1_CPHA_Pos)
   235  	case 1:
   236  		conf &^= (1 << stm32.SPI_CR1_CPOL_Pos)
   237  		conf |= (1 << stm32.SPI_CR1_CPHA_Pos)
   238  	case 2:
   239  		conf |= (1 << stm32.SPI_CR1_CPOL_Pos)
   240  		conf &^= (1 << stm32.SPI_CR1_CPHA_Pos)
   241  	case 3:
   242  		conf |= (1 << stm32.SPI_CR1_CPOL_Pos)
   243  		conf |= (1 << stm32.SPI_CR1_CPHA_Pos)
   244  	default: // to mode 0
   245  		conf &^= (1 << stm32.SPI_CR1_CPOL_Pos)
   246  		conf &^= (1 << stm32.SPI_CR1_CPHA_Pos)
   247  	}
   248  
   249  	// set to SPI master
   250  	conf |= stm32.SPI_Mode_Master
   251  
   252  	// now set the configuration
   253  	spi.Bus.CR1 = stm32.RegValue(conf)
   254  
   255  	// init pins
   256  	spi.setPins(config.SCK, config.MOSI, config.MISO)
   257  
   258  	// enable SPI interface
   259  	spi.Bus.CR1 |= stm32.SPI_CR1_SPE
   260  }
   261  
   262  // Transfer writes/reads a single byte using the SPI interface.
   263  func (spi SPI) Transfer(w byte) (byte, error) {
   264  	// Write data to be transmitted to the SPI data register
   265  	spi.Bus.DR = stm32.RegValue(w)
   266  
   267  	// Wait until transmit complete
   268  	for (spi.Bus.SR & stm32.SPI_SR_TXE) == 0 {
   269  	}
   270  
   271  	// Wait until receive complete
   272  	for (spi.Bus.SR & stm32.SPI_SR_RXNE) == 0 {
   273  	}
   274  
   275  	// Wait until SPI is not busy
   276  	for (spi.Bus.SR & stm32.SPI_SR_BSY) > 0 {
   277  	}
   278  
   279  	// Return received data from SPI data register
   280  	return byte(spi.Bus.DR), nil
   281  }
   282  
   283  func (spi SPI) setPins(sck, mosi, miso uint8) {
   284  	if sck == 0 {
   285  		sck = SPI0_SCK_PIN
   286  	}
   287  	if mosi == 0 {
   288  		mosi = SPI0_MOSI_PIN
   289  	}
   290  	if miso == 0 {
   291  		miso = SPI0_MISO_PIN
   292  	}
   293  
   294  	GPIO{sck}.Configure(GPIOConfig{Mode: GPIO_OUTPUT_50MHz + GPIO_OUTPUT_MODE_ALT_PUSH_PULL})
   295  	GPIO{mosi}.Configure(GPIOConfig{Mode: GPIO_OUTPUT_50MHz + GPIO_OUTPUT_MODE_ALT_PUSH_PULL})
   296  	GPIO{miso}.Configure(GPIOConfig{Mode: GPIO_INPUT_MODE_FLOATING})
   297  }
   298  
   299  // I2C on the STM32F103xx.
   300  type I2C struct {
   301  	Bus *stm32.I2C_Type
   302  }
   303  
   304  // There are 2 I2C interfaces on the STM32F103xx.
   305  // Since the first interface is named I2C1, both I2C0 and I2C1 refer to I2C1.
   306  // TODO: implement I2C2.
   307  var (
   308  	I2C1 = I2C{Bus: stm32.I2C1}
   309  	I2C0 = I2C1
   310  )
   311  
   312  // I2CConfig is used to store config info for I2C.
   313  type I2CConfig struct {
   314  	Frequency uint32
   315  	SCL       uint8
   316  	SDA       uint8
   317  }
   318  
   319  // Configure is intended to setup the I2C interface.
   320  func (i2c I2C) Configure(config I2CConfig) {
   321  	// Default I2C bus speed is 100 kHz.
   322  	if config.Frequency == 0 {
   323  		config.Frequency = TWI_FREQ_100KHZ
   324  	}
   325  
   326  	// enable clock for I2C
   327  	stm32.RCC.APB1ENR |= stm32.RCC_APB1ENR_I2C1EN
   328  
   329  	// I2C1 pins
   330  	switch config.SDA {
   331  	case PB9:
   332  		config.SCL = PB8
   333  		// use alternate I2C1 pins PB8/PB9 via AFIO mapping
   334  		stm32.RCC.APB2ENR |= stm32.RCC_APB2ENR_AFIOEN
   335  		stm32.AFIO.MAPR |= stm32.AFIO_MAPR_I2C1_REMAP
   336  	default:
   337  		// use default I2C1 pins PB6/PB7
   338  		config.SDA = SDA_PIN
   339  		config.SCL = SCL_PIN
   340  	}
   341  
   342  	GPIO{config.SDA}.Configure(GPIOConfig{Mode: GPIO_OUTPUT_50MHz + GPIO_OUTPUT_MODE_ALT_OPEN_DRAIN})
   343  	GPIO{config.SCL}.Configure(GPIOConfig{Mode: GPIO_OUTPUT_50MHz + GPIO_OUTPUT_MODE_ALT_OPEN_DRAIN})
   344  
   345  	// Disable the selected I2C peripheral to configure
   346  	i2c.Bus.CR1 &^= stm32.I2C_CR1_PE
   347  
   348  	// pclk1 clock speed is main frequency divided by PCK1 prescaler (div 2)
   349  	pclk1 := uint32(CPU_FREQUENCY / 2)
   350  
   351  	// set freqency range to pclk1 clock speed in Mhz.
   352  	// aka setting the value 36 means to use 36MhZ clock.
   353  	pclk1Mhz := pclk1 / 1000000
   354  	i2c.Bus.CR2 |= stm32.RegValue(pclk1Mhz)
   355  
   356  	switch config.Frequency {
   357  	case TWI_FREQ_100KHZ:
   358  		// Normal mode speed calculation
   359  		ccr := pclk1 / (config.Frequency * 2)
   360  		i2c.Bus.CCR = stm32.RegValue(ccr)
   361  
   362  		// duty cycle 2
   363  		i2c.Bus.CCR &^= stm32.I2C_CCR_DUTY
   364  
   365  		// frequency standard mode
   366  		i2c.Bus.CCR &^= stm32.I2C_CCR_F_S
   367  
   368  		// Set Maximum Rise Time for standard mode
   369  		i2c.Bus.TRISE = stm32.RegValue(pclk1Mhz)
   370  
   371  	case TWI_FREQ_400KHZ:
   372  		// Fast mode speed calculation
   373  		ccr := pclk1 / (config.Frequency * 3)
   374  		i2c.Bus.CCR = stm32.RegValue(ccr)
   375  
   376  		// duty cycle 2
   377  		i2c.Bus.CCR &^= stm32.I2C_CCR_DUTY
   378  
   379  		// frequency fast mode
   380  		i2c.Bus.CCR |= stm32.I2C_CCR_F_S
   381  
   382  		// Set Maximum Rise Time for fast mode
   383  		i2c.Bus.TRISE = stm32.RegValue(((pclk1Mhz * 300) / 1000))
   384  	}
   385  
   386  	// re-enable the selected I2C peripheral
   387  	i2c.Bus.CR1 |= stm32.I2C_CR1_PE
   388  }
   389  
   390  // Tx does a single I2C transaction at the specified address.
   391  // It clocks out the given address, writes the bytes in w, reads back len(r)
   392  // bytes and stores them in r, and generates a stop condition on the bus.
   393  func (i2c I2C) Tx(addr uint16, w, r []byte) error {
   394  	var err error
   395  	if len(w) != 0 {
   396  		// start transmission for writing
   397  		err = i2c.signalStart()
   398  		if err != nil {
   399  			return err
   400  		}
   401  
   402  		// send address
   403  		err = i2c.sendAddress(uint8(addr), true)
   404  		if err != nil {
   405  			return err
   406  		}
   407  
   408  		for _, b := range w {
   409  			err = i2c.WriteByte(b)
   410  			if err != nil {
   411  				return err
   412  			}
   413  		}
   414  
   415  		// sending stop here for write
   416  		err = i2c.signalStop()
   417  		if err != nil {
   418  			return err
   419  		}
   420  	}
   421  	if len(r) != 0 {
   422  		// re-start transmission for reading
   423  		err = i2c.signalStart()
   424  		if err != nil {
   425  			return err
   426  		}
   427  
   428  		// 1 byte
   429  		switch len(r) {
   430  		case 1:
   431  			// send address
   432  			err = i2c.sendAddress(uint8(addr), false)
   433  			if err != nil {
   434  				return err
   435  			}
   436  
   437  			// Disable ACK of received data
   438  			i2c.Bus.CR1 &^= stm32.I2C_CR1_ACK
   439  
   440  			// clear timeout here
   441  			timeout := i2cTimeout
   442  			for i2c.Bus.SR2&(stm32.I2C_SR2_MSL|stm32.I2C_SR2_BUSY) == 0 {
   443  				timeout--
   444  				if timeout == 0 {
   445  					return errors.New("I2C timeout on read clear address")
   446  				}
   447  			}
   448  
   449  			// Generate stop condition
   450  			i2c.Bus.CR1 |= stm32.I2C_CR1_STOP
   451  
   452  			timeout = i2cTimeout
   453  			for (i2c.Bus.SR1 & stm32.I2C_SR1_RxNE) == 0 {
   454  				timeout--
   455  				if timeout == 0 {
   456  					return errors.New("I2C timeout on read 1 byte")
   457  				}
   458  			}
   459  
   460  			// Read and return data byte from I2C data register
   461  			r[0] = byte(i2c.Bus.DR)
   462  
   463  			// wait for stop
   464  			return i2c.waitForStop()
   465  
   466  		case 2:
   467  			// enable pos
   468  			i2c.Bus.CR1 |= stm32.I2C_CR1_POS
   469  
   470  			// Enable ACK of received data
   471  			i2c.Bus.CR1 |= stm32.I2C_CR1_ACK
   472  
   473  			// send address
   474  			err = i2c.sendAddress(uint8(addr), false)
   475  			if err != nil {
   476  				return err
   477  			}
   478  
   479  			// clear address here
   480  			timeout := i2cTimeout
   481  			for i2c.Bus.SR2&(stm32.I2C_SR2_MSL|stm32.I2C_SR2_BUSY) == 0 {
   482  				timeout--
   483  				if timeout == 0 {
   484  					return errors.New("I2C timeout on read clear address")
   485  				}
   486  			}
   487  
   488  			// Disable ACK of received data
   489  			i2c.Bus.CR1 &^= stm32.I2C_CR1_ACK
   490  
   491  			// wait for btf. we need a longer timeout here than normal.
   492  			timeout = 1000
   493  			for (i2c.Bus.SR1 & stm32.I2C_SR1_BTF) == 0 {
   494  				timeout--
   495  				if timeout == 0 {
   496  					return errors.New("I2C timeout on read 2 bytes")
   497  				}
   498  			}
   499  
   500  			// Generate stop condition
   501  			i2c.Bus.CR1 |= stm32.I2C_CR1_STOP
   502  
   503  			// read the 2 bytes by reading twice.
   504  			r[0] = byte(i2c.Bus.DR)
   505  			r[1] = byte(i2c.Bus.DR)
   506  
   507  			// wait for stop
   508  			return i2c.waitForStop()
   509  
   510  		case 3:
   511  			// Enable ACK of received data
   512  			i2c.Bus.CR1 |= stm32.I2C_CR1_ACK
   513  
   514  			// send address
   515  			err = i2c.sendAddress(uint8(addr), false)
   516  			if err != nil {
   517  				return err
   518  			}
   519  
   520  			// clear address here
   521  			timeout := i2cTimeout
   522  			for i2c.Bus.SR2&(stm32.I2C_SR2_MSL|stm32.I2C_SR2_BUSY) == 0 {
   523  				timeout--
   524  				if timeout == 0 {
   525  					return errors.New("I2C timeout on read clear address")
   526  				}
   527  			}
   528  
   529  			// Enable ACK of received data
   530  			i2c.Bus.CR1 |= stm32.I2C_CR1_ACK
   531  
   532  			// wait for btf. we need a longer timeout here than normal.
   533  			timeout = 1000
   534  			for (i2c.Bus.SR1 & stm32.I2C_SR1_BTF) == 0 {
   535  				timeout--
   536  				if timeout == 0 {
   537  					println("I2C timeout on read 3 bytes")
   538  					return errors.New("I2C timeout on read 3 bytes")
   539  				}
   540  			}
   541  
   542  			// Disable ACK of received data
   543  			i2c.Bus.CR1 &^= stm32.I2C_CR1_ACK
   544  
   545  			// read the first byte
   546  			r[0] = byte(i2c.Bus.DR)
   547  
   548  			timeout = 1000
   549  			for (i2c.Bus.SR1 & stm32.I2C_SR1_BTF) == 0 {
   550  				timeout--
   551  				if timeout == 0 {
   552  					return errors.New("I2C timeout on read 3 bytes")
   553  				}
   554  			}
   555  
   556  			// Generate stop condition
   557  			i2c.Bus.CR1 |= stm32.I2C_CR1_STOP
   558  
   559  			// read the last 2 bytes by reading twice.
   560  			r[1] = byte(i2c.Bus.DR)
   561  			r[2] = byte(i2c.Bus.DR)
   562  
   563  			// wait for stop
   564  			return i2c.waitForStop()
   565  
   566  		default:
   567  			// more than 3 bytes of data to read
   568  
   569  			// send address
   570  			err = i2c.sendAddress(uint8(addr), false)
   571  			if err != nil {
   572  				return err
   573  			}
   574  
   575  			// clear address here
   576  			timeout := i2cTimeout
   577  			for i2c.Bus.SR2&(stm32.I2C_SR2_MSL|stm32.I2C_SR2_BUSY) == 0 {
   578  				timeout--
   579  				if timeout == 0 {
   580  					return errors.New("I2C timeout on read clear address")
   581  				}
   582  			}
   583  
   584  			for i := 0; i < len(r)-3; i++ {
   585  				// Enable ACK of received data
   586  				i2c.Bus.CR1 |= stm32.I2C_CR1_ACK
   587  
   588  				// wait for btf. we need a longer timeout here than normal.
   589  				timeout = 1000
   590  				for (i2c.Bus.SR1 & stm32.I2C_SR1_BTF) == 0 {
   591  					timeout--
   592  					if timeout == 0 {
   593  						println("I2C timeout on read 3 bytes")
   594  						return errors.New("I2C timeout on read 3 bytes")
   595  					}
   596  				}
   597  
   598  				// read the next byte
   599  				r[i] = byte(i2c.Bus.DR)
   600  			}
   601  
   602  			// wait for btf. we need a longer timeout here than normal.
   603  			timeout = 1000
   604  			for (i2c.Bus.SR1 & stm32.I2C_SR1_BTF) == 0 {
   605  				timeout--
   606  				if timeout == 0 {
   607  					return errors.New("I2C timeout on read more than 3 bytes")
   608  				}
   609  			}
   610  
   611  			// Disable ACK of received data
   612  			i2c.Bus.CR1 &^= stm32.I2C_CR1_ACK
   613  
   614  			// get third from last byte
   615  			r[len(r)-3] = byte(i2c.Bus.DR)
   616  
   617  			// Generate stop condition
   618  			i2c.Bus.CR1 |= stm32.I2C_CR1_STOP
   619  
   620  			// get second from last byte
   621  			r[len(r)-2] = byte(i2c.Bus.DR)
   622  
   623  			timeout = i2cTimeout
   624  			for (i2c.Bus.SR1 & stm32.I2C_SR1_RxNE) == 0 {
   625  				timeout--
   626  				if timeout == 0 {
   627  					return errors.New("I2C timeout on read last byte of more than 3")
   628  				}
   629  			}
   630  
   631  			// get last byte
   632  			r[len(r)-1] = byte(i2c.Bus.DR)
   633  
   634  			// wait for stop
   635  			return i2c.waitForStop()
   636  		}
   637  	}
   638  
   639  	return nil
   640  }
   641  
   642  const i2cTimeout = 500
   643  
   644  // signalStart sends a start signal.
   645  func (i2c I2C) signalStart() error {
   646  	// Wait until I2C is not busy
   647  	timeout := i2cTimeout
   648  	for (i2c.Bus.SR2 & stm32.I2C_SR2_BUSY) > 0 {
   649  		timeout--
   650  		if timeout == 0 {
   651  			return errors.New("I2C busy on start")
   652  		}
   653  	}
   654  
   655  	// clear stop
   656  	i2c.Bus.CR1 &^= stm32.I2C_CR1_STOP
   657  
   658  	// Generate start condition
   659  	i2c.Bus.CR1 |= stm32.I2C_CR1_START
   660  
   661  	// Wait for I2C EV5 aka SB flag.
   662  	timeout = i2cTimeout
   663  	for (i2c.Bus.SR1 & stm32.I2C_SR1_SB) == 0 {
   664  		timeout--
   665  		if timeout == 0 {
   666  			return errors.New("I2C timeout on start")
   667  		}
   668  	}
   669  
   670  	return nil
   671  }
   672  
   673  // signalStop sends a stop signal and waits for it to succeed.
   674  func (i2c I2C) signalStop() error {
   675  	// Generate stop condition
   676  	i2c.Bus.CR1 |= stm32.I2C_CR1_STOP
   677  
   678  	// wait for stop
   679  	return i2c.waitForStop()
   680  }
   681  
   682  // waitForStop waits after a stop signal.
   683  func (i2c I2C) waitForStop() error {
   684  	// Wait until I2C is stopped
   685  	timeout := i2cTimeout
   686  	for (i2c.Bus.SR1 & stm32.I2C_SR1_STOPF) > 0 {
   687  		timeout--
   688  		if timeout == 0 {
   689  			println("I2C timeout on wait for stop signal")
   690  			return errors.New("I2C timeout on wait for stop signal")
   691  		}
   692  	}
   693  
   694  	return nil
   695  }
   696  
   697  // Send address of device we want to talk to
   698  func (i2c I2C) sendAddress(address uint8, write bool) error {
   699  	data := (address << 1)
   700  	if !write {
   701  		data |= 1 // set read flag
   702  	}
   703  
   704  	i2c.Bus.DR = stm32.RegValue(data)
   705  
   706  	// Wait for I2C EV6 event.
   707  	// Destination device acknowledges address
   708  	timeout := i2cTimeout
   709  	if write {
   710  		// EV6 which is ADDR flag.
   711  		for i2c.Bus.SR1&stm32.I2C_SR1_ADDR == 0 {
   712  			timeout--
   713  			if timeout == 0 {
   714  				return errors.New("I2C timeout on send write address")
   715  			}
   716  		}
   717  
   718  		timeout = i2cTimeout
   719  		for i2c.Bus.SR2&(stm32.I2C_SR2_MSL|stm32.I2C_SR2_BUSY|stm32.I2C_SR2_TRA) == 0 {
   720  			timeout--
   721  			if timeout == 0 {
   722  				return errors.New("I2C timeout on send write address")
   723  			}
   724  		}
   725  	} else {
   726  		// I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED which is ADDR flag.
   727  		for (i2c.Bus.SR1 & stm32.I2C_SR1_ADDR) == 0 {
   728  			timeout--
   729  			if timeout == 0 {
   730  				return errors.New("I2C timeout on send read address")
   731  			}
   732  		}
   733  	}
   734  
   735  	return nil
   736  }
   737  
   738  // WriteByte writes a single byte to the I2C bus.
   739  func (i2c I2C) WriteByte(data byte) error {
   740  	// Send data byte
   741  	i2c.Bus.DR = stm32.RegValue(data)
   742  
   743  	// Wait for I2C EV8_2 when data has been physically shifted out and
   744  	// output on the bus.
   745  	// I2C_EVENT_MASTER_BYTE_TRANSMITTED is TXE flag.
   746  	timeout := i2cTimeout
   747  	for i2c.Bus.SR1&stm32.I2C_SR1_TxE == 0 {
   748  		timeout--
   749  		if timeout == 0 {
   750  			return errors.New("I2C timeout on write")
   751  		}
   752  	}
   753  
   754  	return nil
   755  }