Пример #1
0
class USB_UART(IO_object):
    def __init__(self, name):
        self.uart = UART(1, 9600)                         # init with given baudrate
        self.uart.init(9600, bits=8, parity=None, stop=1)  # init with given parameters
        self.buffer = bytearray(8)
        self.name = name
        assign_ID(self)
        # Data acqisition variables
        self.timer = pyb.Timer(available_timers.pop())
        self.timestamp = fw.current_time
        self.freq = -1.0
        self.prev_freq = -1.0

    def _timer_ISR(self, t):
        if self.uart.any() > 0:    # no message
            self.uart.readinto(self.buffer, 2)
            self.freq = int.from_bytes(self.buffer, 'little')
            if self.freq != self.prev_freq:
                self.timestamp = fw.current_time
                interrupt_queue.put(self.ID)
                self.prev_freq = self.freq

    def _initialise(self):
        self.timer.init(freq=100)   # this should be 2*(client frequency)
        self.timer.callback(self._timer_ISR)

    def _process_interrupt(self):
        fw.event_queue.put((self.timestamp, fw.event_typ, fw.events[self.name]))
Пример #2
0
def init():
    print("Initializing")

    # Initialize GPS
    # UART(1) is on PB:
    # (TX,  RX)
    # (X9,  X10)
    # (PB6, PB7)
    uart = UART(1, 9600)
    # Maybe add read_buf_len=128?
    # Maybe add timeout_char=200
    uart.init(9600, bits=8, stop=1, parity=None, timeout=5000)

    # Initialize Radio (RFM69)
    # SPI(1) is on PA:
    # (DIO0, RESET, NSS, SCK, MISO, MOSI)
    # (X3,   X4,    X5,  X6,  X7,   X8)
    # (PA2,  PA3,   PA4, PA5, PA6,  PA7)
    rfm69 = RFM69.RFM69()
    sleep(1)
    # Check version
    if (rfm69.getVersion() == 0x24):
        print("RFM69 Version Valid: 0x24")
    else:
        print("RFM69 Version Invalid!")
        return "FAULT"

    return "GPS_ACQ"
Пример #3
0
class uart_ic_interface(object):
    def __init__(self, port=3, data_rate=9600, single_wire=False):
        self.__uart = UART(port, data_rate)
        self.__uart.init(baudrate=data_rate,
                         bits=8,
                         parity=None,
                         stop=1,
                         timeout=1000,
                         timeout_char=1000)
        self.__single_wire = single_wire
        if (self.__single_wire and (port == 3)):
            stm.mem32[stm.GPIOB + stm.GPIO_OTYPER] |= (1 << 10
                                                       )  # Set open drain
            stm.mem32[stm.GPIOB + stm.GPIO_PUPDR] &= ~(1 << 21)
            stm.mem32[stm.GPIOB + stm.GPIO_PUPDR] &= ~(1 << 20)  # Set nopull
            #stm.mem32[stm.USART3 + stm.USART_CR3] |= 0b1000 # set HDSEL
            stm.mem32[stm.GPIOB + stm.GPIO_PUPDR] &= ~(1 << 23)
            stm.mem32[stm.GPIOB + stm.GPIO_PUPDR] |= (1 << 22)  # Set pullup

    def send(self, buf):
        #print("send: {}".format(buf))
        self.__uart.write(buf)
        if (self.__single_wire):
            self.__uart.read(len(buf))

    def recv(self, nbytes):
        buf = self.__uart.read(nbytes)
        #print("recv: {}".format(buf))
        return buf
Пример #4
0
def init():
	print ("Initializing")

	# Initialize GPS
	# UART(1) is on PB: 
	# (TX,  RX) 
	# (X9,  X10)
	# (PB6, PB7)
	uart = UART(1, 9600)
	# Maybe add read_buf_len=128?
	# Maybe add timeout_char=200
	uart.init(9600, bits=8, stop=1, parity=None, timeout=5000)


	# Initialize Radio (RFM69)
	# SPI(1) is on PA:
	# (DIO0, RESET, NSS, SCK, MISO, MOSI) 
	# (X3,   X4,    X5,  X6,  X7,   X8) 
	# (PA2,  PA3,   PA4, PA5, PA6,  PA7)
	rfm69 = RFM69.RFM69()
	sleep(1)
	# Check version
	if (rfm69.getVersion() == 0x24):
		print ("RFM69 Version Valid: 0x24")
	else:
		print ("RFM69 Version Invalid!")
		return "FAULT"

	return "GPS_ACQ"
Пример #5
0
def  uart_hash():
	#  initialize UART(6) to output TX on Pin Y1
	uart = UART(6)
	while True:
		uart.init(9600, bits=8, parity = 0, stop = 2)
		uart.writechar(ord('#'))		# letter '#'
		pyb.delay(5)					# delay by 5ms
Пример #6
0
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
Пример #7
0
def initUART():
    global uartObject
    try:
        #UART(1) uses pins 0 and 1
        uartObject = UART(1)
        uartObject.init(9600, bits=8, parity=None, stop=1, timeout_char=1000)
    except ValueError:
        # print("Error: baud rate +- 5% out of range")
        return False
    return True
Пример #8
0
class Wifi_Driver(object):
    def __init__(self, uart_num=2, uart_baud=9600):
        self.uart = UART(uart_num, uart_baud)
        self.uart.init(uart_baud, bits=8, parity=None, stop=1)

    def receive_char(self):
        temp = self.uart.readchar()
        if temp == -1:
            return None

        temp = chr(temp)
        return temp
Пример #9
0
def  uart_hashtag():
	the_word = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
	#  initialize X5 as  trigger output
	uart = UART(6)
	uart.init(9600, bits=8, parity = None, stop = 2)
	while True:
	#  initialize UART(6) to output TX on Pin Y1
		for i in range(36):
			uart.writechar(ord(the_word[i]))
		uart.writechar(13)
		uart.writechar(10)
		pyb.delay(1000)
