本文整理汇总了Python中pyb.UART.any方法的典型用法代码示例。如果您正苦于以下问题:Python UART.any方法的具体用法?Python UART.any怎么用?Python UART.any使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyb.UART
的用法示例。
在下文中一共展示了UART.any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: remote
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [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()
示例2: keypad
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [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)
示例3: ESP8266
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
class ESP8266(object):
def __init__(self):
self.uart = UART(6, 115200)
def write(self, command):
self.uart.write(command)
count = 5
while count >= 0:
if self.uart.any():
print(self.uart.readall().decode('utf-8'))
time.sleep(0.1)
count-=1
示例4: __init__
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
class UART_Port:
"""Implements a port which can send or receive commands with a bioloid
device using the pyboard UART class. This particular class takes
advantage of some features which are only available on the STM32F4xx processors.
"""
def __init__(self, uart_num, baud):
self.uart = UART(uart_num)
self.baud = 0
self.set_baud(baud)
base_str = 'USART{}'.format(uart_num)
if not hasattr(stm, base_str):
base_str = 'UART{}'.format(uart_num)
self.uart_base = getattr(stm, base_str)
# Set HDSEL (bit 3) in CR3 - which puts the UART in half-duplex
# mode. This connects Rx to Tx internally, and only enables the
# transmitter when there is data to send.
stm.mem16[self.uart_base + stm.USART_CR3] |= (1 << 3)
def any(self):
return self.uart.any()
def read_byte(self):
"""Reads a byte from the bus.
This function will return None if no character was read within the
designated timeout (set when we call self.uart.init).
"""
byte = self.uart.readchar()
if byte >= 0:
return byte
def set_baud(self, baud):
"""Sets the baud rate.
Note, the pyb.UART class doesn't have a method for setting the baud
rate, so we need to reinitialize the uart object.
"""
if self.baud != baud:
self.baud = baud
# The max Return Delay Time is 254 * 2 usec = 508 usec. The default
# is 500 usec. So using a timeout of 2 ensures that we wait for
# at least 1 msec before considering a timeout.
self.uart.init(baudrate=baud, timeout=2)
def write_packet(self, packet_data):
"""Writes an entire packet to the serial port."""
_write_packet(self.uart_base, packet_data, len(packet_data))
示例5: JYMCU
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [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)
示例6: UART
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
gps_uart = UART(6, 9600, read_buf_len=1000)
xbee_uart = UART(2, 9600)
Razor_IMU = IMU.Razor(3, 57600)
# Razor_IMU.set_angle_output()
Razor_IMU.set_all_calibrated_output()
# while True:
# a,b,c = Razor_IMU.get_one_frame()
# print(a,b,c)
# Countdown Timer
start = pyb.millis()
backup_timer = 5400000
# Don't do anything until GPS is found
while gps_uart.any() >= 0:
my_gps.update(chr(gps_uart.readchar()))
print("No GPS signal!!!\n")
print(my_gps.latitude)
if my_gps.latitude[0] != 0:
init_lat = convert_latitude(my_gps.latitude)
init_long = convert_longitude(my_gps.longitude)
initial_point = (init_lat, init_long)
print("Initial Point: {}".format(initial_point))
break
# initial_point = (40.870242, -119.106354)
# while True:
# print('not landed yet')
# if pyb.elapsed_millis(start) >= backup_timer: #This is 90 minutes
示例7: Pin
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
# 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):
示例8: Switch
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
orange.off()
#create switch object
big_red_button = Switch()
big_red_button.callback(start)
finished = False
#########################
# Main Loop #
#########################
while finished == False: #While loop that loops forever
if hc12.any():
data = hc12.readline()
data = data.decode('utf-8')
dataArray = data.split(',') #Split it into an array called dataArray
if dataArray[0] == 'end':
green.off()
sleep(0.5)
green.on()
sleep(0.5)
green.off()
finished == True
elif len(dataArray) == 6:
tagx = dataArray[0]
temp = dataArray[1]
示例9: MicropyGPS
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
my_gps = MicropyGPS()
def print_out(string):
print(string)
#uart_bt.write(string)
try:
log = open('/sd/log.txt','a')
log.write(string+'\n')
log.close()
except:
print('SD Error')
#uart_bt.write('SD Error\n')
# Continuous Tests for characters available in the UART buffer, any characters are feed into the GPS
# object. When enough char are feed to represent a whole, valid sentence, stat is set as the name of the
# sentence and printed
while True:
pyb.wfi()
if uart_gps.any():
stat = my_gps.update(chr(uart_gps.readchar())) # Note the conversion to to chr, UART outputs ints normally
if stat:
ret = ('--------' + stat + '--------\n')
ret += (my_gps.time_string() + '\n')
ret += (my_gps.latitude_string()+ '\n')
ret += (my_gps.longitude_string()+ '\n')
ret += (my_gps.altitude_string()+ '\n')
ret += (my_gps.speed_string()+ '\n')
print_out(ret)
stat = None
示例10: print
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
reason=upower.why() # motivo dell'uscita da low power mode.
# see upower.py module documentation.
uart.write(str(reason) +'\n')
#reason='ALARM_B' # solo per debug
try:
if reason=='X1':
verde.on()
pyb.delay(3)
verde.off()
uart.write('ready'+'\n') # uscito da standby - standby exit.
while test==0:
inBuffer_rx=""
if uart.any():
inBuffer_rx=uart.readline()
print(inBuffer_rx)
inBuffer_chr=""
if inBuffer_rx!='':
inBuffer_chr=inBuffer_rx.decode()
if inBuffer_chr=='connecting':
print('connecting')
uart.write('sono connesso!'+'\n') # uscito da standby - standby exit.
restore_data()
sa=leggi_sonda_a()
pkl['in_sonda_a']=int(sa)
sb=leggi_sonda_b()
pkl['in_sonda_b']=int(sb)
uart.write(str(pkl)+'\n') # invia dati a host - send data to host.
示例11: __init__
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
class SBUSReceiver:
def __init__(self):
self.sbus = UART(3, 100000)
self.sbus.init(100000, bits=8, parity=0, stop=2, timeout_char=3, read_buf_len=250)
# constants
self.START_BYTE = b'0f'
self.END_BYTE = b'00'
self.SBUS_FRAME_LEN = 25
self.SBUS_NUM_CHAN = 18
self.OUT_OF_SYNC_THD = 10
self.SBUS_NUM_CHANNELS = 18
self.SBUS_SIGNAL_OK = 0
self.SBUS_SIGNAL_LOST = 1
self.SBUS_SIGNAL_FAILSAFE = 2
# Stack Variables initialization
self.validSbusFrame = 0
self.lostSbusFrame = 0
self.frameIndex = 0
self.resyncEvent = 0
self.outOfSyncCounter = 0
self.sbusBuff = bytearray(1) # single byte used for sync
self.sbusFrame = bytearray(25) # single SBUS Frame
self.sbusChannels = array.array('H', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # RC Channels
self.isSync = False
self.startByteFound = False
self.failSafeStatus = self.SBUS_SIGNAL_FAILSAFE
# logger.info("SBUS Stack Started")
def get_rx_channels(self):
return self.sbusChannels
def get_rx_channel(self, num_ch):
return self.sbusChannels[num_ch]
def get_failsafe_status(self):
return self.failSafeStatus
def get_rx_report(self):
rep = {}
rep['Valid Frames'] = self.validSbusFrame
rep['Lost Frames'] = self.lostSbusFrame
rep['Resync Events'] = self.resyncEvent
return rep
def decode_frame(self):
# TODO: DoubleCheck if it has to be removed
for i in range(0, self.SBUS_NUM_CHANNELS - 2):
self.sbusChannels[i] = 0
# counters initialization
byte_in_sbus = 1
bit_in_sbus = 0
ch = 0
bit_in_channel = 0
for i in range(0, 175): # TODO Generalization
if self.sbusFrame[byte_in_sbus] & (1 << bit_in_sbus):
self.sbusChannels[ch] |= (1 << bit_in_channel)
bit_in_sbus += 1
bit_in_channel += 1
if bit_in_sbus == 8:
bit_in_sbus = 0
byte_in_sbus += 1
if bit_in_channel == 11:
bit_in_channel = 0
ch += 1
# Decode Digitals Channels
# Digital Channel 1
if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 0):
self.sbusChannels[self.SBUS_NUM_CHAN - 2] = 1
else:
self.sbusChannels[self.SBUS_NUM_CHAN - 2] = 0
# Digital Channel 2
if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 1):
self.sbusChannels[self.SBUS_NUM_CHAN - 1] = 1
else:
self.sbusChannels[self.SBUS_NUM_CHAN - 1] = 0
# Failsafe
self.failSafeStatus = self.SBUS_SIGNAL_OK
if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 2):
self.failSafeStatus = self.SBUS_SIGNAL_LOST
if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 3):
self.failSafeStatus = self.SBUS_SIGNAL_FAILSAFE
def get_sync(self):
if self.sbus.any() > 0:
#.........这里部分代码省略.........
示例12: print
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
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])
uart0.write(b'1234567890')
pyb.delay(2) # because of the fifo interrupt levels
print(uart1.any() == 10)
print(uart1.readline() == b'1234567890')
print(uart1.any() == 0)
uart0.write(b'1234567890')
print(uart1.readall() == b'1234567890')
# tx only mode
uart0 = UART(0, 1000000, pins=('GP12', None))
print(uart0.write(b'123456') == 6)
print(uart1.read() == b'123456')
print(uart1.write(b'123') == 3)
print(uart0.read() == b'')
# rx only mode
uart0 = UART(0, 1000000, pins=(None, 'GP13'))
示例13: port
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
class Receiver:
# Allowed System Field values
_DSM2_1024_22MS = 0x01
_DSM2_2048_11MS = 0x12
_DSMS_2048_22MS = 0xa2
_DSMX_2048_11MS = 0xb2
_SYSTEM_FIELD_VALUES = (_DSM2_1024_22MS, _DSM2_2048_11MS, _DSMS_2048_22MS, _DSMX_2048_11MS)
# Channel formats depending on system field value
_MASK_1024_CHANID = 0xFC00 # when 11ms
_MASK_1024_SXPOS = 0x03FF # when 11ms
_MASK_2048_CHANID = 0x7800 # when 22ms
_MASK_2048_SXPOS = 0x07FF # when 22ms
# Serial configuration
_uart = None
_uart_port = 0 # Which UART port to use?
_uart_speed = 0 # Which UART speed to use?
# Serial buffer and frame data
_system_field = None
_frame = [0] * 16 # Assumption: frames are received correctly, no need of intermediate buffer and controls
_channels = [0] * 20 # Up-to 20 channels can be used by SPM4648
_debug = False
# ########################################################################
# ### Properties
# ########################################################################
@property
def port(self):
return self._uart_port
@property
def speed(self):
return self._uart_speed
@property
def frame(self):
return self._frame
@property
def channels(self):
return self._channels
@property
def system_field(self):
return self._system_field
# ########################################################################
# ### Constructor and destructor
# ########################################################################
def __init__(self, port, speed, debug=False):
self._debug = debug
self._uart_port = port
self._uart_speed = speed
self._uart = UART(self._uart_port, self._uart_speed)
# ########################################################################
# ### Functions
# ########################################################################
def read_serial(self):
# Lire un frame
if self._uart.any():
index = 0
while index < 16:
self._frame[index] = self._uart.readchar()
index += 1
self._decode_frame()
return True
else:
return False
def _decode_frame(self):
# Verify the system field (_channels[2])
if self._frame[1] in self._SYSTEM_FIELD_VALUES:
self._system_field = self._frame[1]
if self._frame[1] == self._DSM2_1024_22MS:
for i in range(1, 7):
data = self._frame[i * 2] * 256 + self._frame[(i * 2) + 1]
channel = (data & self._MASK_1024_CHANID) >> 10
value = data & self._MASK_1024_SXPOS
self._channels[channel] = value
else:
for i in range(1, 7):
data = self._frame[i * 2] * 256 + self._frame[(i * 2) + 1]
channel = (data & self._MASK_2048_CHANID) >> 11
value = data & self._MASK_2048_SXPOS
self._channels[channel] = value
else:
pass # Invalid system field value -> Do nothing
if self._debug:
self.debug()
def debug(self):
if not self._debug:
return
print("RX OUT: ", end="")
#.........这里部分代码省略.........
示例14: UART
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
from pyb import UART
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()
示例15: Counter
# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import any [as 别名]
#.........这里部分代码省略.........
msg_len = self.ROW_LENGTH - col
msg_hex = self.bin2hex(msg[:self.ROW_LENGTH - col]) # Truncate
else:
msg_hex = self.bin2hex(msg) # Convert to hex string (no '0x' before each byte)
''' Can only transfer max 16 chars to scratchpad LCD memory per transfer: First tfr 16 chrs + 2nd tfr for rest '''
if msg_len > 16:
len_hex = self.bin2hex(chr(16 + 2)) # Limit to 16 + 2 bytes first transmission
dummy = self.tx_rx('W' + len_hex + '4E' + line_adr + msg_hex[:16 * 2] + '\r', 37) # Write first 16 chars to
# scratchpad
delay(1)
dummy = self.tx_rx('M\r', 17) # Reset AND reselect
dummy = self.tx_rx('W0148\r', 3) # Copy Scratchpad to LCD
''' Adjust parameters for next part of msg to write to LCD memory '''
msg_len -= 16
msg_hex = msg_hex[16 * 2:] # keep unsent part only
line_adr = self.bin2hex(chr(lcd_row_adr[row_nr] + col + 16)) # LCD memory adr to use on LCD for 17:th
# char
dummy = self.tx_rx('M\r', 17) # Reset AND reselect (enl HA7S doc)
len_hex = self.bin2hex(chr(msg_len + 2)) # Len = BYTE count for remaining data
dummy = self.tx_rx('W' + len_hex + '4E' + line_adr + msg_hex + '\r', len(msg_hex) + 5) # Write to scratchpad
delay(1)
resp1 = self.tx_rx('M\r', 17) # Reset AND reselect
dummy = self.tx_rx('W0148\r', 3) # Copy Scratchpad to LCD
delay(2)
''' Turn LCD back-light ON '''
dummy = self.tx_rx('M\r', 17) # Reset AND reselect
dummy = self.tx_rx('W0108\r', 3) # Write block '08' 1 byte: LCD backlight on
dummy = self.tx_rx('R', 1) # Reset
def tx_rx(self, tx, nr_chars):
""" Send command to and receive respons from SA7S"""
''' rx = uart.readall() # Receive respons TAKES 1.0 sec ALWAYS (after uart.any) TimeOut!!!! '''
i = 0
rx = ''
# todo: do check if respons == same as sent: repeat otherwise
self.uart.write(tx) # Send to unit
# print("uart.write: i, tx: ", i, tx[:-1])
while True: # Typiskt 2–3 (search: 4) varv i loopen
i += 1
if self.uart.any(): # returns True if any characters wait
dbg.high()
strt = micros()
rx = b''
j = 0
while True: # Typically 10–20 (search: 12; M, R & W0144: 1) loops
j += 1
rxb = self.uart.read(nr_chars) # uart.readln och uart.readall ger båda timeout (1s default)
rx = rx + rxb
if (len(rx) >= nr_chars) or (rxb == b'\r'): # End of search returns \r
break
dbg.low()
##print("uart.read: i, j, tx, rx, ∆time ", i, j, tx[:-1], rx, len(rx), elapsed_micros(strt) / 1e6, 's')
delay(84)
break
else:
delay(10)
return rx
def hex_bytes_to_str(self, s):
""" Convert bytes (2 ascii hex char each) to string of ascii chars """
def hex_char_to_int(c):
##print("c:", hex(c), chr(c))
if c >= 65: