当前位置: 首页>>代码示例>>Python>>正文


Python UART.write方法代码示例

本文整理汇总了Python中pyb.UART.write方法的典型用法代码示例。如果您正苦于以下问题:Python UART.write方法的具体用法?Python UART.write怎么用?Python UART.write使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyb.UART的用法示例。


在下文中一共展示了UART.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: lcd

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
class lcd():
    def __init__(self,uart=3):
        #UART serial
        self.lcd = UART(uart, 115200)  # init with given baudrate

        #set lcd to same baudrate
        b = bytearray(3)
        b[0] = 0x7C
        b[1] = 0x07
        b[2] = 0x36
        self.lcd.write(b)

        #set background duty
        b = bytearray(3)
        b[0] = 0x7C
        b[1] = 0x02
        b[2] = 80
        self.lcd.write(b)

    def clear(self):
        b = bytearray(2)
        b[0] = 0x7c
        b[1] = 0x00
        self.lcd.write(b)

    def send(self,string):
        self.lcd.write(string)

    def replace(self,string):
        self.clear()
        self.lcd.write(string)
开发者ID:B3AU,项目名称:micropython,代码行数:33,代码来源:lcd.py

示例2: ESP8266

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [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
开发者ID:hiroki8080,项目名称:micropython,代码行数:15,代码来源:esp8266.py

示例3: __init__

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
class WIFI:
  """docstring for wifi"""

  def __init__(self, uart, baudrate = 115200):
    """ uart = uart #1-6, baudrate must match what is set on the ESP8266. """
    self._uart = UART(uart, baudrate)

  def write( self, aMsg ) :
    self._uart.write(aMsg)
    res = self._uart.readall()
    if res:
      print(res.decode("utf-8"))

  def read( self ) : return self._uart.readall().decode("utf-8")

  def _cmd( self, cmd ) :
    """ Send AT command, wait a bit then return results. """
    self._uart.write("AT+" + cmd + "\r\n")
    udelay(500)
    return self.read()

  @property
  def IP(self): return self._cmd("CIFSR")

  @property
  def networks( self ) : return self._cmd("CWLAP")

  @property
  def baudrate(self): return self._cmd("CIOBAUD?")

  @baudrate.setter
  def baudrate(self, value): return self._cmd("CIOBAUD=" + str(value))

  @property
  def mode(self): return self._cmd("CWMODE?")

  @mode.setter
  def mode(self, value): self._cmd("CWMODE=" + str(value))

  def connect( self, ssid, password = "" ) :
    """ Connect to the given network ssid with the given password """
    constr = "CWJAP=\"" + ssid + "\",\"" + password + "\""
    return self._cmd(constr)

  def disconnect( self ) : return self._cmd("CWQAP")

  def reset( self ) : return self._cmd("RST")
开发者ID:rolandvs,项目名称:GuyCarverMicroPythonCode,代码行数:49,代码来源:ESP8266.py

示例4: UART

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
from pyb import UART

uart = UART(6, 115200)                         # init with given baudrate

cmdStr = ""
for i in range(1000):
	uart.write("hello ")
	pyb.delay(100)
	if uart.any() > 0:
		for i in range(uart.any()):
			ch = uart.readchar()
			if ch == 0x0d:
				print("Command is:", cmdStr)
				cmdStr = ""
				continue
			if ch == 0x0a:
				continue
			cmdStr += chr(ch)
			print (chr(ch))
开发者ID:robdobsn,项目名称:SingleArmScaraSoftware,代码行数:21,代码来源:testserial.py

示例5: JYMCU

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [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)
开发者ID:rolandvs,项目名称:GuyCarverMicroPythonCode,代码行数:45,代码来源:JYMCU.py

示例6: command

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
class BLE:
    BLE_NONE=0
    BLE_SHIELD=1

    def command(self, cmd):
        if self.type==self.BLE_SHIELD:
            self.uart.write(cmd)
            self.uart.write("\r\n")
            r=self.uart.read(9)
            if r[0]!=82: raise OSError("Response corrupted!")
            if r[1]==49: raise OSError("Command failed!")
            if r[1]==50: raise OSError("Parse error!")
            if r[1]==51: raise OSError("Unknown command!")
            if r[1]==52: raise OSError("Too few args!")
            if r[1]==53: raise OSError("Too many args!")
            if r[1]==54: raise OSError("Unknown variable or option!")
            if r[1]==55: raise OSError("Invalid argument!")
            if r[1]==56: raise OSError("Timeout!")
            if r[1]==57: raise OSError("Security mismatch!")
            if r[1]!=48: raise OSError("Response corrupted!")
            for i in range(2,6):
                if r[i]<48 or 57<r[i]: raise OSError("Response corrupted!")
            if r[7]!=13 or r[8]!=10: raise OSError("Response corrupted!")
            l=((r[2]-48)*10000)+\
              ((r[3]-48)*1000)+\
              ((r[4]-48)*100)+\
              ((r[5]-48)*10)+\
              ((r[6]-48)*1)
            if not l: return None
            if l==1 or l==2: raise OSError("Response corrupted!")
            response=self.uart.read(l-2)
            if self.uart.readchar()!=13: raise OSError("Response corrupted!")
            if self.uart.readchar()!=10: raise OSError("Response corrupted!")
            return response

    def deinit(self):
        if self.type==self.BLE_SHIELD:
            self.uart.deinit()
            self.rst=None
            self.uart=None
            self.type=self.BLE_NONE

    def init(self, type=BLE_SHIELD):
        self.deinit()
        if type==self.BLE_SHIELD:
            self.rst=Pin("P7",Pin.OUT_OD,Pin.PULL_NONE)
            self.uart=UART(3,115200,timeout_char=1000)
            self.type=self.BLE_SHIELD
            self.rst.low()
            sleep(100)
            self.rst.high()
            sleep(100)
            self.uart.write("set sy c m machine\r\nsave\r\nreboot\r\n")
            sleep(1000)
            self.uart.readall() # clear

    def uart(self):
        if self.type==self.BLE_SHIELD: return self.uart

    def type(self):
        if self.type==self.BLE_SHIELD: return self.BLE_SHIELD

    def __init__(self):
        self.rst=None
        self.uart=None
        self.type=self.BLE_NONE
开发者ID:Killercotton,项目名称:OpenMV_medialab,代码行数:68,代码来源:ble.py

示例7: gestione_power_on

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
def gestione_power_on():

    print("Power On")
    uart.write("Power On.")

 
#imposto setting seriale - set MCU serial port1  
uart = UART(1, 9600)                         
uart.init(9600, bits=8, parity=None, stop=1)
 
test=0

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=""
开发者ID:BOB63,项目名称:My-uPy-Gardener,代码行数:32,代码来源:irrigatoreBT.V07.py

示例8: convert_latitude

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
pin_d = pyb.Pin('X10', pyb.Pin.AF_PP, pull=pyb.Pin.PULL_NONE,
                af=pyb.Pin.AF2_TIM4)

enc_timer_A = pyb.Timer(2, prescaler=0, period=65535)
enc_timer_B = pyb.Timer(4, prescaler=0, period=65535)

enc_channel_A = enc_timer_A.channel(1, pyb.Timer.ENC_AB)
enc_channel_B = enc_timer_B.channel(2, pyb.Timer.ENC_AB)

# init_lat = convert_latitude(my_gps.latitude)
# init_long = convert_longitude(my_gps.longitude)
# init_point = (init_lat, init_long)

# Start motorA
motorA.start(30,'cw')
xbee_uart.write('MotorA started!\n')
init_A = enc_timer_A.counter()
total_A = 0
another_A = 0
correction_A = 0
pid_A = 0

# Start motorB
motorB.start(30,'ccw')
xbee_uart.write('MotorB started!\n')
init_B = enc_timer_B.counter()
total_B = 0
another_B = 0
correction_B = 0
pid_B = 0
开发者ID:CRAWlab,项目名称:ARLISS,代码行数:32,代码来源:main.py

示例9: UART

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
uart = UART(baudrate=38400, pins=('GP12', 'GP13'))
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
开发者ID:rubencabrera,项目名称:micropython,代码行数:33,代码来源:uart.py

示例10: Counter

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [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

#.........这里部分代码省略.........
开发者ID:fojie,项目名称:micropython--In-Out,代码行数:103,代码来源:Lib_HA7S.py

示例11: UART

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [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()
开发者ID:Dreamapple,项目名称:micropython,代码行数:19,代码来源:uart.py

示例12: UART

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [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(1200)
print(uart)

print(uart.any())
print(uart.write("123"))
print(uart.write(b"abcd"))
print(uart.writechar(1))
开发者ID:cav71,项目名称:micropython,代码行数:16,代码来源:uart.py

示例13: print

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
from pyb import UART
import network
import socket

if __name__ == "__main__":
    nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)
    nic.connect('Joi', 'deadbeef')
    while not nic.isconnected():
        pyb.delay(50)
    print(nic.ifconfig())

    uart = UART(1, 9600)
    addr = ('192.168.1.242', 9999)
    while True:
        s = socket.socket()
        s.connect(addr)
        s.send(b"Hello\r\n")
        while True:
            try:
                incoming = "" 
                incoming = s.recv(1024)
                uart.write("%s\r"%incoming.decode().strip())
                while uart.any():
                    serialdata = uart.readline()
                    s.send("%s\n"%serialdata.decode().strip())
            except:
                print("error")
                break
        s.close()

开发者ID:johannfr,项目名称:fillinn,代码行数:31,代码来源:connectToNetwork.py

示例14: int

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
    # Find faces.
    # Note: Lower scale factor scales-down the image more and detects smaller objects.
    # Higher threshold results in a higher detection rate, with more false positives.
    faces = img.find_features(face_cascade, threshold=0.5, scale=1.5)

    # send larget face over UART
    largest_face = 0,0,0,0
    for face in faces:
        x,y,w,h = face
        area = x * y
        l_area = largest_face[2] * largest_face[3]

        if area > l_area:
            largest_face = face

    x = int(largest_face[0] + largest_face[2]/2)
    y = int(largest_face[1] + largest_face[3]/2)
    size = int((largest_face[2] + largest_face[3]) / 2)
    packet = array('b')
    packet.append(START_FRAME)
    packet.append(x)
    packet.append(y)
    packet.append(size)
    packet.append(int(clock.fps()))
    uart.write(packet)

    # Draw objects
    for r in faces:
        img.draw_rectangle(r)
开发者ID:djnugent,项目名称:ButterBot,代码行数:31,代码来源:main.py

示例15: open

# 需要导入模块: from pyb import UART [as 别名]
# 或者: from pyb.UART import write [as 别名]
			for x in my_sentence:
				my_gps.update(x)

			latitude = my_gps.latitude_string()
			longitude = my_gps.longitude_string()
			timestamp = my_gps.timestamp
			#alt2 = my_gps.altitude

			#open backup.csv to write data to, write to it, then close it
			backup = open('/sd/backup.csv', 'a')
			backup.write('{},{},{},{},{},{},{}\n'.format(tag,timestamp,temp,pres,alt,latitude,longitude))
			backup.close()

			data = str(tag) + ',' + str(temp) + ',' + str(pres) + ',' + str(alt) + ',' + str(latitude) + ',' + str(longitude) #concatenate data with commas

			hc12.write(data) #write data over UART4 to transmit to ground station

			green.on()
			sleep(1) #sleep for a second to buffer

		finished = True
		sleep(2)
		hc12.write('end')


#########################
#      End Program      #
#########################


for i in range(0,4):
开发者ID:aurorasat,项目名称:cansataurora,代码行数:33,代码来源:lumos2.py


注:本文中的pyb.UART.write方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。