Custom code used in ArduinoLatency.psyexp project ---------------------------------------- Python code used in the 'sample' Routine ---------------------------------------- BEFORE EXPERIMENT TAB --------------------- #connect to Arduino via USB serial port import serial import time com_port = "COM18" #Windows serial port address #com_port = "/dev/cu.usbmodem14101" #Mac serial port try: arduino=serial.Serial(com_port,baudrate=115200,timeout=1.0) time.sleep(3.0) arduino.flushInput() arduino.flushOutput() arduino.write(bytes('p','utf-8')) # Ping arduino serial_data = arduino.read() #wait for Ping reply character ('R') print("Serial port %s successfully openned." % (com_port)) except: print("Unable to open serial port: ", com_port) sys.exit() BEGIN EXPERIMENT TAB -------------------- import time startTime = time.perf_counter() endTime = time.perf_counter() transportLatency = [] usdLatency = 0.0 strLatency = str(0) BEGIN ROUTINE TAB ----------------- #Ping Arduino microcontroller startTime = time.perf_counter() arduino.write(bytes('p','utf-8')) #block until immediate reply detected serial_data = arduino.read() endTime = time.perf_counter() #compute and save 2-way transport latency usdLatency = (endTime-startTime) * 1000 #convert to millisec transportLatency.append(usdLatency) #results buffer strLatency = str(round(usdLatency,3)) EACH FRAME TAB -------------- #End Routine after 200 msec if t > 0.2: continueRoutine = False #end routine after 200 msec END ROUTINE TAB --------------- thisExp.addData("Latency", usdLatency) #append data to output file END EXPERIMENT TAB ------------------ #Shutdown serial connection to Arduino arduino.close() ---------------------------------------- Python code used in the 'Report' Routine ---------------------------------------- BEGIN ROUTINE TAB ----------------- import numpy as np np_latencies = np.array(transportLatency) mean_latency = np.mean(np_latencies) strMeanLatency = "Mean = %.3f" % (mean_latency) std_latency = np.std(np_latencies) strStdLatency = "Std Dev = %.3f" % (std_latency) min_latency = np.min(np_latencies) strMinLatency = "Minimum = %.3f" % (min_latency) max_latency = np.max(np_latencies) strMaxLatency = "Maximum = %.3f" % (max_latency) # #save latency distribution to disk file np.save('np_arduino_latencies.npy', np_latencies) print("Mean latency ="+strMeanLatency)