本文整理汇总了Python中serial.Serial方法的典型用法代码示例。如果您正苦于以下问题:Python serial.Serial方法的具体用法?Python serial.Serial怎么用?Python serial.Serial使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类serial
的用法示例。
在下文中一共展示了serial.Serial方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def __init__(self, port, baud_rate, debug='off', sector_size=DEFAULT_SECTOR_SIZE, page_size=DEFAULT_PAGE_SIZE):
self.sector_size = sector_size
self.page_size = page_size
self.pages_per_sector = self.sector_size // self.page_size
if debug == 'normal':
self.debug = DEBUG_NORMAL
elif debug == 'verbose':
self.debug = DEBUG_VERBOSE
else: # off
self.debug = 0
self._debug('Opening serial connection')
self.sock = serial.Serial(port, baud_rate, timeout=1)
self._debug('Serial connection opened successfully')
time.sleep(2) # Wait for the Arduino bootloader
示例2: open
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def open(self):
self.lock.acquire()
self.ser = serial.Serial(self.devname,baudrate=self.baud,timeout=2)
self.ser.flushInput()
self.ser.write('ANCNFG 0\r\n')
self.lock.release()
if self.mode == "analog":
self.set_mode_analog()
elif self.mode == "serial":
self.set_mode_serial()
else:
raise AttributeError("No such mode: "+str(self.mode))
self.lock.acquire()
self.ser.write('EN\r\n')
self.ser.write('MH\r\n')
self.lock.release()
示例3: __init__
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def __init__(self, dev=None):
# pyserial 3.x has min requirement python2.7
# read() returns string in 2.7, bytes object otherwise
if sys.version_info[0] < 3:
if sys.version_info[1] < 7:
raise ValueError('This library is based on pyserial v3.x. Python 2.7 or higher is required.')
self._version = 2
self._ubox_synch = '\xb5b'
else:
self._version = 3
self._ubox_synch = ['b5', '62']
if(dev):
self.dev = dev
else:
self.dev = serial.Serial(timeout=1)
try:
if(self._dev.open):
self.baudrate = dev.baudrate
except AttributeError:
print("Serial Port is closed; open before using.")
示例4: read
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def read(self):
"""
Midi Serial Read.(In)
:return: Midi message
"""
msg = [None, None, None]
for i in range(len(msg)):
raw_byte = self.ser.read()
if not raw_byte:
return
byte_value = ord(raw_byte)
if byte_value in [248, 250, 252]:
return byte_value
else:
msg[i] = byte_value
return msg
示例5: connect
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def connect(parameter):
# Connecting
print ("Welcome to serial-init")
print ("------------------------------------------")
print ("Establishing connection to serial port:")
try:
#print ("TEST", baudrate,parity,bytesize,stopbits,timeout)
ser = serial.Serial(port, baudrate=baudrate, parity=parity, bytesize=bytesize, stopbits=stopbits, timeout=timeout)
print('.... Connection made.')
except:
print('.... Connection flopped.')
print('--- Aborting ---')
sys.exit(2)
print('')
return ser
示例6: __init__
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def __init__(self, port, baud, timeout):
self._port = port
self._baud = baud
self._timeout = timeout
self.serial_rx_queue = Queue.Queue() # Infinite
self.serial_tx_queue = Queue.Queue() # Infinite
self.enabled = True
try:
self.ser = serial.Serial(port, baud, timeout=timeout)
except serial.SerialException as e:
logger.error(e)
sys.exit(1) # Sys.exit(1) is an error
#Start
threading.Thread.__init__(self)
self.start() #Starts the run() function and thread
示例7: main
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def main():
try:
# Open serial port
ser = serial.Serial('/dev/ttys009', 9600)
# Create XBee Series 1 object
xbee = XBee(ser, callback=handle_data)
while True:
yield gen.sleep(1)
# Send AT packet
xbee.send('at', frame_id='B', command='DL')
except KeyboardInterrupt:
ioloop.IOLoop.current().stop()
finally:
xbee.halt()
ser.close()
示例8: __init__
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def __init__(self, *args):
kwargs = args[0] # Because one cannot pass multiple kwargs when creating
# a process...
for key, value in kwargs.items():
setattr(self, key, value)
self.arduino_ser = serial.Serial(port=self.port,
baudrate=self.baudrate)
self.collect_serial_queue = Queue_threading() # To collect serial
self.submit_serial_queue = Queue_threading() # To send in serial
# A thread that runs independently to collect serial port continuously.
self.collect_serial_threaded = Thread(target=collect_serial,
args=(self.arduino_ser,
self.collect_serial_queue))
self.collect_serial_threaded.daemon = True
self.init_main_window()
self.collect_serial_threaded.start()
self.bool_loop = True
self.main_loop()
示例9: NX_waitok
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def NX_waitok():
endcount = 0
bytecount = 0
ok = False
byte = ''
while endcount != 3:
try:
byte = ser.read()
except termios.error, e:
logger.error(_(u'termios.error in NX_waitok: {}').format(e[1]))
if byte == '':
logger.info(_(u'Serial Communication Timeout!'))
break
bytecount += 1
if (byte[0] == '\xff'):
endcount += 1
elif (byte[0] == '\x01' and bytecount == 1):
endcount = 0
ok = True
else:
endcount = 0
示例10: connect
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def connect(self):
try:
print "Connecting to Arduino on port", self.port, "..."
self.port = Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout, writeTimeout=self.writeTimeout)
# The next line is necessary to give the firmware time to wake up.
time.sleep(1)
test = self.get_baud()
if test != self.baudrate:
time.sleep(1)
test = self.get_baud()
if test != self.baudrate:
raise SerialException
print "Connected at", self.baudrate
print "Arduino is ready."
except SerialException:
print "Serial Exception:"
print sys.exc_info()
print "Traceback follows:"
traceback.print_exc(file=sys.stdout)
print "Cannot connect to Arduino!"
os._exit(1)
示例11: load_stg1
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def load_stg1(ser:Serial, program:bytes):
maxlen = 0xFC00 - 0xFA60
if len(program) > maxlen:
raise IndexError('Maximum program size is {} bytes'.format(maxlen))
pgmlen = tohex(struct.pack('<H', len(program)))
stage1 = fromhex(''.join([
'E6F160FA', # mov r1, #0FA60h
'E6F2'+pgmlen, # mov r2, len(program)
# wait:
'9AB7FE70', # jnb S0RIR, wait
'7EB7', # bclr S0RIR
'F2F3B2FE', # mov r3, S0RBUF
'B961', # movb [r1], rl3
'0811', # add r1, #1
'2821', # sub r2, #1
'3DF7', # jmpr cc_NZ, wait
'CC00', # nop
'CC00', # nop
'CC00' # nop
]))
load_bsl(ser, stage1+program, allow_overflow=True)
示例12: serial_ports
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/ttyUSB*') # ubuntu is /dev/ttyUSB0
elif sys.platform.startswith('darwin'):
# ports = glob.glob('/dev/tty.*')
ports = glob.glob('/dev/tty.SLAB_USBtoUART*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except serial.SerialException as e:
if e.errno == 13:
raise e
pass
except OSError:
pass
return result
# if __name__ == '__main__':
# print(serial_ports())
示例13: __init__
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def __init__(self, port_name=None, white_point=(1.0, 1.0, 1.0)):
self.port_name = port_name
self._channel_count = 4
self._channels = [None] * self._channel_count
self._channel_flags = [0] * self._channel_count
self._clear_on_exit = False
self.white_point = white_point
if self.port_name is None:
self.port_name = self._find_serial_port(VID, PID, NAME)
if self.port_name is None:
raise IOError("Unable to find Mote device")
self.port = serial.Serial(self.port_name, 115200, timeout=1)
示例14: __init__
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def __init__(self, **params):
if type(params['port']) is str:
params['port']=serial.Serial(
port=params['port'],
baudrate=115200
)
self._port = params['port']
self._ssh_pubkey_data = params['ssh_pubkey_data']
self._has_jtag = params['has_jtag']
self._check_uboot = params['check_uboot']
self._cleanup_payload = params['cleanup_payload']
self._reboot_after = params['reboot_after']
self._uboot_only = params['uboot_only']
self._boot_only = params['boot_only']
self._jtag_hardware = params['jtag_hardware']
示例15: getSerialOrNone
# 需要导入模块: import serial [as 别名]
# 或者: from serial import Serial [as 别名]
def getSerialOrNone(portname):
try:
return serial.Serial(port=portname,baudrate=115200,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS)
except:
return None