如何在串行总线(Arduino)中"separate"阅读写作?



我正在做一个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。如果我输入像 1000 (ms) 这样的timeDelay,那么我编写的一个命令(打开/关闭LED)将需要 1 秒才能处理。你们明白了吗?

有人有解决方案吗?

我建议使用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的其他任务管理器可用,这只是我熟悉的那个。您可能想探索其他内容。

最新更新