You can give Keyboard Input using Arduino Nano, Uno or any other boards by doing these following steps:
- Sending the serial data using
Serial.println() in the Arduino Script. A Demo script is given below:
#include <Arduino.h>
void setup() {
Serial.begin(9600); // Start serial communication
}
void loop() {
int accelerator = analogRead(A0);
int decelerator = analogRead(A1);
int x = analogRead(A4);
int y = analogRead(A5);
if (accelerator > 15) {
Serial.println("q"); // Send 'q' over serial
delay(10);
}
if (decelerator > 590) {
Serial.println("z"); // Send 'z' over serial
delay(10);
}
if (x > 400) {
Serial.println("i"); // Forward
delay(250);
}
if (x < 290) {
Serial.println(","); // Backward
delay(250);
}
if (y > 400) {
Serial.println("j"); // Left
delay(250);
}
if (y < 290) {
Serial.println("l"); // Right
delay(250);
}
}
Then, running the python script below:
import serial
from pynput.keyboard import Controller
keyboard = Controller()
arduino = serial.Serial('/dev/ttyUSB0', 9600) # Change this to match your Arduino's port
while True:
data = arduino.readline().decode().strip()
if data:
keyboard.press(data)
keyboard.release(data)
Here, change this '/dev/ttyUSB0' according to the port you're using the Arduino board.