I have been messing around with some intensive debugging with my Arduino scripts and I have noticed something odd: after running for some time, the simulated USB-HID inputs from my pro micro start to lag behind the actual trigger for the inputs. I have also noticed this when using a Python library called Pyserial, and whenever I try to read serial monitor data and print/store it, my code begins to lag badly (which is not good when you are trying to log multiple inputs in real time!). If I don't store/read the serial data, the scripts seem to run indefinitely without a hitch.
Here is the code I have been using on a Pro Micro board:
/* Tilt Control - King Dub Dub, 11/15/19
A tilt-controller script for USB-HID enabled Arduino boards with the MPU-6050 sensor.
Tilt to control the WASD controls and spacebar (I lied about the W :D).
There is an additional fail-safe that keeps any keyboard data from being printed
if pin 9 isn't grounded. Ground pin 9 with a switch/button when you want to send
keyboard inputs.
VCC to 5V
GND to GND
SCL to A5 or SCL
SDA to A4 or SDA
ADO to GND
Pin 9 to button/switch to ground
*/
#include<Wire.h>
#include<Keyboard.h>
const int MPU_addr=0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; //sets up the accelerometer XYZ's, temperature, and gyro XYZ's
int minVal=265;
int maxVal=402;
double x,y,z;
void setup(){
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
Serial.begin(9600);
pinMode(9, INPUT_PULLUP); //pin 9 is a fail-safe switch
Keyboard.begin();
}
void loop(){
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true);
AcX=Wire.read()<<8|Wire.read();
AcY=Wire.read()<<8|Wire.read();
AcZ=Wire.read()<<8|Wire.read();
int xAng = map(AcX,minVal,maxVal,-90,90);
int yAng = map(AcY,minVal,maxVal,-90,90);
int zAng = map(AcZ,minVal,maxVal,-90,90);
x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);
Serial.print("X= "); Serial.print(x); //print the X value
Serial.print(" Y= "); Serial.print(y); //print the Y value
Serial.print(" Z= "); Serial.print(z); //print the Z value
Serial.print("\n"); //prints a new line
if ((y >=110) and (digitalRead(9) == LOW)){
Keyboard.press('a'); //if tilted left, "press" the [a] key
} else {
Keyboard.release('a'); //else, stop "pressing" the [a] key
}
if ((z <=345) and (z>=180) and (digitalRead(9) == LOW)){ //if tilted down:
Keyboard.press('s');
delay(10);
} else {
Keyboard.release('s');
}
if ((y<=70) and (digitalRead(9) == LOW)){ //if tilted right:
Keyboard.press('d');
delay(10);
} else {
Keyboard.release('d');
}
if ((z >= 10) and (z<=179) and (digitalRead(9) == LOW)){ //if tilted up:
Keyboard.press(' ');
delay(10);
} else {
Keyboard.release(' ');
}
}
I have also noticed this with scripts on my UNO board, so it is not a problem with the Micro.