- Home /
Using Arduino as controller in Unity is giving me bad framerate
My framerate drops to ~15fps when u use an Arduino as my input, ~25fps when i use my keyboard as input however if i exclude Arduino completely from my game i get a solid 100+fps. My game in in 2D. Here is my code ```
public class Player : MonoBehaviour {
public float moveSpeed = 6;
public float gravity = -20;
public float jumpDistance = 8;
Vector3 moveDistance;
byte arduinoInput;
SerialPort stream = new SerialPort("COM7", 9600);
Controller2D controller;
void Start() {
controller = GetComponent<Controller2D>();
//sp.DtrEnable = true;
stream.ReadTimeout = 100;
stream.Open();
}
void Update() {
if (stream.IsOpen) {
try {
arduinoInput = (byte) stream.ReadByte();
print(arduinoInput);
}
catch (System.Exception) {
}
}
if (arduinoInput == 2) { // Als je de 2de drukknop indrukt
moveDistance.x = -moveSpeed; // Ga je links bewegen
controller.Move(moveDistance * Time.deltaTime); // Leest de input
}
if (arduinoInput == 3) { // Als je de 3de druknop indrukt
moveDistance.x = moveSpeed; // Ga je rechts bewegen
controller.Move(moveDistance * Time.deltaTime); // Leest de input
}
if (controller.collisions.above || controller.collisions.below ) {
moveDistance.y = 0;
}
if ((Input.GetKeyDown(KeyCode.Space) || arduinoInput == 1) && controller.collisions.below) {
moveDistance.y = jumpDistance; // Je gaat springen langs de y-as
//moveDistance.x = 0;
}
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveDistance.x = input.x * moveSpeed;
moveDistance.y += gravity * Time.deltaTime;
controller.Move(moveDistance * Time.deltaTime);
}
} ```
Would appreciate if anyone could identify this problem
Answer by rh_galaxy · Feb 07, 2020 at 12:52 PM
Probably because stream.ReadByte() takes time to do, it includes waiting for the Arduino. Your frame rate will be limited to how fast you can get data from the serial port, which also is limited to 9600 bits/sec (1200 bytes) it will take 1ms just to get one char.
You need to run the serial receive code in another thread and let the Update() method run freely and just check if there is a new input received from the Arduino and if so take action.
Your answer
![](https://koobas.hobune.stream/wayback/20220612222604im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Arduino Button Input not working 0 Answers
Send many ints from Unity To Arduino. 2 Answers
Issues after updating to Unity 5 1 Answer
parse serial data from arduino 1 Answer
Long delay sending data to Arduino via Serial Communication 0 Answers