How to send string to arduino from raspberry pi using python - python

I have an Arduino microcontroller (Adafruit feather M0), and if I have it plugged into my windows PC and open the serial monitor, I can type P 0 2 1 0 and then enter, the Arduino interprets this command and works as expected.
Now I want to plug in the same device into my raspberry pi, and have python do this instead.
I have done this in the past on a different microcontroller (sparkfun pro micro) and it worked great. I can't seem to get it to work and am not sure what I am missing.
python code:
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 115200, timeout = None)
time.sleep(2)
returnKey = "\r\n"
ser.write(str.encode("P 2 1 0"))
ser.write(str.encode(returnKey)
The code finishes, but the Arduino simply does nothing, as if it discarded the command or didn't get it at all.
The serial speed is matching on the Arduino too (115200).
I also tried:
ser.write(b'P 2 1 0')
ser.write(returnKey.encode())
Any ideas what I am missing here?

Solved it.
Ended up using
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 115200, timeout = None)
time.sleep(2)
ser.write(b'P 2 1 0 \r\n')

Related

Communicate between 2 Raspberry Pi with UART

I want to send data from one pi to another with UART communication. The first Raspberry model is Raspberry Pi 4, and the second one Raspberry Pi 3. To do this communication Im connecting both Raspberry pins in this way:
Pi 4 -> Pi 3
Tx -> Rx
Rx -> Tx
Ground -> Ground
I have already activated both Pis serial connection on the raspberry configuration following the steps of this link: https://iot4beginners.com/raspberry-pi-configuration-settings/. In order to write and send the data I have created the next python program:
import time
import serial
ser = serial.Serial(
port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS)
counter=0
while True:
ser.write(str.encode(str(counter)))
time.sleep(1)
counter += 1
To read and print the data received I have created the next program:
import time
import serial
ser = serial.Serial(
port='/dev/ttySO', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS
)
counter=0
while 1:
x = ser.readline()
print(x)
Finally when I run the reading program I get the next error:
Traceback (most recent call last):
File "serial_read.py", line 14, in <module>
x = ser.readline()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 501, in read
'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
I'm new to Raspberry communication and I will be thankful for any suggestion.
Python 2.7 is officially dead, so I would recommend using Python3 - especially for new projects such as yours.
So, rather than run your script with:
python3 YourScript.py
you could put a proper shebang at the start so it automatically uses the correct Python version you intended:
#!/usr/bin/env python3
import ...
Then make the script executable with:
chmod +x YourScript.py
Now you can run it with:
./YourScript.py
and be happy it will use Python3, and also even if someone else uses it.
The actual issue, I think, is that the readline() on the receiving end is looking for a newline that you didn't send. So I would try adding one:
ser.write(str.encode(str(counter) + '\n'))
Personally, I find f-strings to be much easier than the older % and .format() stuff, so maybe try:
ser.write(str.encode(f'{counter}\n'))

Python Serial Writing but seemingly not reading. Raspberry Pi 0 to Arduino

I'm having trouble with a python script running on an RPI0 reading serial input from an Arduino. I know the Arduino's code is correct as everything works as intended interacting with the Arduino over the built in serial monitor in the Arduino software(send code a10(code to drive a relay HIGH), Arduino sends back 11(basically asking for how long), send code b5, Arduino will hold pin HIGH for 5 seconds(b5)).
However when I attempt to read any serial input in python using the pyserial module, nothing happens. I know it does successfully send the code to the arduino as it will hold the pin HIGH for the specified seconds when I rewrite the python script with ser.write("a10b5").
The serial connection is NOT USB. I'm using jumper wires with a voltage shifter in between them using the Arduino's and Pi's GPIO TX and RX pins.
using python -V in the terminal it tells me I'm running version 3.8
I've tried multiple baud rates(300, 1200, 9600, 57600) with no change in behavior
I've also tried changing if x == 11: to if x == "11": in case for some reason it was receiving strings and not ints, also to no avail.
Here is the code:
import time
import serial
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=None
)
print("sending data over serial now")
ser.write("a10") #a10 is relay HIGH code
while True:
x = ser.read()
if x == 11: ##arduino code 11(asking for how long)
print("recieved code 11")
print("arduino recieved relay HIGH code and is waiting for time to hold relay for")
print("sending time now")
ser.write('a5') # 5 seconds
time.sleep(1)
if x == 13: #arduino code 13(water success)
print("recieved code 13")
print("arduino reports watering complete")
x = 0 ##this is to clear the variable every loop. Not sure if it's needed
And here is a simple serial reader I've pulled from online. Opening it up in a second terminal and running it at the same time with my own script it will actually read the codes from the arduino business as usual.
#!/usr/bin/env python
import time
import serial
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate = 57600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
while True:
x=ser.readline()
print x
What gives?
Answering my own question. In the arduino code I used
Serial.println(whatevergoeshere)
instead of
Serial.print(whatevergoeshere)
So the arduino was sending out '\n' at the end of every serial line that was not being printed by either the arduino serial console and the python script. Updating my IF statements in python to
if x == "11\n":
Solves the issue and everything works as intended.

