Water Calibration with Arduino
The Water Calibration panel opens the valves through a
built-in Bpod sequence. With an Arduino (BEHAVIOR_CONTROLLER set to OTHER), the
project needs a task that inherits from WaterCalibrationTaskBase and runs the same
sequence on the board. This page gives one, ready to use, for the firmware of the
Arduino examples, village_arduino.ino, which already
understands the message it sends.
How It Works
When you click CALIBRATE or TEST, the panel creates the task with three arguments
(so its __init__ must not change):
indices: the ports to open, 0-based (0is port 1).times: the opening time of each one, in seconds, in the same order.maximum_number_of_trials: the number of iterations.
Every trial opens each valve for its time, one after the other, with 0.1 s in between,
as the Bpod sequence does. To open a valve, the task sends a single message,
CMD_OPEN_VALVE (the port and the time in microseconds), and waits for the reply,
EVENT_VALVE_CLOSED. The Arduino times each opening itself, so the USB latency does not
change the volume delivered.
Installing It
Download
water_calibration_arduino.pybelow and copy it to your project’scodedirectory.Make sure the board runs a firmware that understands
CMD_OPEN_VALVE: the firmware of the Arduino examples does (see below). If you use your own, add the same message to it, so that one firmware serves for the tasks and for the calibration.Check that
CONTROLLER_PORT(SETTINGS→CONTROLLER SETTINGS) is the board’s port, and that the baud rate is the same in the task and in the firmware (9600).Restart the Training Village, so that it finds the new class.
The Task
Download water_calibration_arduino.py
import struct
import time
import serial
from village.custom_classes.water_calibration_task_base import (
WaterCalibrationTaskBase,
)
from village.scripts.time_utils import time_utils
from village.settings import settings
# Water calibration with an Arduino instead of Bpod.
#
# Copy this file to your project's code directory: the Water Calibration
# panel then runs this class instead of the built-in Bpod sequence. Keep only
# one WaterCalibrationTaskBase subclass in the project. The board must
# understand CMD_OPEN_VALVE, as the firmware of the Arduino examples does.
#
# Protocol (see openValve() in village_arduino/village_arduino.ino):
#
# Pi -> Arduino, 6 raw bytes, once per valve opening:
# [CMD_OPEN_VALVE, port, time_us (uint32, little-endian)]
# Opens the valve of that port (1-based) for time_us microseconds. The
# Arduino times the opening itself, so the USB latency does not change
# the volume delivered.
#
# Arduino -> Pi, 6 raw bytes, once the valve is closed again:
# [EVENT_VALVE_CLOSED, port, elapsed_us (uint32, little-endian)]
# elapsed_us is how long the valve was actually open.
CMD_OPEN_VALVE = 20
EVENT_VALVE_CLOSED = 4
BAUDRATE = 9600 # must match the Arduino sketch's Serial.begin(...)
READ_TIMEOUT = 0.05 # seconds; also how often should_stop gets re-checked
MESSAGE_SIZE = 6 # every Arduino -> Pi message is exactly this many bytes
STARTUP_WAIT = 2.0 # seconds; opening the port resets most Arduino boards
WAIT_BETWEEN_VALVES = 0.1 # seconds, as in the built-in Bpod sequence
class WaterCalibrationArduino(WaterCalibrationTaskBase):
"""The same sequence as the built-in Bpod one: every trial opens each
valve in self.indices (0-based ports) for its time in self.times
(seconds), one after the other. The panel creates the task with those
lists and with maximum_number_of_trials set to the number of iterations,
so __init__ is inherited unchanged."""
def start(self):
"""Opens the serial connection to the Arduino."""
self.serial_port = serial.Serial(
port=settings.get("CONTROLLER_PORT"),
baudrate=BAUDRATE,
timeout=READ_TIMEOUT,
)
# Opening the port resets most Arduino boards: wait for the sketch
# to be running, or the first command would be lost.
time.sleep(STARTUP_WAIT)
self.serial_port.reset_input_buffer()
def create_trial(self):
"""Opens each valve for its time, waiting for the Arduino to report
it closed before going on to the next one."""
for index, valve_time in zip(self.indices, self.times, strict=False):
if self.should_stop:
return
port = index + 1
time_us = round(valve_time * 1_000_000)
self.serial_port.write(struct.pack("<BBI", CMD_OPEN_VALVE, port, time_us))
# The deadline is only a safety net for a lost message.
self.wait_valve_closed(time_utils.now_timestamp() + valve_time + 1.0)
time.sleep(WAIT_BETWEEN_VALVES)
def wait_valve_closed(self, deadline):
"""Waits for EVENT_VALVE_CLOSED, the task to stop or the deadline."""
buffer = bytearray()
while not self.should_stop and time_utils.now_timestamp() < deadline:
chunk = self.serial_port.read(MESSAGE_SIZE - len(buffer))
if not chunk:
continue # nothing arrived within READ_TIMEOUT; keep waiting
buffer += chunk
if len(buffer) < MESSAGE_SIZE:
continue
event, _, _ = struct.unpack("<BBI", bytes(buffer))
buffer.clear()
if event == EVENT_VALVE_CLOSED:
return
def close(self):
"""Closes the serial connection to the Arduino."""
if self.serial_port.is_open:
self.serial_port.close()
The Firmware
In village_arduino.ino, the firmware of the Arduino
examples, CMD_OPEN_VALVE is handled by openValve(). The valve pins are the ones of
the side ports (valvePinLeft, valvePinRight); a port without a valve replies at once
with an elapsed time of 0:
// === Water calibration (water_calibration_arduino.py) =====================
//
// [CMD_OPEN_VALVE, port, time_us (uint32, LE)]
// Opens the valve of that port for time_us microseconds, timed with
// micros() so the USB latency does not change the volume delivered, and
// reports [EVENT_VALVE_CLOSED, port, elapsed_us] once it is closed again
// (elapsed_us is 0 if the port has no valve).
void openValve(byte port, unsigned long timeUs) {
if (port != LEFT_PORT && port != RIGHT_PORT) {
sendEvent(EVENT_VALVE_CLOSED, port, 0);
return;
}
byte valvePin = valvePinOf(port);
unsigned long t0 = micros();
digitalWrite(valvePin, HIGH);
while (micros() - t0 < timeUs) {
}
digitalWrite(valvePin, LOW);
sendEvent(EVENT_VALVE_CLOSED, port, micros() - t0);
}