def setUp(self): self.s = serial.serial_for_url(PORT, timeout=1) self.io = io.TextIOWrapper( io.BufferedRWPair(io.BufferedRandom(self.s), io.bufferedRandom(self.s)))
def __init__(self, *args, **kwargs): '''Constructs a TextSerial object. Two instances of serial.Serial are used; one for input and the other for output. The constructor can be called either with specifying the keyword argument ser which must then refer to an instance of serial.Serial that will be used for both inputs and outputs, or specifying arguments to be passed to the constructor of serial.Serial for creating an input and and output instance. When the argument ser is not specified, the following arguments will be used to initialize the serial.Serial objects to be created. Args passed to serial.Serial (the first three are commonly used): port (str, int or None): Device name or port number number or None. Defaults to None. baudrate (int): Baud rate such as 9600 or 115200 etc. Defaults to 9600. timeout (float or None): Timeout for reading operations. It defaults to None, indefinite blocking. The value of 0 means non-blocking mode. Unit is in seconds. bytesize (special): Number of data bits. Default value: serial.EIGHTBITS. parity (special): Enable parity checking. Default value: serial.PARITY_NONE. stopbits (special): Number of stop bits. Default value: serial.STOPBITS_ONE. xonxoff (bool): Enable software flow control. Default value: False rtscts (bool): Enable hardware (RTS/CTS) flow control. Default value: False. writeTimeout (float or None): Set a write timeout value. Default value: None. dsrdtr (bool): Enable hardware (DSR/DTR) flow control. Default value: False. interCharTimeout (float): Inter-character timeout, None to disable. Default value: None. See http://pyserial.sourceforge.net/pyserial_api.html for extra information on these arguments Other args: encoding (str): The text encoding to be used. Defaults to 'ascii'. errors (str): How encoding and decoding errors should be handled. For details see the documentation of TextIOWrapper. Defaults to None. newline (str, or None): Controls how line endings are handled. For details see the documentation of TextIOWrapper; e.g., https://docs.python.org/3/library/io.html#io.TextIOWrapper Defaults to None (universal newline mode). line_buffering (bool): Whether upon seeing '\n' in the output, the stream will be flushed. If this is set to False, it is the user's responsibility to call flush to make sure that the data is actually sent to the receiver. Defaults to True. write_through (bool): if True, calls to write() are guaranteed not to be buffered. Defaults to False. Only in Python 3.3 or newer. ser (Serial): The serial object to be used, for both input and output. This will work properly only with some serial objects, such as the loop back object. This is meant mainly for testing purposes. Raises: ValueError: Will be raised when parameter are out of range, e.g. baud rate, data bits. SerialException: In case the device can not be found or can not be configured. ''' # We initialize two Serial objects; one for the input, another # for the output. We need two objects, as upon the destruction # of this object, BufferedRWPair will attempt to close both # the reader and the writer, leading to an exception. # # The documentation of BufferedRWPair at # https://docs.python.org/3/library/io.html#io.BufferedRWPair # mentions that one should not pass the same object to it both # as a reader and writer, but the suggestion there to use # BufferedRandom won't work for us as our stream (serial) # is non-seekable. Hence, we are forced to open the serial port # twice. # def getkwarg(parname, defval, kwargs): v = defval if parname in kwargs: v = kwargs[parname] del kwargs[parname] return v # get and remove TextIOWrapper specific arguments; # luckily for us these do not overlap with any of the serial arguments encoding = getkwarg('encoding', 'ascii', kwargs) errors = getkwarg('errors', None, kwargs) newline = getkwarg('newline', None, kwargs) line_buffering = getkwarg('line_buffering', True, kwargs) write_through = getkwarg('write_through', False, kwargs) if 'ser' in kwargs: self.ser_in = self.ser_out = kwargs.get('ser') else: self.ser_in = serial.Serial(*args, **kwargs) self.ser_out = serial.Serial(*args, **kwargs) # note: a try/catch won't work here, as a failing __init__ # is kinda fatal, it will put the object into a failed # state and I don't know how to recover it from that state # otherwise I would prefer try/catch # note 2: We need to set BufferedRWPair's buffer size to 1; # BufferedRWPair forwards the read call to BuferredReader's # read function, which expects the # underlying stream to return None or b"" when there # is no more data available, rather than to block. # However, as of pyserial 2.7, Serial.read() blocks. # What would be needed is a non-blocking version of Serial. # This can be achieved by setting the timeout to zero on Serial, # but this kinda defeats the purpose of having nonzero timeouts. # Hence, we turn off buffering. if sys.version_info.major >= 3 and sys.version_info.minor >= 3: # This works in Python 3.3 and newer super().__init__(io.BufferedRWPair(self.ser_in, self.ser_out, 1), encoding=encoding, errors=errors, newline=newline, line_buffering=line_buffering, write_through=write_through) else: # no write_through in earlier pythons super().__init__(io.BufferedRWPair(self.ser_in, self.ser_out, 1), encoding=encoding, errors=errors, newline=newline, line_buffering=line_buffering) # Explanation of the next line: # TextIOWrapper reads data in chunks, and NOT ONLY THROUGH # BufferedRWPair's buffering interface, but it has its own chunk-based # processing. When the sender did not send data with size>=chunk size, # processing will block indefinitely (or as long as the timeout is). # The solution suggested here is to reset the chunk size to 1. # The cons is that maybe data processing will not be the most # efficient, as data is obtained one byte at time. # Adding a timeout kind-of defeats the purpose of timeouts; # without changing the chunk size, the wrapper will always wait # until the timeout expires! This totally defeats the purpose of # timeouts (again). self._CHUNK_SIZE = 1
#sets control pins for serial port expander GPIO.setmode(GPIO.BCM) S0_pin = 18 S1_pin = 23 GPIO.setup(S0_pin, GPIO.OUT) GPIO.setup(S1_pin, GPIO.OUT) #switches to temperature sensor (y3) GPIO.output(S0_pin, 1) GPIO.output(S1_pin, 1) sio = io.TextIOWrapper(io.BufferedRWPair(ser,ser,1), newline = "\r") ser.write("R\r") #reads temperature value temp = sio.readline() #print(temp) ser.close() GPIO.cleanup() #closes old connetion #--------------------END Temperature---------------------- #-------------------pH Start--------------------------- usbport = '/dev/ttyAMA0'
def __init__(self, parent=None): super(self.__class__, self).__init__(parent) # connect to the TIC through serial port # ll /sys/class/tty/ttyUSB* to check port number try: self.ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=.5) self.sio = io.TextIOWrapper(io.BufferedRWPair(self.ser, self.ser)) printInfo('Connected to TIC Controller') except: printError('Could not connect to TIC Controller') # connect to the NEXTorr controller through serial port try: self.serIon = serial.Serial(port='/dev/ttyUSB1', baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=.5) self.sioIon = io.TextIOWrapper( io.BufferedRWPair(self.serIon, self.serIon)) printInfo('Connected to NEXTorr Power Supply') except: printError('Could not connect to NEXTorr Power Supply') # list of TIC commands - consist of preceding identifier, message type, object ID, space, data, cr self.turbo_on = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.TURBO_PUMP, self.SEPARATOR, self.ON, self.TERMINAL ]) self.turbo_off = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.TURBO_PUMP, self.SEPARATOR, self.OFF, self.TERMINAL ]) self.turbo_check = "".join([ self.PRECEDING_QUERY, self.TYPE_VALUE, self.TURBO_PUMP, self.TERMINAL ]) self.backing_on = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.BACKING_PUMP, self.SEPARATOR, self.ON, self.TERMINAL ]) self.backing_off = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.BACKING_PUMP, self.SEPARATOR, self.OFF, self.TERMINAL ]) self.backing_check = "".join([ self.PRECEDING_QUERY, self.TYPE_VALUE, self.BACKING_PUMP, self.TERMINAL ]) self.gauge_read = "".join([ self.PRECEDING_QUERY, self.TYPE_VALUE, self.GAUGE_1, self.TERMINAL ]) # instance of graphing window class self.graph_window = SecondUiClass() self.plotting = True # pressure holder self.pressure_reading = 0 self.ion_pressure_reading = 0
def __init__(self, model, address, syringe_type={}, ser=None, bus=None): self.pump_models = {'names': ['NE-1000', 'DIY', 'Chemyx', 'HA-PHD-Ultra']} self.address = address #Adress for the pump self.model = model #model self.syringe_type = syringe_type self.ser = ser #serial object self.bus = bus #i2c bus object #Validation if self.model not in self.pump_models['names']: raise ValueError('Please choose one of the listed pumps'+ json.dumps(self.pump_models,indent=2)) if self.model == 'NE-1000' and self.ser is None: raise ValueError('Serial object must be provided for communication with the NE-1000.') if self.model == 'DIY' and self.bus is None: raise ValueError('i2C bus must be provided for communication with the DIY pump.') if self.model == 'Chemyx' and self.ser is None: raise ValueError('Serial object must be provided for communication with the NE-1000.') if self.model == 'HA-PHD-Ultra' and self.ser is None: raise ValueError('Serial object must be provided for communication with Harvard Apparatus PHD Ultra') #Internal variables self.sio = io.TextIOWrapper(io.BufferedRWPair(self.ser, self.ser)) self.rate = {'value': None,'units': None} self.direction = None #INF for infuse or WDR for withdraw self.sleep_time = 0.1 try: #rate limits in microliters/hr self.rate_limits = self.syringe_type['rate_limits'] self.diameter = self.syringe_type['diameter'] #Volume in mL if self.syringe_type['volume'][1] != 'ml': raise ValueError("Volume must be in ml") self.volume = self.syringe_type['volume'][0] except KeyError: self.rate_limits = {} self.diameter = None self.volume = None if self.model == 'Chemyx': raise ValueError("Please pass diameter, volume and rate limits array in syringe_type") else: pass #Set up pumps using serial if self.model == 'NE-1000': #Set NE-1000 continuous pumping (i.e., 0 volume to dispense) serial_write(self.ser, construct_cmd("VOL0\x0D", self.address), "setup continuous pumping") time.sleep(0.5) self.ser.flush() if self.model == 'Chemyx': #Check pump address by units (i.e., I'm setting pump_1 units to 1 and pump_2 units to 2) response = sio_write(self.sio, "view parameter\x0D", True, timeout =5) try: match2 = re.search(r'(?<=unit = )\d', response, re.M) unit_number = match2.group(0) except Exception: raise IOError("Wrong pump address") #raise IOError("Wrong pump address") if int(unit_number) != int(address): raise IOError("Wrong pump address") if self.diameter is not None: cmd = 'set diameter %0.3f\x0D'%(self.diameter) diameter = serial_write(self.ser, cmd, "set_diameter", True) self.ser.flush() #Set up PHD Ultra if self.model == 'HA-PHD-Ultra': #Set the syringe type try: #Check that it's plugged into this port #and the right type of commands are being used # for i in range(3): self.ser.flush() # response = sio_write(self.sio, "CMD", True, timeout=5) # match = re.search(r'(Ultra)', response, re.M) # if match is None: # status_text = "Pump not set to Ultra command set" # raise IOError(status_text) cmd = "syrm {} {} {}\x0D".format( syringe_type["code"], syringe_type['volume'][0], syringe_type['volume'][1] ) for i in range(3): self.ser.flush() sio_write(self.sio, cmd, False, timeout=1) time.sleep(0.1) #Check back on that the manfacturer was set correctly for i in range(3): self.ser.flush() output = sio_write(self.sio, "syrm\x0D", True, timeout = 2) logging.debug("Output from setting syringe manufacture: {}".format(output)) except ValueError as e: logging.debug(e)
def connect(self, port, baudrate, item_to_device, init_finished_string): """ connect to serial port to talk to machine :param port: descriptive name of the serial port :param baudrate: :param item_to_device: dictionary from descriptive name of serial devices to OS name of serial devices :param init_finished_string: string to wait for to indicate machine is initialized :return: """ if port == "": return if port == "Not connected": self.close() return if port in item_to_device: device = item_to_device[port] self.serial = serial_for_url(device) self.close() self.serial.port = device self.serial.timeout = TIMEOUT self.serial.baudrate = baudrate try: self.serial.open() sleep(SETTLING_TIME) # sleep a while before accessing the port if self.serial.isOpen(): self.serial_is_open = True self.on_open_port.emit() self.enabledisable_send_controls.emit(True) self.log.emit( "[Server] Serial port {0} opened successfully.{1}Waiting for initialization to complete.{1}" .format(port, linesep)) started = False while not started: sleep(0.1) readval = b'' while self.serial.inWaiting() > 0: readval += self.serial.read(1) if readval: # print(readval) reply = str(readval, "utf-8").splitlines() for r in reply: self.log.emit("[Server] > {0}{1}".format( r, linesep)) if init_finished_string in r: started = True self.sio = io.TextIOWrapper( io.BufferedRWPair(self.serial, self.serial, 1)) self.on_connected.emit(True) else: self.log.emit( "[Server] Error opening serial port. Unknown reason.") except SerialException as e: self.serial_is_open = False self.on_connected.emit(False) self.enabledisable_send_controls(False) self.log.emit("[Server] Error opening serial port: {0}".format( e.strerror)) else: print("[Server] port = '{0}' not present in {1}".format( port, item_to_device.keys()))
def sensordata(outfile): port = "/dev/ttyS0" #serial port baudrate = 9600 #baud number dir_data = '/home/pi/data/' #output data directory #open the serial board of the instrument ser =serial.Serial() #configure port timeout refers to the data rate ser.port = port ser.baudrate = baudrate ser.parity = serial.PARITY_NONE ser.stopbits = serial.STOPBITS_ONE ser.bytesize = serial.EIGHTBITS ser.timeout = 60 #checking to see if the file is open or not. As it may over write or not save. if ser.isOpen(): ser.close() ser.open() ser.isOpen() #get and write the data #example of data string SWS100,001,060,05.14 KM,99.999,04,+99.9 C,05.19 KM,XOO sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), encoding='ascii') sio._CHUNK_SIZE =1 while ser.isOpen(): #get datetime datestring = datetime.utcnow().isoformat() #print(type(datestring)) datastring = sio.readline() #print(datastring) #print(type(datastring)) datastring.strip('\r') print(datestring+ ',' + datastring) data = (datestring+ ',' + datastring) #check for new day dt = time.strptime(datestring,'%Y-%m-%dT%H:%M:%S.%f') start_day = dt[2] now_day = dt[2]; if now_day != start_day: start_day = now_day yy = str(dt[0]) mm = str(dt[1]) if len(mm) < 2: mm = '0' + mm dd = str(dt[2]) if len(dd) < 2: dd = '0' + dd names = 'ncas-pws-1_' + yy + mm + dd + '.txt' outfile = os.path.join(dirpath, names) f = open(outfile,'a') f.write(data) f.close()
class Robot: global x_p global c rospy.init_node('omoros', anonymous=True) # fetch /global parameters param_port = rospy.get_param('~port') param_baud = rospy.get_param('~baud') param_modelName = rospy.get_param('~modelName') # Open Serial port with parameter settings ser = serial.Serial(param_port, param_baud) #ser = serial.Serial('/dev/ttyS0', 115200) #For raspberryPi ser_io = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), newline='\r', line_buffering=True) config = VehicleConfig() pose = MyPose() goal_1 = MyGoal_1() goal_2 = MyGoal_2() joyAxes = [] joyButtons = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Buttons 15 joyDeadband = 0.15 exp = 0.3 # Joystick expo setting isAutoMode = True isArrowMode = False # Whether to control robo with arrow key or not arrowCon = ArrowCon #initialize data cmd = Command enc_L = 0.0 # Left wheel encoder count from QENCOD message enc_R = 0.0 # Right wheel encoder count from QENCOD message enc_L_prev = 0.0 enc_R_prev = 0.0 enc_offset_L = 0.0 enc_offset_R = 0.0 enc_cnt = 0 odo_L = 0.0 # Left Wheel odometry returned from QODO message odo_R = 0.0 # Right Wheel odometry returned from QODO message RPM_L = 0.0 # Left Wheel RPM returned from QRPM message RPM_R = 0.0 # Right Wheel RPM returned from QRPM message speedL = 0.0 # Left Wheel speed returned from QDIFF message speedR = 0.0 # Reft Wheel speed returned from QDIFF message vel = 0.0 # Velocity returned from CVW command rot = 0.0 # Rotational speed returned from CVR command def __init__(self): ## Set vehicle specific configurations if self.param_modelName == "r1": print "**********" print "Driving R1" print "**********" self.config.WIDTH = 0.591 # Apply vehicle width for R1 version self.config.WHEEL_R = 0.11 # Apply wheel radius for R1 version self.config.WHEEL_MAXV = 1200.0 # Maximum speed can be applied to each wheel (mm/s) self.config.V_Limit = 0.6 # Limited speed (m/s) self.config.W_Limit = 0.1 self.config.V_Limit_JOY = 0.25 # Limited speed for joystick control self.config.W_Limit_JOY = 0.05 self.config.ArrowFwdStep = 250 # Steps move forward based on Odometry self.config.ArrowRotRate = 0.125 self.config.encoder.Dir = 1.0 self.config.encoder.PPR = 1000 self.config.encoder.GearRatio = 15 elif self.param_modelName == "mini": print "***************" print "Driving R1-mini" print "***************" self.config.WIDTH = 0.170 # Apply vehicle width for mini version self.config.WHEEL_R = 0.0336 # Apply wheel radius for mini version self.config.WHEEL_MAXV = 500.0 self.config.V_Limit = 0.5 self.config.W_Limit = 0.2 self.config.V_Limit_JOY = 0.5 self.config.W_Limit_JOY = 0.1 self.config.ArrowFwdStep = 100 self.config.ArrowRotRate = 0.1 self.config.encoder.Dir = -1.0 self.config.encoder.PPR = 234 self.config.encoder.GearRatio = 21 else: print "Error: param:modelName, Only support r1 and mini. exit..." exit() print('Wheel Track:{:.2f}m, Radius:{:.2f}m'.format( self.config.WIDTH, self.config.WHEEL_R)) self.config.BodyCircumference = self.config.WIDTH * math.pi print('Platform Rotation arc length: {:04f}m'.format( self.config.BodyCircumference)) self.config.WheelCircumference = self.config.WHEEL_R * 2 * math.pi print('Wheel circumference: {:04f}m'.format( self.config.WheelCircumference)) self.config.encoder.Step = self.config.WheelCircumference / ( self.config.encoder.PPR * self.config.encoder.GearRatio * 4) print('Encoder step: {:04f}m/pulse'.format(self.config.encoder.Step)) print(self.ser.name) # Print which port was really used self.joyAxes = [0, 0, 0, 0, 0, 0, 0, 0] self.joyButtons = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Configure data output if self.ser.isOpen(): print("Serial Open") self.resetODO() sleep(0.05) self.reset_odometry() self.setREGI(0, 'QENCOD') sleep(0.05) self.setREGI(1, 'QODO') sleep(0.05) self.setREGI(2, 'QDIFFV') sleep(0.05) self.setREGI(3, '0') sleep(0.05) self.setREGI(4, '0') #self.setREGI(3,'QVW') #sleep(0.05) #self.setREGI(4,'QRPM') sleep(0.05) self.setSPERI(20) sleep(0.05) self.setPEEN(1) sleep(0.05) self.reset_odometry() # Subscriber rospy.Subscriber("joy", Joy, self.callbackJoy) rospy.Subscriber('/scan', LaserScan, self.callback) rospy.Subscriber("cmd_vel", Twist, self.callbackCmdVel) # publisher self.pub_enc_l = rospy.Publisher('motor/encoder/left', Float64, queue_size=10) self.pub_enc_r = rospy.Publisher('motor/encoder/right', Float64, queue_size=10) self.pub_motor_status = rospy.Publisher('motor/status', R1MotorStatusLR, queue_size=10) self.odom_pub = rospy.Publisher("odom", Odometry, queue_size=10) self.odom_broadcaster = TransformBroadcaster() rate = rospy.Rate(rospy.get_param('~hz', 30)) # 30hz rospy.Timer(rospy.Duration(0.05), self.joytimer) rospy.Timer(rospy.Duration(0.01), self.serReader) #rospy.Timer(rospy.Duration(0.05), self.callback) self.pose.timestamp = rospy.Time.now() while not rospy.is_shutdown(): if self.cmd.isAlive == True: self.cmd.cnt += 1 if self.cmd.cnt > 1000: #Wait for about 3 seconds self.cmd.isAlive = False self.isAutoMode = False rate.sleep() self.ser.close() def callback(self, msg): global x_p s0 = 0 s1 = 0 s2 = 0 s2 = numpy.mean(msg.ranges[0:24]) s1 = numpy.mean(msg.ranges[108:132]) s0 = numpy.mean(msg.ranges[216:240]) #print('=========================================') #print(s0)#left #print(s1) #print(s2)#right #print(msg.ranges) if abs(x_p) < 1: if (s0 < 0.5) or (s1 < 0.5) or (s2 < 0.5): a = 0 b = 0 elif (s1 > 0.5): a = 50 b = 50 else: a = 0 b = 0 else: a = 0 b = 0 cmd = '$CDIFFV,{:.0f},{:.0f}'.format(a, b) self.ser.write(cmd + "\r" + "\n") def MoveGoal(self, pose, goal, msg): global x_p global c x_p = pose.x y_p = pose.y theta_p = pose.theta x_g = goal.x y_g = goal.y theta_g = goal.theta print(pose.x - goal.x) if (x_p != x_g): if abs(x_p) < abs(x_g / 2): a = 100 * x_p + 25 else: a = (x_g - x_p) * 100 + 10 if a > 250: a = 250 if a < -250: a = -250 a = a if -0.01 < (pose.x - goal.x) < 0.01: c = 0 cmd = '$CDIFFV,{:.0f},{:.0f}'.format(a, a) if self.ser.isOpen(): print cmd self.ser.write(cmd + "\r" + "\n") def serReader(self, event): global x_p global c reader = self.ser_io.readline() if reader: packet = reader.split(",") try: header = packet[0].split("#")[1] if header.startswith('QVW'): self.vel = int(packet[1]) self.rot = int(packet[2]) elif header.startswith('QENCOD'): enc_L = int(packet[1]) enc_R = int(packet[2]) if self.enc_cnt == 0: self.enc_offset_L = enc_L self.enc_offset_R = enc_R self.enc_cnt += 1 self.enc_L = enc_L * self.config.encoder.Dir - self.enc_offset_L self.enc_R = enc_R * self.config.encoder.Dir - self.enc_offset_R self.pub_enc_l.publish(Float64(data=self.enc_L)) self.pub_enc_r.publish(Float64(data=self.enc_R)) self.pose = self.updatePose(self.pose, self.enc_L, self.enc_R) #print('Encoder:L{:.2f}, R:{:.2f}'.format(self.enc_L, self.enc_R)) elif header.startswith('QODO'): self.odo_L = float(packet[1]) * self.config.encoder.Dir self.odo_R = float(packet[2]) * self.config.encoder.Dir #print('Odo:{:.2f}mm,{:.2f}mm'.format(self.odo_L, self.odo_R)) elif header.startswith('QRPM'): self.RPM_L = int(packet[1]) self.RPM_R = int(packet[2]) #print('RPM:{:.2f}mm,{:.2f}mm'.format(self.RPM_L, self.RPM_R)) elif header.startswith('QDIFFV'): self.speedL = int(packet[1]) self.speedR = int(packet[2]) except: pass status_left = R1MotorStatus(low_voltage=0, overloaded=0, power=0, encoder=self.enc_L, RPM=self.RPM_L, ODO=self.odo_L, speed=self.speedL) status_right = R1MotorStatus(low_voltage=0, overloaded=0, power=0, encoder=self.enc_R, RPM=self.RPM_R, ODO=self.odo_R, speed=self.speedR) self.pub_motor_status.publish( R1MotorStatusLR(header=Header(stamp=rospy.Time.now()), Vspeed=self.vel, Vomega=self.rot, left=status_left, right=status_right)) def callbackJoy(self, data): self.joyAxes = deepcopy(data.axes) #print('Joy:{:.2f},{:.2f}'.format(self.joyAxes[0], self.joyAxes[1])) # Read the most recent button state newJoyButtons = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] newJoyButtons = deepcopy(data.buttons) # Check if button 1(B) is newly set if (newJoyButtons[1] == 1) and (newJoyButtons[1] != self.joyButtons[1]): if self.isAutoMode != True: self.isAutoMode = True print "In Auto mode" else: self.isAutoMode = False print "In Manual mode" if (newJoyButtons[10] == 1) and (newJoyButtons[10] != self.joyButtons[10]): if self.isArrowMode != True: self.isArrowMode = True self.arrowCon.isFinished = True print "Joystick Arrow Mode" else: self.isArrowMode = False print "Joystick Axis Mode" if self.isArrowMode == True: #if (newJoyButtons[13]==1) or (newJoyButtons[14]==1): #if (self.joyAxes[7]==1.0) or (self.joyAxes[7]==-1.0): if (self.joyAxes[5] == 1.0) or (self.joyAxes[5] == -1.0): if self.arrowCon.isFinished == True: self.arrowCon.isFinished = False #if newJoyButtons[13]==1: # FWD arrow #if self.joyAxes[7]==1.0: if self.joyAxes[5] == 1.0: self.arrowCommand("FWD", self.arrowCon, self.config) else: self.arrowCommand("REAR", self.arrowCon, self.config) #print "Arrow: {:.2f} {:.2f} ".format(self.arrowCon.startOdo_L, self.arrowCon.targetOdo_L) #elif (newJoyButtons[11]==1) or (newJoyButtons[12]==1): #For Xbox360 controller #elif (self.joyAxes[6]==1.0) or (self.joyAxes[6]==-1.0): elif (self.joyAxes[4] == 1.0) or (self.joyAxes[4] == -1.0): if self.arrowCon.isFinished == True: turnRate = 10.5 self.arrowCon.isFinished = False #if newJoyButtons[11]==1: # Left arrow #if self.joyAxes[6]==1.0: if self.joyAxes[4] == 1.0: self.arrowCommand("LEFT", self.arrowCon, self.config) else: # Right arrow self.arrowCommand("RIGHT", self.arrowCon, self.config) # Update button state self.joyButtons = deepcopy(newJoyButtons) def arrowCommand(self, command, arrowCon, config): if command == "FWD": arrowCon.setFwd = 1 arrowCon.targetOdo_L = self.odo_L + config.ArrowFwdStep #target 1 step ahead arrowCon.targetOdo_R = self.odo_R + config.ArrowFwdStep #target 1 step ahead print "Arrow Fwd" elif command == "REAR": self.arrowCon.setFwd = -1 self.arrowCon.targetOdo_L = self.odo_L - self.config.ArrowFwdStep #target 1 step rear self.arrowCon.targetOdo_R = self.odo_R - self.config.ArrowFwdStep #target 1 step rear print "Arrow Rev" elif command == "LEFT": arrowCon.setRot = 1 arrowCon.targetOdo_L = self.odo_L - config.BodyCircumference * 1000 * config.ArrowRotRate arrowCon.targetOdo_R = self.odo_R + config.BodyCircumference * 1000 * config.ArrowRotRate print "Arrow Left" elif command == "RIGHT": arrowCon.setRot = -1 arrowCon.targetOdo_L = self.odo_L + config.BodyCircumference * 1000 * config.ArrowRotRate arrowCon.targetOdo_R = self.odo_R - config.BodyCircumference * 1000 * config.ArrowRotRate print "Arrow Right" def callbackCmdVel(self, cmd): """ Set wheel speed from cmd message from auto navigation """ if self.isAutoMode: #print "CMD_VEL: {:.2f} {:.2f} ".format(cmd.linear.x, cmd.angular.z) cmdV = cmd.linear.x cmdW = cmd.angular.z if cmdV > self.config.V_Limit: cmdV = self.config.V_Limit elif cmdV < -self.config.V_Limit: cmdV = -self.config.V_Limit if cmdW > self.config.W_Limit: cmdW = self.config.W_Limit elif cmdW < -self.config.W_Limit: cmdW = -self.config.W_Limit (speedL, speedR) = self.getWheelSpeedLR(self.config, cmdV, cmdW) #print "SPEED LR: {:.2f} {:.2f} ".format(speedL, speedR) self.sendCDIFFVcontrol(speedL * 200, speedR * 200) def reset_odometry(self): self.last_speedL = 0.0 self.last_speedR = 0.0 def joytimer(self, event): if not self.isAutoMode: self.joy_v = self.joyAxes[1] self.joy_w = self.joyAxes[0] #print "Joy mode: {:.2f} {:.2f} ".format(self.joy_v, self.joy_w) else: return if not self.isArrowMode: # Apply joystick deadband and calculate vehicle speed (mm/s) and rate of chage of orientation(rad/s) joyV = 0.0 joyR = 0.0 if abs(self.joy_v) < self.joyDeadband: joyV = 0.0 else: joyV = (1 - self.exp) * self.joy_v + ( self.exp) * self.joy_v * self.joy_v * self.joy_v if abs(self.joy_w) < self.joyDeadband: joyR = 0.0 else: joyR = (1 - self.exp) * self.joy_w + ( self.exp) * self.joy_w * self.joy_w * self.joy_w # Apply max Vehicle speed (speedL, speedR) = self.getWheelSpeedLR(self.config, joyV * self.config.V_Limit_JOY, joyR * self.config.W_Limit_JOY) #print "Joystick VL, VR: {:.2f} {:.2f}".format(speedL, speedR) self.sendCDIFFVcontrol(speedL * 1000, speedR * 1000) else: if self.arrowCon.isFinished == False: if self.arrowCon.setFwd == 1: # For forward motion if (self.odo_L < self.arrowCon.targetOdo_L) or ( self.odo_R < self.arrowCon.targetOdo_R): #print "Fwd: {:.2f} {:.2f} ".format(self.odo_L, self.odo_R) self.sendCDIFFVcontrol(100, 100) else: self.sendCDIFFVcontrol(0, 0) self.arrowCon.isFinished = True self.arrowCon.setFwd = 0 print "Finished!" elif self.arrowCon.setFwd == -1: if (self.odo_L > self.arrowCon.targetOdo_L) or ( self.odo_R > self.arrowCon.targetOdo_R): #print "Rev: {:.2f} {:.2f} ".format(self.odo_L, self.odo_R) self.sendCDIFFVcontrol(-100, -100) else: self.sendCDIFFVcontrol(0, 0) self.arrowCon.isFinished = True self.arrowCon.setFwd = 0 print "Finished!" elif self.arrowCon.setRot == 1: #Turning left if (self.odo_L > self.arrowCon.targetOdo_L) or ( self.odo_R < self.arrowCon.targetOdo_R): #print "Left: {:.2f} {:.2f} ".format(self.odo_L, self.odo_R) self.sendCDIFFVcontrol(-100, 100) else: self.sendCDIFFVcontrol(0, 0) self.arrowCon.isFinished = True self.arrowCon.setRot = 0 print "Finished!" elif self.arrowCon.setRot == -1: #Turning Right if (self.odo_L < self.arrowCon.targetOdo_L) or ( self.odo_R > self.arrowCon.targetOdo_R): #print "Right: {:.2f} {:.2f} ".format(self.odo_L, self.odo_R) self.sendCDIFFVcontrol(100, -100) else: self.sendCDIFFVcontrol(0, 0) self.arrowCon.isFinished = True self.arrowCon.setRot = 0 print "Finished!" def updatePose(self, pose, encoderL, encoderR): """Update Position x,y,theta from encoder count L, R Return new Position x,y,theta""" global x_p print c now = rospy.Time.now() dL = encoderL - self.enc_L_prev dR = encoderR - self.enc_R_prev self.enc_L_prev = encoderL self.enc_R_prev = encoderR dT = (now - pose.timestamp) / 1000000.0 pose.timestamp = now x = pose.x y = pose.y theta = pose.theta R = 0.0 if (dR - dL) == 0: R = 0.0 else: R = self.config.WIDTH / 2.0 * (dL + dR) / (dR - dL) Wdt = (dR - dL) * self.config.encoder.Step / self.config.WIDTH ICCx = x - R * np.sin(theta) ICCy = y + R * np.cos(theta) pose.x = np.cos(Wdt) * (x - ICCx) - np.sin(Wdt) * (y - ICCy) + ICCx pose.y = np.sin(Wdt) * (x - ICCx) + np.cos(Wdt) * (y - ICCy) + ICCy pose.theta = theta + Wdt twist = TwistWithCovariance() twist.twist.linear.x = self.vel / 1000.0 twist.twist.linear.y = 0.0 twist.twist.angular.z = self.rot / 1000.0 Vx = twist.twist.linear.x Vy = twist.twist.linear.y Vth = twist.twist.angular.z odom_quat = quaternion_from_euler(0, 0, pose.theta) self.odom_broadcaster.sendTransform((pose.x, pose.y, 0.), odom_quat, now, 'base_link', 'odom') #self.odom_broadcaster.sendTransform((pose.x,pose.y,0.),odom_quat,now,'base_footprint','odom') odom = Odometry() odom.header.stamp = now odom.header.frame_id = 'odom' odom.pose.pose = Pose(Point(pose.x, pose.y, 0.), Quaternion(*odom_quat)) odom.child_frame_id = 'base_link' #odom.child_frame_id = 'base_footprint' odom.twist.twist = Twist(Vector3(Vx, Vy, 0), Vector3(0, 0, Vth)) print "x:{:.2f} y:{:.2f} theta:{:.2f}".format( pose.x, pose.y, pose.theta * 180 / math.pi) self.odom_pub.publish(odom) x_p = pose.x return pose def getWheelSpeedLR(self, config, V_m_s, W_rad_s): """Takes Speed V (m/s) and Rotational sepeed W(rad/s) and compute each wheel speed in m/s Kinematics reference from http://enesbot.me/kinematic-model-of-a-differential-drive-robot.html""" speedL = V_m_s - config.WIDTH * W_rad_s / config.WHEEL_R / 2.0 speedR = V_m_s + config.WIDTH * W_rad_s / config.WHEEL_R / 2.0 return speedL, speedR def sendCVWcontrol(self, config, V_mm_s, W_mrad_s): """ Set Vehicle velocity and rotational speed """ if V_mm_s > config.V_Limit: V_mm_s = config.V_Limit elif V_mm_s < -config.V_Limit: V_mm_s = -config.V_limit if W_mrad_s > config.W_Limit: W_mrad_s = config.W_Limit elif W_mrad_s < -config.W_Limit: W_mrad_s = -config.W_Limit # Make a serial message to be sent to motor driver unit cmd = '$CVW,{:.0f},{:.0f}'.format(V_mm_s, W_mrad_s) print cmd if self.ser.isOpen(): print cmd self.ser.write(cmd + "\r" + "\n") def sendCDIFFVcontrol(self, VLmm_s, VRmm_s): """ Set differential wheel speed for Left and Right """ if VLmm_s > self.config.WHEEL_MAXV: VLmm_s = self.config.WHEEL_MAXV elif VLmm_s < -self.config.WHEEL_MAXV: VLmm_s = -self.config.WHEEL_MAXV if VRmm_s > self.config.WHEEL_MAXV: VRmm_s = self.config.WHEEL_MAXV elif VRmm_s < -self.config.WHEEL_MAXV: VRmm_s = -self.config.WHEEL_MAXV # Make a serial message to be sent to motor driver unit cmd = '$CDIFFV,{:.0f},{:.0f}'.format(VLmm_s, VRmm_s) if self.ser.isOpen(): #print cmd self.ser.write(cmd + "\r" + "\n") def setREGI(self, param1, param2): msg = "$SREGI," + str(param1) + ',' + param2 self.ser.write(msg + "\r" + "\n") def setSPERI(self, param): msg = "$SPERI," + str(param) self.ser.write(msg + "\r" + "\n") def setPEEN(self, param): msg = "$SPEEN," + str(param) self.ser.write(msg + "\r" + "\n") def resetODO(self): self.ser.write("$SODO\r\n")
def ph_query(command): global ph_list global lst GPIO.setmode(GPIO.BCM) # change channel on serial communications board S0_pin = 17 S1_pin = 23 GPIO.setup(S0_pin, GPIO.OUT) # S0 GPIO.setup(S1_pin, GPIO.OUT) # S1 GPIO.output(S0_pin, GPIO.LOW) GPIO.output(S1_pin, GPIO.LOW) usbport = '/dev/ttyAMA0' ser = serial.Serial(usbport, 9600, timeout=0) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser), encoding='ascii', newline='\r', line_buffering=True) di = {} # handle the different commands conn1 = r.connect(db='poolpi').repl() if command == 'r': try: command += '\r' sio.write(command) while True: try: time.sleep(.1) line = sio.readline() lg = len(line) if lg > 0: if line == '*ER\r': sio.write(command) sio.flush() continue else: float_ph_reading = float(line) rounded_result = round(float_ph_reading, 1) # print('raw pH: %r' % (rounded_result)) try: if len(ph_list) == 10: del ph_list[0] ph_list.append(rounded_result) ph_sum = sum(ph_list) ph_avg = ph_sum / 10 rounded_ph_avg = round(ph_avg, 1) else: ph_list.append(rounded_result) ph_list_length = len(ph_list) ph_sum = sum(ph_list) ph_avg = ph_sum / ph_list_length rounded_ph_avg = round(ph_avg, 1) except ValueError: GPIO.cleanup() return "Value Error" try: # mqttc.publish('ph_sensor',char_line[:-1], 0) di['ph'] = rounded_ph_avg di['ph_time'] = r.now().to_iso8601() r.table('ph').insert(di).run(conn1) GPIO.cleanup() return 'pH: %r' % (rounded_ph_avg) except: print(sys.exc_info()) GPIO.cleanup() return "Error writing to database" except: print(sys.exc_info()) except KeyboardInterrupt: GPIO.cleanup() elif command == 'off': return else: try: retry = 0 print('sending command...') command += '\r' sio.write(command) try: while True: time.sleep(.1) line = sio.readline() lg = len(line) if lg > 0: if line[0] in lst: print(line) mqttc.publish('server', line, 0) return line elif line == '*ER\r': sio.write(command) sio.flush() mqttc.publish('server', 'error, trying again', 0) retry += 1 continue elif line == '*OK\r': print(line) mqttc.publish('server', line, 0) return line elif retry >= 10: mqttc.publish('server', 'error, please try again', 0) return else: retry += 1 print('hello there') continue except: return except KeyboardInterrupt: GPIO.cleanup()
pi.wiringPiSetupGpio() PIN_STAR = 17 PIN_END = 27 END = 22 pi.pinMode(PIN_STAR, 0) pi.pinMode(PIN_END, 1) pi.pinMode(END, 0) pi.digitalWrite(PIN_END, 0) # Configure sensor tlv.CONF() port = serial.Serial("/dev/ttyUSB0", baudrate=115200, timeout=2.0, parity=serial.PARITY_NONE) sio = io.TextIOWrapper(io.BufferedRWPair(port, port)) rr = b'155' # if is b'35' is to parametric curves and if is b'155' # is manual for an nxn matrix aa = b'@' # to separate words in the serial line to arduiono # point 1 X1 = b'3694' Y1 = b'0' Z1 = b'0' # point 2 X2 = b'12127' Y2 = b'0' Z2 = b'0' # Resolution
import queue, threading, io, serial, pynmea2 from time import sleep import logging from pitop.miniscreen import Miniscreen from PIL import Image, ImageDraw, ImageFont gpsSerial = serial.Serial('/dev/ttyS0', 9600, timeout=1.) gpsIO = io.TextIOWrapper(io.BufferedRWPair(gpsSerial, gpsSerial)) gpsSerial.write(b'$PMTK314,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1*34\r\n') ms = Miniscreen() image = Image.new( ms.mode, ms.size, ) canvas = ImageDraw.Draw(image) ms.set_max_fps(60) nmea_list = ['GGA', 'GSA', 'RMC', 'ZDA'] nmea_dict = { 'latitude': "", 'longitude': "", 'speed': "", 'date_time': "", 'satelites': 0, 'altitude': "", 'fix': True, 'fix_type': "" } q = queue.Queue()
serialport = 'COM6' recognizer.read( "C:\\Users\\boles\\OneDrive\\Desktop\\MOJE_PROJEKTY\\Arduino\\dunc_zaczepia\\face_rec\\face_rec_BOL_MAC_ANA.yml" ) else: FACESDATA_PATH = "/home/pi/duncanStream/facesData/" pathToCascadeClassifier = "/home/pi/.local/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_alt_tree.xml" serialport = '/dev/ttyUSB0' recognizer.read("face_rec.yml") try: arduino = serial.Serial(serialport, 9600) arduino.timeout = 1 logD(arduino.name) sio = io.TextIOWrapper(io.BufferedRWPair(arduino, arduino)) except: logD("______________NO ARDUINO FOUND!!!!!") input( "arduino not found - text will be send to dummy file instead of arduino serila port" ) sio = io.TextIOWrapper( io.BufferedRWPair(io.FileIO("bubuin.txt"), io.FileIO("bubuout.txt", mode='w'))) logD(sio.readlines()) sayInit() face_cascade = cv2.CascadeClassifier(pathToCascadeClassifier)
def __init__(self, parent=None): super(self.__class__, self).__init__(parent) try: self.ser = serial.Serial(port='/dev/ttyUSB1', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=.5) self.sio = io.TextIOWrapper(io.BufferedRWPair(self.ser, self.ser)) printInfo('Connected to TIC Controller.') except: printError('Could not connect to TIC Controller.') # Connect to the NEXTorr controller through serial port, # USB0 is the top port in the middle column. try: self.serIon = serial.Serial(port='/dev/ttyUSB0', baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=.5) self.sioIon = io.TextIOWrapper( io.BufferedRWPair(self.serIon, self.serIon)) printInfo('Connected to NEXTorr Power Supply.') except: printError('Could not connect to NEXTorr Power Supply.') # List of TIC commands - consist of preceding identifier, # message type, object ID, space, data, cr. self.gauge_read = "".join([ self.PRECEDING_QUERY, self.TYPE_VALUE, self.GAUGE_1, self.TERMINAL ]) self.backing_on = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.BACKING_PUMP, self.SEPARATOR, self.ON, self.TERMINAL ]) self.backing_off = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.BACKING_PUMP, self.SEPARATOR, self.OFF, self.TERMINAL ]) self.backing_check = "".join([ self.PRECEDING_QUERY, self.TYPE_VALUE, self.BACKING_PUMP, self.TERMINAL ]) self.turbo_on = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.TURBO_PUMP, self.SEPARATOR, self.ON, self.TERMINAL ]) self.turbo_off = "".join([ self.PRECEDING_COMMAND, self.TYPE_COMMAND, self.TURBO_PUMP, self.SEPARATOR, self.OFF, self.TERMINAL ]) self.turbo_check = "".join([ self.PRECEDING_QUERY, self.TYPE_VALUE, self.TURBO_PUMP, self.TERMINAL ]) self.pressure_reading = None self.ion_pressure_reading = None # Event to set when venting, will kill the pump down thread self.vent_event = threading.Event()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 2 15:14:34 2019 @author: aahunter """ import serial import io dev = "/dev/cu.usbserial-DA01233R" baudRate = 56700 ser = serial.Serial(dev, baudRate, timeout=1) #open serial port sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser), encoding='ascii') def drive(u_l, u_r): v = (int(u_l), int(u_r)) commandStr = '[{0[0]:d},{0[1]:d}]\n'.format(v) # commandStr = '-50,50 \n' # command = bytes(commandStr, 'ascii') # sio.flush() # ser.reset_output_buffer() sio.write(commandStr) sio.flush() sio.write(commandStr) sio.flush()
def __init__(self, conf): self.config = conf (Year, Month, Day) = self.config.get("settings", 'date').split('/') (Hour, Minute, Sec) = self.config.get("settings", 'time').split(':') flashpulse = float(self.config.get("settings", 'pulse')) self.ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, timeout=1.0) self.io = io.TextIOWrapper(io.BufferedRWPair(self.ser, self.ser, 1), newline='\n', line_buffering=True) # Make sure we are using the right settings: self.SendAndRecieve('ECHO,0') # Turn echoing of commands off self.SendAndRecieve('TMODE,0') # 0=UTC, 1=GPS, 2=LOCAL self.SendAndRecieve('DSTSTATE,0') # Disable Daylight Savings Time self.SendAndRecieve('PPMODE,0') # Disable Programmable Pulse Gtk.Window.__init__(self, title="GpsFlasher") self.set_border_width(10) grid = Gtk.Grid() self.add(grid) self.Mainlabel = Gtk.Label("gpsFlasher") self.Datelabel = Gtk.Label("Date") self.Timelabel = Gtk.Label("Time") self.Pulselabel = Gtk.Label("PulseLenght") self.Yearlabel = Gtk.Label("Year") self.Monthlabel = Gtk.Label("Month") self.Daylabel = Gtk.Label("Day") self.Hourlabel = Gtk.Label("Hour") self.Minutelabel = Gtk.Label("Minute") self.Seclabel = Gtk.Label("Seconds") self.adjustYear = Gtk.Adjustment(value=float(Year), lower=2018, upper=2027, step_incr=1, page_incr=5, page_size=0) self.adjustMonth = Gtk.Adjustment(value=float(Month), lower=0, upper=12, step_incr=1, page_incr=.4, page_size=0) self.adjustDay = Gtk.Adjustment(value=float(Day), lower=1, upper=31, step_incr=1, page_incr=.5, page_size=0) self.adjustHour = Gtk.Adjustment(value=float(Hour), lower=00, upper=23, step_incr=1, page_incr=1, page_size=0) self.adjustMinute = Gtk.Adjustment(value=float(Minute), lower=00, upper=59, step_incr=1, page_incr=1, page_size=0) self.adjustSec = Gtk.Adjustment(value=float(Sec), lower=0, upper=59, step_incr=1, page_incr=1, page_size=0) self.adjustSpPulse = Gtk.Adjustment(value=flashpulse, lower=.01, upper=.99, step_incr=.01, page_incr=.1, page_size=0) self.button = Gtk.Button.new_with_mnemonic("_Close") self.Applybutton = Gtk.Button.new_with_mnemonic("Apply") self.spin_button_Year = Gtk.SpinButton(adjustment=self.adjustYear, climb_rate=1, digits=0) self.spin_button_Month = Gtk.SpinButton(adjustment=self.adjustMonth, climb_rate=1, digits=0) self.spin_button_Day = Gtk.SpinButton(adjustment=self.adjustDay, climb_rate=1, digits=0) self.spin_button_Hour = Gtk.SpinButton(adjustment=self.adjustHour, climb_rate=1, digits=0) self.spin_button_Minute = Gtk.SpinButton(adjustment=self.adjustMinute, climb_rate=1, digits=0) self.spin_button_Sec = Gtk.SpinButton(adjustment=self.adjustSec, climb_rate=1, digits=0) self.spin_button = Gtk.SpinButton(adjustment=self.adjustSpPulse, climb_rate=.01, digits=2) grid.attach(self.Mainlabel, 0, 0, 2, 1) grid.attach_next_to(self.Datelabel, self.Mainlabel, Gtk.PositionType.BOTTOM, 1, 3) grid.attach_next_to(self.Timelabel, self.Datelabel, Gtk.PositionType.BOTTOM, 1, 3) grid.attach_next_to(self.Pulselabel, self.Timelabel, Gtk.PositionType.BOTTOM, 1, 1) grid.attach_next_to(self.spin_button_Year, self.Datelabel, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.Yearlabel, self.spin_button_Year, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.spin_button_Month, self.spin_button_Year, Gtk.PositionType.BOTTOM, 1, 1) grid.attach_next_to(self.Monthlabel, self.spin_button_Month, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.spin_button_Day, self.spin_button_Month, Gtk.PositionType.BOTTOM, 1, 1) grid.attach_next_to(self.Daylabel, self.spin_button_Day, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.spin_button_Hour, self.Timelabel, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.Hourlabel, self.spin_button_Hour, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.spin_button_Minute, self.spin_button_Hour, Gtk.PositionType.BOTTOM, 1, 1) grid.attach_next_to(self.Minutelabel, self.spin_button_Minute, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.spin_button_Sec, self.spin_button_Minute, Gtk.PositionType.BOTTOM, 1, 1) grid.attach_next_to(self.Seclabel, self.spin_button_Sec, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.spin_button, self.Pulselabel, Gtk.PositionType.RIGHT, 1, 1) grid.attach_next_to(self.Applybutton, self.Pulselabel, Gtk.PositionType.BOTTOM, 3, 1) grid.attach_next_to(self.button, self.Applybutton, Gtk.PositionType.BOTTOM, 3, 1) self.button.connect("clicked", self.on_close_clicked) self.Applybutton.connect("clicked", self.on_Apply_clicked)
import serial import io #ser = serial.Serial("/dev/ttyACM0", 9600) #opens serial port with this baudrate #print(ser.name) #this gives you the name of the port youre using #ser.open() #returns if port is open #ser.baudrate=9600 #sets baudrate in another way reader = io.open("limits.txt", "rb") writer = io.open("Sample1.txt", "wb") sio = io.TextIOWrapper(io.BufferedRWPair( reader, writer)) #bufferes streams that are both readable and writeable str1 = "hello" #sio.write(str(converted)) #pass in used array #sio.flush() # it is buffering. required to get the data out *now* #hello = sio.readline() this is to read from the stm so reieving #print(hello == unicode("hello\n")) #unicode? ascii? up to you to decide the format values = open("limits.txt").read().split() #function that convrts the string commands into bit array def tobits(s): result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return result #function to convert the int array into a string to be passed via serialize def convert(list):
def on_connectButton_clicked(self): if not self.connect_status: portl = self.comboBoxL.currentText() portr = self.comboBoxR.currentText() if portl == "": portl = 'loop://' if portr == "": portr = 'loop://' try: self.serL = serial.serial_for_url( portl, baudrate=int(self.comboBoxLBaudrate.currentText()), bytesize=int(self.comboBoxLBytesizes.currentText()), parity=self.comboBoxLParity.currentText(), stopbits=float(self.comboBoxLStopbits.currentText()), timeout=TIMEOUT_READLINE) except serial.serialutil.SerialException as e: QMessageBox.warning( None, "", "Unable to open serial port " + portl + ".") return try: self.serR = serial.serial_for_url( portr, baudrate=int(self.comboBoxRBaudrate.currentText()), bytesize=int(self.comboBoxLBytesizes.currentText()), parity=self.comboBoxLParity.currentText(), stopbits=float(self.comboBoxLStopbits.currentText()), timeout=TIMEOUT_READLINE) except serial.serialutil.SerialException as e: QMessageBox.warning( None, "", "Unable to open serial port " + portr + ".") return self.sioL = io.TextIOWrapper( io.BufferedRWPair(self.serL, self.serL)) self.sioR = io.TextIOWrapper( io.BufferedRWPair(self.serR, self.serR)) # test code # self.sioL.write(u"hello l") # self.sioL.flush() # self.sioR.write(u"hello r") # self.sioR.flush() self.connectButton.setText(DISCONNECT_LABEL) self.connect_status = True self.textL.append(CONNECT_LABEL + " " + str(self.serL)) self.textR.append(CONNECT_LABEL + " " + str(self.serR)) self.timer = QTimer(self) self.timer.timeout.connect(self.timeout) self.timer.start(TIMEOUT_TIMER) else: self.timer.stop() self.serL.close() self.serR.close() self.serL = None self.serR = None self.sioL = None self.sioR = None self.connectButton.setText(CONNECT_LABEL) self.connect_status = False self.textL.append(DISCONNECT_LABEL) self.textR.append(DISCONNECT_LABEL)
def record_serial(fname, badValue, gpsNumSamples, dataDir, numlines, gpsPort, baud, eventLog, elapsed, gpsGpio, startBaud): tStart = time.time() global burst_num burst_num += 1 eventLog.info('[%.3f] - Record_serial' % elapsed) print ('[%.3f] - Record_serial' % elapsed) eventLog.info('[%.3f] - Burst number: %s' % (elapsed,str(burst_num))) print ('[%.3f] - Burst number: %s' % (elapsed,str(burst_num))) u = np.empty(gpsNumSamples) u.fill(badValue) v = np.empty(gpsNumSamples) v.fill(badValue) z = np.empty(gpsNumSamples) z.fill(badValue) lat = np.empty(gpsNumSamples) lat.fill(badValue) lon = np.empty(gpsNumSamples) lon.fill(badValue) eventLog.info('[%.3f] - Create empty array for u,v,z,lat,lon,temp,volt with number of samples' % elapsed) #calculate elapsed time here elapsedTime = getElapsedTime(tStart,elapsed) setTimeAtEnd = False try: with serial.Serial('/dev/ttyS0',115200,timeout=.25) as pt, open(fname, 'a') as gpsOut: ser = io.TextIOWrapper(io.BufferedRWPair(pt,pt,1), encoding='ascii', errors='ignore', newline='\r', line_buffering=True) eventLog.info('[%.3f] - Open GPS port and file name: %s, %s' % (elapsed, gpsPort,fname)) #test for incoming data over serial port for i in range(1): newline = ser.readline() print('[%.3f] - New GPS output: %s' % (elapsedTime,newline)) eventLog.info('[%.3f] - New GPS output' % elapsedTime) #sleep(1) gpgga_stc = '' gpvtg_stc = '' ipos = 0 ivel = 0 if newline != '': #while loop record n seconds of serial data isample = 0 while ((ipos < gpsNumSamples or ivel < gpsNumSamples) and (ivel < (gpsNumSamples +10) and ipos< (gpsNumSamples+10))): # calculate elapsed time here elapsedTime = getElapsedTime(tStart,elapsed) # get new line from gps and write to file newline = ser.readline() gpsOut.write(newline) gpsOut.flush() if "GPGGA" in newline: gpgga_stc = newline #grab gpgga sentence to return parse_data_pos = parse_nmea_gpgga(gpgga_stc,eventLog,elapsedTime) eventLog.info('parse_nmea %s',str(parse_data_pos)); if ipos < gpsNumSamples: z[ipos] = parse_data_pos['altitude'] print ('[%.3f] - z[ipos]: %s' % (elapsedTime, z[ipos])) lat[ipos] = parse_data_pos['lat'] print ('[%.3f] - lat[ipos]: %s' % (elapsedTime, lat[ipos])) lon[ipos] = parse_data_pos['lon'] print ('[%.3f] - lon[ipos]: %s' % (elapsedTime, lon[ipos])) ipos = ipos + 1 if "GPVTG" in newline: gpvtg_stc = newline #grab gpvtg sentence parse_data_vel = parse_nmea_gpvtg(gpvtg_stc,eventLog,elapsedTime) eventLog.info('parse_nmea %s',str(parse_data_vel)); if ivel < gpsNumSamples: u[ivel] = parse_data_vel['u_vel'] print ('[%.3f] - u[ivel]: %s' % (elapsedTime, u[ivel])) v[ivel] = parse_data_vel['v_vel'] print ('[%.3f] - v[ivel]: %s' % (elapsedTime,v[ivel])) ivel = ivel + 1 #isample = isample + 1 #print('[%.3f] - isample:%d,ivel:%d,ipos:%d' %(elapsedTime,isample,ivel,ipos)) #eventLog.info('[%.3f] - isample:%d,ivel:%d,ipos:%d' %(elapsedTime,isample,ivel,ipos)) if (ivel > gpsNumSamples) and (setTimeAtEnd == False): if ("GPRMC" in newline): splitLine = newline.split(',') UTCTime = splitLine[1] date = splitLine[9] splitTime = list(UTCTime) hour = (splitTime[0] + splitTime[1]) minute = splitTime[2] + splitTime[3] sec = splitTime[4] + splitTime[5] second = (int(sec) + 2) dateSplit = list(date) day = dateSplit[0] + dateSplit[1] month = dateSplit[2] + dateSplit[3] year = dateSplit[4] + dateSplit[5] if (hour >= 7 and hour >= 19 or hour == 0): hour = int(hour) - 7 elif (hour >= 20 and hour <= 24): hour = int(hour) - 19 else: hour = int(hour) + 5 hour = format(hour, "02") second = format(second, "02") timeStr = (year,month,day,hour,minute,sec) subprocess.call(['/home/pi/microSWIFT/utils/setTimeAgain'] + [str(n) for n in timeStr]) setTimeAtEnd = True isample = isample + 1 else: print("[%.3f] - No serial data" % elapsedTime) eventLog.info('[%.3f] - No serial data' % elapsedTime) print('IN SERIAL:',(elapsedTime,u,v,z,lat,lon)) return u,v,z,lat,lon except Exception as e1: print('[%.3f] - Error: %s' % (elapsedTime,str(e1 ))) eventLog.error('[%.3f] - Error: %s' % (elapsedTime,str(e1 ))) return u,v,z,lat,lon
second=0, microsecond=0) # secStart = datetime.datetime.now() secOld = datetime.datetime.now() # set previous event to start time try: rPID = subprocess.Popen(["cat", "/tmp/raspi_PID"], stdout=subprocess.PIPE).communicate()[0] except: rPID = -1 print("Raspistill process is %s " % rPID) print(rPID) with serial.Serial(addr, 115200) as pt, open(fname, fmode) as outf: spb = io.TextIOWrapper(io.BufferedRWPair(pt, pt, 1), encoding='ascii', errors='ignore', newline='\r', line_buffering=True) spb.readline( ) # throw away first line; likely to start mid-sentence (incomplete) while (1): inline = spb.readline() # read one line of text from serial port secNow = datetime.datetime.now() if (1): # if ((secNow - secOld) > minInterval): # only pay attention if exceeded minInterval indat = inline.lstrip().rstrip() # input data if indat != "": # add other needed checks to skip titles cols = indat.split(",")
def get_io_wrapper(projector): return io.TextIOWrapper( io.BufferedRWPair(projector, projector, 1), newline='\r', line_buffering=True )
import serial from datetime import datetime import io outfile = 'serial_temp.tsv' ser = serial.Serial( port='/dev/ttyUSB0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE ) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), encoding='ascii', newline='\r') sio._CHUNK_SIZE = 1 with open(outfile, 'a') as f: while ser.isOpen(): datastring = sio.readline() f.write(datetime.utcnow().isoformat() + '\t' + datastring + '\n') print(datetime.utcnow().isoformat(), datastring) f.flush() ser.close()
# update controllers to produce it, # or stop polling if done. try: ppm = next(ppms) except StopIteration: return (schedule.CancelJob()) spikeccm, bulkccm = conc2flows(ppm, spiketankppm, totalflowccm) sendflow(sio, spike, spikeccm) sendflow(sio, bulk, bulkccm) ## And we're ready to go. # Set up connections s = serial.Serial(devname, baudrate=19200, timeout=0.1) sio = io.TextIOWrapper(io.BufferedRWPair(s, s)) try: # Set up controller polling schedule pollbulk = schedule.every(pollinterval).seconds.do(poll, con=sio, id=bulk) pollspike = schedule.every(pollinterval).seconds.do(poll, con=sio, id=spike) # Flush LGR with zero air and wait to obtain stable concentration sendflow(sio, bulk, totalflowccm) sendflow(sio, spike, 0) sleep(zeropurge * 60) for i in range(nramps): rampup = iter(range(ppmlow, ppmhigh + 1, ppmstep))
def __main(): # Get the LD parameters if len(sys.argv) < 7: raise ValueError( 'Command line:\n\tappname hexpath stacklen ldexe ldscript ldoself ldmap ldobjelf ldobj*\nGiven:\n\t' + str(sys.argv)) appname = sys.argv[1].strip()[:MAX_NAME_LENGTH] hexpath = sys.argv[2] stacklen = int(sys.argv[3][3:], 16) if sys.argv[3].strip().lower()[0:2] == '0x' else int( sys.argv[3]) ldexe = sys.argv[4] ldscript = sys.argv[5] ldoself = sys.argv[6] ldmap = sys.argv[7] ldobjelf = sys.argv[8] ldobjs = sys.argv[9:] # Get the length of each section pgmlen, bsslen, datalen = 0, 0, 0 with open(ldobjelf, 'rb') as f: elffile = ELFFile(f) for section in elffile.iter_sections(): if section.name == '.text': pgmlen = int(section['sh_size']) elif section.name == '.bss': bsslen = int(section['sh_size']) elif section.name == '.data': datalen = int(section['sh_size']) # Open the serial port ser = serial.Serial(SERIAL_PORT, SERIAL_BAUD) sio = io.TextIOWrapper(buffer=io.BufferedRWPair(ser, ser, 1), newline='\r\n', line_buffering=True, encoding='ascii') try: sio.write(unicode('\n\n')) time.sleep(0.1) while ser.inWaiting(): ser.flushInput() time.sleep(0.1) sio.write(unicode('app_install\n')) print '"' + sio.readline() + '"' # Send the section sizes and app name sizestr = '%0.8X,%0.8X,%0.8X,%0.8X,%0.2X%s' % ( pgmlen, bsslen, datalen, stacklen, len(appname), appname) print sizestr sio.write(unicode(sizestr + '\n')) # Receive the allocated addresses addrs = sio.readline().split(',') pgmadr = int(addrs[0].strip(), 16) bssadr = int(addrs[1].strip(), 16) dataadr = int(addrs[2].strip(), 16) datapgmadr = int(addrs[3].strip(), 16) # Link to the OS symbols sectopt = [ '--section-start', '.text=0x%0.8X' % pgmadr, '--section-start', '.bss=0x%0.8X' % bssadr, '--section-start', '.data=0x%0.8X' % dataadr ] args = [ ldexe, '--script', ldscript, '--just-symbols', ldoself, '-Map', ldmap, '-o', ldobjelf ] + sectopt + ldobjs print args subprocess.call(args) subprocess.call(['make']) with open(ldobjelf, 'rb') as f: elffile = ELFFile(f) threadadr = __find_address(elffile, ENTRY_THREAD_NAME) print 'app_thread = 0x%0.8X' % threadadr # Read the generated IHEX file and remove unused records with open(hexpath, 'r') as f: hexdata = f.readlines() hexdata = [ line.strip() for line in hexdata if not line[7:9] in ['05', '03'] and len(line) >= 11 ] hexdata = [line for line in hexdata if len(line) > 0] if len([None for line in hexdata if line[7:9] == '01' ]) != 1 and hexdata[-1][7:9] != '01': raise RuntimeError( 'The IHEX must contain a single EOF record, as last record') # Insert the entry point thread record chks = threadadr & 0xFFFFFFFF chks = (chks >> 24) + (chks >> 16) + (chks >> 8) + (chks & 0xFF) chks = 0x100 - (0x04 + 0x00 + 0x00 + 0x05 + chks) & 0xFF hexdata[0:0] = [':04000005%0.8X%0.2X' % (threadadr, chks)] # Send IHEX records for i in range(len(hexdata)): line = sio.readline().strip() print line if line != ',': raise RuntimeError( 'Error while loading line %d ("%s", received "%s")' % (i, hexdata[i], line)) sio.write(unicode(hexdata[i] + '\n')) print hexdata[i] line = sio.readline().strip() print line if line != '$': raise RuntimeError( 'Error while terminating programming (received "%s")' % line) ser.close() except: ser.close() raise
import time import struct import io import webbrowser import datetime import serial.tools.list_ports import os connected_port = '/dev/ttyACM0' ports = list(serial.tools.list_ports.comports()) for p in ports: if 'ttyACM' in p[0]: connected_port = p[0] arduino = serial.Serial(connected_port, 9600, timeout=1) dataio = io.TextIOWrapper(io.BufferedRWPair(arduino, arduino)) url = 'http://localhost/dpf/' # webbrowser.open(url) done = 0 # dataio.flush() i = 1 while True: filename = "/var/www/html/dpf/pillSettings.json" # print filename if os.path.isfile(filename): with open(filename) as settingsFile: data = json.load(settingsFile) now = datetime.datetime.now() today = now.strftime("%A")
arc_map = plt.imread("map.png") fig, ax = plt.subplots(figsize=(8, 7)) ax.set_title('GPS coordinates received') ax.set_xlim(BBox[0], BBox[1]) ax.set_ylim(BBox[2], BBox[3]) plt.ion() plt.show() print("setup done") # start bridge conn.write(b'\x0f') conn.read(1) sio = io.TextIOWrapper(io.BufferedRWPair(conn, conn)) while True: try: output = sio.read() lines = output.split("\n") for line in lines: if line: msg = pynmea2.parse(line) if isinstance(msg, pynmea2.GGA) and int(msg.num_sats) != 0: print(repr(msg)) if isinstance(msg, pynmea2.GGA) and int(msg.gps_qual) != 0: logfile.write(repr(msg) + "\n") update_figure(ax, BBox, float(msg.longitude), float(msg.latitude), arc_map) except serial.SerialException as e:
def __init__(self, channel, ttyBaudrate=115200, timeout=1, bitrate=None, **kwargs): """ :param string channel: port of underlying serial or usb device (e.g. /dev/ttyUSB0, COM8, ...) :param int ttyBaudrate: baudrate of underlying serial or usb device :param int bitrate: Bitrate in bits/s :param float poll_interval: Poll interval in seconds when reading messages :param float timeout timeout in seconds when reading message """ if channel == '': raise TypeError("Must specify a serial port.") if '@' in channel: (channel, ttyBaudrate) = channel.split('@') self.serialPortOrig = serial.Serial(channel, baudrate=ttyBaudrate, timeout=timeout) self.serialPort = io.TextIOWrapper(io.BufferedRWPair( self.serialPortOrig, self.serialPortOrig, 1), newline='\r', line_buffering=True) time.sleep(2) if bitrate is not None: self.close() if bitrate == 10000: self.write('S0') elif bitrate == 20000: self.write('S1') elif bitrate == 50000: self.write('S2') elif bitrate == 100000: self.write('S3') elif bitrate == 125000: self.write('S4') elif bitrate == 250000: self.write('S5') elif bitrate == 500000: self.write('S6') elif bitrate == 750000: self.write('S7') elif bitrate == 1000000: self.write('S8') elif bitrate == 83300: self.write('S9') else: raise ValueError( "Invalid bitrate, choose one of 10000 20000 50000 100000 125000 250000 500000 750000 1000000 83300" ) self.open() super(slcanBus, self).__init__(channel, **kwargs)
def setUp(self): self.s = serial.serial_for_url(PORT, timeout=1) #~ self.io = io.TextIOWrapper(self.s) self.io = io.TextIOWrapper(io.BufferedRWPair(self.s, self.s))
else: locations = ['/dev/ttyACM0'] date = datetime.datetime.now().strftime('%Y-%m-%d') folder = "/Users/Odroid/Documents/GPS_logs/" filename = date + '.log' for device in locations: try: print("Trying..." + device) #creates serial object #with device=/dev/ttyACMO, at 9600 baud, timeout units are seconds ser = serial.Serial(device, 9600, timeout=2) #TextIOWrapper takes a read/write stream (in this case the serial port) #and specifies an End-of-line character for the readlin() method serial_in = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), newline='\n', line_buffering=True) print("connected") break except: print("Failed to connect to " + device) if (not os.path.isdir(folder + date)): path = folder + date os.makedirs(path) #while not connected: # line = serial_in.readln() # connected = True
port_found = False for p in all_ports: curr = p.lower() if 'usb serial' in curr: serial_port = p.split(':')[0] port_found = True print("Found STM32 device on serial port") if not port_found and not debug_mode: print("Arduino not found! Ending Program") # os.kill(os.getpid(), signal.SIGTERM) exit() elif not debug_mode: ser = Serial(serial_port, 9600, timeout=0) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) print("------------------SYNTAX------------------") print("|Type v_.__ to set voltage output of DAC|") print("|Type i_.__ to set current output of DAC|") print("------------------------------------------") analog_val = 0 # max for test will be 0.45 if even needed ## ----- CHANGE TO BE ANALOG VALUE OF 0-4095 INSTEAD OF VOLTAGE data = [] data_w_current = [] err = False while port_found or debug_mode: if not debug_mode and not err: sio.write(str(analog_val) + 'f') # TODO: Make this into a function sio.flush()
def __init__(self, port): self.port = serial.Serial(port, 115200, timeout=0.1) self.iow = io.TextIOWrapper(io.BufferedRWPair(self.port, self.port, 1), 'utf-8', newline='\r\n')