Using python serial connection to communicate with Roboclaw motorcontroller

So im newish to python and im trying to use the following program to control a roboclaw motor controller. I have one motor i am just trying to turn via serial commands and am failing miserably. Everything works well with pwm using an arduino but when i run it via raspi over serial in python...it just turns slow and always in the same direction. Roboclaw specifies that full fwd motion achieved by sending 127, 64 is stop, and 1 is full reverse. Electrically its connected appropriately and the motorcontroller is set to the right setting and baudrate, but something with this code is no good...just turns slow and only in one direction and never stops with the stop command. Help an old man out and let me know what you think. The code is as follows:
import RPi.GPIO as GPIO
import time
import serial
GPIO.setmode(GPIO.BOARD)
ser = serial.Serial(
port='/dev/ttyS0',
baudrate = 38400,
parity =serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
#allstop = 0b00000000 or 0
#fwd = 0b00000001 or 1
#stop = 0b01000000 or 64
#rev = 0b01111111 or 127
ser.write('00000001')
time.sleep(5)
ser.write('01000000')
time.sleep(5)
ser.write('01111111')
time.sleep(5)
ser.write('00000000')
print 'done'

Raspberry Pi Zero reboot after some AT commands to A6 gsm modem through serial

I have a problem with Raspberry Pi Zero 1.3 and A6 GSM modem. When I send speciffically commands which should communicate with the sim card on the gsm module (like AT+CGATT=1), the raspberry reboots with no entries in the logs pointing to the reboot. I am running latest Raspbian Lite.
Modem is connected to the Serial port on raspberry (Tx+Rx) and also 5V and Gnd. Raspberry is powered by 1,5A power supply through USB (pwr).
This errors also when Tx from GSM module is disconnected (so no received answer on raspberry).
I have tried changing the modem modules, but the error still occurs. I have also changed raspberry boards and the error seems to be absent on some boards.
Have any of you encountered something similar?
Here is my testing code in python:
import time
import serial
import sys
import os
print "Starting program"
os.system('echo raspberry | stty -F /dev/ttyAMA0 9600')
ser = serial.Serial('/dev/ttyAMA0', baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=5
)
time.sleep(1)
try:
while True:
input = raw_input('Give me command master: ')
ser.write(input + '\r\n')
data = ser.read(10000)
print data
except KeyboardInterrupt:
print "Exiting Program"
except:
print "Error Occurs, Exiting Program"
finally:
ser.close()
pass
Thank you in advance :)

PySerial. Read failed: device reports readiness to read but returned no data

I have a windows 7 os pc, using pyserial in python3.6 to talk to an embedded board with a debian Jessie os that is using pyserial python 3.6 to listen. The cable between the two is a USB to UART bridge controller from a microUSB port on the board to a USB port on the pc. These are my scripts:
PC:
import serial
ser = serial.Serial('COM5')
ser.baudrate = 115200
ser.bytesize = 8
ser.parity = 'N'
ser.stopbits = 1
data = bytearray(b'A')
No = ser.write(data)
ser.close()
BOARD:
import serial
ComPort = serial.Serial('dev/ttyS0')
ComPort.baudrate = 115200
ComPort.bytesize = 8
ComPort.parity = 'N'
ComPort.stopbits = 1
data = ComPort.read(1)
print(data)
ComPort.close()
THE PROBLEM:
I run the script on the board first, it will run and wait without incident until I run the script on the pc. Once I run the pc script, it takes a second or two for the error in the title to pop up on the board and stop the script. There are no errors on the pc side, and the script runs and finishes in less than a second.
I am connected to the board via putty ssh on the pc. I need to be able to send commands and files between these two via this serial connection. Any help or working examples would be a great help. Is there a problem with using pyserial on both the sender and receiver?

Categories