首先,我使用Arduino代码接收传感器数据,然后将python输出传感器数据转换为文本文件进行保存,问题是将两个传感器数据写入同一文件,如何将其拆分为两个不同的文件保存?
arduino代码:
int counter = 0;
int counter2 = 0;
int laststate = HIGH;
int laststate2 = HIGH;
const int irReceiver = 2;
const int irReceiver2 = 6;
const int irLed = 3;
const int irLed2 = 4;
const int ledPin = 13;
const int ledPin2 = 14;
const unsigned int frequency = 38000;
const unsigned int frequency2 = 38000;
void setup() {
Serial.begin(9600);
pinMode(irReceiver, INPUT);
pinMode(irReceiver2, INPUT);
pinMode(irLed, OUTPUT);
pinMode(irLed2, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
tone(irLed, frequency);
tone(irLed2, frequency2);
}
void blinkLED() {
for (int i=1; i<= 4; i++) {
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
}
void blinkLED2() {
for (int i=1; i<= 4; i++) {
digitalWrite(ledPin2, HIGH);
delay(100);
digitalWrite(ledPin2, LOW);
delay(100);
}
}
void loop() {
int ir_status = digitalRead(irReceiver);
int ir_status2 = digitalRead(irReceiver2);
if (laststate == LOW && ir_status == HIGH) // only count on a LOW-> HIGH transition
{
counter++;
Serial.println(" A zone:");
Serial.println(counter);
}
laststate = ir_status;
if (laststate2 == LOW && ir_status2 == HIGH) // only count on a LOW-> HIGH transition
{
counter2++;
Serial.println("B zone:");
Serial.println(counter2);
}
laststate2 = ir_status2; // remember last state
if (ir_status == 0)
blinkLED();
if (ir_status2 == 0)
blinkLED2();
}
这个python部分读取Arduino代码中的所有输出,我想只读取第一个传感器,怎么办? python代码:
import serial
connected = False
locations=['/dev/ttyUSB0']
for device in locations:
try:
print "Trying...", device
ser = serial.Serial(device, 9600)
break
except:
print "Failed to connect on",device
while not connected:
serin = ser.read()
connected = True
text_file = open("position4.txt", 'w')
while 1:
if ser.inWaiting():
x=ser.read()
print(x)
text_file.write(x)
if x=="":
text_file.seek(0)
text_file.truncate()
text_file.flush()
enter code here
text_file.close()
ser.close()
答案 0 :(得分:0)
您可能错过了这些示例中非常重要的部分 - &#34; recv()&#34;调用
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()