如何从串行总线(Arduino)读取中“分开”写入?

时间:2019-01-28 12:42:29

标签: arduino serial-port delay

我正在做一个writes inreads from的Arduino(Uno)应用程序。我希望Arduino工作的方式仅在有数据时(如侦听器)读取,并在每次(定期使用delay写入)中进行。但是我不知道如何设置侦听器(或者是否有办法实现),因为我不希望delay影响reading

 unsigned long timeDelay = 100;   //Some configurations
 String comand;
 char received;
 const int LED = 12;

void setup() {
  //start serial connection
  Serial.begin(9600);
  pinMode(LED, OUTPUT);   //LED is only a way that I know the Arduino is 
  digitalWrite(LED,LOW);  //reading correctly

}

void loop() {
  //How to separate this part--------------Reading from Serieal--------
  comand = "";
  while(Serial.available() > 0){    
    received = Serial.read();
    comand += received;
    if(comand == "DELAY"){            //Processing the command
      timeDelay = Serial.parseInt();
    }
  }
  if(comand == "Desliga"){            //Processing the command
     digitalWrite(LED,LOW);       //'Desliga' means 'turn on' in portuguese
  }
  else if(comand == "Liga"){          //Processing the command
    digitalWrite(LED,HIGH);       //'Liga' means 'turn off' in portuguese
  }
  //-------------------------------------------------------------------

  //From this other part-----------------Writing on Serial-------------
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  Serial.flush();
  delay(timeDelay);        // delay in between reads for stability
  //-------------------------------------------------------------------
}

OBS:我正在通过Java应用程序进行连接。因此,我可以在此处设置timeDelay。如果我输入timeDelay(ms)这样的1000,则我编写的一个命令(打开/关闭LED)将花费1秒的时间来处理。 你们知道了吗?

有人解决吗?

1 个答案:

答案 0 :(得分:0)

我建议使用Arduino的任务管理器来运行您的模拟代码。

为此,我使用TaskAction

您可以将模拟代码包装在一个函数中,并创建一个TaskAction对象:

void AnalogTaskFunction(TaskAction * pThisTask)
{
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  Serial.flush();
}

static TaskAction AnalogTask(AnalogTaskFunction, 100, INFINITE_TICKS);

并且在您的loop中,您可以运行任务并设置任务期限:

void loop() {
  //How to separate this part--------------Reading from Serieal--------
  comand = "";
  while(Serial.available() > 0){    
    received = Serial.read();
    comand += received;
    if(comand == "DELAY"){            //Processing the command
      AnalogTask.SetInterval(Serial.parseInt()); // Change the task interval
    }
  }
  if(comand == "Desliga"){            //Processing the command
     digitalWrite(LED,LOW);       //'Desliga' means 'turn on' in portuguese
  }
  else if(comand == "Liga"){          //Processing the command
    digitalWrite(LED,HIGH);       //'Liga' means 'turn off' in portuguese
  }

  AnalogTask.tick(); // Run the task
}

注意:可以使用Arduino的其他任务管理器,这只是我所熟悉的。您可能想探索其他人。