Arduino 串行输入停止和启动

Arduino Serial Input to Stop and Start

我正在尝试等待用户输入以启动程序操作,然后当用户发送停止命令时,循环停止 运行。当循环为 运行 时,我一直无法让串口继续读取输入。

所以我希望用户按下 1,然后它会进入循环并显示来自中断的数据。但我希望它继续监视串行输入,所以当我输入 2 时,我将跳出循环并停止打印到串行端口。

串行端口没有注册我的第二个输入。

我遗漏了一些代码,但重要的东西应该在那里。

int userStart = 0;   // Holder for user input to start program
int userStop = 0; // Holder for user input to stop program

void setup() {
  Serial.begin(115200);
  pinMode(motorEncoderA, INPUT);
  digitalWrite(motorEncoderA, HIGH); // Pull up resistor
  pinMode(motorEncoderB, INPUT);
  digitalWrite(motorEncoderB,HIGH); // Pull up resistor

  // Interrupt on change of Pin A
  attachInterrupt(digitalPinToInterrupt(2), encoderFunc, CHANGE); 

  Serial.print("Press 1 to start the Process & 2 to Stop");
}

void loop() {
if (Serial.available() > 0) 
{
   userStart = Serial.read();
   if (userStart = 1) {
       Serial.print('\n');
       while(userStop != 2) {  

       unsigned long timee = millis(); 

       // Only update if the shaft has moved
       if (encoderPositionLast != rotationCounter) {
           Serial.print("Time: ");
           Serial.print(timee);
           Serial.print(" Count: "); 
           Serial.print (rotationCounter);
           Serial.print('\n');
           encoderPositionLast = rotationCounter;
           Serial.print(userStart);

     }
    if (Serial.available() > 0) {
    userStop = Serial.read();
    Serial.print(userStop);
 }
   }
  }
}

嗯,我认为你的问题是 userStartuserStop 不应该是 12,而是 '1''2'.

也就是说,您的代码中有些地方我不喜欢。

首先,为什么每个人都使用 int 作为所有数字变量的基本类型?如果一个 byte 就足够了,就用它。在 32 位机器上 intbyte 几乎相同,但在 8 位机器上使用 ints 浪费 space 和时间。

其次,我强烈建议您阻止循环功能,否则您将无能为力。相反,使用一个变量来跟踪你是否是运行,用串行接口更新它,如果你是运行,然后执行代码。

这段代码应该可以做到。恕我直言,它比阻塞循环要好得多:

bool running = false;

void setup()
{
    ...
    running = false;
}

void loop()
{
    if (Serial.available() > 0) 
    {
        switch(Serial.read())
        {
        case '1':
            running = true;
            Serial.print('\n');
            break;
        case '2':
            running = false;
            Serial.print("stopped");
            break;
        }
    }

    if (running)
    {
        unsigned long timee = millis(); 

        // Only update if the shaft has moved
        if (encoderPositionLast != rotationCounter) {
            Serial.print("Time: ");
            Serial.print(timee);
            Serial.print(" Count: "); 
            Serial.print (rotationCounter);
            Serial.print('\n');
            encoderPositionLast = rotationCounter;
            Serial.print("running");
        }
    }
}