Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending serial communication from Raspberry pi

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.

like image 503
Daanii Avatar asked Feb 18 '14 22:02

Daanii


People also ask

Can Raspberry Pi read serial data?

Using serial communication with your Raspberry Pi is a simple and efficient way to read and write from and to an external device. To do this, we use the GPIO pins provided on the board, and by the end of this article, you should be able to connect your Raspberry Pi to any serial device.

How do you communicate between two Raspberry Pi?

The easiest way is to use a USB cable between both board. On the Raspberry Pi side, a simple USB connector is all you need. You can choose any of the 4 USB ports available on the board. For Arduino, you will use the USB port that you use to upload code from your computer (with the Arduino IDE) to your board.


1 Answers

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)
like image 97
Cugomastik Avatar answered Sep 26 '22 05:09

Cugomastik