2

First, I am very new to Python, but I am trying to write a Python program to write serial data to my Arduino for the purpose to control servos. I am basically wanting my computer’s keyboard to act as a controller for the servos. The process would go something like this:

  1. Once a key is pressed, the servo would start moving a certain direction.
  2. If the key is held, the servo would continue moving
  3. Once the key is released, the servo would stop moving.

I have tried using Pygame and Pynput, but I can’t get it to work. I have been using Pyserial to connect to the Arduino.

Any related questions already on here, help, or other links would be greatly appreciated.

2
  • Does stackoverflow.com/q/10649208 help? Commented Mar 31, 2018 at 0:17
  • Sort, but I am not sure he/she is using keyboard input to then write to the arduino. I need to look more into it though. Commented Mar 31, 2018 at 1:51

1 Answer 1

1

The simplest way is to use basic serial I/O.

I use this kind of setup for my data-loggers that occasionally need the Arduino to take action based on the data or the clock.

EXAMPLE:

Assuming that you want to use a USB port (like on a RPi3), say you want to send a command that will cause the Arduino to emit two long beeps. (Or it could trip relays, whatever) the code would look something like this:

PYTHON SIDE:

#!/usr/bin/python
import serial

First open up the port:

(Often as shown, but for CHG340 Arduinos will be more like /dev/ttyACM0)

ser = serial.Serial("/dev/ttyUSB0",9600)

To read from the port, use:

linein = ser.readline()

To write to the Arduino use:

ser.write("A")

ARDUINO SIDE, (remembering that it will arrive as type char)

In setup()

char cTMP;
int beePin=12;

Serial.begin(9600);
while (Serial.available()>0) cTMP=Serial.read();  // flush the buffer

Then somewhere in loop()

if (Serial.available) > 0) {
    if (serIn=='A') {
      digitalWrite(beePin,HIGH); delay(2000); digitalWrite(beePin,LOW);
      delay(2000);
      digitalWrite(beePin,HIGH); delay(2000); digitalWrite(beePin,LOW);
    }

}

I tend to stick to single-letter commands to the Arduinos


The beauty of this setup is that you can also run the Arduino IDE on the RPi3 for Arduino programming, and you can use VNC or xrdp (with Windows Remote Desktop or remmina) to access it remotely.

I call it a Piduino.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I plan to use something like that to control the servos. The biggest issue is taking keyboard input and then ser.writing that. How could I get it to send an “a” to the arduino when I press a on my keyboard and then send another “a” when I release it

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.