c# - Attemping two-way serial port communication in Unity, Serial.Write() causes freeze -
i'm building arduino controller used unity game communicates on serial port. reading data sent arduino works fine, when attempting write serial port unity instantly freezes , needs shut down task manager. need getting serialport.write()
work. below, i've detailed how i'm sending data arduino , reading in unity, , how attempt write data arduino doesn't work. i've got controller sending button states unity control character on screen so
c#, unity
private serialport arduinostream = new serialport("com3", 38400); void start(){ //setup serial connection try{ arduinostream.readbuffersize = 8192; arduinostream.writebuffersize = 128; arduinostream.parity = parity.none; arduinostream.stopbits = stopbits.one; arduinostream.open(); //arduinostream.basestream.readtimeout = 20; } catch(exception e){ debug.log("could not open serial port: " + e.message); useserialcontroller = false; } } private void steerandacceleratewitharduino(){ //attemp read serial data , handle try{ string serialdata; //attempt read serial data serialdata = arduinostream.readline(); debug.log ("serialdata received arduino: " + serialdata); handleserialinputdata(serialdata); } catch(exception e){ //if there's error, disable serial controller avoid blocking on serial.read()/write() debug.log ("serial read error: " + e.message); useserialcontroller = false; } //flush serial stream arduinostream.basestream.flush(); }
and arduino sending data simple
c++, arduino
serial.println(buildjsonstring(keys,values)); delay(30);
but attempt write serialport @ in unity, crashes. i'm trying write string
c#, unity
string serialdata = "{bluescore:" + bluescore + ",redscore:" + redscore + "}"; //write serial try{ if(arduinostream.isopen) arduinostream.write (serialdata); }catch(exception e){ debug.log ("couldn't write serial port. " + e.message); }
on arduino i'm attempting read serial 1 char @ time, never gets far because unity crashes
c++, arduino
void receivestatesoverserial(){ string readstring; while (serial.available()) { delay(3); //delay allow buffer fill if (serial.available() >0) { char c = serial.read(); //gets 1 byte serial buffer readstring += c; //makes string readstring } } if (readstring.length() >0) { serial.println(readstring); //see received } readstring = ""; }
has been able read , write same serialport in unity? see wrong here? appreciated
Comments
Post a Comment