class uart_tmcl_interface(tmcl_interface, tmcl_host_interface):

    def __init__(self, port=3, data_rate=9600, host_id=2, module_id=1, debug=False):
        tmcl_interface.__init__(self, host_id, module_id, debug)
        tmcl_host_interface.__init__(self, host_id, module_id, debug)

        self.__uart = UART(port, data_rate)
        self.__uart.init(baudrate=data_rate, bits=8, parity=None, stop=1, timeout=10000, timeout_char=10000)

    def __enter__(self):
        return self

    def __exit__(self, exitType, value, traceback):
        del exitType, value, traceback
        self.close()

    def close(self):
        self.__uart.deinit()
        return 0;

    def data_available(self, hostID=None, moduleID=None):
        del hostID, moduleID
        return self.__uart.any()

    def _send(self, hostID, moduleID, data):
        del hostID, moduleID

        self.__uart.write(data)

    def _recv(self, hostID, moduleID):
        del hostID, moduleID

        read = self.__uart.read(9)

        return read

    def printInfo(self):
        pass

    def enableDebug(self, enable):
        self._debug = enable

    @staticmethod
    def supportsTMCL():
        return True

    @staticmethod
    def supportsCANopen():
        return False

    @staticmethod
    def available_ports():
        return set([2, 3, 4])
Пример #11
0
class US100UART:
    distance = None
    buf_dis = bytearray(2)

    temperature = None
    buf_temper = bytearray(1)

    def __init__(self, port):
        self.uart = UART(port, 9600)
        self.uart.init(9600, bits=8, parity=None, stop=1, timeout=3000)

    def isDistance(self):
        if self.uart.any() and self.uart.any() % 2 == 0:
            self.buf_dis = self.uart.read(2)
            self.distance = (self.buf_dis[0] * 256) + self.buf_dis[1]
            return True
        else:
            return False

    async def read_distance(self):
        """
        支持热插拔

        :return: None
        """
        self.uart.write(b'\x55')
        while True:
            await asyncio.sleep_ms(100)
            if self.isDistance():
                break
            else:
                await asyncio.sleep_ms(200)
                if self.isDistance():
                    break
                else:
                    self.distance = None
                    self.uart.read(self.uart.any())
                    self.uart.write(b'\x55')

    async def read_temperature(self):
        """写着玩的"""
        self.uart.write(b'\x50')
        while True:
            await asyncio.sleep_ms(100)
            if self.uart.any():
                self.buf_temper = self.uart.read(1)
                self.temperature = self.buf_temper[0] - 45
                break
            else:
                self.temperature = None
                self.uart.write(b'\x50')
Пример #12
0
def initializeAntenna():
    global uart
    uart = UART(1, currentBaud)
    uart.init(currentBaud, bits=8, parity=None, stop=1)

    time.sleep(0.5)

    print("Antenna Initial STATUS")

    uart.write("AT")
    print(uart.readline())
    uart.write("AT+RB")
    print(uart.readline())
    uart.write("AT+RC")
    print(uart.readline())
    uart.write("AT+RF")
    print(uart.readline())
    uart.write("AT+RP")
    print(uart.readline())

    print("\r\n\n\n")
    print("SENDING CONFIG")
    print("\r\n")

    uart.write("AT+B" + antennaConfig["baud"])
    uart.write("AT+C" + antennaConfig["channel"])
    uart.write("AT+P" + antennaConfig["power"])
    uart.write("AT+F" + antennaConfig["fu"])

    print("\r\nDONE")

    print("Antenna Final STATUS")

    uart.write("AT")
    print(uart.readline())
    uart.write("AT+RB")
    print(uart.readline())
    uart.write("AT+RC")
    print(uart.readline())
    uart.write("AT+RF")
    print(uart.readline())
    uart.write("AT+RP")
    print(uart.readline())

    time.sleep(0.5)

    baudBaseString = "AT+B"
    desiredBaud = 9600

    uart.write(baudBaseString + str(desiredBaud))
    print(uart.readline())
Пример #13
0
class cjmcu(object):
    """docstring for cjmcu"""
    _CONTINUOUS = const(1)
    _POLL = const(2)

    _RATEBASE = 0x11
    _BAUD9600 = const(0)
    _BAUD19200 = const(1)
    _BAUD38400 = const(2)

    def __init__(self, aLoc):
        super(cjmcu, self).__init__()
        self._uart = UART(aLoc, 9600)
        self._mode = _POLL
        self._output = bytearray(4)
        self._output[0] = 0x66
        self._output[1] = 0x66
        self._output[2] = self._mode
        self._output[3] = 0x56
        self._input = bytearray(9)

        self.update()

    def write(self):
        '''write output buffer to board.'''
        self._uart.write(self._output)

    def read(self):
        '''read into input buffer from board.  Always 9 bytes.'''
        self._uart.readinto(self._input)

    def update(self):
        '''Send command to prompt data output from board, then read data.
       Note that this only needs to be done if board in in POLL mode.'''
        self.write()
        self.read()

    def setbaud(self, aBaud):
        '''Set baud rate on board then re-connect with new rate.'''
        self._output[2] = _BAUDBASE + aBaud
        self.update()
        self._output[2] = self._mode
        self._uart.deinit()
        self._uart.init(9600 << aBaud)

    def temps(self):
        '''Return (ambient, object) temperatures in celcius.'''
        v1 = (self._input[4] << 8) | self._input[5]
        v2 = (self._input[6] << 8) | self._input[7]
        return (v1 / 100.0, v2 / 100.0)
