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

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

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

# -----------------------------------------------------------------------------
# Import Standard Libraries
# -----------------------------------------------------------------------------
import numpy as np
import serial
import time

import os

# -----------------------------------------------------------------------------
# Definition of Directories
# -----------------------------------------------------------------------------
out_dir = # some generic path

# -----------------------------------------------------------------------------
# Definition of Parameters
# -----------------------------------------------------------------------------
# Serial Port
port = 'COM4' # Arduino Serial Port
b_rate = 38400 # Serial Baud Rate

# Test
T = 5 # Test Time (s)
test_id = 'A_0456_001' # Test ID

# -----------------------------------------------------------------------------
# Open Serial Port
# -----------------------------------------------------------------------------
ard = serial.Serial(port,b_rate)
time.sleep(1)

# -----------------------------------------------------------------------------
# Acquire Data
# -----------------------------------------------------------------------------
# Create Output Text File
out_path = os.path.join(out_dir,test_id + '.txt')
if os.path.exists(out_path):
    os.remove(out_path)
    
out_file = open(out_path,'w')

# Start Arduino
ard.write(str.encode('s'))
print('Data acquisition started...')
time.sleep(1)

t_0 = time.time_ns()
t_c = t_0

p_count = 0
while t_c < t_0 + T*10**9:

    # Write Header
    if p_count == 0:
        header = 'System Time, Type, ard_time, x, y, z'
        out_file.write(header + '\n')

        
    # Read Serial
    s_line = ard.readline()

    t_c = time.time_ns() # High precision time

    # Write data to text file
    out_file.write(str(t_c) + ',' + str(s_line)[2:-5] + '\n')

    p_count = p_count+1

print('Data acquisition ended.')

# Stop Arduino and close serial
ard.write(str.encode('e'))
ard.close()

# Close Text File
out_file.close()

Arduino

#include <Arduino_LSM6DS3.h>

void setup() {
  Serial.begin(9600);
  while (!Serial);

  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");

    while (1);
  }

  Serial.print("Accelerometer sample rate = ");
  Serial.print(IMU.accelerationSampleRate());
  Serial.println(" Hz");
  Serial.println();
  Serial.println("Acceleration in G's");
  Serial.println("X\tY\tZ");
}

void loop() {
  float x, y, z;

  if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(x, y, z);

    Serial.print(x, 5); // 5 decimal places
    Serial.print('\t');
    Serial.print(y, 5);
    Serial.print('\t');
    Serial.println(z, 5);
  }
}
英文:

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

# -----------------------------------------------------------------------------
# Import Standard Libraries
# -----------------------------------------------------------------------------
import numpy as np
import serial
import time
import os
# -----------------------------------------------------------------------------
# Definition of Directories
# -----------------------------------------------------------------------------
out_dir = # some generic path
# -----------------------------------------------------------------------------
# Definition of Parameters
# -----------------------------------------------------------------------------
# Serial Port
port = &#39;COM4&#39; # Arduino Serial Port
b_rate = 38400 # Serial Baud Rate
# Test
T = 5 # Test Time (s)
test_id = &#39;A_0456_001&#39; # Test ID
# -----------------------------------------------------------------------------
# Open Serial Port
# -----------------------------------------------------------------------------
ard = serial.Serial(port,b_rate)
time.sleep(1)
# -----------------------------------------------------------------------------
# Acquire Data
# -----------------------------------------------------------------------------
# Create Output Text File
out_path = os.path.join(out_dir,test_id + &#39;.txt&#39;)
if os.path.exists(out_path):
os.remove(out_path)
out_file = open(out_path,&#39;w&#39;)
# Start Arduino
ard.write(str.encode(&#39;s&#39;))
print(&#39;Data aquisition started...&#39;)
time.sleep(1)
t_0 = time.time_ns()
t_c = t_0
p_count = 0
while t_c &lt; t_0 + T*10**9:
# Write Header
if p_count == 0:
header = &#39;System Time, Type, ard_time, x, y, z&#39;
out_file.write(header + &#39;\n&#39;)
# Read Serial
s_line = ard.readline()
t_c = time.time_ns() # High precision time
# Write data to text file
out_file.write(str(t_c) + &#39;,&#39; + str(s_line)[2:-5] + &#39;\n&#39;)
p_count = p_count+1
print(&#39;Data aquisition ended.&#39;)
# Stop Arduino and close serial
ard.write(str.encode(&#39;e&#39;))
ard.close()
# Close Text File
out_file.close()

Arduino

#include &lt;Arduino_LSM6DS3.h&gt;
void setup() {
Serial.begin(9600);
while (!Serial);
if (!IMU.begin()) {
Serial.println(&quot;Failed to initialize IMU!&quot;);
while (1);
}
Serial.print(&quot;Accelerometer sample rate = &quot;);
Serial.print(IMU.accelerationSampleRate());
Serial.println(&quot; Hz&quot;);
Serial.println();
Serial.println(&quot;Acceleration in G&#39;s&quot;);
Serial.println(&quot;X\tY\tZ&quot;);
}
void loop() {
float x, y, z;
if (IMU.accelerationAvailable()) {
IMU.readAcceleration(x, y, z);
Serial.print(x,5);
// 5 decimal places
Serial.print(&#39;\t&#39;);
Serial.print(y,5);
Serial.print(&#39;\t&#39;);
Serial.println(z,5);
}
}

答案1

得分: 0

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

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

# 启动Arduino
ard.write('s'.encode())
print('数据采集已开始...')
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:

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

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:

确定