0

I've built 2 motor drivers for a robotics project and need to set positions that I want the motors to move to, and read that using the arduino. The arduino then uses a rotary encoder to implement a closed loop PID controller and move the motor the set point. My code wasn't working so I started troubleshooting and found out that my setpoint was getting reset to 0 automatically!

The only thin that changes the setpoint was the serial read so I made a smaller sketch for troubleshooting which is this:

volatile long setpoint;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

The result was quite odd, it sets the value correctly but resets back to 0 without me sending any new commands!

I tried updating the IDE to 1.8.12, tried old and new arduinos (with old and new bootloader) but all had the same result. Here is a demo video showing the weird reset to 0 problem:

https://streamable.com/kfgv61

I tried changing the buadrate higher or lower but that also didn't fix anything. Any ideas on what I'm doing wrong?

2

The problem here is that Serial.parseInt() stops when it sees the newline, but it does not consume that newline, which is left in the input buffer. Thus, at the next loop iteration, Serial.available() returns true because of this newline and, unless you send another value fast enough, Serial.parseInt() times out and returns zero.

The easy fix is to consume that newline yourself:

void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    if (Serial.peek() == '\n') Serial.read();  // consume LF
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

I personally would not use Serial.parseInt() at all, and would buffer the data myself until I see the '\n'. This way there are no surprises with timeouts being read as zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.