Пример #14
0
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))
Пример #15
0
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))
Пример #16
0
class Mode():
	def __init__(self):
		#bluetooth communication
		self.key = (0, 1, 2, 3, 'U', 'D', 'L', 'R')
		self.uart = UART(6)
		self.uart.init(9600, bits = 8, parity = None, stop = 2)
		self.key_press = None

	def loop(self):
		if self.uart.any() > 5:   #wait for a message to be sent
		    self.command = self.uart.read(5)   #read the message which was sent
		    self.key_index = self.command[2] - ord('1')      #convert ascii character send to an index for the list of keys
		    if 0 <= self.key_index <= 7:  # checks the index is valid
		        self.key_press = self.key[self.key_index]

		    print("You've selected: ", str(self.key_press))    #print what is being pressed
Пример #17
0
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()		
Пример #18
0
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)
Пример #19
0
class uRFID:
    # Class for using the Priority 1 Design Micro RFID module to read FDX-B tags.
    # http://www.priority1design.com.au/rfid_reader_modules.html

    def __init__(self, bus):
        self.uart = UART(bus)
        self.uart.init(baudrate=9600, bits=8, parity=None, stop=1, timeout=1)
        self.uart.write(b'ST2\r')  # Put reader in FDX-B tag mode.
        sleep(0.01)
        self.uart.read()  # Clear input buffer.

    def read_tag(self):
        # Return the ID of the most recent tag read, if not tag has been read return None.
        read_bytes = self.uart.read()
        if not read_bytes:
            return
        try:
            ID = int(read_bytes[-13:-1])
            return ID
        except ValueError:
            return
Пример #20
0
def readgps(uart):
    u2 = UART(uart, 115200)
    u2.init(115200, timeout=100)
    u2.write('AT+GPSPWR=1\r\n')
    u2.write('AT+GPSRST=2,0\r\n')
    u2.write('AT+GPSLOC=1\r\n')
    pyb.delay(1000)
    _dataRead = u2.read()
    u2.write('AT+GPSLOC=0\r\n')
    pyb.delay(1000)
    _dataRead = u2.read()
    if _dataRead != None:
        if 60 < len(_dataRead) < 70:
            _dataRead = _dataRead.decode('utf-8')
            _dataRead1 = _dataRead.split(',')
            if len(_dataRead1) > 4:
                #*******************纬度计算********************
                weidu = _dataRead1[1]
                WD = DataConver(weidu, 0)
                #*******************经度计算********************
                jingdu = _dataRead1[2]
                JD = DataConver(jingdu, 1)
                return JD, WD
    return None
Пример #21
0
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()
Пример #22
0
hist = [37, 98, -68, 21, 34, 99]

# Power-Cell tracker is device #2
can = frc_can.frc_can(2)

# Set the configuration for our OpenMV frcCAN device.
can.set_config(2, 0, 0, 0)
# Set the mode for our OpenMV frcCAN device.
can.set_mode(1)

pc_roi = (0, 110, 325, 120)
mag_roi = (0, 155, 320, 90)

#lidar initialization
uart = UART(3)
uart.init(115200, bits=8, parity=None, stop=1, timeout_char=20, timeout=80)


#lidar setup
def lidar_command(command, purpose):
    if purpose:
        print("%s Command : %s" % (purpose, command))
    uart.write(command)
    response = uart.read()
    if purpose:
        print("%s Response : %s" % (purpose, response))
    return purpose


command = bytes(b'\x5A\x05\x07\x00\x66')
lidar_command(command, "Disable")
Пример #23
0
from pyb import UART

# test we can correctly create by id
for bus in (-1, 0, 1, 2, 5, 6, 7):
    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))
