import os
import utime
from machine import UART, Pin

progName="serTxRx_pico.py"
# tested OK on 2021FJun15 by D@CC
# the b'H'<lf> have not yet been converted to "H"

#based pm progName="mpy_uart_pico.py"
print("progName:"+progName)
txPin=4
rxPin=5
print("Jumper GP"+str(rxPin)+" to GP"+str(txPin))
#print sys info
print(os.uname())

#indicate program started visually
led_onboard = machine.Pin(25, machine.Pin.OUT)
led_onboard.value(0)     # onboard LED OFF for 0.5 sec
utime.sleep(0.5)
led_onboard.value(1)


#self.uart = UART(1, 115200, parity=None, stop=1, bits=8, rx=Pin(rxPin), tx=Pin(txPin))
# speed of 400 only reads 4 bytes . . Doh?

uart = machine.UART(1,600, parity=None, stop=1, bits=8, tx=Pin(txPin), rx=Pin(rxPin))
#print uart info
#uart = machine.UART(1)
print(uart)
def serTxRx_pico(uartObject,rOrT="R",txtToBeSent="UUUUUUUUUU"):
    #print("entering serTxRx")
    #print("rOrT:"+rOrT)
    isValidRorT=False
    txtIn=" mt "
    if rOrT=="T":
        isValidRorT=True
        txtOut=txtToBeSent
        #print("1 transmitting:"+txtOut+":")
        if txtOut=="":
            txtOut="Hello"
        #end if
        print("2 transmitting:"+txtOut+":")
        uartObject.write(txtOut)
        utime.sleep(0.1)
        return
    #end if
    if rOrT=="X":
        isValidRorT=True
        txtIn=""
        while uartObject.any():
            txtIn=uartObject.read(1)
        #end while
        if txtIn=="":
            pass
        else:
            print(txtIn)
        #end if
    #end if
    if rOrT=="R" :
        isValidRorT=True
        #print("doing R")
        while uart.any():
            print(uart.read(1))
        #end while
        #print("after R loop")
    #end if
    if isValidRorT :
        return txtIn
    else:
        txtIn="?"
        return
    #end if
#end def

#transmit the default text (then print and return any received text)
serTxRx_pico(uart,"T","HelloYou")
#    the program executes so fast that we must wait for the message
#    to be fully sent before we start reading the message.
#    if we sleep(0), we will only see the final "o" Doh!
utime.sleep(0.1)
msg=serTxRx_pico(uart,"R")
if False:
    while uart.any():
        print(uart.read(1))
    #end while
#end if

for j in range(51):
    byteRecd=serTxRx_pico(uart,"R")
    strRecd=str(byteRecd)
    #print("strRecd:"+strRecd+":")
    if strRecd==" mt ":
        pass
    else:
        #strRecd=str(byteRecd)
        print(j,"txtRecd:"+strRecd+":")
    #end if
#end for
#print("end of j loop")
if False:
    while uart.any():
        print(uart.read(1))
    #end while
#end if
print()
print(j,"- bye -")
#Source:http://helloraspberrypi.blogspot.com/2021/01/raspberry-pi-picomicropython-simple.html
#program end