1

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.

5
  • 1
    What is a small delay for you? 100ms? You are sending the values as fast as the Arduino can.
    – chrisl
    Commented Dec 25, 2021 at 21:58
  • @chrisl the issue happens even with a delay in the python while loop of 10ms. I added the code with the loop to my question. Commented Dec 26, 2021 at 0:51
  • @ManavBokinala, Like chrisl said, you're sending as fast as you can. What keeps approximately 9.6 characters per iteration from piling up in the host's inbound buffer?
    – timemage
    Commented Dec 26, 2021 at 2:26
  • You may find printing ser.in_waiting inside your loop enlightening.
    – timemage
    Commented Dec 26, 2021 at 2:35
  • 1
    @timemage Thank you so much, this solved my problem! I'm new to all of this, so I did not understand the concept of the inbound buffer. Your comment made things clear for me. I really appreciate it. Commented Dec 26, 2021 at 8:05

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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