Пример #24
0
class CANLogger(object):
    def __init__(self):
        # Constants and variables #

        # UART cmd to en-/disable the GPS
        self.GPS_OFF = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x08,
                        0x00, 0x16, 0x74)
        self.GPS_ON = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x09,
                       0x00, 0x17, 0x76)

        self.SIM_DISABLED = False
        self.GPS_LOG_TIME = 5000  # 5s
        self.SHUTOFF_TIME = 30000  # 30s of no CAN activity
        self.TOKEN = "REDACTED"

        self.VERSION = 1.0
        if 'sd' in os.listdir('/'):
            self.PATH = '/sd/'
        else:
            self.PATH = ''
        self.CAN_FILE = open(self.PATH + 'can.log', 'a+')

        # This will hold CAN IDs to be filtered for in the can log
        self.can_filter = []
        self.allowed_users = ["610574975"]
        self.interrupt = False
        self.shutdown = False

        # Init modules #

        # GPS init
        self.gps_uart = UART(1, 9600)  # init with given baudrate
        self.gps_uart.init(9600,
                           bits=8,
                           parity=None,
                           stop=1,
                           read_buf_len=512 // 2)  # init with given parameters
        self.gps = MicropyGPS()

        # CAN init (500 MHz)
        self.can = CAN(1, CAN.NORMAL)  # recv
        self.can2 = CAN(2, CAN.NORMAL)  # send
        self.can.init(CAN.NORMAL,
                      prescaler=4,
                      sjw=1,
                      bs1=14,
                      bs2=6,
                      auto_restart=True)
        self.can2.init(CAN.NORMAL,
                       prescaler=4,
                       sjw=1,
                       bs1=14,
                       bs2=6,
                       auto_restart=True)
        self.can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0))

        # SIM800L init
        sim_uart = UART(4, 9600, timeout=1000, read_buf_len=2048 // 4)
        self.modem = Modem(sim_uart)
        self.modem.initialize()

        try:
            self.modem.connect('internet.eplus.de')
        except:
            self.SIM_DISABLED = True
            print("LOG ONLY MODE (NO GSM)")

        # Clock init
        self.rtc = RTC()
        self.rtc.wakeup(5000)  # wakeup call every 5s

        # Interrupt Flag init
        self.interrupt = False
        pyb.ExtInt('X5', pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP,
                   self.incoming_call)

        # Sleep pins for GSM
        self.gsm_sleep = pyb.Pin('X6', pyb.Pin.OUT_PP)
        self.gsm_sleep.value(0)

        if not self.SIM_DISABLED:
            # Software Update
            self.ota()

            # Telegram Bot
            self.telegram = TelegramBot(token=self.TOKEN, modem=self.modem)

    # Logs input to can.log
    # args will be separated by comma and printed each time a new line
    def log(self, *args, file='can.log'):
        # With this case writing to can.log is quite a lot faster, as closing a file takes ages due to writing to fs
        # But we must ensure to close the file at some point
        if file is not 'can.log':
            with open(self.PATH + file, 'a+') as f:
                print(','.join(args), file=f)
            os.sync()
        else:
            # ensure we have an open file
            # if self.CAN_FILE.closed:  # closed does not exists, thus need workaround below
            try:
                self.CAN_FILE.read()
            except OSError:
                self.CAN_FILE = open(self.PATH + 'can.log', 'a+')
            print(','.join(args), file=self.CAN_FILE)

    # Override is working
    def ota(self):
        url = 'https://raw.githubusercontent.com/jsonnet/CANLogger/master/version'
        response = self.modem.http_request(url, 'GET')

        # If a newer version is available
        if float(response.text) > self.VERSION:
            url = 'https://raw.githubusercontent.com/jsonnet/CANLogger/master/code/main.py'
            response = self.modem.http_request(url, 'GET')
            # Override existing main file and reboot
            with open(self.PATH + 'main.py', 'w') as f:
                print(response.text, file=f)
                # Force buffer write and restart
                os.sync()
                machine.soft_reset()

    # Callback function for incoming call to initiate attack mode
    def incoming_call(self, _):
        # Hangup call
        self.modem.hangup()

        # Reactivate logger if called during sleep phase
        if self.shutdown:
            self.shutdown = False
            self.gsm_sleep.value(0)
            self.sendGPSCmd(self.GPS_ON)

        for u in self.allowed_users:
            self.telegram.send(u, 'Ready in attack mode!')

        # light up yellow to indicate attack mode
        LED(3).intensity(16)

        self.interrupt = True

    # PoC for Telegram
    def message_handler(self, messages):
        for message in messages:
            # Check permitted users
            if message['id'] not in self.allowed_users:
                continue
            if message[2] == '/start':
                self.telegram.send(
                    message[0], 'CAN Logger in attack mode, ready for you!')
            else:
                if message['text'] == "log":
                    params = message['text'].strip().split(" ")[1:]
                    # get
                    if params[0] == 'get':
                        self.telegram.sendFile(
                            message[0], open(self.PATH + 'can.log', 'rb'))
                        # with open(self.PATH + 'can.log', 'r') as f:
                        #    data = f.read()  # Okay, will print \n explicitly!
                        # self.telegram.send(message[0], data)
                        os.remove(self.PATH + 'can.log')

                    # clear
                    elif params[0] == 'clear':
                        os.remove(self.PATH + 'can.log')

                    else:
                        self.helpMessage(message)

                elif message['text'] == "replay":
                    # Find first message of id and resend x times
                    params = message['text'].strip().split(" ")[1:]
                    if len(params) < 2:
                        self.helpMessage(message)
                        continue

                    id, times = params[0:1]

                    while True:
                        can_id, _, _, can_data = self.can.recv(0)

                        if can_id == id:
                            for _ in times:
                                self.can2.send(can_data, can_id, timeout=1000)
                            self.log("sent {} from {} {} times".format(
                                can_data, can_id, times))
                            break
                elif message['text'] == "injection":
                    params = message['text'].split(" ")[1:]

                    if len(params) < 4:
                        self.helpMessage(message)
                        continue

                    can_id, can_data, times, _delay = params[0:2]
                    for _ in times:
                        self.can2.send(can_data, can_id, timeout=1000)
                        pyb.delay(_delay)
                elif message['text'] == "reply":

                    params = message['text'].strip().split(" ")[1:]
                    if len(params) < 4:
                        self.helpMessage(message)
                        continue

                    id, message, id_a, answer = params[0:3]

                    while True:
                        can_id, _, _, can_data = self.can.recv(0)

                        if can_id == id and can_data == message:
                            self.can2.send(answer, id_a, timeout=1000)
                            break
                elif message[
                        'text'] == "busoff":  # TODO WIP feature only manual at that point
                    params = message['text'].strip().split(" ")[1:]

                    if len(params) < 4:
                        self.helpMessage(message)
                        continue

                    mark_id, vic_id, payload, _delay = params[0:3]

                    self.can.setfilter(0, CAN.LIST16, 0, (
                        mark_id,
                        vic_id,
                    ))

                    # Clear buffer (maybe/hopefully)
                    for _ in range(5):
                        if not self.can.any(0):
                            break
                        self.can.recv(0)

                    count = 0
                    while count <= 5:
                        can_id, _, _, can_data = self.can.recv(0)
                        if can_id == mark_id:
                            pyb.delay(_delay)
                            self.can2.send(payload, vic_id, timeout=1000)

                        while True:
                            can_id, _, _, can_data = self.can.recv(0)
                            if can_id == vic_id and can_data != payload:
                                count = 0
                                break
                            count += 1

                    # reset filter
                    self.can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0))
                elif message['text'] == "filter":  # CAN Log Filter by ID
                    params = message['text'].strip().split(" ")[1:]

                    # add
                    if params[0] == 'add':
                        for id in params[1:]:
                            self.can_filter.append(id)
                    # remove
                    elif params[0] == 'remove':
                        for id in params[1:]:
                            self.can_filter.remove(id)
                    # clear
                    elif params[0] == 'clear':
                        self.can_filter.clear()

                    else:
                        self.helpMessage(message)

                elif message['text'] == "ota":
                    self.ota()

                elif message['text'] == "help":
                    self.helpMessage(message)

                elif message['text'] == "exit":
                    LED(3).off()
                    self.interrupt = False

                self.telegram.send(message[0], 'Executed!')

    def helpMessage(self, message):
        helpme = """
                        log get|clear - Retrieve or clear saved can data log
                        replay id freq - Replay messages of given id
                        reply id message answer - Reply to a specified message with an answer
                        injection id data freq delay - Inject given can packet into bus at a given frequency
                        busoff marker victim payload freq - Manual BUS off attack for given victim
                        filter add|remove|clear id - Set a filter for when logging
                        ota - Check and update newest version
                        help - Displays this message
                        exit - Exit this mode and return to logging                
                    """
        self.telegram.send(message[0], helpme)

    def sendGPSCmd(self, cmd):
        for i in range(len(cmd)):
            self.gps_uart.writechar(cmd[i])

    def loop(self):
        gps_time = utime.ticks_ms()

        while True:
            # Check if new messages arrived after shutdown
            if self.shutdown and not self.can.any(0):
                pyb.stop()  # soft sleep (500 uA)
                continue
            elif self.shutdown and self.can.any(0):
                self.shutdown = False
                self.gsm_sleep.value(0)
                self.sendGPSCmd(self.GPS_ON)

            # Main loop
            if not self.interrupt:
                # Free memory
                # gc.collect()
                ## Logging mode ##

                # Only log gps once a few seconds
                if utime.ticks_ms() - gps_time >= self.GPS_LOG_TIME:
                    gps_time = utime.ticks_ms()

                    # if module retrieved data: update and log
                    if self.gps_uart.any():
                        self.gps.updateall(self.gps_uart.read())
                        self.log(str(self.rtc.datetime()),
                                 self.gps.latitude_string(),
                                 self.gps.longitude_string(),
                                 self.gps.speed_string())

                # Log new incoming can messages
                try:
                    # throws OSError
                    can_id, _, _, can_data = self.can.recv(
                        0, timeout=self.SHUTOFF_TIME)
                    # Filter for CAN Log
                    if not self.can_filter or can_id in self.can_filter:
                        self.log(str(self.rtc.datetime()), str(can_id),
                                 binascii.hexlify(can_data).decode('utf-8'))

                except OSError:
                    # We timed out from can connection -> could mean car is shut down
                    self.shutdown = True
                    self.CAN_FILE.close()
                    os.sync()
                    self.gsm_sleep.value(1)
                    self.sendGPSCmd(self.GPS_OFF)
                    continue

            else:
                ## Attack mode ##
                self.CAN_FILE.close()  # Close log file first
                os.sync()
                while self.interrupt:
                    self.telegram.listen(self.message_handler)
