Welcome to the Pycom forum Forum
    • \[\[global:header.categories\]\]
    • \[\[global:header.recent\]\]
    • \[\[global:header.tags\]\]
    • \[\[global:header.popular\]\]
    • Login

    Explore Pybytes | Official Documentation | Report a Firmware Bug/Issue | GitHub

    How to send Lopy received data to a computer via serial port?

    Scheduled Pinned Locked Moved MicroPython
    lopy loraserialpythonmicropython
    13 Posts 2 Posters 5.3k Views 3 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • robert-hhR Offline
      robert-hh @monersss
      last edited by robert-hh

      @monersss Like you said, you need an instance to a) send data from the LoPy and to b) receive it on the PC. Lets assume you decide to use printable characters in the messages.
      a) This is easy, especially if you decide to use UART0, since by default in _boot.py UART 0 is connected to the REPL. To get data about of UART 0, simple use print statements. UART0 is connected to the SERIAL/USB bridge on the expansion board, so this is pretty convenient. Otherwise, you have to open a UART and write to it, like using UART 1 at 115200 baud.

      from machine import UART
      uart = UART(1, 115200)
      ...
      uart.write("value = %d\n" % value)
      

      value is here an arbitrary name for something to send. I use here \n at the end of the write to send the data nicely in lines, so you could see it in the PC well ordered, even with a terminal software
      b) This is an example of a little python3 script, which receives the data from the USB serial and puts it optionally into a file. It requires pyserial.py to be installed beforehand, with pip3 install pyserial

      import sys
      import serial
      from time import sleep
      
      
      def main():
          if len(sys.argv) > 1:
              port = sys.argv[1]
              if len(sys.argv) > 2:
                  filename = sys.argv[2]
                  try:
                      f = open(filename, "w")
                  except:
                      print("Could not open file:", filename)
                      return
              else:
                  f = None
      # open file
              try:
                  ser = serial.Serial(port, 115200)
                  sleep(3)
                  ser.reset_input_buffer()
              except Exception as err:
                  print("Could not connect: {!r}".format(err))
                  return
              print("Data connection at:", port)
              while True:
                  try:
                      line = ser.readline().decode().rstrip("\r\n")
                      if line != '': # Still alive?
                          print(line)
                          if f is not None:
                              f.write(line + "\r\n")
                      else: # EOF
                          break
                  except Exception as err:
                      print("{!r}".format(err))
                      break
                  except KeyboardInterrupt:
                      print("Interrupted!")
                      break
              if f is not None:
                  f.close()
          else:
              print("Usage: usbrecv port [filename]")
      
      if __name__ == "__main__":
          main()
      
      1 Reply Last reply Reply Quote 0
      • M Offline
        monersss
        last edited by

        @robert-hh Hello, thanks for a fast answer. I still cannot get anything printed out on my putty screet. The code in my main.py in first lopy is this one:

        from network import LoRa
        import socket
        import time
        from machine import UART

        uart = UART(1, 115200)

        lora = LoRa(mode=LoRa.LORA, frequency=863000000)
        s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        s.setblocking(False)
        while True:
        s.send('In range?')
        my_message = s.recv(64)

        if len(my_message) > 0:
            uart.write("my_message\n")
        else:
            uart.write("out of range\n")
        
        time.sleep(10)
        

        it is connected via serial to PC and when i connect via Putty I get nothing

        the code on second lopy is this one:

        from network import LoRa
        import socket
        import time

        lora = LoRa(mode=LoRa.LORA, frequency=863000000)
        s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        s.setblocking(False)

        while True:
        if s.recv(64) == b'In range?':
        s.send('You are within LORA range!')

        time.sleep(10)
        

        everything works perfect when i operate with Atom....

        Where do i make a mistake??

        robert-hhR 1 Reply Last reply Reply Quote 0
        • robert-hhR Offline
          robert-hh @monersss
          last edited by

          @monersss Which USB/UART connection do you use? If you use the expansion board, the you have to open UART 0. So the line above must read as:
          uart = UART(0, 115200)
          Then you should see something in Putty.
          Another reason why you may not see messages with Putty may be its flow control. Please set Putty's flow control to 'off'.

          M 1 Reply Last reply Reply Quote 0
          • M Offline
            monersss @robert-hh
            last edited by

            @robert-hh I am connecting via expantion board micro usb, so I understand that i need to update my code changing uart: uart = UART(0, 115200) right?
            PS there are two uart buses that i can connect to, does it mean i can connect lopy to one device to receive data from one source and to another one to receive data from another data source?

            robert-hhR 1 Reply Last reply Reply Quote 0
            • robert-hhR Offline
              robert-hh @monersss
              last edited by

              @monersss Yes, you can use both UARTs.But only one of them is connected to the USB/Serial bridge on the expansion board. UART1, connected to P3/P4, has just it's digital outputs. So if you want to use it for USB or standard RS232, you have to add an appropriate adapter.

              M 1 Reply Last reply Reply Quote 0
              • M Offline
                monersss @robert-hh
                last edited by

                @robert-hh i cannot see the messages on putty. I have set the flow control to none and still not working. The code is ok, when running it from atom i am getting response, so it seems there is a problem with my uart code i guess?

                robert-hhR 1 Reply Last reply Reply Quote 0
                • robert-hhR Offline
                  robert-hh @monersss
                  last edited by robert-hh

                  @monersss How do you connect with Atom? Are you using Telnet? If not, did you close Atom when you tried to use the UART? And are you sure that you are using the right COM port on your PC?

                  M 1 Reply Last reply Reply Quote 0
                  • M Offline
                    monersss @robert-hh
                    last edited by

                    @robert-hh i connect to atom via serial, before trying to connect with putty to serial port i disconnect with atom. the port i am using is ok. serial setting are speed 115200, data bits 8, stop bits 1, parity none, flow control none.

                    Maybe i am missing part of the code where i define data bits and stop bits so they are defined exactly like the ones in putty?

                    PS i have updated the firmware on my lopys and running my code from main.py on both. in atom everything is ok

                    robert-hhR 1 Reply Last reply Reply Quote 0
                    • robert-hhR Offline
                      robert-hh @monersss
                      last edited by robert-hh

                      @monersss 8 data bits/1 stop bit is the default.
                      When you have connected Putty and push reset, do you see the boot messages ot the bootstrap loader in Putty, and the first Microypthon Banner? Because these are definitely sent to UART0. If not, then there is a problem with Putty. If yes, then UART0 is properly connected, and unless you changed _boot.py, REPL is connecetd to the UART, and you can for instance terminate your code with Ctrl-C. If you want to disconnect REPL from the UART, you have to use the statement os.dupterm(None)
                      If you keep REPL connected to UART, you can use print() statements instead of uart.write() in your code.

                      M 2 Replies Last reply Reply Quote 0
                      • M Offline
                        monersss @robert-hh
                        last edited by

                        @robert-hh yes i can see the rester going on on putty and the micropython prompt. I did not change boot.py, only main.py which looks like that now:

                        from network import LoRa
                        import socket
                        import time
                        from machine import UART
                        uart = UART(0, 115200)
                        lora = LoRa(mode=LoRa.LORA, frequency=863000000)
                        s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
                        s.setblocking(False)
                        while True:
                        s.send('In range?')
                        my_message = s.recv(64)
                        if len(my_message) > 0:
                        uart.write(my_message)
                        else:
                        uart.write("out of range")
                        time.sleep(10)

                        I do not want to run a code from putty but to run it from main and only see messages sent between two lopys in putty, the final step will be to receive through spyder, but as a first step i wanted to see if they are sent by lopy to a computer correctly.

                        robert-hhR 1 Reply Last reply Reply Quote 0
                        • M Offline
                          monersss @robert-hh
                          last edited by

                          @robert-hh maybe here is the answer:

                          seems that there is some error in main.py line 6 OSError: the requested operation failed, thats what i get when restarting the board:

                          rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
                          ets Jun 8 2016 00:22:57

                          rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
                          configsip: 0, SPIWP:0xee
                          clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
                          mode:DIO, clock div:1
                          load:0x3fff9010,len:12
                          ho 0 tail 12 room 4
                          load:0x3fff9020,len:388
                          load:0x40078000,len:11584
                          load:0x4009fb00,len:848
                          entry 0x4009fc9c
                          Traceback (most recent call last):
                          File "main.py", line 6, in <module>
                          OSError: the requested operation failed
                          MicroPython v1.8.6-796-g489fafa0 on 2017-10-15; LoPy with ESP32
                          Type "help()" for more information.

                          and the line 6 in main.py is an uart line:
                          uart = UART(0, 115200)

                          1 Reply Last reply Reply Quote 0
                          • robert-hhR Offline
                            robert-hh @monersss
                            last edited by

                            @monersss Then, start your script with:

                            from network import LoRa
                            import socket
                            import time
                            import os
                            os.dupterm(None)
                            ...
                            
                            1 Reply Last reply Reply Quote 0

                            Hello! It looks like you're interested in this conversation, but you don't have an account yet.

                            Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

                            With your input, this post could be even better 💗

                            Register Login
                            • 1 / 1
                            • First post
                              Last post

                            Pycom on Twitter

                            Pycom