本文整理汇总了Python中pyb.UART.read方法的典型用法代码示例。如果您正苦于以下问题:Python UART.read方法的具体用法?Python UART.read怎么用?Python UART.read使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyb.UART
的用法示例。
在下文中一共展示了UART.read方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MTC
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
class MTC():
def __init__(self):
self.clock = {'frames':0, 'seconds':0, 'mins':0, 'hours':0, 'mode':0}
self.frame_count = 1
self.uart1 = UART(1)
self.message = [-1] * 8
self.uart1.init(31250, parity=None, stop=1,read_buf_len=1)
print(dir(self.uart1))
def saveClock(self):
self.clock['frames'] = (self.message[1] << 4) + self.message[0] # 2 half bytes 000f ffff
self.clock['seconds'] = (self.message[3] << 4) + self.message[2] # 2 half bytes 00ss ssss
self.clock['mins'] = (self.message[5] << 4) + self.message[4] # 2 half bytes 00mm mmmm
self.clock['hours'] = ((self.message[7] & 1) << 4) + self.message[6] # 2 half bytes 0rrh hhhh the msb has to be masked as it contains the mode
self.clock['mode'] = ((self.message[7] & 6) >> 1) # get the fps mode by masking 0rrh with 0110 (6)
def getMs(self):
self.readFrame()
mins = ((self.clock['hours'] * 60) + self.clock['mins'])
seconds = (mins * 60) + self.clock['seconds']
frames = (seconds * 25) + self.clock['frames']
milliseconds = frames * 40
return milliseconds
def readFrame(self):
indice = 0
self.message = [-1] * 8
while True:
data = self.uart1.read(1)
if data != None:
if ord(data) == 241: # if Byte for quater frame message
try: mes = ord(self.uart1.read(1)) # Read next byte
except: continue
piece = mes >> 4 # Get which part of the message it is (e.g seconds mins)
if piece == indice:
self.message[piece] = mes & 15 # store message using '&' to mask the bit type
indice += 1
if indice > 7:
self.saveClock()
break
#self.uart1.deinit()
return self.clock
示例2: remote
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
def remote():
#initialise UART communication
uart = UART(6)
uart.init(9600, bits=8, parity = None, stop = 2)
# define various I/O pins for ADC
adc_1 = ADC(Pin('X19'))
adc_2 = ADC(Pin('X20'))
# set up motor with PWM and timer control
A1 = Pin('Y9',Pin.OUT_PP)
A2 = Pin('Y10',Pin.OUT_PP)
pwm_out = Pin('X1')
tim = Timer(2, freq = 1000)
motor = tim.channel(1, Timer.PWM, pin = pwm_out)
# Motor in idle state
A1.high()
A2.high()
speed = 0
DEADZONE = 5
# Use keypad U and D keys to control speed
while True: # loop forever until CTRL-C
while (uart.any()!=10): #wait we get 10 chars
n = uart.any()
command = uart.read(10)
if command[2]==ord('5'):
if speed < 96:
speed = speed + 5
print(speed)
elif command[2]==ord('6'):
if speed > - 96:
speed = speed - 5
print(speed)
if (speed >= DEADZONE): # forward
A1.high()
A2.low()
motor.pulse_width_percent(speed)
elif (speed <= -DEADZONE):
A1.low() # backward
A2.high()
motor.pulse_width_percent(-speed)
else:
A1.low() # idle
A2.low()
示例3: keypad
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
def keypad():
key = ('1','2','3','4','U','D','L','R')
uart = UART(6)
uart.init(9600, bits=8, parity = None, stop = 2)
while True:
while (uart.any()!=10): #wait we get 10 chars
n = uart.any()
command = uart.read(10)
key_index = command[2]-ord('1')
if (0 <= key_index <= 7) :
key_press = key[key_index]
if command[3]==ord('1'):
action = 'pressed'
elif command[3]==ord('0'):
action = 'released'
else:
action = 'nothing pressed'
print('Key',key_press,' ',action)
示例4: JYMCU
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
class JYMCU(object):
"""JY-MCU Bluetooth serial device driver. This is simply a light UART wrapper
with addition AT command methods to customize the device."""
def __init__( self, uart, baudrate ):
""" uart = uart #1-6, baudrate must match what is set on the JY-MCU.
Needs to be a #1-C. """
self._uart = UART(uart, baudrate)
def __del__( self ) : self._uart.deinit()
def any( self ) : return self._uart.any()
def write( self, astring ) : return self._uart.write(astring)
def writechar( self, achar ) : self._uart.writechar(achar)
def read( self, num = None ) : return self._uart.read(num)
def readline( self ) : return self._uart.readline()
def readchar( self ) : return self._uart.readchar()
def readall( self ) : return self._uart.readall()
def readinto( self, buf, count = None ) : return self._uart.readinto(buf, count)
def _cmd( self, cmd ) :
""" Send AT command, wait a bit then return result string. """
self._uart.write("AT+" + cmd)
udelay(500)
return self.readline()
def baudrate( self, rate ) :
""" Set the baud rate. Needs to be #1-C. """
return self._cmd("BAUD" + str(rate))
def name( self, name ) :
""" Set the name to show up on the connecting device. """
return self._cmd("NAME" + name)
def pin( self, pin ) :
""" Set the given 4 digit numeric pin. """
return self._cmd("PIN" + str(pin))
def version( self ) : return self._cmd("VERSION")
def setrepl( self ) : repl_uart(self._uart)
示例5: Pin
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
A2 = Pin('Y10',Pin.OUT_PP)
pwm_out = Pin('X1')
tim = Timer(2, freq = 1000)
motor = tim.channel(1, Timer.PWM, pin = pwm_out)
# Motor in idle state
A1.high()
A2.high()
speed = 0
DEADZONE = 5
# Use keypad U and D keys to control speed
while True: # loop forever until CTRL-C
while (uart.any()!=10): #wait we get 10 chars
n = uart.any()
command = uart.read(10)
if command[2]==ord('5'):
if speed < 96:
speed = speed + 5
print(speed)
elif command[2]==ord('6'):
if speed > - 96:
speed = speed - 5
print(speed)
if (speed >= DEADZONE): # forward
A1.high()
A2.low()
motor.pulse_width_percent(speed)
elif (speed <= -DEADZONE):
A1.low() # backward
A2.high()
示例6: print
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
print(uart)
uart = UART(pins=('GP12', 'GP13'))
print(uart)
uart = UART(pins=(None, 'GP17'))
print(uart)
uart = UART(baudrate=57600, pins=('GP16', 'GP17'))
print(uart)
# now it's time for some loopback tests between the uarts
uart0 = UART(0, 1000000, pins=uart_pins[0][0])
print(uart0)
uart1 = UART(1, 1000000, pins=uart_pins[1][0])
print(uart1)
print(uart0.write(b'123456') == 6)
print(uart1.read() == b'123456')
print(uart1.write(b'123') == 3)
print(uart0.read(1) == b'1')
print(uart0.read(2) == b'23')
print(uart0.read() == b'')
uart0.write(b'123')
buf = bytearray(3)
print(uart1.readinto(buf, 1) == 1)
print(buf)
print(uart1.readinto(buf) == 2)
print(buf)
# try initializing without the id
uart0 = UART(baudrate=1000000, pins=uart_pins[0][0])
示例7: Counter
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
class HA7S:
""" Class for 1-wire master using HA7S.
Contains drivers for:
DS18B20 temp sensor
Display controller PIC for LCD
DS2423 Counter (2 channels 32 bits counters)
"""
def __init__(self, uart_port):
self.ROW_LENGTH = 20 # LCD 4 rows x 20 chars
self.uart = UART(uart_port, 9600)
def scan_for_devices(self):
""" Find all 1-Wire rom_codes on the bus """
strt = micros()
rom_codes = [] # Prepare list with Units found on the bus
r = "" # Return string
r = self.tx_rx('S', 17) # Search for first device
if len(r) > 1:
rom_codes.append(r[:-1]) # Add to list (Skip final <cr>)
##print("Första enhet: ", rom_codes)
while True:
# delay(100)
r = self.tx_rx('s', 17) # Search next rom_codes todo: ger timeout sista gången
if len(r) > 1:
rom_codes.append(r[:-1]) # Add to list (Skip final <cr>)
else:
break
# print("Enheter: ", rom_codes)
##print("Scan for devices: ", elapsed_micros(strt) / 1e6, 's')
return rom_codes
def read_ds18b20_temp(self, rom):
""" Setup and read temp data from DS18b20 """
# Todo: check negative temps works
retries = 3
while retries:
""" Initiate Temperature Conversion by selecting and sending 0x44-command """
resp = self.tx_rx(b'A' + rom + '\r', 17) # Adressing
dummy = self.tx_rx('W0144\r', 3) # Write block of data '44' Trigg measurement
resp1 = self.tx_rx('M\r', 17) # Reset AND reselect (enl HA7S doc)
if resp1 == resp:
delay(750) # Give DS18B20 time to measure
# The temperature result is stored in the scratchpad memory
data = self.tx_rx(b'W0ABEFFFFFFFFFFFFFFFFFF\r', 21) # Write to scratchpad and READ result
dummy = self.tx_rx('R', 1) # Reset
m = self.hex_byte_to_int(data[4:6])
l = self.hex_byte_to_int(data[2:4])
t = (m << 8) | (l & 0xff)
if m < 8:
t *= 0.0625 # Convert to Temp [°C]; Plus
else:
# temp given as 2's compl 16 bit int
t = (t - 65536) * 0.0625 # Convert to Temp [°C]; Minus
print("Rom, retur temperatur: ", rom, data, t, '°C')
return t
else:
retries -= 1
print("Retries: resp, resp1: ", retries, resp, resp1)
if retries < 1:
break
def read_ds2423_counters(self, rom):
""" Read counter values for the two counters (A & B) conncted to external pins """
resp = self.tx_rx(b'A' + rom + '\r', 17) # Adressing
""" Write/read block: A5 01C0/01E0(CounterA/B) [MSByte sent last] + 'FF'*42 (timeslots during which slave
returns 32 bytes scratchpad data + 4(cntA/cntB) + 4(zeroBytes) + 2 CRC bytes """
# Todo: check if respons = written; repeat otherwise
# We set adr so we only read LAST byte of page 14. We also get counter(4 B) + zerobytes(4 B) and CRC(2 B)
dataA = self.tx_rx('W0EA5DF01' + 'FF' * 11 + '\r', 29) # Read mem & Counter + TA1/TA2 (adr = 0x11C0)
dummy = self.tx_rx('M\r', 17) # Reset AND reselect (enl HA7S doc)
# We set adr so we only read LAST byte of page 15. We also get counter(4 B) + zerobytes(4 B) and CRC(2 B)
dataB = self.tx_rx('W0EA5FF01' + 'FF' * 11 + '\r', 29) # Read mem & Counter + TA1/TA2 (adr = 0x11C0)
dummy = self.tx_rx('R\r', 1) # Reset and red data (b'BE66014B467FFF0A102D\r')
''' Convert 32 bits hexadecimal ascii-string (LSByte first) to integer '''
cntA = self.lsb_first_hex_ascii_to_int32(dataA[8:16])
cntB = self.lsb_first_hex_ascii_to_int32(dataB[8:16])
print("ReadCnt: ", cntA, cntB, dataA, dataB)
return (cntA, cntB)
def write_ds2423_scratchpad(self, rom, s, target_adr):
""" Write to Scratchpad (max 32 bytes)
target_adr [0..0x1FF] as integer
Not implemented: readback of CRC after end of write. This works ONLY if data
written extends to end of page """
self.tx_rx(b'A' + rom + '\r', 17) # Adressing
#.........这里部分代码省略.........
示例8: in
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import read [as 别名]
# test we can correctly create by id or name
for bus in (-1, 0, 1, 2, 3, 4, 5, 6, 7, "XA", "XB", "YA", "YB", "Z"):
try:
UART(bus, 9600)
print("UART", bus)
except ValueError:
print("ValueError", bus)
uart = UART(1)
uart = UART(1, 9600)
uart = UART(1, 9600, bits=8, parity=None, stop=1)
print(uart)
uart.init(2400)
print(uart)
print(uart.any())
print(uart.write('123'))
print(uart.write(b'abcd'))
print(uart.writechar(1))
# make sure this method exists
uart.sendbreak()
# non-blocking mode
uart = UART(1, 9600, timeout=0)
print(uart.write(b'1'))
print(uart.write(b'abcd'))
print(uart.writechar(1))
print(uart.read(100))