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

     1  // +build avr nrf sam stm32
     2  
     3  package machine
     4  
     5  import "errors"
     6  
     7  type UARTConfig struct {
     8  	BaudRate uint32
     9  	TX       uint8
    10  	RX       uint8
    11  }
    12  
    13  // To implement the UART interface for a board, you must declare a concrete type as follows:
    14  //
    15  // 		type UART struct {
    16  // 			Buffer *RingBuffer
    17  // 		}
    18  //
    19  // You can also add additional members to this struct depending on your implementation,
    20  // but the *RingBuffer is required.
    21  // When you are declaring your UARTs for your board, make sure that you also declare the
    22  // RingBuffer using the NewRingBuffer() function when you declare your UART:
    23  //
    24  //		UART{Buffer: NewRingBuffer()}
    25  //
    26  
    27  // Read from the RX buffer.
    28  func (uart UART) Read(data []byte) (n int, err error) {
    29  	// check if RX buffer is empty
    30  	size := uart.Buffered()
    31  	if size == 0 {
    32  		return 0, nil
    33  	}
    34  
    35  	// Make sure we do not read more from buffer than the data slice can hold.
    36  	if len(data) < size {
    37  		size = len(data)
    38  	}
    39  
    40  	// only read number of bytes used from buffer
    41  	for i := 0; i < size; i++ {
    42  		v, _ := uart.ReadByte()
    43  		data[i] = v
    44  	}
    45  
    46  	return size, nil
    47  }
    48  
    49  // Write data to the UART.
    50  func (uart UART) Write(data []byte) (n int, err error) {
    51  	for _, v := range data {
    52  		uart.WriteByte(v)
    53  	}
    54  	return len(data), nil
    55  }
    56  
    57  // ReadByte reads a single byte from the RX buffer.
    58  // If there is no data in the buffer, returns an error.
    59  func (uart UART) ReadByte() (byte, error) {
    60  	// check if RX buffer is empty
    61  	buf, ok := uart.Buffer.Get()
    62  	if !ok {
    63  		return 0, errors.New("Buffer empty")
    64  	}
    65  	return buf, nil
    66  }
    67  
    68  // Buffered returns the number of bytes currently stored in the RX buffer.
    69  func (uart UART) Buffered() int {
    70  	return int(uart.Buffer.Used())
    71  }
    72  
    73  // Receive handles adding data to the UART's data buffer.
    74  // Usually called by the IRQ handler for a machine.
    75  func (uart UART) Receive(data byte) {
    76  	uart.Buffer.Put(data)
    77  }