Python Forum
Taking serial data to perform key.press functions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Taking serial data to perform key.press functions (/thread-29482.html)



Taking serial data to perform key.press functions - ausbollinger13 - Sep-04-2020

I am trying to take an IMU's data via serial port to press arrow keys to be able to play a game with the use of an accelerometer, gyroscope, and magnetometer.

I am able to print the serial data with roll, pitch, and yaw direction but i want the data to go into if statements to press up, down, right, and left arrow keys if the values of the data are between ranges such as from 0 to 25 pitch would be up and 0 to -25 pitch would be down.

Could I get some help on how to send the serial data into if statements?


Python Code:
from pynput.keyboard import Key, Controller
from time import *
import numpy as np
import math
import serial
ad=serial.Serial('com11',115200)
sleep(1)

keyboard = Controller()
toRad=2*np.pi/360
toDeg=1/toRad


while (True):
    while (ad.inWaiting()==0):
        pass
    dataPacket=ad.readline()
    dataPacket=str(dataPacket,'utf-8')
    splitPacket=dataPacket.split(",")
    roll=float(splitPacket[0])*toRad
    pitch=float(splitPacket[1])*toRad
    yaw=float(splitPacket[2])*toRad+np.pi

    if pitch <= -5:
        print('Down')
        break
    if pitch >= 5:
        print('Up')
        break
   
    print("Pitch=",pitch*toDeg," Roll=",roll*toDeg,"Yaw=",yaw*toDeg)



RE: Taking serial data to perform key.press functions - bowlofred - Sep-04-2020

Please put your code inside python tags.

Not sure what is happening without any output shown, but I find it odd that you're immediately converting the read data to radians, then you convert back to degrees to print. Any reason why the double conversion?

Also, you are printing the value in degrees, but you are comparing the value in radians. If you have a 10 degree pitch, it will print bigger than 5, but it is much less than 5 radians so won't trigger.