Serial read & write using Arduino and Python Arduino和Python进行串行读写

huangapple go评论111阅读模式
英文:

Serial read & write using Arduino and Python

问题

I'm trying to write a command to my COM PORT but the write method won't take my string
我试图向我的COM端口写入命令,但write方法无法接受我的字符串。

I expected a text file to be written by reading directly from the Arduino Nano 33 IoT with an inertial measurement unit LSM6DS3. However, the Python script gets stuck at write stage, so the line 'Data Acquisition started" does not write, and no data is read to the text file. Can anybody please help?
我希望通过直接从Arduino Nano 33 IoT与惯性测量单元LSM6DS3读取数据来写入一个文本文件。然而,Python脚本在写入阶段卡住了,所以“数据采集已开始”的那行没有写入,也没有数据读入文本文件。有人可以帮忙吗?

Python

  1. # -----------------------------------------------------------------------------
  2. # Import Standard Libraries
  3. # -----------------------------------------------------------------------------
  4. import numpy as np
  5. import serial
  6. import time
  7. import os
  8. # -----------------------------------------------------------------------------
  9. # Definition of Directories
  10. # -----------------------------------------------------------------------------
  11. out_dir = # some generic path
  12. # -----------------------------------------------------------------------------
  13. # Definition of Parameters
  14. # -----------------------------------------------------------------------------
  15. # Serial Port
  16. port = 'COM4' # Arduino Serial Port
  17. b_rate = 38400 # Serial Baud Rate
  18. # Test
  19. T = 5 # Test Time (s)
  20. test_id = 'A_0456_001' # Test ID
  21. # -----------------------------------------------------------------------------
  22. # Open Serial Port
  23. # -----------------------------------------------------------------------------
  24. ard = serial.Serial(port,b_rate)
  25. time.sleep(1)
  26. # -----------------------------------------------------------------------------
  27. # Acquire Data
  28. # -----------------------------------------------------------------------------
  29. # Create Output Text File
  30. out_path = os.path.join(out_dir,test_id + '.txt')
  31. if os.path.exists(out_path):
  32. os.remove(out_path)
  33. out_file = open(out_path,'w')
  34. # Start Arduino
  35. ard.write(str.encode('s'))
  36. print('Data acquisition started...')
  37. time.sleep(1)
  38. t_0 = time.time_ns()
  39. t_c = t_0
  40. p_count = 0
  41. while t_c < t_0 + T*10**9:
  42. # Write Header
  43. if p_count == 0:
  44. header = 'System Time, Type, ard_time, x, y, z'
  45. out_file.write(header + '\n')
  46. # Read Serial
  47. s_line = ard.readline()
  48. t_c = time.time_ns() # High precision time
  49. # Write data to text file
  50. out_file.write(str(t_c) + ',' + str(s_line)[2:-5] + '\n')
  51. p_count = p_count+1
  52. print('Data acquisition ended.')
  53. # Stop Arduino and close serial
  54. ard.write(str.encode('e'))
  55. ard.close()
  56. # Close Text File
  57. out_file.close()

Arduino

  1. #include <Arduino_LSM6DS3.h>
  2. void setup() {
  3. Serial.begin(9600);
  4. while (!Serial);
  5. if (!IMU.begin()) {
  6. Serial.println("Failed to initialize IMU!");
  7. while (1);
  8. }
  9. Serial.print("Accelerometer sample rate = ");
  10. Serial.print(IMU.accelerationSampleRate());
  11. Serial.println(" Hz");
  12. Serial.println();
  13. Serial.println("Acceleration in G's");
  14. Serial.println("X\tY\tZ");
  15. }
  16. void loop() {
  17. float x, y, z;
  18. if (IMU.accelerationAvailable()) {
  19. IMU.readAcceleration(x, y, z);
  20. Serial.print(x, 5); // 5 decimal places
  21. Serial.print('\t');
  22. Serial.print(y, 5);
  23. Serial.print('\t');
  24. Serial.println(z, 5);
  25. }
  26. }
英文:

I'm trying to write a command to my COM PORT but the write method won't take my string

I expected a text file to be written by reading directly from the Arduino Nano 33 IoT with an inertial measurement unit LSM6DS3. However, the Python script gets stuck at write stage, so the line 'Data Acquisition started" does not write, and no data is read to the text file. Can anybody please help?

