Speeding up pyserial-arduino communication on mac

I am trying to quickly send serial commands to an arduino via pyserial in GHpython on mac. I have achieved this but at a very slow speed. I realize firefly has this function, but us mac users cannot run the program.

Here is a video of my script turning off and on an led based on a gh boolean toggle:

In order for this to work I had to add a 2 second wait time before sending the serial data. I think this is because the ghpython component is opening a serial connection each time the script is updated.
Does anyone know of a way to speed this transfer up?

Here is my ghpython code:

import rhinoscriptsyntax as rs
import serial
import time
arduino = serial.Serial('/dev/tty.usbmodem14101', 9600)
c = str(y)

time.sleep(2)

arduino.write(bytes(c + '\n','utf-8'))

here is my arduino code:

String inByte;
void setup(){
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
  if (Serial.available()){
    inByte = Serial.readStringUntil('\n');
    if(inByte.toInt() == 0){
      digitalWrite(13, LOW);
    }
    if(inByte.toInt() == 1){
        digitalWrite(13, HIGH);
    }
  }
}

Thanks,
Tristan

In your GHPython script, have you tried to only open the serial connection the “first” time the component is run?

import serial

if not "arduino" in globals():
    arduino = serial.Serial("/dev/tty.usbmodem14101", 9600)

c = str(y)

arduino.write(bytes(c * "\n", "utf-8"))

You probably want to add a case to close the serial connection too, or delete the arduino variable.

1 Like

This worked great, thanks! Problem solved.

1 Like

Hi Tristan,

could you please share your final code solution here?

Cheers