Sending serial communication from Raspberry pi

2019-02-17 18:38发布

问题:

I am sending serial data from a Raspberry Pi to an Arduino using a Python program. I am running Python 2.7.3. The program is:

import serial

ser = serial.Serial('/dev/ttyACM0', 115200)

ser.write(b'\x4c\xff\x46')

The problem is that nothing seems to be sent by these three lines if they are run in a program. But if I run them line by line in a Python shell, they work fine.

Also, if I have the Arduino Serial Monitor open, the program works fine as well, without running the lines one by one in the shell.

EDITED TO ADD:

It seems that there is some delay in sending to the Arduino. So when I run the code in interpretive mode, it works, but if as a program, it doesn't. I think that because I tried the same program on a Windows machine.

import serial

ser = serial.Serial('COM8', 115200)

ser.write(b'\x4c\x20\x46')

If I run the program in interpretive mode, or even in debugging mode with a breakpoint on the ser.write command, it works. But not if run as a program.

EDITED TO ADD MORE:

It turns out that the Arduino has an auto-reset on serial communications that has to be disabled:

http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection#.UwP_wfldV8E

http://forum.arduino.cc/index.php/topic,28723.0.html

I used a 220 uF capacitor between the RESET pin and ground. That works.

Tough to be bitten by a bug like that! It still smarts.

回答1:

Try this. If you can't run it under idle or etc, try terminal by typing python name.py. I also suggest you to check the data coming or written from/to Rpi with putty to be sure.

import serial
import time


def readlineCR(port):
    rv = ""
    while True:
    ch = port.read()
    rv += ch
    if ch == '\r' or ch == '':
         return rv


port = serial.Serial("/dev/ttyAMA0", baudrate = 7200, timeout = 2)

while True: 
     rcv = readlineCR(port)
     port.write("I typed: " + repr(rcv))
     print(rcv)