Hello!
So I just started using arduino again since i got an amazing thing i wanted to try out.
So on my PC im going to scan for objects using a program i wrote which then will send the information to move my mouse to the arduino so it handles the mouse movement.
Everything works great when it reads it as an int but if I use string it takes about 1 second to execute my command and move my mouse.
I found out if I use the "Serial.setTimeout(50)" it does it instant but do I risk loosing out on information using that?
Here is my arduino code
#include <Mouse.h>
int LED = 13;
void setup(){
Serial.begin(345600);
Serial.setTimeout(50);
pinMode(LED, OUTPUT);
Mouse.begin();
}
void loop(){
String data = Serial.readString();
if(data == "GGNOOB") {
Mouse.move(1000, 200);
}
}
Here is my C++ code:
#include "pch.h"
using namespace System;
using namespace System::IO::Ports;
int main(array<System::String ^> ^args)
{
SerialPort connection("COM13", 345600);
connection.Open();
while (true)
{
int input = Convert::ToInt32(Console::ReadLine());
if (input == 1)
connection.Write("GGNOOB");
else
connection.Write("K");
}
return 0;
}
Its really important that it doesnt loose the data sent so I would love if someone could help me out here!
Also random extra question: Can you somehow choose what COM port it always should use?
What COM port number that's used is up to the operating system. Typically built in serial ports are assigned the same number, but USB to serial converters vary wildly. The best you can do is give the user the ability to choose or to identify it at runtime.
Yes, there is a risk. I'll advise you to go through the above link, but Serial.readBytesUntil() might be a usable alternative with the standard timeout; you will have to add a terminating character (e.g. '\n') at the end of the data that you send.
I had this exact same issue. The fix was to use Serial.readStringUntil("~"); where "~" being the terminating character I would send it from my c++ program. The reason setting Serial.setTimout(50); worked for you, is because you reduced the amount of time that it would wait for all characters of the String to arrive. By giving it a terminating character, the function knows immediately that it is finished once that character arrives and moves on to process the string.