I want to send some data to Arduino via pyserial in Python. All I want Arduino to do is read the variable-length string data from the serial port and write it back so that Python can read it. Since I was unable to do this, the code below only has Python sent by character. Here's the Python code:
import serial import sys import pywapi import time def main(): ser = serial.Serial(3, 9600, timeout=1) print "Conn established" print "Sending: %s" % "z".__repr__() print ser.write('z'.encode("ascii")) time.sleep(2) print "Received: %s" % ser.read(10).__repr__() ser.close()
Here is the Arduino code:
void setup(){ analogReference(DEFAULT); Serial.begin(9600); } void loop(){ if(Serial.available() > 0) Serial.println("x"); while(Serial.available() > 0){ Serial.print(Serial.read(), BYTE); } }
Exit:
Conn established Sending: 'z' 1 Received: ''
I know that the code for Arduino works because it works when data is sent from the Arduino terminal. However, the moment I try to send something with Python, it fails. I struggled with this all day. Any help would be greatly appreciated.
Johns source share