Пример #25
0
       z = pickle.dumps(reset_dict).encode('utf8')
       bkram[0] = len(z)
       ba[4: 4+len(z)] = z
       restore_data()

    return pkl

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.
    (79, 100, -37, -2, -4, 24),  # 绿色激光
    (50, 77, 16, 65, -19, 31)  # 红色激光
]  # generic_blue_thresholds

sensor.reset()  # 传感器复位sensor.set_pixformat(sensor.GRAYSCALE) # use grayscale.
sensor.set_pixformat(
    sensor.RGB565
)  # RGB565即一个彩色图像点由RGB三个分量组成,总共占据2Byte,高5位为R分量,中间6位为G分量,低5位为B分量
sensor.set_framesize(sensor.QVGA)  # 320*240
sensor.skip_frames(time=500)  # 跳过,等待摄像头稳定
sensor.set_auto_gain(False)  # 自动增益在颜色识别中一般关闭,不然会影响阈值
sensor.set_auto_whitebal(False)  # 白平衡在颜色识别中一般关闭,不然会影响阈值
clock = time.clock()  # 构造时钟对象

uart = UART(3, 115200)
uart.init(115200, bits=8, parity=None, stop=1,
          timeout_char=1000)  # 使用给定参数初始化 timeout_char是以毫秒计的等待字符间的超时时长


class ctrl_info(object):
    WorkMode = 0x01  # 色块检测模式  0x01为固定单颜色识别  0x02为自主学习颜色识别  0x03 巡线
    Threshold_index = 0x00  # 阈值编号


ctrl = ctrl_info()  # 定义控制信息类
single_blob.InitSuccess_LED()  # 初始化完成 Green LED 快闪2下
'''-----------------------------------------------初始化分割线------------------------------------------------'''

while (True):

    clock.tick()  # 追踪时钟
    img = sensor.snapshot()  # thresholds为阈值元组0
Пример #27
0
# Hello World Example
#
# Welcome to the OpenMV IDE! Click on the green run arrow button below to run the script!

import sensor, image, time
from pyb import UART

sensor.reset()  # Reset and initialize the sensor.
sensor.set_pixformat(
    sensor.RGB565)  # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA)  # Set frame size to QVGA (320x240)
sensor.skip_frames(time=2000)  # Wait for settings take effect.
clock = time.clock()  # Create a clock object to track the FPS.
uart = UART(3, 9600, timeout_char=1000)
uart.init(9600, bits=8, parity=None, stop=1, timeout_char=1000)

while (True):
    #clock.tick()                    # Update the FPS clock.
    #img = sensor.snapshot()         # Take a picture and return the image.
    #print(clock.fps())              # Note: OpenMV Cam runs about half as fast when connected
    # to the IDE. The FPS should increase once disconnected.
    uart.write(b'MOF\r')
    print(b'' + uart.read())
