string 如何将数据写入Arduino上的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40480737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write data to a text file on Arduino
提问by Michael Zakariaie
I have some position data continually coming in and I am currently printing it to the serial.
我有一些位置数据不断传入,我目前正在将其打印到串行。
Say I have the string "5" and want to print that to a text file, "myTextFile", what would I need to do to achieve this? To be clear, the text file would be saved on my computer not on an SD card on the Arduino.
假设我有字符串“5”并想将其打印到文本文件“myTextFile”,我需要做什么来实现这一目标?需要明确的是,文本文件将保存在我的计算机上,而不是保存在 Arduino 的 SD 卡上。
Also, is their a way to create a text file within the program before I start saving to it?
另外,在我开始保存之前,他们是一种在程序中创建文本文件的方法吗?
回答by Ulad Kasach
You can create a python script to read the serial port and write the results into a text file:
您可以创建一个python脚本来读取串口并将结果写入文本文件:
##############
## Script listens to serial port and writes contents into a file
##############
## requires pySerial to be installed
import serial # sudo pip install pyserial should work
serial_port = '/dev/ttyACM0';
baud_rate = 9600; #In arduino, Serial.begin(baud_rate)
write_to_file_path = "output.txt";
output_file = open(write_to_file_path, "w+");
ser = serial.Serial(serial_port, baud_rate)
while True:
line = ser.readline();
line = line.decode("utf-8") #ser.readline returns a binary, convert to string
print(line);
output_file.write(line);
回答by Aravind R Pillai
U have to Use serial-lib for this
你必须为此使用串行库
Serial.begin(9600);
Write your sensor values to the serial interface using
使用以下命令将传感器值写入串行接口
Serial.println(value);
in your loop method
在你的循环方法中
on the processing side use a PrintWriter to write the data read from the serial port to a file
在处理端使用 PrintWriter 将从串口读取的数据写入文件
import processing.serial.*;
Serial mySerial;
PrintWriter output;
void setup() {
mySerial = new Serial( this, Serial.list()[0], 9600 );
output = createWriter( "data.txt" );
}
void draw() {
if (mySerial.available() > 0 ) {
String value = mySerial.readString();
if ( value != null ) {
output.println( value );
}
}
}
void keyPressed() {
output.flush(); // Writes the remaining data to the file
output.close(); // Finishes the file
exit(); // Stops the program
}