从 Raspberry pi 发送串行通信

Sending serial communication from Raspberry pi(从 Raspberry pi 发送串行通信)

本文介绍了从 Raspberry pi 发送串行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 程序将串行数据从 Raspberry Pi 发送到 Arduino.我正在运行 Python 2.7.3.程序是:

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'x4cxffx46')

问题是如果这三行在程序中运行,它们似乎没有发送任何内容.但是,如果我在 Python shell 中逐行运行它们,它们就可以正常工作.

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.

另外,如果我打开了 Arduino 串行监视器,程序也可以正常工作,而无需在 shell 中逐行运行.

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.

编辑添加:

发送到 Arduino 似乎有一些延迟.因此,当我在解释模式下运行代码时,它可以工作,但如果作为程序,它就不行.我认为这是因为我在 Windows 机器上尝试了相同的程序.

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'x4cx20x46')

如果我在解释模式下运行程序,甚至在调试模式下使用 ser.write 命令上的断点,它都可以工作.但如果作为程序运行则不会.

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.

编辑添加更多内容:

事实证明,Arduino 具有必须禁用的串行通信自动重置功能:

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

我在 RESET 引脚和地之间使用了一个 220 uF 的电容器.这样可行.

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.

推荐答案

试试这个.如果您无法在空闲等下运行它,请通过键入 python name.py 尝试终端.我还建议您使用 putty 检查来自/写入 Rpi 的数据以确保.

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 == '
' 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)

这篇关于从 Raspberry pi 发送串行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 Raspberry pi 发送串行通信

基础教程推荐