Пример #28
0
from pyb import UART, Pin, delay

UART_ID = 3 # Uses Y9 as TX and Y10 as RX

uart = UART(UART_ID, 115200)
uart.init(115200, bits=8, parity=None, stop=1)

green_button = Pin("X5", Pin.IN)
red_button = Pin("X6", Pin.IN)

count = 0

while True:

    message = None
    while message == None:
        message = uart.read()
    
    message = str(message, 'utf-8')
    print("Message from ESP32: [", message, "]")

    message = '0'
    
    #while green_button.value() + red_button.value() == 0:
    #    pass
        
    if green_button.value() == 1 and red_button.value() == 1:
        message = '3'
    elif green_button.value() == 1:
        message = '2'
    elif red_button.value() == 1:
Пример #29
0
if 'LaunchPad' in machine:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
elif 'WiPy' in machine:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
else:
    raise Exception('Board not supported!')

# just in case we have stdio duplicated on any of the uarts
pyb.repl_uart(None)

for uart_id in uart_id_range:
    uart = UART(uart_id, 38400)
    print(uart)
    uart.init(baudrate=57600, stop=1, parity=None, pins=uart_pins[uart_id][0])
    uart.init(baudrate=9600, stop=2, parity=0, pins=uart_pins[uart_id][1])
    uart.init(baudrate=115200, parity=1, pins=uart_pins[uart_id][0])
    uart.sendbreak()

# 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')
Пример #30
0
                total_dist = 40
                right()
                stop()
                start()
                state = 'left'
        x0 = x
        y0 = y
    stop()
    print("map has been traced")


#############################################################################################################
#														SETUP												#
#############################################################################################################
uart = UART(4, 9600)  #UART for ESP communication
uart.init(9600, bits=8, parity=None, stop=1, read_buf_len=64)
dacA.write(init_dacA)
dacB.write(init_dacB)
motor_relay_L.high()
motor_relay_R.high()
motor1_switch.high()
motor2_switch.high()
motor_L_brake.high()
motor_R_brake.high()

setSpeedR(0)
setSpeedL(0)
Switch().callback(lambda: forward(2000))
tim.callback(speedCorrection)
ExtInt('Y1', ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE,
       cfreq_R)  #hall sensors as inperrupts
Пример #31
0
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))
#_________________________________________________
#  Task 6: Function to generate UART sequence for '#' on Y1
#  initialize UART(6) to output TX on Pin Y1

import pyb
from pyb import Pin, Timer, UART
print('Task 6: Using UART to send "#"')

uart = UART(6)
while True:
	uart.init(9600, bits=8, parity = 0, stop = 2)
	uart.writechar(ord('#'))
	pyb.delay(5)
Пример #33
0
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:

            if self.startByteFound:
                if self.frameIndex == (self.SBUS_FRAME_LEN - 1):
                    self.sbus.readinto(self.sbusBuff, 1)  # end of frame byte
                    if self.sbusBuff[0] == 0:  # TODO: Change to use constant var value
                        self.startByteFound = False
                        self.isSync = True
                        self.frameIndex = 0
                else:
                    self.sbus.readinto(self.sbusBuff, 1)  # keep reading 1 byte until the end of frame
                    self.frameIndex += 1
            else:
                self.frameIndex = 0
                self.sbus.readinto(self.sbusBuff, 1)  # read 1 byte
                if self.sbusBuff[0] == 15:  # TODO: Change to use constant var value
                    self.startByteFound = True
                    self.frameIndex += 1

    def get_new_data(self):

        if self.isSync:
            if self.sbus.any() >= self.SBUS_FRAME_LEN:
                self.sbus.readinto(self.sbusFrame, self.SBUS_FRAME_LEN)  # read the whole frame
                if (self.sbusFrame[0] == 15 and self.sbusFrame[
                        self.SBUS_FRAME_LEN - 1] == 0):  # TODO: Change to use constant var value
                    self.validSbusFrame += 1
                    self.outOfSyncCounter = 0
                    self.decode_frame()
                else:
                    self.lostSbusFrame += 1
                    self.outOfSyncCounter += 1

                if self.outOfSyncCounter > self.OUT_OF_SYNC_THD:
                    self.isSync = False
                    self.resyncEvent += 1
        else:
            self.get_sync()
# main.py -- put your code here!
from pyb import Pin, ExtInt, UART, delay
from time import sleep
import pyb

start_pin = Pin('Y3', Pin.IN, Pin.PULL_UP) # PB8 monitors start button push event.
stop_pin = Pin('X2', Pin.IN, Pin.PULL_UP) # PA1 monitors stop button push event.
led_pin = Pin('X5', Pin.OUT_PP) # PA4 drives LED indicator.
led_pin.low() 
uart = UART(2, 9600) # UART2 communcates to CSi8.
uart.init(9600, bits=7, parity=1, stop=1) 
start_pressed = 0
# stop_pressed = 0
t1_set = 200
t1_last = 30
t2_set = 600
t1_t2_step = 1
t1_t2_last = 480
t2_last = 120
off_last = 390
cmd_prefix = '*P012' # Write to RAM of point 1 with positive sign and decimal point 2
cmd_standby = '*D03' # Standby mode with output off
cmd_dis_standby = '*E03'# Disable standby
start_value = 0
stop_value = 0
print("stop_pin.value="+str(stop_pin.value()))
print("start_pin.value="+str(start_pin.value()))

def start_callback(line):
  
  global start_pressed, start_int, pyb, start_pin, stop_pin
