Hi there,
I am trying to have PsychoPy send signals to my Arduino board to activate two pumps at the same time. Iβm able to activate the pumps independently from PsychoPy, but when I run my experiment none of my if-else statements seem to be working. The only time the pumps are able to go off if I assign only one value to my variable in PsychoPy, but I have multiple pairs of pumps I want to randomly present to my subjects. Below is my PsychoPy if-else statement and Arduino board code. Is there an error in my code that isnβt allowing PsychoPy to properly communicate with my board? Iβm running PsychoPy 2022.2.5.
--------PsychoPy--------
*Begin Experiment Tab
import time
import serial
import PY_arduino
ser = serial.Serial(βCOM3β, 115200, timeout=1)
*Begin Routine Tab
if number == β3β:
pumpPair = bβ0β
elif number == β5β:
pumpPair = bβ1β
elif number == β9β:
pumpPair = bβ2β
elif number == β6β:
pumpPair = bβ3β
elif number == β10β:
pumpPair = bβ4β
elif number == β12β:
pumpPair = bβ5β
ser.write(pumpPair)
print(pumpPair)
--------- Arduino---------
char state;
int pump[4] = {2, 3, 4, 5}; // Pump pins: pump1 β pin 2, pump2 β pin 3, etc.
void setup() {
Serial.begin(115200);
// Define pump pins as outputs
for (int i = 0; i < 4; i++) {
pinMode(pump[i], OUTPUT);
}
}
void loop() {
// Check if data is available from the serial connection
if (Serial.available() > 0) {
state = Serial.read(); // Read pumpPair value sent by PsychoPy
int pumpPair = state - '0'; // Convert the state to an integer
activatePumps(pumpPair); // Call the function to activate pumps
}
}
void activatePumps(int pumpPair) {
// Activate pumps based on bitmask (one-hot encoded values)
if (pumpPair == 3) { // Pump 1 and Pump 2 (binary 0011)
digitalWrite(pump[0], HIGH); // Activate Pump 1
digitalWrite(pump[1], HIGH); // Activate Pump 2
}
else if (pumpPair == 5) { // Pump 1 and Pump 3 (binary 0101)
digitalWrite(pump[0], HIGH); // Activate Pump 1
digitalWrite(pump[2], HIGH); // Activate Pump 3
}
else if (pumpPair == 9) { // Pump 1 and Pump 4 (binary 1001)
digitalWrite(pump[0], HIGH); // Activate Pump 1
digitalWrite(pump[3], HIGH); // Activate Pump 4
}
else if (pumpPair == 6) { // Pump 2 and Pump 3 (binary 0110)
digitalWrite(pump[1], HIGH); // Activate Pump 2
digitalWrite(pump[2], HIGH); // Activate Pump 3
}
else if (pumpPair == 10) { // Pump 2 and Pump 4 (binary 1010)
digitalWrite(pump[1], HIGH); // Activate Pump 2
digitalWrite(pump[3], HIGH); // Activate Pump 4
}
else if (pumpPair == 12) { // Pump 3 and Pump 4 (binary 1100)
digitalWrite(pump[2], HIGH); // Activate Pump 3
digitalWrite(pump[3], HIGH); // Activate Pump 4
}
// Wait for a specified amount of time (2 seconds for testing)
delay(2000);
// Turn off all pumps
for (int i = 0; i < 4; i++) {
digitalWrite(pump[i], LOW);
}
}