def __init__(self, com_port, settings, bpod): """helper class to deal with rotary encoder module, set thresholds, set and reset position aswell as read prosition Args: com_port (str): com port (usb) where rotary encoder module is connected to settings (TrialParameterHandler object): the object for all the session parameters from TrialPArameterHandler """ # rotary encoder settings self.com_port = com_port self.rotary_encoder = RotaryEncoderModule(self.com_port) self.bpod = bpod self.reset = settings.RESET_ROTARY_ENCODER self.WRAP_POINT = 0 # set thresholds self.all_thresholds = settings.thresholds self.enable_thresholds = [(True if x != 0 else False) for x in self.all_thresholds] while len(self.enable_thresholds) < 8: self.enable_thresholds.append(False) self.events = [ "RotaryEncoder1_{}".format(x) for x in list(range(1, len(self.all_thresholds) + 1)) ]
def configure(self): if self.RE_PORT == 'COM#': return m = RotaryEncoderModule(self.RE_PORT) m.set_zero_position() # Not necessarily needed m.set_thresholds(self.SET_THRESHOLDS) m.enable_thresholds(self.ENABLE_THRESHOLDS) m.close()
def find_rotary_com_port(): for port in range(10): com_port = f"COM{port}" try: ro = RotaryEncoderModule(com_port) ro.close() except: pass else: return com_port
def rotary_encoder_ok() -> bool: # Check RE try: pars = _grep_param_dict() m = RotaryEncoderModule(pars["COM_ROTARY_ENCODER"]) m.set_zero_position() # Not necessarily needed m.close() out = True except BaseException as e: log.warning(f"{e} \nCan't connect to Rotary Encoder.") out = False return out
class BpodRotaryEncoder(): def __init__(self, com_port, settings, bpod): """helper class to deal with rotary encoder module, set thresholds, set and reset position aswell as read prosition Args: com_port (str): com port (usb) where rotary encoder module is connected to settings (TrialParameterHandler object): the object for all the session parameters from TrialPArameterHandler """ # rotary encoder settings self.com_port = com_port self.rotary_encoder = RotaryEncoderModule(self.com_port) self.bpod = bpod self.reset = settings.RESET_ROTARY_ENCODER self.WRAP_POINT = 0 # set thresholds self.all_thresholds = settings.thresholds self.enable_thresholds = [(True if x != 0 else False) for x in self.all_thresholds] while len(self.enable_thresholds) < 8: self.enable_thresholds.append(False) self.events = [ "RotaryEncoder1_{}".format(x) for x in list(range(1, len(self.all_thresholds) + 1)) ] def get_events(self): return self.events def load_message(self): """load reset messag to rotary encoder so bpod can reset rotary encoder position Args: bpod (Bpod object): """ rotary_encoder = [ x for x in self.bpod.modules if x.name == "RotaryEncoder1" ][0] self.bpod.load_serial_message(rotary_encoder, self.reset, [ord('Z'), ord('E')]) def configure(self): """loads rotary enoder module with thresholds """ self.rotary_encoder.set_thresholds(self.all_thresholds) self.rotary_encoder.enable_thresholds(self.enable_thresholds) self.rotary_encoder.enable_evt_transmission() self.set_wrap_point(self.WRAP_POINT) def close(self): self.rotary_encoder.close() def enable_stream(self): self.rotary_encoder.enable_stream() def disable_stream(self): self.rotary_encoder.disable_stream() def read_stream(self): return self.rotary_encoder.read_stream() def read_position(self): position = self.rotary_encoder.read_stream() if len(position) != 0: return position[0][2] # log postition def enable_logging(self): self.rotary_encoder.enable_logging() def disable_logging(self): self.rotary_encoder.disable_logging() def get_logging(self): return self.rotary_encoder.get_logged_data() def set_zero_position(self): self.rotary_encoder.set_zero_position() def set_wrap_point(self, wrap_point): """set the point at which the position is automatically set back to 0 => one half rotation Args: wrap_point (int): one half rotation wehre set to zero again Returns: [type]: [description] """ array = np.array([np.uint8(wrap_point)]) self.rotary_encoder.arcom.write_array([ord('W')] + array) return self.rotary_encoder.arcom.read_uint8() == 1
trials = 10 #============================================================================== # rotary encoder config #============================================================================== rotary_encoder = [x for x in bpod.modules if x.name == "RotaryEncoder1"][0] reset_re = 1 bpod.load_serial_message(rotary_encoder, 1, [ord('Z'), ord('E')]) bpod.load_serial_message(rotary_encoder, 2, [ord("#"), 2]) #==================================== # onfigure encoder #==================================== rotary_encoder = RotaryEncoderModule('COM6') ALL_THRESHOLDS = [-10, 10] ENABLE_THRESHOLDS = [True, True, False, False, False, False, False, False] rotary_encoder.set_zero_position() # Not necessarily needed rotary_encoder.set_thresholds(ALL_THRESHOLDS) rotary_encoder.enable_thresholds(ENABLE_THRESHOLDS) rotary_encoder.enable_evt_transmission() rotary_encoder.close() movement_left = "RotaryEncoder1_1" movement_right = "RotaryEncoder1_2" #====================================
# F2TTL CALIBRATION: check f2ttl values from params, warn if old calibration PARAMS["F2TTL_DARK_THRESH"] PARAMS["F2TTL_LIGHT_THRESH"] PARAMS["F2TTL_CALIBRATION_DATE"] # WATER CALIBRATION: check water calibration values from params, warn if old calibration log.debug("Checking water calibration...") PARAMS["WATER_CALIBRATION_RANGE"] PARAMS["WATER_CALIBRATION_OPEN_TIMES"] PARAMS["WATER_CALIBRATION_WEIGHT_PERDROP"] PARAMS["WATER_CALIBRATION_DATE"] # F2TTL CALIBRATION: check f2ttl values from params, warn if old calibration # WATER CALIBRATION: check water calibration values from params, warn if old calibration # Check RE log.debug("RE: Connect") m = RotaryEncoderModule(PARAMS["COM_ROTARY_ENCODER"]) log.debug("RE: set 0 position") m.set_zero_position() # Not necessarily needed log.debug("RE: Close") m.close() # Check Bpod log.debug("Bpod Connect") ser = serial.Serial(port=PARAMS["COM_BPOD"], baudrate=115200, timeout=1) log.debug("Bpod lights OFF") ser.write(struct.pack("cB", b":", 0)) log.debug("Bpod lights ON") ser.write(struct.pack("cB", b":", 1)) log.debug("Bpod Close") ser.close() # Check Frame2TTL (by setting the thresholds) f = Frame2TTL(PARAMS["COM_FRAME2TTL"])
import pygame from player_class import Player from pybpod_rotaryencoder_module.module_api import RotaryEncoderModule #============================================================================= GAIN = 3 THRESHOLD = 2000 FPS = 100 SCREEN_WIDTH = 5760 SCREEN_HEIGHT = 1200 t_end = time.time() + 20 #============================================================================ # rotary encoder config ro = RotaryEncoderModule('COM6') ro.enable_stream() data_pref = [[0, 0, 0]] # pygame config pygame.init() fpsClock = pygame.time.Clock() fpsClock.tick(FPS) # define keys and user interaction from pygame.locals import ( K_ESCAPE, KEYDOWN, QUIT, )
from pybpodapi.bpod import Bpod from pybpodapi.state_machine import StateMachine import numpy as np from pybpod_rotaryencoder_module.module_api import RotaryEncoderModule from pybpodapi.com.arcom import ArCOM, ArduinoTypes import time import pygame from player_class import Player import threading rotary_encoder = RotaryEncoderModule('COM6') rotary_encoder.enable_stream() # Simple player in pygame #==================================================================================================================== #pygame #==================================================================================================================== class py_game(): def __init__(self): self.run_open_loop = True self.display_stim_event = threading.Event() self.move_stim_event = threading.Event() self.still_show_event = threading.Event() self.GAIN = 3 self.THRESHOLD = 2000 self.FPS = 100 self.SCREEN_WIDTH = 5760 self.SCREEN_HEIGHT = 1200
def __init__(self, parent_win=None): BaseWidget.__init__(self, self.TITLE, parent_win=parent_win) RotaryEncoderModule.__init__(self) self._port = ControlCombo( 'Serial port', changed_event=self.__combo_serial_ports_changed_evt) self._refresh_serial_ports = ControlButton( '', icon=QtGui.QIcon(conf.REFRESH_SMALL_ICON), default=self.__refresh_serial_ports_btn_pressed, helptext="Press here to refresh the list of available devices.") self._connect_btn = ControlButton('Connect', checkable=True) self._filename = ControlText('Stream Filename', '') self._saveas_btn = ControlButton('Save As...') self._events = ControlCheckBox('Enable events') self._output_stream = ControlCheckBox('Output stream') self._stream = ControlCheckBox('Stream data') self._stream_file = ControlCheckBox('Stream to file') self._zero_btn = ControlButton('Reset position') self._start_reading = ControlButton('Start Reading') self._reset_threshs = ControlButton('Reset thresholds') self._thresh_lower = ControlNumber('Lower threshold (deg)', 0, minimum=-360, maximum=360) self._thresh_upper = ControlNumber('Upper threshold (deg)', 0, minimum=-360, maximum=360) self._graph = ControlMatplotlib('Value') self._clear_btn = ControlButton('Clear') self.set_margin(10) self.formset = [('_port', '_refresh_serial_ports', '_connect_btn'), ('_filename', '_saveas_btn'), ('_events', '_output_stream', '_stream', '_stream_file', '_zero_btn'), '_start_reading', ('_thresh_lower', '_thresh_upper', '_reset_threshs'), '=', '_graph', '_clear_btn'] self._stream.enabled = False self._stream_file.enabled = False self._events.enabled = False self._output_stream.enabled = False self._zero_btn.enabled = False self._reset_threshs.enabled = False self._thresh_lower.enabled = False self._thresh_upper.enabled = False self._start_reading.enabled = False self._connect_btn.value = self.__toggle_connection_evt self._saveas_btn.value = self.__prompt_savig_evt self._stream_file.changed_event = self.__stream_file_changed_evt self._events.changed_event = self.__events_changed_evt self._output_stream.changed_event = self.__output_stream_changed_evt self._thresh_upper.changed_event = self.__thresh_evt self._thresh_lower.changed_event = self.__thresh_evt self._reset_threshs.value = self.__reset_thresholds_evt self._zero_btn.value = self.__zero_btn_evt self._start_reading.value = self.__start_reading_evt self._graph.on_draw = self.__on_draw_evt self._clear_btn.value = self.__clear_btn_evt self._filename.changed_event = self.__filename_changed_evt self.history_x = [] self.history_y = [] self._timer = QTimer() self._timer.timeout.connect(self.__update_readings) self._fill_serial_ports()
# sinple psychopy example of different stimuli # using pybpod roatry encoder as input from psychopy import visual, core, event, monitors, info #import some libraries from PsychoPy from psychopy.hardware import keyboard import numpy as np import time from pybpod_rotaryencoder_module.module_api import RotaryEncoderModule # Setup Bpod Rotary Encoder Input ======================================= rotary_encoder = RotaryEncoderModule('/dev/cu.usbmodem65305701') rotary_encoder.enable_stream() def set_wrap_point(ro,wrap_point): """set the point at which the position is automatically set back to 0 => one half rotation Args: wrap_point (int): one half rotation wehre set to zero again Returns: [type]: [description] """ array = np.array([np.uint8(wrap_point)]) ro.arcom.write_array([ord('W')] + array ) return ro.arcom.read_uint8() == 1 set_wrap_point(rotary_encoder,0)
import time import sys sys.path.insert(0, '..') from pybpod_rotaryencoder_module.module_api import RotaryEncoderModule m = RotaryEncoderModule('COM3') """ m.enable_stream() #print the first 100 outputs count = 0 while count<100: data = m.read_stream() if len(data)==0: continue else: count += 1 print(data) m.disable_stream() print('set', m.set_position(179)) m.set_zero_position() m.enable_thresholds([True, False, True, True, False, False, True, True]) print(m.current_position()) """ print('--------') m.enable_logging()
from pybpod_rotaryencoder_module.module_api import RotaryEncoderModule import time ro = RotaryEncoderModule('COM6') ro.enable_stream() ro.set_zero_position() pos_li = [] pos_change_li = [] t_end = time.time() + 20 data_pref = [[0, 0, 0]] # test with read hole stream while time.time() < t_end: data = ro.read_stream() if len(data) == 0: continue else: pos_li.append(data) pos_change = data[0][2] - data_pref[0][2] data_pref = data pos_change_li.append(pos_change) """ # test with read only current position while time.time() < t_end: pos = ro.current_position() if len(data)==0: continue else: pos_li.append(pos)