Python Forum
User serial/pyserial to send messages to an arudino via terminal manually
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
User serial/pyserial to send messages to an arudino via terminal manually
#1
Is there a way to send a byte/char to the arudino using serial/pyserial without tying up the serial port continuously so I can send control commands to the arduino via the command line/keyboard inputs when needed and be able to read for events from the arudino?

We plan on using command line to interact with the arudino such as start/stop on command but we have a sensor that we want to constantly listen to for events?

Is this possible through pyserial/serial?
Reply
#2
Do you mean open the port, write data (some bytes), receive data, close connection?
Example:

import sys
import time
from argparse import ArgumentParser
from binascii import hexlify, unhexlify
from pathlib import Path

from serial import Serial, SerialException


def send_receive(port, baudrate, command, delay, timeout):
    port = Path("/dev", port)
    if not port.exists():
        raise ValueError(f"{port} does not exist.")
    raw_data = unhexlify(command)  # str as hex representation -> bytes
    with Serial(port=str(port), baudrate=baudrate, timeout=timeout / 1000) as ser:
        ser.write(raw_data)
        time.sleep(delay / 1000)
        return hexlify(ser.read()).decode()


def get_args():
    parser = ArgumentParser()
    parser.add_argument("port", help="Name of serial port without /dev/")
    parser.add_argument(
        "baudrate", default=9600, type=int, help="Baudrate of serial connection"
    )
    parser.add_argument("command", help="hexadecimal string literal to send.")
    parser.add_argument(
        "delay", default=1000, type=int, help="Delay in ms to wait after sending data"
    )
    parser.add_argument(
        "timeout", default=5000, type=int, help="Timeout in ms for receiving data"
    )
    return parser.parse_args()


def main():
    args = get_args()
    received_data = send_receive(
        args.port, args.baudrate, args.command, args.delay, args.timeout
    )
    if not received_data:
        print("No data received...")
    else:
        print(received_data)


if __name__ == "__main__":
    try:
        main()
    except SerialException as e:
        print(" ".join(e.args[1:]), file=sys.stderr)
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Not plug and play, but a very robust solution:

You could use something like https://www.adafruit.com/product/4471 which uses a Microchip MCP2221A
https://www.microchip.com/wwwproducts/en/MCP2221A uSB to I2C bridge

It can be wired to an Arduino's I2C connectors as follows: https://howtomechatronics.com/tutorials/...h-arduino/

It will take a bit of work to get everything in sync, but software is provided by adafruit.

If you use this approach, you will have the ability to hook multiple devices to the same I2C port.

Here are a couple of I2C tutorials if you are interested in this form of communications (most use python):

These specifically for the arduino:
Video: https://www.youtube.com/watch?v=6IAkYpmA1DQ
https://howtomechatronics.com/tutorials/...h-arduino/

https://learn.sparkfun.com/tutorials/i2c/all

https://www.circuitbasics.com/basics-of-...-protocol/

more video:
https://www.youtube.com/watch?v=DsSBTYbXAKg
https://www.youtube.com/watch?v=HGX457RA4IU
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using print command to send command to rasberry pi terminal MondazeBear 2 305 Aug-02-2021, 03:15 PM
Last Post: Larz60+
  Lib PySerial Pelathaon 2 787 Jul-07-2020, 12:41 PM
Last Post: DashOrion
  pySerial why do i need \r Mad_Max 1 783 May-26-2020, 01:29 AM
Last Post: Larz60+
  Can't transmit serial fast Python to Arduino pyserial mRKlean 0 1,033 Mar-29-2020, 08:12 PM
Last Post: mRKlean
  Manually create a hex value Stas43 5 1,386 Feb-27-2020, 08:28 AM
Last Post: Stas43
  send repeated messages with apscheduler pylab 1 855 Jan-04-2020, 08:43 PM
Last Post: snippsat
  How to manually define color bar scale in seaborn heatmap SriRajesh 3 8,741 Sep-08-2019, 11:12 AM
Last Post: RudraMohan
  logging messages ahead of print messages vindo 6 1,346 Jun-18-2019, 02:45 PM
Last Post: vindo
  how to clear the console when the programm is running (not manually) hello_its_me 5 3,478 Sep-30-2017, 09:14 PM
Last Post: wavic
  PySerial Soichiro 1 3,743 Jun-09-2017, 03:56 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020