Python

  1. # -----------------------------------------------------------------------------
  2. # Import Standard Libraries
  3. # -----------------------------------------------------------------------------
  4. import numpy as np
  5. import serial
  6. import time
  7. import os
  8. # -----------------------------------------------------------------------------
  9. # Definition of Directories
  10. # -----------------------------------------------------------------------------
  11. out_dir = # some generic path
  12. # -----------------------------------------------------------------------------
  13. # Definition of Parameters
  14. # -----------------------------------------------------------------------------
  15. # Serial Port
  16. port = &#39;COM4&#39; # Arduino Serial Port
  17. b_rate = 38400 # Serial Baud Rate
  18. # Test
  19. T = 5 # Test Time (s)
  20. test_id = &#39;A_0456_001&#39; # Test ID
  21. # -----------------------------------------------------------------------------
  22. # Open Serial Port
  23. # -----------------------------------------------------------------------------
  24. ard = serial.Serial(port,b_rate)
  25. time.sleep(1)
  26. # -----------------------------------------------------------------------------
  27. # Acquire Data
  28. # -----------------------------------------------------------------------------
  29. # Create Output Text File
  30. out_path = os.path.join(out_dir,test_id + &#39;.txt&#39;)
  31. if os.path.exists(out_path):
  32. os.remove(out_path)
  33. out_file = open(out_path,&#39;w&#39;)
  34. # Start Arduino
  35. ard.write(str.encode(&#39;s&#39;))
  36. print(&#39;Data aquisition started...&#39;)
  37. time.sleep(1)
  38. t_0 = time.time_ns()
  39. t_c = t_0
  40. p_count = 0
  41. while t_c &lt; t_0 + T*10**9:
  42. # Write Header
  43. if p_count == 0:
  44. header = &#39;System Time, Type, ard_time, x, y, z&#39;
  45. out_file.write(header + &#39;\n&#39;)
  46. # Read Serial
  47. s_line = ard.readline()
  48. t_c = time.time_ns() # High precision time
  49. # Write data to text file
  50. out_file.write(str(t_c) + &#39;,&#39; + str(s_line)[2:-5] + &#39;\n&#39;)
  51. p_count = p_count+1
  52. print(&#39;Data aquisition ended.&#39;)
  53. # Stop Arduino and close serial
  54. ard.write(str.encode(&#39;e&#39;))
  55. ard.close()
  56. # Close Text File
  57. out_file.close()

Arduino

  1. #include &lt;Arduino_LSM6DS3.h&gt;
  2. void setup() {
  3. Serial.begin(9600);
  4. while (!Serial);
  5. if (!IMU.begin()) {
  6. Serial.println(&quot;Failed to initialize IMU!&quot;);
  7. while (1);
  8. }
  9. Serial.print(&quot;Accelerometer sample rate = &quot;);
  10. Serial.print(IMU.accelerationSampleRate());
  11. Serial.println(&quot; Hz&quot;);
  12. Serial.println();
  13. Serial.println(&quot;Acceleration in G&#39;s&quot;);
  14. Serial.println(&quot;X\tY\tZ&quot;);
  15. }
  16. void loop() {
  17. float x, y, z;
  18. if (IMU.accelerationAvailable()) {
  19. IMU.readAcceleration(x, y, z);
  20. Serial.print(x,5);
  21. // 5 decimal places
  22. Serial.print(&#39;\t&#39;);
  23. Serial.print(y,5);
  24. Serial.print(&#39;\t&#39;);
  25. Serial.println(z,5);
  26. }
  27. }

答案1

得分: 0

你所遇到的问题出现在代码的Python部分的写入命令中。

encode() 函数的参数是编码(默认为UTF-8),而不是要编码的字符串。应该将它应用于你要发送的字符串,像这样:

  1. # 启动Arduino
  2. ard.write('s'.encode())
  3. print('数据采集已开始...')
  4. time.sleep(1)
英文:

The problem you are facing is with your write command in the python portion of the code.

The encode() function's argument is the encoding (default is UTF-8) and not the string to encode. This should then be applied to the string you are sending. Like this:

  1. -----
  2. # Start Arduino
  3. ard.write(&#39;s&#39;.encode())
  4. print(&#39;Data aquisition started...&#39;)
  5. time.sleep(1)
  6. -----

huangapple
  • 本文由 发表于 2023年4月19日 21:59:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定