I want to send 4 float numbers from Python code to an Arduino; I was trying to send it via serial and I have some problems.
here is my Python code:
import timeimport serialimport structdata = serial.Serial('COM6', 9600, timeout=1)time.sleep(1)while True: a = str(47.256*1000) data.write(a.encode())Here is my Arduino code :
String msg;void setup(){ Serial.begin(9600); pinMode(13, OUTPUT); }void loop(){ if (Serial.available()) { msg = Serial.readString(); } if (msg.toInt()>30){ digitalWrite(13, 1); }}end of code
Thanks in advance.
My problem is that it does not work (LED does not turn on while I send data from the Python code in a while loop; when I remove the while and make it send data 1 time it works (LED turns on). Any ideas why this could be happening?
- instructables.com/id/Interface-Python-and-Arduino-with-pySerialFilip Franik– Filip Franik2020-03-21 10:12:01 +00:00CommentedMar 21, 2020 at 10:12
- 2"I can't do it" is not a good problem description. What exactly is your problem in writing the code? What exactly did you try? Please add this information to the question by editing itchrisl– chrisl2020-03-21 10:18:43 +00:00CommentedMar 21, 2020 at 10:18
- 1When you say it does not work, what do you mean? Exactly what happens? What is in your
init ()method? Are you setting up Serial? Are you setting the LED for output? Please submit the entire code.GMc– GMc2020-03-23 10:59:57 +00:00CommentedMar 23, 2020 at 10:59 - 1That while loop in the python code is going to send that number over and over really really fast. I wonder if you shouldn't slow that down just a little. Put a sleep call in that while loop.Delta_G– Delta_G2020-03-23 16:48:53 +00:00CommentedMar 23, 2020 at 16:48
1 Answer1
It would be easier if you used Arduino <--> Python compatible libraries to ensure the communication between the two is robust and reliable. An example of such libraries would bepySerialTransfer andSerialTransfer.h.
pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.
Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.
Example Python Script:
import timefrom pySerialTransfer import pySerialTransfer as txferif __name__ == '__main__': try: link = txfer.SerialTransfer('COM17') link.open() time.sleep(2) # allow some time for the Arduino to completely reset while True: send_size = 0 ################################################################### # Send a list ################################################################### list_ = [1, 3] list_size = link.tx_obj(list_) send_size += list_size ################################################################### # Send a string ################################################################### str_ = 'hello' str_size = link.tx_obj(str_, send_size) - send_size send_size += str_size ################################################################### # Send a float ################################################################### float_ = 5.234 float_size = link.tx_obj(float_, send_size) - send_size send_size += float_size ################################################################### # Transmit all the data to send in a single packet ################################################################### link.send(send_size) ################################################################### # Wait for a response and report any errors while receiving packets ################################################################### while not link.available(): if link.status < 0: if link.status == -1: print('ERROR: CRC_ERROR') elif link.status == -2: print('ERROR: PAYLOAD_ERROR') elif link.status == -3: print('ERROR: STOP_BYTE_ERROR') ################################################################### # Parse response list ################################################################### rec_list_ = link.rx_obj(obj_type=type(list_), obj_byte_size=list_size, list_format='i') ################################################################### # Parse response string ################################################################### rec_str_ = link.rx_obj(obj_type=type(str_), obj_byte_size=str_size, start_pos=list_size) ################################################################### # Parse response float ################################################################### rec_float_ = link.rx_obj(obj_type=type(float_), obj_byte_size=float_size, start_pos=(list_size + str_size)) ################################################################### # Display the received data ################################################################### print('SENT: {} {} {}'.format(list_, str_, float_)) print('RCVD: {} {} {}'.format(rec_list_, rec_str_, rec_float_)) print(' ') except KeyboardInterrupt: link.close() except: import traceback traceback.print_exc() link.close()Example Arduino Sketch:
#include "SerialTransfer.h"SerialTransfer myTransfer;void setup(){ Serial.begin(115200); myTransfer.begin(Serial);}void loop(){ if(myTransfer.available()) { // send all received data back to Python for(uint16_t i=0; i < myTransfer.bytesRead; i++) myTransfer.txBuff[i] = myTransfer.rxBuff[i]; myTransfer.sendData(myTransfer.bytesRead); }}Note that you can send more than just individual chars with these libraries. It is possible to transfer floats, ints, bytes, arrays, and even structs (or any combination of the like) within your program using the libraries! See the examples inSerialTransfer.h for more info
For theory behind robust serial communication, check out the tutorialsSerial Input Basics andSerial Input Advanced.
Explore related questions
See similar questions with these tags.


