首页 > 解决方案 > 如何将两个红外传感器数据拆分为不同的文件?

问题描述

首先,我使用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代码中的所有输出,我只想读取第一个传感器,怎么办?蟒蛇代码:

 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()

标签: pythonarduino

解决方案


您可能错过了这些示例中非常重要的部分——“recv()”调用之后的行

while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

推荐阅读