1

I'm developing an embedded project and I need to connect Arduino and Raspberry pi because I want to control Arduino with Raspberry Pi over the serial port. My question is how can I get the Arduino port in Linux dynamicaly with python?

My python program will loop sending commands to Arduino and I don't want to lose communication if someone connects and disconnects the Arduino.

Thanks for any help. Zulin

0

2 Answers 2

3

1st install Pyserial

if you have connected you arduino with you pc, you can see all serial message:

sudo screen /dev/ttyAMC0

now come to python to control arduino:

import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write("something")           # this will write "your stuff" to Arduino serial.

now using Cprogram you can read from serial what the input is. And you can command your arduino using python

C pogram to read from Serial and write to serial:

char a[10];
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if(Serial.available()>0)
  {
      Serial.readBytes(a,10);
      Serial.println(a);
  }
} 
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it like this:

def get_serial_port():
    return "/dev/"+os.popen("dmesg | egrep ttyACM | cut -f3 -d: | tail -n1").read().strip()

Then you can just connect with arduino doing:

device = serial.Serial(get_serial_port(), baudrate=9600, timeout=3)

(assuming you are using the default rate 9600, you can just change the params...)

1 Comment

os.popen is depreciated since python 2.6, the subprocess module should be used

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.