#通信协议:0x5a/0x5a/   X    /     Y     / mode                            /color/distance/0xb3
#       头帧 / 头帧/色块x 默认0/色块Y 默认0/默认0,圆,1、三角形2、正方形3 篮球4 排球5 足球6/默认0 R1G2B3/默认0 物体长度 /尾帧
#三角形和正方形由于旋转的影响可能不准
import sensor, image, time, math
from pyb import UART

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA)  #160*120
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
clock = time.clock()

uart = UART(3, 115200)
uart.init(115200, bits=8, parity=None, stop=1)  #8位数据位,无校验位,1位停止位
threshold_index = 0  # 0 for red, 1 for green, 2 for blue
thresholds = [
    (16, 71, 15, 102, -23, 97),  # red_thresholds
    (11, 29, -33, -17, 0, 48),  # green_thresholds
    (0, 42, -23, 16, -46, -5)
]  # blue_thresholds

while (True):
    clock.tick()
    img = sensor.snapshot().rotation_corr(z_rotation=180)
    #参数初始化
    X = 0  #物体中心x坐标
    Y = 0  #物体中心Y坐标
    mode = 0  #形状 默认0 圆1角2方3
    color = 0  #颜色 默认0 R1G2B3
class SBUSReceiver:
    def __init__(self, uart_port):
        self.sbus = UART(uart_port, 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

    def get_rx_channels(self):
        """
        Used to retrieve the last SBUS channels values reading
        :return:  an array of 18 unsigned short elements containing 16 standard channel values + 2 digitals (ch 17 and 18)
        """
        return self.sbusChannels

    def get_rx_channel(self, num_ch):
        """
        Used to retrieve the last SBUS channel value reading for a specific channel
        :param: num_ch: the channel which to retrieve the value for
        :return:  a short value containing
        """
        return self.sbusChannels[num_ch]

    def get_failsafe_status(self):
        """
        Used to retrieve the last FAILSAFE status
        :return:  a short value containing
        """
        return self.failSafeStatus

    def get_rx_report(self):
        """
        Used to retrieve some stats about the frames decoding
        :return:  a dictionary containg three information ('Valid Frames','Lost Frames', 'Resync Events')
        """

        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:

            if self.startByteFound:
                if self.frameIndex == (self.SBUS_FRAME_LEN - 1):
                    self.sbus.readinto(self.sbusBuff, 1)  # end of frame byte
                    if self.sbusBuff[0] == 0:  # TODO: Change to use constant var value
                        self.startByteFound = False
                        self.isSync = True
                        self.frameIndex = 0
                else:
                    self.sbus.readinto(self.sbusBuff, 1)  # keep reading 1 byte until the end of frame
                    self.frameIndex += 1
            else:
                self.frameIndex = 0
                self.sbus.readinto(self.sbusBuff, 1)  # read 1 byte
                if self.sbusBuff[0] == 15:  # TODO: Change to use constant var value
                    self.startByteFound = True
                    self.frameIndex += 1

    def get_new_data(self):
        """
        This function must be called periodically according to the specific SBUS implementation in order to update
        the channels values.
        For FrSky the period is 300us.
        """

        if self.isSync:
            if self.sbus.any() >= self.SBUS_FRAME_LEN:
                self.sbus.readinto(self.sbusFrame, self.SBUS_FRAME_LEN)  # read the whole frame
                if (self.sbusFrame[0] == 15 and self.sbusFrame[
                        self.SBUS_FRAME_LEN - 1] == 0):  # TODO: Change to use constant var value
                    self.validSbusFrame += 1
                    self.outOfSyncCounter = 0
                    self.decode_frame()
                else:
                    self.lostSbusFrame += 1
                    self.outOfSyncCounter += 1

                if self.outOfSyncCounter > self.OUT_OF_SYNC_THD:
                    self.isSync = False
                    self.resyncEvent += 1
        else:
            self.get_sync()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQSIF)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(True)
sensor.set_auto_whitebal(False)
sensor.set_auto_exposure(True)
sensor.set_contrast(3)
sensor.set_saturation(3)
ImageX = 88
ImageY = 60
letter_thresholds = (0, 50)
red_thresholds = (30, 70, 30, 100, 30, 100)
yellow_thresholds = (70, 100, -10, 30, 60, 100)
green_thresholds = (30, 100, -100, -40, 30, 100)
uart = UART(3, 9600, timeout_char=10)
uart.init(9600)
clock = time.clock()
blobHcenter = 0
blobHtop = 255
blobHbottom = 255
blobHleft = 0
blobHright = 0
blobHtopleft = 0
blobHtopright = 0
blobHbottomleft = 0
blobHbottomright = 0
blobScenter = 0
blobStop = 0
blobSbottom = 0
blobSleft = 255
blobSright = 255
Пример #38
0
from pyb import UART

uart = UART(1)
uart = UART(1, 9600)
uart = UART(1, 9600, bits=8, stop=1, parity=None)
print(uart)

uart.init(1200)
print(uart)

uart.any()
uart.send(1, timeout=500)


import sensor, image, time, math, pyb
from pyb import UART, Pin, Timer


# LEDs for debugging
red = pyb.LED(1)
blue = pyb.LED(3)
green = pyb.LED(2)


# Setting up UART for Bluetooth
uart = UART(3, 9600, timeout_char = 10000)
uart.init(9600, bits=8, parity=None, stop=1)


# MOTOR AND SERVO INIT CODE
inA = pyb.Pin("P0", pyb.Pin.OUT_PP)
inB = pyb.Pin("P1", pyb.Pin.OUT_PP)

inA.low()
inB.low()

tim = Timer(4, freq=300) # Frequency in Hz

tim2 = Timer(2, freq=200)
ch1 = tim2.channel(1, Timer.PWM, pin=Pin("P6"), pulse_width_percent=20)

