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

     1  // This is a echo console running on the device UART.
     2  // Connect using default baudrate for this hardware, 8-N-1 with your terminal program.
     3  package main
     4  
     5  import (
     6  	"machine"
     7  	"time"
     8  )
     9  
    10  // change these to test a different UART or pins if available
    11  var (
    12  	uart = machine.Serial
    13  	tx   = machine.UART_TX_PIN
    14  	rx   = machine.UART_RX_PIN
    15  )
    16  
    17  func main() {
    18  	uart.Configure(machine.UARTConfig{TX: tx, RX: rx})
    19  	uart.Write([]byte("Echo console enabled. Type something then press enter:\r\n"))
    20  
    21  	input := make([]byte, 64)
    22  	i := 0
    23  	for {
    24  		if uart.Buffered() > 0 {
    25  			data, _ := uart.ReadByte()
    26  
    27  			switch data {
    28  			case 13:
    29  				// return key
    30  				uart.Write([]byte("\r\n"))
    31  				uart.Write([]byte("You typed: "))
    32  				uart.Write(input[:i])
    33  				uart.Write([]byte("\r\n"))
    34  				i = 0
    35  			default:
    36  				// just echo the character
    37  				uart.WriteByte(data)
    38  				input[i] = data
    39  				i++
    40  			}
    41  		}
    42  		time.Sleep(10 * time.Millisecond)
    43  	}
    44  }