How do I read serial between interrupts on Arduino?

时间:2016-12-02 05:08:35

标签: arduino serial-port interrupt

I have steppers stepping during an interrupt timer at 50 and have all my code working between the interrupts until I tried reading serial commands more than one character long.

I'm getting dropped bytes so my strings are missing a letter every 4-5 chars. I researched all day to try and figure out a solution but have come up with nothing. If I don't use an interrupt my stepper stops for 2 seconds reading a one char serial input as a string.

My goal is to have a remote control app sending speed commands. I need help working this problem out.

https://sourceforge.net/p/open-slider/code/ci/master/tree/OpenSliderFirmware/

String incomingString = "";
if (Serial.available() > 0) {
    incomingString = Serial.readString();
    Serial.println(incomingString);
}

Using Accelstepper library

interrupt:

//Interrupt Timer1
void ISR_stepperManager() {
    Slide.runSpeed();
    Xaxis.runSpeed();
    Yaxis.runSpeed(); 
}

2 个答案:

答案 0 :(得分:0)

我不确定它是否对您的问题有所帮助,但我发现当其他事情需要发生时,String类型不安全。 我更喜欢使用char数组并一次读取一个char。

__hash__

我发现它更可靠。

希望它有所帮助!

答案 1 :(得分:0)

快速回答:如果中断计时器过于频繁切换,你就不会这样做。

我通过使用可变中断计时器和步进乘法器解决了这个问题。基本上每次定时器中断时都会调用这些步骤,而不是在中断函数中检查毫秒数。这解决了许多问题。步进器的速度现在由中断计时器控制。这给了我更多的自由周期来完全读取传入的序列而不会损坏并提高效率。当执行超过4k步/ s时,每个周期调用更多步骤也提高了效率,需要更少的周期来实现高步长。

每个周期处理一个字符串以防止阻塞。

总的来说,如果你使用的是串行和中断定时器,那么任何中断都会发生在< 100us你应该小心你在中断期间运行了多少代码。这将导致传入的串行和用户输入出现问题。 25us定时器中断中的几行代码,输入串行不起作用。