I am attempting to control the position of my computer's cursor using a potentiometer hooked up to my arduino nano. The arduino is running the following code:
int potPin = 3; // select the input pin for the potentiometer
int val = 0; // variable to store the value coming from the sensor
void setup() {
Serial.begin(9600);
}
void loop() {
val = analogRead(potPin); // read the value from the sensor
Serial.println(val);
}
When I ran the following python script, it worked properly and the sensor values were printing out in my terminal.
import serial
import pyautogui
ser = serial.Serial("/dev/cu.usbserial-141220", 9600, timeout=0.1)
while True:
data = ser.readline().decode("UTF-8").strip()
if data:
print(data)
However, when I added a small time delay in the while loop, the output would either get stuck on a single value or take multiple seconds to reflect a change to the potentiometer.
import serial
import pyautogui
import time
ser = serial.Serial("/dev/cu.usbserial-141220", 9600, timeout=0.1)
while True:
data = ser.readline().decode("UTF-8").strip()
if data:
print(data)
time.sleep(0.01)
I'd appreciate any help fixing this issue.
1 Answer 1
Thanks to chrisl and timemage's comments, I figured out the issue: the Arduino was sending the data too fast and the bytes were piling up in the computer's inbound buffer. I solved this by adding a delay to the loop()
function of the Arduino code.
Explore related questions
See similar questions with these tags.
ser.in_waiting
inside your loop enlightening.