0
votes

I have an Arduino script to send commands to some sensitive hardware. I don't want to alter the Arduino's code very much because I didn't write it, but I want to be able to enter a sequence of commands without having to type them manually.

I want my python script's output to become the input into the Arduino serial monitor, and then to have the script send the command to the board. Is it possible to have python talk to the Arduino IDE in this way?

1
If you have a command-line command you can use to send commands to the arduino, then python can at least definitely do that, through either subprocess (preferred) or system() - Green Cloak Guy
Have you tried using serial protocol? - Plochie

1 Answers

2
votes

You just need to connect your Arduino board to your computer and send and receive data with a python script through a Serial port. I created a simple example and put an acknowledge to confirm the received command on Arduino, but remember to modify your code based on your needs:

Arduino code:

void setup()
{
    Serial.begin(9600);
}

// read a command from serial and do proper action
void read_command()
{
    String command;
    if (Serial.available())
    {
        command = Serial.readString();
        // sending answer back to PC
        Serial.println("ACK");
        // do proper work with command
    }
}

void loop()
{
    // get new commands
    read_command();
    delay(1000);
}

Python code:

import serial
from time import sleep


# remember to set this value to a proper serial port name
ser = serial.Serial('COM1', 9600)
ser.open()
# flush serial for unprocessed data
ser.flushInput()
while True:
    command = input("Enter your command: ")
    if command:
        command += "\r\n"
        ser.write(command.encode())
        print("Waiting for answer")
        while True:
            answer = ser.readline()
            if answer:
                print("Answer:", answer)
                break
            sleep(0.1)
    ser.flushInput()