"""Program 4-7: Example of querying the user for an input Connect the GP21 pin and the GP20 pin to a PC through a USB-to-Serial Converter """ from machine import UART, Pin uart1 = UART(1, baudrate = 9600, rx = Pin(21), tx = Pin(20)) def uart1_get_char(): """This is a blocking function to get a character from UART1""" while True: char = uart1.read(1) if char is not None: print(char) # for debugging only return char def uart1_get_line(): """Read a line ending with a carriage return character ('\r')""" s = bytearray() # instatiate an empty byte array while True: c = uart1_get_char() # get a character from UART1 if c == b'\r': # if enter key was hit print('eol') # for debugging only return s # return the bytearray if c == b'\b': # for backspace if len(s) > 0: # do nothing if the bytearray is empty s = s[:-1] # otherwise, trim the last character entered uart1.write(b'\b \b') # echo backspace-space-backspace else: uart1.write(c) # echo the character print(s, c) # for debugging only s = s + c # append the new character to the end of s def uart1_get_number(): """Read a string from UART1 and convert it to a float number""" s = uart1_get_line() print(s, type(s)) # for debugging only f = float(s) # convert bytearray to a floating-point number print(f, type(f)) # for debugging only return f uart1.write('\r\nPlease enter a number: ') # give user a prompt n = uart1_get_number() # get a number from user input print(n, type(n)) # for debugging only sn = str(n) # convert to a string for UART write print(sn, type(sn)) # for debugging only uart1.write('\r\nYou have entered a number ' + sn + '\r\n')