ch2 = tim.channel(2, Timer.PWM, pin=Pin("P8"), pulse_width=4500)
Пример #40
0
#programamos pines
wixel = pyb.Pin('Y11',pyb.Pin.OUT_PP)
wixel.low() #turn on
geigerPower = pyb.Pin('Y9', pyb.Pin.OUT_PP) #relay for power geiger
geigerPower.high()  #turn off
geigerIn = pyb.Pin('Y10', pyb.Pin.IN)

#pitido inicial en salida Y8
tim12 = pyb.Timer(12, freq=3500)
ch2=tim12.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.Y8, pulse_width=12000)
pyb.delay(100) #in msecs
ch2.pulse_width(0)

#uart6 a wixel, pins Y1 y Y2
uart = UART(6,9600)
uart.init(9600,bits=8,stop=1,parity=None)
pyb.repl_uart(uart)

#initalize fram
fr = fram.fram()
frt = fram_t.fram_t(fr)

#rtc
rtc = pyb.RTC()

#initialize am2302
a = am2302.am2302(ch2, frt)

#initialize loop
l = loop.loop(geigerPower, a, fr, frt, ch2, uart, wixel)
Пример #41
0

class Dot(object):
    x = 0
    y = 0
    last_dot=0
class receive(object):
    uart_buf = []
    _data_len = 0
    _data_cnt = 0
    state = 0
Receive=receive()
clock = time.clock()
dot  = Dot()
uart = UART(3,115200)
uart.init(115200,timeout_char=1000)

#Global variables End


def init(is_debug,delay_time):
    uart.deinit()
    sensor.reset()
    sensor.set_pixformat(sensor.GRAYSCALE)
    sensor.set_framesize(sensor.QVGA)
    sensor.set_contrast(3)
    sensor.set_brightness(-3)
    sensor.set_auto_exposure(True)
    sensor.skip_frames(time = delay_time)
    sensor.set_auto_whitebal(False)
    uart.init(115200,timeout_char=1000)
Пример #42
0
if 'LaunchPad' in machine:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
elif 'WiPy' in machine:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
else:
    raise Exception('Board not supported!')

# just in case we have stdio duplicated on any of the uarts
pyb.repl_uart(None)

for uart_id in uart_id_range:
    uart = UART(uart_id, 38400)
    print(uart)
    uart.init(57600, 8, None, 1, pins=uart_pins[uart_id][0])
    uart.init(baudrate=9600, stop=2, parity=UART.EVEN, pins=uart_pins[uart_id][1])
    uart.init(baudrate=115200, parity=UART.ODD, stop=0, pins=uart_pins[uart_id][0])
    uart = UART(baudrate=1000000)
    uart.sendbreak()

uart = UART(baudrate=1000000)
uart = UART()
print(uart)
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'))
from pyb import UART

# test we can correctly create by id or name
for bus in (-1, 0, 1, 2, 3, 4, 5, 6, 7, "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))
Пример #44
0
class RS485(object):   
    def __init__(self, uart_num, pin_rw, dev_id):
        self.error = []
        self.uart = UART(uart_num)
        self.uart.init(57600, bits=8, parity=0, timeout=10, read_buf_len=64)
        self.pin_rw = Pin(pin_rw)
        self.pin_rw.init(Pin.OUT_PP)
        self.pin_rw.value(0)
        self.dev_id = dev_id
        
        self.file_parts = 0
        self.file_parts_i = 1
        self.file_is_open = False

    def check_lan(self):
        res = []
        uart = self.uart
        try:
            
            buf = uart.readall()            
            if buf:
                buf = buf.decode("utf-8")
                LED(2).toggle()
                for pack in buf.split(chr(0x0)):
                    if pack:
                        try:
                            data = False
                            data = loads(pack)
                            if len(data) > 0 and data[0] == self.dev_id:
                                if data[2][0] == "SET_CONFIG_FILE":
                                    res = [data]
                                    if data[2][2] == False:
                                        self.file_parts = data[2][1]
                                        self.file_parts_i = 1
                                        self._write_config(True, '')
                                        self.file_is_open = True
                                    else:
                                        if self.file_is_open:
                                            if self.file_parts_i == data[2][1]:
                                                self._write_config(False, data[2][2])
                                                if self.file_parts_i == self.file_parts:
                                                    self.file_is_open = False
                                                self.file_parts_i += 1
                                            else:
                                                res = [[self.dev_id, 3]]
                                                self.error += ["Error 3  %s" % (data)]
                                                self.file_is_open = False
                                                break
                                        else:
                                            res = [[self.dev_id, 3]]
                                            self.error += ["Error 4 DATA: %s" % (data)]
                                            break
                                else:
                                    self.file_is_open = False
                                    res = [data]
                        except Exception as e:
                            res = [[self.dev_id, 3]]
                            if data:
                                self.error += ["Error 1 {}".format(e.args) + " DATA:  %s" % (data)]
                            else:
                                self.error += ["Error 1 {}".format(e.args) + " PACK:  %s" % (pack)]
                            LED(4).on()
        except Exception as e:
            res = [[self.dev_id, 3]]
            self.error += ["Error 2 {}".format(e.args)]
            LED(4).on()
        return res

    def send_pack(self, pack_type, pack_data):
        pin_rw = self.pin_rw.value
        uart = self.uart
        pin_rw(1)
        try:
            buf = [self.dev_id, pack_type, pack_data]
            data = dumps(buf).encode("utf-8")
            data += bytearray([0x0])
            uart.write(data)
        except:
            #print("Возникла ошибка при отправке пакета")
            #print(data)
            LED(3).on()
        pin_rw(0)

    def _write_config(self, is_start, data):
        if is_start:
            f = open("config.py", "w")
        else:
            f = open("config.py", "a")
        try:
            f.write(data)
        except:
            pass
        f.close()