def main(): p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=SRATE, frames_per_buffer=CHUNK, output=True) delay = Delay(3.0) kb = kbhit.KBHit() c = ' ' numBloque = 0 while c != 'q': c = ' ' bloque = delay.getNextChunk( generateChunk(500.0, CHUNK, numBloque * CHUNK)) print(bloque) stream.write(bloque.astype(np.float32).tobytes()) if kb.kbhit(): c = kb.getch() numBloque += 1 kb.set_normal_term() stream.stop_stream() stream.close() p.terminate()
def __init__(self): rospy.loginfo("Creating Obj3DDetector class") # flags and vars self.ph_model = image_geometry.PinholeCameraModel() self.tracked_pixel = Point() self.use_kb = False self.ball_radius = 0 self.p_ball_to_cam = [] self.bridge = CvBridge() self.tb_val = self.window_with_trackbars('image_red', GREEN_TB_DEFAULTS, GREEN_TB_HIGHS) # Get and set params self.get_and_set_params() # kbhit instance self.kb = kbhit.KBHit() if self.use_kb: self.print_help() rospy.on_shutdown(self.kb.set_normal_term) self.imwritecounter = 0 # subscribers self.cam_info_sub = rospy.Subscriber("/camera/rgb/camera_info", CameraInfo, self.update_model_cb) self.msg_filt_rgb_img_sub = message_filters.Subscriber("/camera/rgb/image_color", Image) self.msg_filt_depth_img_sub = message_filters.Subscriber("/camera/depth_registered/hw_registered/image_rect", Image) self.t_sync = message_filters.ApproximateTimeSynchronizer([self.msg_filt_rgb_img_sub, self.msg_filt_depth_img_sub], 1, slop = 0.01) self.t_sync.registerCallback(self.time_sync_img_cb) # publishers and timers self.kb_timer = rospy.Timer(rospy.Duration(0.1), self.keycb) self.start_time = 0 self.tf_br = tf.TransformBroadcaster()
def __init__(self): rospy.loginfo("Creating SimpleTargets class") # setup local variables: self.position = ZERO_POS self.orientation = ZERO_ORI self.ee_dot = np.array([0, 0, 0]) self.th = 0.0 self.th_dot = 0.0 self.run_flag = ON self.run_flag = OFF # Instantiating keyboard object self.key = kbhit.KBHit() rospy.on_shutdown(self.key.set_normal_term) #Subscribers and Publishers self.br = tf.TransformBroadcaster() self.key_timer = rospy.Timer(rospy.Duration(0.01), self.running_cb) self.js_sub = rospy.Subscriber('/omni1_joint_states', JointState, self.js_cb) self.ref_pose_pub = rospy.Publisher('ref_pose', Pose, queue_size=3) self.integrate_and_pub_timer = rospy.Timer( rospy.Duration(1 / float(FREQUENCY)), self.timer_cb) self.listen = tf.TransformListener() return
def run(self): frame = 0 t = time.time() frame_time = 1 / self.framerate kb = kbhit.KBHit() print('Move with WASD') game_start = time.time() while self.running: # self.draw_grid() self.frame += 1 start_time = time.time() if self.player.cooldown > 0: self.player.cooldown -= 1 if kb.kbhit(): c = kb.getch() if ord(c) == 27: # ESC break if self.player.cooldown <= 0: self.player.process_command(c) for enemy in self.enemies: enemy.act(self.frame) for weapon in self.weapons: weapon.act(self.frame) wait_time = max([0, frame_time - (time.time() - start_time)]) time.sleep(frame_time) print("Game Over!") kb.set_normal_term()
def __init__(self, HOST, PORT): self.HOST = HOST self.PORT = PORT self.kb = kbhit.KBHit() self.thread_s = threading.Thread(target=self.ClientSend, ) self.thread_a = threading.Thread(target=self.ClientAccept, ) self.body = [] self.food = [] self.Graphic = GraphicGUI()
def main(): # abrimos wav y recogemos frecMuestreo y array de datos CHUNK = 1024 # tamanio del buffer data = lab2.osc(1000, 10) # miramos formato de samples if data.dtype.name == 'int16': fmt = 2 elif data.dtype.name == 'int32': fmt = 4 elif data.dtype.name == 'float32': fmt = 4 elif data.dtype.name == 'uint8': fmt = 1 else: raise Exception('Not supported') p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, # formato de los samples channels=len(data.shape), # num canales (shape de data) rate=lab2.SRATE, # frecuencia de muestreo frames_per_buffer=CHUNK, # tamanio buffer output=True) # stream de salida # En data tenemos el wav completo, ahora procesamos por bloques (chunks) numBloque = 0 kb = kbhit.KBHit() c= ' ' vol = 1.0 volIncr = 0.05 frec = 500 maxfrec = 2000 frecIncr = 5 bloque = lab2.generateChunk(frec, CHUNK, 0) while c!= 'q': c = ' ' # nuevo bloque #bloque = data[ numBloque*CHUNK : numBloque*CHUNK+CHUNK ] bloque = lab2.generateChunk(frec, CHUNK, bloque[-1]) # modificación del volumen: multiplicacion de todas las muestras * vol bloque = bloque*vol #pasamos al stream haciendo conversion de tipo stream.write(bloque.astype(np.float32).tobytes()) if kb.kbhit(): c = kb.getch() if (c=='v'): vol= max(0,vol-volIncr) elif (c=='V'): vol= min(1,vol+volIncr) elif (c=='f'): frec= max(1/maxfrec,frec-frecIncr) elif (c=='F'): frec= min(maxfrec,frec+frecIncr) print("Vol: ",vol) print("Frec: ",frec) numBloque += 1 kb.set_normal_term() stream.stop_stream() stream.close() p.terminate()
def escala(): tecla = kb.KBHit().getch() frec = wf.getframerate() ok = False i = 0 if tecla == 'z': ok = True elif tecla == 'x': ok = True frec = frec * np.power(2, float(2 / 12)) elif tecla == 'c': ok = True while i < 2: frec = frec * np.power(2, float(2 / 12)) i = i + 1 elif tecla == 'v': ok = True while i < 2: frec = frec * np.power(2, float(2 / 12)) i = i + 1 frec = frec * np.power(2, float(1 / 12)) elif tecla == 'b': ok = True while i < 3: frec = frec * np.power(2, float(2 / 12)) i = i + 1 frec = frec * np.power(2, float(1 / 12)) elif tecla == 'n': ok = True while i < 3: frec = frec * np.power(2, float(2 / 12)) i = i + 1 frec = frec * np.power(2, float(1 / 12)) frec = frec * np.power(2, float(2 / 12)) elif tecla == 'm': ok = True while i < 3: frec = frec * np.power(2, float(2 / 12)) i = i + 1 frec = frec * np.power(2, float(1 / 12)) i = 0 while i < 2: frec = frec * np.power(2, float(2 / 12)) i = i + 1 if ok: stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=int(frec), output=True) stream.write(data) else: if tecla != 'q': print("Las teclas son: z.x.c.v.b.n.m")
def _get_keyboard_verify_code(self): print('验证码: ', end='', flush=True) kb = kbhit.KBHit() code = '' while not self.done: if kb.kbhit(): c = kb.getch() code += c print(c, end='', flush=True) if c == '\n': break return code
def game_play(): """ This function collects characters from the keyboard and send them to the server """ kb = kbhit.KBHit() while time.time() < end_time: try: if kb.kbhit(): kb.__init__() s.send(b'.') print('.', end='') except: break
def __init__(self): rospy.loginfo("Creating BallWatcher class") self.print_help() self.objDetector = Obj3DDetector() # flags and vars # for ball dropping position self.kinect_calibrate_flag = False self.running_flag = False self.start_calc_flag = False self.ball_marker = sawyer_mk.MarkerDrawer("/base", "ball", 500) self.drop_point = Point() self.drop_point_arr = [] # self.pos_rec_list = np.array([]) self.pos_xyzt = np.array([]) self.drop_point_marker = sawyer_mk.MarkerDrawer( "/base", "dropping_ball", 500) self.ik_cont = IKController() self.robot = URDF.from_parameter_server() self.kin = KDLKinematics(self.robot, BASE, EE_FRAME) self.limb_interface = intera_interface.Limb() self.pos_rec = [ PointStamped() for i in range(2) ] # array 1x2 with each cell storing a PointStamped with cartesian position of the ball in the past two frames self.old_pos_rec = [PointStamped() for i in range(2)] self.last_tf_time = rospy.Time() self.tf_listener = tf.TransformListener() self.tf_bc = tf.TransformBroadcaster() self.tf_listener.waitForTransform("base", "camera_link", rospy.Time(), rospy.Duration(0.5)) self.T_sc_p, self.T_sc_q = self.tf_listener.lookupTransform( "base", "camera_link", rospy.Time()) self.T_sc = tr.euler_matrix(*tr.euler_from_quaternion(self.T_sc_q)) self.T_sc[0:3, -1] = self.T_sc_p self.t_min = 0 # kbhit instance self.kb = kbhit.KBHit() rospy.on_shutdown(self.kb.set_normal_term) # publishers and timers self.kb_timer = rospy.Timer(rospy.Duration(0.1), self.keycb) self.tf_timer = rospy.Timer(rospy.Duration(0.01), self.tf_update_cb) self.final_x_total = 0 self.final_y_total = 0 self.init_guess = np.array([])
def __init__(self): # create all publishers and subscribers: self.cmd_pub = rospy.Publisher("cmd_vel", Twist, queue_size=1) self.raw_sub = rospy.Subscriber("cmd_vel_raw", Twist, self.callback, queue_size=10) self.kb_timer = rospy.Timer(rospy.Duration(0.01), self.keycb) self.kb = kbhit.KBHit() rospy.on_shutdown(self.kb.set_normal_term) #the flag which tells if to publish "cmd_vel" self.publish_cmd_vel = 1 self.arm_client = actionlib.SimpleActionClient('arm_1/arm_controller/follow_joint_trajectory', FollowJointTrajectoryAction) return
def main(): srate, data = wavfile.read('piano.wav') global SRATE global canPress SRATE = srate # miramos formato de samples if data.dtype.name == 'int16': fmt = 2 elif data.dtype.name == 'int32': fmt = 4 elif data.dtype.name == 'float32': fmt = 4 elif data.dtype.name == 'uint8': fmt = 1 else: raise Exception('Not supported') p = pyaudio.PyAudio() stream = p.open( format=p.get_format_from_width(fmt), # formato de los samples channels=len(data.shape), # num canales (shape de data) rate=SRATE, # frecuencia de muestreo frames_per_buffer=CHUNK, # tamanio buffer output=True) # En data tenemos el wav completo, ahora procesamos por bloques (chunks) bloque = np.arange(CHUNK, dtype=data.dtype) numBloque = data.shape[0] kb = kbhit.KBHit() c = ' ' while True: # nuevo bloque bloque = data[numBloque * CHUNK:numBloque * CHUNK + CHUNK] # pasamos al stream haciendo conversion de tipo if kb.kbhit() & canPress: c = kb.getch() canPress = False numBloque = 0 numBloque, block = keyboard_Proc(c, bloque, numBloque, kb) stream.write(block.astype((data.dtype)).tobytes()) numBloque += 1 kb.set_normal_term() stream.stop_stream() stream.close() p.terminate()
def control(head): directions = {'w': 'up', 's': 'down', 'a': 'left', 'd': 'right'} keys = {v: k for k, v in directions.items()} illegal_key = {'w': 's', 's': 'w', 'a': 'd', 'd': 'a'} kb = kbh.KBHit() while True: if kb.kbhit(): c = kb.getch() if ord(c) == 27: break legal = directions.copy() del legal[illegal_key[keys[head.state]]] try: head.state = legal[c] except: pass kb.set_normal_term()
def run(self): self.print_screen() kb = kbhit.KBHit() while self.running: if kb.kbhit(): c = kb.getch() if c == "q": # Hit `q` to break out of the loop self.running = False self.process_command(c) self.print_screen() kb.set_normal_term() # Reset terminal to normal
def __init__(self): rospy.loginfo("Creating HandControl class") # Instatiating objects self.kb = kbhit.KBHit() rospy.on_shutdown(self.kb.set_normal_term) self.rh = baxter_interface.Gripper("right") rospy.sleep(1.0) self.run_state = ON # Always on self.gripper_state = OPEN self.gripper_state = CLOSED # Subscribers self.run_flag_sub = rospy.Subscriber('/run_status', Bool, self.run_cb) self.omni_white_sub = rospy.Subscriber('omni1_button', PhantomButtonEvent, self.omni_white_cb, queue_size=1) return
def __init__(self): rospy.loginfo("Creating ReferencePublisher class") # create flags self.pub_flag = False self.controller_flag = False self.cube_flag = False self.area_flag = False self.home_flag = False self.area_test_flag = False # get params: self.get_and_set_params() # kbhit instance self.kb = kbhit.KBHit() rospy.on_shutdown(self.kb.set_normal_term) # create publisher and timers: self.ref_pub = rospy.Publisher("ref_pose", PoseStamped, queue_size=3) self.joints_pub = rospy.Publisher("joint_states", JointState, queue_size=3) self.br = tf.TransformBroadcaster() self.pub_timer = rospy.Timer(rospy.Duration(self.dt), self.pubtimercb) self.base_time = rospy.Time.now() self.kb_timer = rospy.Timer(rospy.Duration(0.1), self.keycb) # create miscelleneous self.area_test_count = 0 self.stopwatch_temp = self.stopwatch(0, 0) self.past_time_array = [0.] * 8 # create service clients rospy.wait_for_service("reset") self.reset_client = rospy.ServiceProxy("reset", Empty) rospy.wait_for_service("random") self.random_client = rospy.ServiceProxy("random", Empty) rospy.wait_for_service("toggle_controller") self.toggle_controller_client = rospy.ServiceProxy( "toggle_controller", SetBool) self.print_help() return
def runCLI(self): self.__consoleLogger.info(( "Press '%s' to start the program.\n" + "Press '%s' to exit the program.\n" + "Press '%s' to pause the program (while still receiving data).\n" + "Press ''%s to resume the program (to continue processing inpit).") % (CONST.START_C, CONST.CLOSE_C, CONST.PAUSE_C, CONST.RESUME_C)) self.__consoleLogger.info('Logs are written in file ' + self.__infoLog + ' and file ' + self.__errLog) kb = kbhit.KBHit() try: while True: try: if not kb.kbhit(): continue ch = kb.getch() if ch == CONST.START_C: self.__startCLI() continue if ch == CONST.CLOSE_C: break if ch == CONST.PAUSE_C: self.__pendCLI() continue if ch == CONST.RESUME_C: self.__resumeCLI() continue except KeyboardInterrupt: self.__consoleLogger.warning('Ctrl-C press, exiting...') self.__fileLogger.warning('Ctrl-C press caught.') break except Exception as e: self.__consoleLogger.error('Exception caught, stop running.') self.__fileLogger.error(e) _, _, tb = sys.exc_info() traceback.print_tb(tb) finally: kb.set_normal_term() self.__stopCLI() return None
def input_async(timeout, echo=True): kb = kbhit.KBHit() ret = "" elapsed = 0 while True: if kb.kbhit(): c = kb.getch().capitalize() ret += c if echo == True: print_part(c) if c == CR: break else: time.sleep(0.1) elapsed += 0.1 if elapsed > timeout: break return ret
def main(): global dash dash = robot(getRobotDevice()) kb = kbhit.KBHit() STOP = 0 FORWARD = 1 BACKWARD = 2 LEFT = 3 RIGHT = 4 k_in = '' status = STOP idle = 0 while (k_in != 'x'): print("Key not pressed") # Do something if kb.kbhit(): # If a key is pressed: k_in = kb.getch() # Detect what key was pressed print("You pressed ", k_in, "!") # Do something kb.set_normal_term() dash.disconnect()
def __init__(self): rospy.loginfo("Creating KeyboardController Class") # flag self.start_flag = False # create broadcaster and listener self.br = tf.TransformBroadcaster() self.ln = tf.TransformListener() # kbhit instance self.kb = kbhit.KBHit() self.print_help() # initialize start point of Pepper self.p = (0, 0, 0) self.q = tr.quaternion_from_euler(0, 0, 0, 'sxyz') # call rospy.Timer(rospy.Duration(0.3), self.keyboard_cb) rospy.Timer(rospy.Duration(0.1), self.sendTF_cb) return
def run(self): kb = kbhit.KBHit() print('Starting monitor, press q to exit') self.bar.update(self.parts_recieved) while True: if not self.in_queue.empty(): message = self.in_queue.get() if message['msg'] == 'PARTS': self.parts_recieved += 1 self.bar.update(message['parts']) if message['msg'] == 'END': break else: if kb.kbhit(): c = kb.getch() if c is 'q': # Press q to exit print('q pressed') self.out_queue.put({'msg': 'CLOSE'}) self.bar.finish() logging.info('MONITOR: Returning') return #break time.sleep(0.1)
def __init__(self): self.marker_id = rospy.get_param("~marker_id", 12) self.frame_id = rospy.get_param("~frame_id", "odom_meas") self.camera_frame_id = rospy.get_param("~camera_frame_id", "overhead_cam_frame") self.count = rospy.get_param("~count", 50) # local vars: self.calibrate_flag = False self.calibrated = False self.calibrate_count = 0 self.kb = kbhit.KBHit() self.trans_arr = np.zeros((self.count, 3)) self.quat_arr = np.zeros((self.count, 4)) self.trans_ave = np.zeros(3) self.quat_ave = np.zeros(3) # now create subscribers, timers, and publishers self.br = tf.TransformBroadcaster() self.kb_timer = rospy.Timer(rospy.Duration(0.1), self.keycb) rospy.on_shutdown(self.kb.set_normal_term) self.alvar_sub = rospy.Subscriber("ar_pose_marker", AlvarMarkers, self.alvarcb) return
def galvoHiLoScan(focus, offset, stripewidth, duration, focusChannel="Dev1/ao0", scanChannel="Dev1/ao1"): """Function that will scan the laser through the field of view, discontinuously jumping at certain intervals in order to make excitation stripes. This could be used the do structured illumination with the IR laser, which lacks a Pockels cell for intensity modulation. At the moment, the visible galvo takes 0.45V (0.9V with IR lens) to traverse the field of view. """ analog_output = pydaq.Task() analog_output.CreateAOVoltageChan(focusChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) analog_output.CreateAOVoltageChan(scanChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) #scan = np.linspace(-0.600, 0.600, samples) + offset temp = np.arange(0,75) temp = np.repeat(temp, np.floor(2048/75)) y = np.linspace(0,1,len(temp)) scan = (y+temp/75.)/2.*1.2 - 0.6 + offset focus = focus*np.ones(len(scan)) """.""" samples = len(y) samplingRate = float(samples)/duration analog_output.CfgSampClkTiming(None, samplingRate, pydaq.DAQmx_Val_Rising, pydaq.DAQmx_Val_ContSamps, samples) """Since the analog out write function has an ouput that is the actual number of samples per channel successfully written to the buffer, create a variable to store those values: """ temp = (pydaq.c_byte*4)() actualWritten = pydaq.cast(temp, pydaq.POINTER(pydaq.c_long)) if (focusChannel == "Dev1/ao0"): writeData = np.concatenate((focus, scan),1) else: writeData = np.concatenate((scan, focus),1) analog_output.WriteAnalogF64(samples, True, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) kb = kbhit.KBHit() while(True): if kb.kbhit(): try: k_in = kb.getarrow() analog_output.StopTask() if (k_in == 1): focus = focus + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 3): focus = focus - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 0): scan = scan + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 2): scan = scan - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) else: derp = "derr" writeData = np.concatenate((focus, scan),1) analog_output.WriteAnalogF64(samples, False, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) analog_output.StartTask() #print(k_in, k_in==1) #I currently can't figure out how to exit gracefully, this exception doesn't allow the function to be called again, as the task is still reserved (?) # except KeyboardInterrupt: # print("caught a keyboard interrupt!") except: Exit = raw_input("Want to exit?") if (Exit == 'y'): analog_output.StopTask() analog_output.ClearTask() return [np.median(scan), focus[0]] #sys.exit(0) else: analog_output.StopTask() return
angleErrPrev = 0 angleCmd = 0 positionErrPrev = 0 positionCmd = 0 controlEnabled = False danceEnabled = False danceAmpl = 500 dancePeriodS = 8 loggingEnabled = False kbAvailable = True try: kb = kbhit.KBHit( ) # can only use in posix terminal; cannot use from spyder ipython console for example except: kbAvailable = False printparams() help() startTime = time.time() lastTime = startTime lastAngleControlTime = lastTime lastPositionControlTime = lastTime angleErr = 0 positionErr = 0 # for printing even if not controlling p.stream_output(True) # now start streaming state while True: # Adjust Parameters
def ContinuousScan(focus, offset, duration=10., focusChannel="Dev1/ao0", scanChannel="Dev1/ao1"): """Function to continuously scan galvo mirror across field of view, centered on offset voltage and with the focus set by the perpendicular galvo. This function is specific to a National Instruments DAQ card, used to send signals to the mirror galvonometers. This function is useful when the camera is in free-runnung mode for, e.g. sample location, focus adjustment, etc. The main differences between this function and galvoScan are that 1. writing to the DAQ card occurs continuously in a loop and 2. writing starts immediately (there is no waiting for an external trigger). ***To Do: - add error handling with Try/Except Inputs: focus - float, Voltage (in V) used by the off-axis galvo to bring the laser into focus. offset - float, Voltage (in V) that steers the laser through the center of the scan range. duration - float, Time (in ms) that the scan should take to completely sweep the field of view. focusChannel - string, Hardware device and channel that controls the focus galvo, e.g. "Dev1/ao0" scanChannel - string, Hardware device and channel that controls the scan galvo, e.g. "Dev1/ao1" """ duration = duration/1000. analog_output = pydaq.Task() analog_output.CreateAOVoltageChan(focusChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) analog_output.CreateAOVoltageChan(scanChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) """For the time being, I am assuming that the field of view is (over)filled by sweeping through 600 milliVolts. At 40x with the Hamamatsu sCMOS, this should be about 333 microns, so there is a rough correspondence of 1.8mV to 1um. Since the NIR (bessel) beam has a FWHM of about 3um, I will move in 1mV (0.55um) steps, which should appear continuos. This means that the sampling rate should be set to samples/duration (where samples is 600).""" samples = 10000*2 samplingRate = float(samples)/duration analog_output.CfgSampClkTiming(None, samplingRate, pydaq.DAQmx_Val_Rising, pydaq.DAQmx_Val_ContSamps, samples) scan = np.linspace(-0.250, 0.250, samples/2.) + offset """Trace backward for less acceleration on the galvo (pyramid instead of sawtooth): """ scan = np.concatenate((scan,scan[::-1]),0) focus = focus*np.ones(samples) """Since the analog out write function has an ouput that is the actual number of samples per channel successfully written to the buffer, create a variable to store those values: """ temp = (pydaq.c_byte*4)() actualWritten = pydaq.cast(temp, pydaq.POINTER(pydaq.c_long)) if (focusChannel == "Dev1/ao0"): writeData = np.concatenate((focus, scan),1) else: writeData = np.concatenate((scan, focus),1) analog_output.WriteAnalogF64(samples, True, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) kb = kbhit.KBHit() while(True): if kb.kbhit(): try: k_in = kb.getarrow() analog_output.StopTask() if (k_in == 1): focus = focus + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 3): focus = focus - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 0): scan = scan + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[len(scan)/2.], focus[0])) elif (k_in == 2): scan = scan - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[len(scan)/2.], focus[0])) else: derp = "derr" writeData = np.concatenate((focus, scan),1) analog_output.WriteAnalogF64(samples, False, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) analog_output.StartTask() except: Exit = raw_input("Want to exit?") if (Exit == 'y'): analog_output.StopTask() analog_output.ClearTask() return [np.median(scan), focus[0]] else: analog_output.StopTask() return
def NoScanFocus(focus, offset, focusChannel="Dev1/ao0", scanChannel="Dev1/ao1"): """Function to hold scan galvo mirror in middle of field of view (at offset voltage) and with the initial focus set by the perpendicular galvo. This function is specific to a National Instruments DAQ card, used to send signals to the mirror galvonometers. This function is used when the camera is in free-runnung mode for focus adjustment, taking keyboard input to adjust the focus voltage. ***To Do: - add error handling with Try/Except Inputs: focus - float, Voltage (in V) used by the off-axis galvo to bring the laser into focus. offset - float, Voltage (in V) that steers the laser through the center of the scan range. focusChannel - string, Hardware device and channel that controls the focus galvo, e.g. "Dev1/ao0" scanChannel - string, Hardware device and channel that controls the scan galvo, e.g. "Dev1/ao1" """ analog_output = pydaq.Task() analog_output.CreateAOVoltageChan(focusChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) analog_output.CreateAOVoltageChan(scanChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) samples = 1000 samplingRate = 1000. analog_output.CfgSampClkTiming(None, samplingRate, pydaq.DAQmx_Val_Rising, pydaq.DAQmx_Val_ContSamps, samples) scan = offset*np.ones(samples) focus = focus*np.ones(samples) """Since the analog out write function has an ouput that is the actual number of samples per channel successfully written to the buffer, create a variable to store those values: """ temp = (pydaq.c_byte*4)() actualWritten = pydaq.cast(temp, pydaq.POINTER(pydaq.c_long)) """Attempt to assign the correct channels to x and y galvos""" if (focusChannel == "Dev1/ao0"): writeData = np.concatenate((focus, scan),1) else: writeData = np.concatenate((scan, focus),1) analog_output.WriteAnalogF64(samples, False, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) analog_output.StartTask() kb = kbhit.KBHit() while(True): if kb.kbhit(): try: k_in = kb.getarrow() analog_output.StopTask() if (k_in == 1): focus = focus + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 3): focus = focus - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 0): scan = scan + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 2): scan = scan - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) else: derp = "derr" writeData = np.concatenate((focus, scan),1) analog_output.WriteAnalogF64(samples, False, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) analog_output.StartTask() Exit = raw_input("Want to exit?") if (Exit == 'y'): analog_output.StopTask() analog_output.ClearTask() return [scan[0], focus[0]] else: analog_output.StopTask() return
elif command == keyboard.Commands.Command3: print('Command3') emulator.clear_display() else: print('Failed to connect to server, exiting ...') # This is kinda normal - just exit except KeyboardInterrupt as ex: print('Forcing a quit') pass # We got something we really weren't expecting here except Exception as ex: print("\n>>> EXCEPTION : {} <<<\n".format(ex)) log.error(ex, exc_info=True) pass finally: emulator.close() # Flush the keyboard here try: kb = KBHit.KBHit() kb.flush() except: pass # Shut this puppy down destroy_logging() print('Done!')
# generate samples, note conversion to float32 array #data = (np.sin(2 * np.pi * np.arange(SRATE * duration) * frec / SRATE)).astype(np.float32) data = triangle() plt.plot(data) plt.xlabel('time in seconds') plt.ylabel('value') plt.show() # for paFloat32 sample values must be in range [-1.0, 1.0] stream = p.open(format=pyaudio.paFloat32, channels=1, rate=SRATE, output=True) # En data tenemos el wav completo, ahora procesamos por bloques (chunks) #bloque = np.arange(CHUNK,dtype=data.dtype) numBloque = 0 kb = kb.KBHit() c = ' ' while c != 'q': # nuevo bloque # data = (np.sin(2 * np.pi * np.arange(SRATE * duration) * frec / SRATE)).astype(np.float32) data = square() bloque = data[numBloque * CHUNK:numBloque * CHUNK + CHUNK] bloque *= vol # bloque *= frec/SRATE # pasamos al stream haciendo conversion de tipo stream.write(bloque.astype((data.dtype)).tobytes()) if kb.kbhit(): c = kb.getch()
elif data.dtype.name == 'float32': fmt = 4 elif data.dtype.name == 'uint8': fmt = 1 else: raise Exception('Not supported') p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(fmt), channels=len(data.shape), rate=SRATE, frames_per_buffer=CHUNK, output=True) interval = np.array([20000, 40000]) # intervalo del sustain sampler = Sampler( data, interval, notes['DO'] ) # nota de referencia del sample (sin modificar, se identifica como esa nota) kb = kbhit.KBHit() c = ' ' while c != 'q': if kb.kbhit(): c = kb.getch() sampler.handleInput(c) sampler.noteOn() sampler.noteOff() kb.set_normal_term() stream.stop_stream() stream.close() p.terminate()
def aotfModScan(focus, offset, duration, aomV, aomStripeWidth, phase=0, focusChannel="Dev1/ao0", scanChannel="Dev1/ao1", aomChannel="Dev1/ao2"): """Function to scan the visible laser and simultaneously modulate the AOTF in order to perform structured illumination, e.g. for HiLo imaging. Currently, an 'aomStripeWidth' value of 7-10 looks good, but this will likely change as I figure out more appropriate scaling for this galvo. """ duration = duration/1000. analog_output = pydaq.Task() analog_output.CreateAOVoltageChan(focusChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) analog_output.CreateAOVoltageChan(scanChannel, "", -5.0, 5.0, pydaq.DAQmx_Val_Volts, None) analog_output.CreateAOVoltageChan(aomChannel, "", 0., 10.0, pydaq.DAQmx_Val_Volts, None) analog_output.CreateAOVoltageChan("Dev1/ao3", "", 0., 10.0, pydaq.DAQmx_Val_Volts, None) samples = 1000*2 samplingRate = float(samples)/duration # samplingRate = 10000 analog_output.CfgSampClkTiming(None, samplingRate, pydaq.DAQmx_Val_Rising, pydaq.DAQmx_Val_ContSamps, samples) scan = np.linspace(-1.800, 1.800, samples) + offset # scan = np.concatenate((scan,scan[::-1]),0) focus = focus*np.ones(samples) temp = np.concatenate((np.zeros(aomStripeWidth),aomV*np.ones(aomStripeWidth)),0) temp = np.tile(temp, samples/len(temp)) aom = temp[0:samples+1] # aom = np.concatenate((aom, aom[::-1]),0) blank = 10*np.ones(samples) if (phase == 1): aom = np.roll(aom, int(aomStripeWidth/3)) elif (phase == 2): aom = np.roll(aom, int(aomStripeWidth/3*2)) """Since the analog out write function has an ouput that is the actual number of samples per channel successfully written to the buffer, create a variable to store those values: """ temp = (pydaq.c_byte*4)() actualWritten = pydaq.cast(temp, pydaq.POINTER(pydaq.c_long)) if (focusChannel == "Dev1/ao0"): writeData = np.concatenate((focus, scan, aom, blank),1) else: writeData = np.concatenate((scan, focus, aom, blank),1) analog_output.WriteAnalogF64(samples, True, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) kb = kbhit.KBHit() while(True): if kb.kbhit(): try: k_in = kb.getarrow() analog_output.StopTask() if (k_in == 1): focus = focus + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 3): focus = focus - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 0): scan = scan + 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) elif (k_in == 2): scan = scan - 0.001 print('offset = %5.3f, focus = %5.3f' % (scan[0], focus[0])) else: derp = "derr" writeData = np.concatenate((focus, scan, aom, blank),1) analog_output.WriteAnalogF64(samples, False, -1, pydaq.DAQmx_Val_GroupByChannel, writeData, actualWritten, None) analog_output.StartTask() #print(k_in, k_in==1) #I currently can't figure out how to exit gracefully, this exception doesn't allow the function to be called again, as the task is still reserved (?) # except KeyboardInterrupt: # print("caught a keyboard interrupt!") except: Exit = raw_input("Want to exit?") if (Exit == 'y'): analog_output.StopTask() analog_output.ClearTask() return [np.median(scan), focus[0]] #sys.exit(0) else: analog_output.StopTask() return #def spimSideSelect(diSPIMEnable=True): """Function to coordinate the laser source between the ASI diSPIM and home-built setup. Requires one digital input, one user input, and two digital outputs. If the program can exit with the DAQ outputs staying where they are at, then it can be called and allowed to return (This depends on DAQ functionality, which I am unsure about).