Esempio n. 1
0
	def __init__(self, UART_number):

		# initiate sensor with a UART value
		UART.setup("UART" + str(UART_number))

		# UART number corresponds to terminal number (convenient)
		self.tty = UART_number
Esempio n. 2
0
def imu():
    pub = rospy.Publisher("lisa/sensors/imu", Imu, queue_size=10)
    times_per_second = 5
    bytes_to_read = 130  #This is slightly over twice the length of a single line of data.  A single line is ~58 characters.

    rospy.loginfo("Initializing IMU")
    rospy.init_node("imu")
    rate = rospy.Rate(times_per_second) # 10hz
    UART.setup("UART1")
    ser = serial.Serial(port = "/dev/ttyO1", baudrate=115200)
    ser.close()
    ser.open()
    if ser.isOpen():
    	print "Serial is open!"

    while not rospy.is_shutdown():
        ser.flushInput() #The imu blasts us with data and fills up the serial input buffer.  We clear it out here to wait for new values
        stream = ser.read(bytes_to_read)
        full_orientation = stream.split('\n')[-2] #Since we're getting a stream of data, we don't know whether we're starting at the beginning of the line or the middle. This throws out the last partial line and gets the previous full line
        yaw_deg = float(re.split('\s*', full_orientation)[-2])
        rospy.loginfo("yaw=%0.3f", yaw_deg)
        # correct backwards yaw
        #yaw = yaw_deg * math.pi / 180.0
        yaw = -1.0 * yaw_deg * math.pi / 180.0
        q = tf.transformations.quaternion_from_euler(0, 0, yaw)
        o = Imu()
        o.orientation.x = q[0]
        o.orientation.y = q[1]
        o.orientation.z = q[2]
        o.orientation.w = q[3]
        publish_orientation(pub, o)
        rate.sleep()

    ser.close()
Esempio n. 3
0
 def __init__(self):
     UART.setup("UART1")
     self.ser = serial.Serial(port="/dev/ttyS1", baudrate=9600)
     self.ser.close()
     self.ser.open()
     self.ser.isOpen()
     print("Serial communication ready!")
Esempio n. 4
0
 def __init__(self):
     self._backend = 'http://localhost:5000/'
     self._headers = {'Content-type': 'application/json'}
     UART.setup("UART1")
     ser = serial.Serial(port="/dev/ttyS1", baudrate=19200)
     ser.close()
     ser.open()
Esempio n. 5
0
    def __init__(self):
        import Adafruit_BBIO.UART as UART
        import serial

        self.type = 'output'
        self.name = 'airu'

        # Turn off LEDs
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr0/trigger',
            shell=True)
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr1/trigger',
            shell=True)
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr2/trigger',
            shell=True)
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr3/trigger',
            shell=True)

        UART.setup("UART1")

        # Open a connection with the PMS3003 sensor
        self._pm = serial.Serial(port=PM_PORT,
                                 baudrate=9600,
                                 rtscts=True,
                                 dsrdtr=True)

        if not self._pm.isOpen():
            self._pm.open()
Esempio n. 6
0
    def __init__(self, Beagle_UART="UART1", port="/dev/ttyO1", address=128):
        """
            Beagle_UART - UART0, UART1 or UART2 on BeagleBone Black to use
            port        - /dev/ttyXX device to connect to
            address     - address of Sabertooth controller to send commands to
            
        """
        self.UART = Beagle_UART
        self.port = port
        self.address = address

        if (self.UART == None) or (self.port == None) or (self.address < 128 or
                                                          self.address > 135):
            raise ("Invalid parameters")
            return None

        # Setup UART on BeagleBone (loads device tree overlay)
        UART.setup(self.UART)

        # Initialiase serial port
        self.saber = serial.Serial()
        self.saber.baudrate = 9600
        self.saber.port = '/dev/%s' % (self.port)
        self.saber.open()
        self.isOpen = self.saber.isOpen()
        return None
Esempio n. 7
0
    def __init__(self, Beagle_UART="UART1", port="/dev/ttyO1", address=128):
        """
            Beagle_UART - UART0, UART1 or UART2 on BeagleBone Black to use
            port        - /dev/ttyXX device to connect to
            address     - address of Sabertooth controller to send commands to
            
        """
        self.UART = Beagle_UART
        self.port = port
        self.address = address

        if (self.UART == None) or (self.port == None) or (self.address < 128 or self.address > 135):
            raise ("Invalid parameters")
            return None

        # Setup UART on BeagleBone (loads device tree overlay)
        UART.setup(self.UART)
        
        # Initialiase serial port
        self.saber = serial.Serial()
        self.saber.baudrate = 9600
        self.saber.port = '/dev/%s' % (self.port)
        self.saber.open()
        self.isOpen = self.saber.isOpen()
        return None
Esempio n. 8
0
    def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=TIMEOUT):
        self.type = 'output'
        self.name = 'dylos'

        self.running = True
        self.queue = Queue()

        # Turn off LEDs
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr0/trigger',
            shell=True)
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr1/trigger',
            shell=True)
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr2/trigger',
            shell=True)
        subprocess.call(
            'echo none > /sys/class/leds/beaglebone\:green\:usr3/trigger',
            shell=True)

        # Setup UART
        UART.setup("UART1")

        self.ser = serial.Serial(port=port,
                                 baudrate=baudrate,
                                 parity=serial.PARITY_NONE,
                                 stopbits=serial.STOPBITS_ONE,
                                 bytesize=serial.EIGHTBITS,
                                 timeout=timeout)

        if not self.ser.isOpen():
            self.ser.open()
    def __init__(self, queue_input, stopevent, sel_uart, occupe):
        #Les liaisons valides sont les liaisons 1,2,4
        if (sel_uart not in [1, 2, 4]):
            return "Erreur : la liaison série spécifiée n'est pas valide"
        #Initialisation du thread lui-même
        threading.Thread.__init__(self)
        #Les informations à émettre sur la liaison série
        self.input = queue_input
        #variable écoutant l'arrêt du thread par le controleur
        self.stoprequest = stopevent

        #Variable empechant l'empiêtement des classes Série (pas de lecture quand envoi, et pas d'envoi quand lecture)
        self.occupe = occupe
        ### Liaison série
        #On choisit la liaison série spécifiée, sinon la liaison série 1 par défaut
        UART.setup("UART" + str(sel_uart))

        #Ouverture de la liaison série
        #le parametre stopbits DOIT etre égal à 1, le mettre à deux entraine une incompréhension par le controleur des moteurs des ordres à envoyer
        self.ser = serial.Serial(port="/dev/ttyO" + str(sel_uart),
                                 baudrate=38400,
                                 bytesize=8,
                                 stopbits=1,
                                 timeout=None)
        #On ferme la liaison série instanciée, afin de ne pas occuper constamment le canal
        self.ser.close()
Esempio n. 10
0
def set_uart(uart_id):
    """Active le port de communication série.
    """

    if uart_id not in (1, 2, 3, 4, 5):
        logging.error("Port série invalide : UART{}".format(uart_id))
        return

    elif uart_id == 1:
        pins_uart = ("P9_26", "P9_24", "P9_20", "P9_19")
    elif uart_id == 2:
        pins_uart = ("P9_22", "P9_21")
    elif uart_id == 3:
        pins_uart = ("P9_42", "P8_36", "P8_34")
    elif uart_id == 4:
        pins_uart = ("P9_11", "P9_13", "P8_35", "P8_33")
    elif uart_id == 5:
        pins_uart = ("P8_38", "P8_37", "P8_31", "P8_32")

    for pin in pins_uart:
        try:
            if pins[pin] is not None:
                logging.error("{} est déjà configurée en '{}'".format(pin, pins[pin]))
                return
            else:
                pins[pin] = "uart{}".format(uart_id)
        except KeyError:
            continue
    UART.setup("UART{}".format(uart_id))
Esempio n. 11
0
    def __init__(self):
        self.UDP_IPReceive = ""
        self.UDP_IPSend = "192.168.1.19"
        self.UDP_PORT_RECV = 5005
        self.UDP_PORT_SEND = 5006

        self.receiveSock = socket.socket(socket.AF_INET,  # Internet
                         socket.SOCK_DGRAM)  # UDP
        self.receiveSock.bind((self.UDP_IPReceive, self.UDP_PORT_RECV))

        self.sendSock = socket.socket(socket.AF_INET,  # Internet
                             socket.SOCK_DGRAM)  # UDP

        uart.setup("UART2")  # Sensor Board
        self.telemetry = serial.Serial(port="/dev/ttyO2", baudrate=115200)
        self.telemetry.close()
        self.telemetry.open()

        uart.setup("UART1")  # Motor Driver Board
        self.thrusters = serial.Serial(port="/dev/ttyO1", baudrate=115200)
        self.thrusters.close()
        self.thrusters.open()

        self.vert = 0
        self.port = 0
        self.stbd = 0
        self.port1 = 0
        self.stbd1 = 0
        self.port2 = 0
        self.stbd2 = 0

        self.receiver()
        self.telemetryStatus()
Esempio n. 12
0
def dumb_tty(port):
	"""
	Simple dumb TTY that allows you to execute commands in Command
	Mode. Bit buggy when reading output. Good demo of CommandMode.

	Dependency on Adafruit_BBIO, but may be removed if your UART is
	already prepared.

	Parameters
	----------
	port : string
		the dir to the TTY or COM port

	"""
	UART.setup("UART1")
	hlsd = pyhypnolsd.command_mode.from_port(port)

	get_command = True
	while (get_command):
		# Get input
		command = raw_input("> ")

		# Check for exit
		if (command == "exit"):
			get_command = False
			continue

		# Send command, let it print output
		hlsd.send_command(command, True)

	# Close remaining connections
	hlsd.close()
    def test_pocketbeagle(self):
        if kernel < '4.1.0':
            pass
        value = open('/proc/device-tree/model').read()
        if (value.startswith("TI AM335x PocketBeagle")):
            uarts = {
                'PB-UART0': '/dev/ttyO0',
                'PB-UART1': '/dev/ttyO1',
                'PB-UART2': '/dev/ttyO2',
            }
        else:
            uarts = {
                'UART1': '/dev/ttyO1',
                'UART2': '/dev/ttyO2',
                'UART4': '/dev/ttyO4'
                # note: UART5 requires
                # "disable_uboot_overlay_video=1" in /boot/uEnv.txt
                #'UART5': '/dev/ttyO5'
            }

        for name, device in sorted(uarts.items()):
            UART.setup(name)
            uart = serial.Serial(port=device, baudrate=9600)
            uart.close()
            uart.open()
            if uart.isOpen():
                uart.write("hello world".encode("utf-8"))
            uart.close()
Esempio n. 14
0
 def __init__(self):
     Sensor.__init__(self)
     UART.setup("UART1")
     self.ser = serial.Serial(port='/dev/ttyO1', baudrate=9600)
     #This sets up variables for useful commands.
     #This set is used to set the rate the GPS reports
     UPDATE_10_sec = "$PMTK220,10000*2F\r\n"  #Update Every 10 Seconds
     UPDATE_5_sec = "$PMTK220,5000*1B\r\n"  #Update Every 5 Seconds
     UPDATE_1_sec = "$PMTK220,1000*1F\r\n"  #Update Every One Second
     UPDATE_200_msec = "$PMTK220,200*2C\r\n"  #Update Every 200 Milliseconds
     #This set is used to set the rate the GPS takes measurements
     MEAS_10_sec = "$PMTK300,10000,0,0,0,0*2C\r\n"  #Measure every 10 seconds
     MEAS_5_sec = "$PMTK300,5000,0,0,0,0*18\r\n"  #Measure every 5 seconds
     MEAS_1_sec = "$PMTK300,1000,0,0,0,0*1C\r\n"  #Measure once a second
     MEAS_200_msec = "$PMTK300,200,0,0,0,0*2F\r\n"  #Meaure 5 times a second
     #Set the Baud Rate of GPS
     BAUD_57600 = "$PMTK251,57600*2C\r\n"  #Set Baud Rate at 57600
     BAUD_9600 = "$PMTK251,9600*17\r\n"  #Set 9600 Baud Rate
     #Commands for which NMEA Sentences are sent
     self.ser.write(BAUD_57600)
     sleep(1)
     self.ser.baudrate = 57600
     GPRMC_ONLY = "$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n"  #Send only the GPRMC Sentence
     GPRMC_GPGGA = "$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n"  #Send GPRMC AND GPGGA Sentences
     SEND_ALL = "$PMTK314,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n"  #Send All Sentences
     SEND_NOTHING = "$PMTK314,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n"  #Send Nothing
     self.ser.write(UPDATE_200_msec)
     sleep(1)
     self.ser.write(MEAS_200_msec)
     sleep(1)
     self.ser.write(GPRMC_GPGGA)
     sleep(1)
     self.ser.flushInput()
     self.ser.flushInput()
     print "GPS Initialized"
Esempio n. 15
0
def read_once():
    import serial
    import Adafruit_BBIO.UART as UART
    UART.setup("UART4")
    GPS = serial.Serial('/dev/ttyO4', 9600)
    str = GPS.readline()
    print(str)
    return str
 def setup_bbb_uart(self):
     # Is this necessary if I don't want to use it myself??
     UART.setup(self.uart)
     self.ser = serial.Serial(port=self.tty, baudrate=9600)
     self.ser.close()
     self.ser.open()
     if self.ser.isOpen():
         return True
     else:
         return False
Esempio n. 17
0
def __main__():
	UART.setup("UART1")
	UART.setup("UART4")
	GPS1 = serial.Serial('/dev/ttyO1', 4800)
	GPS4 = serial.Serial('/dev/ttyO4', 4800)
	while(1):
		if GPS1.inWaiting() ==1:
			parse(GPS1.readline(),1)	 
		if GPS4.inWaiting() ==1:
			parse(GPS4.readline(),4)
Esempio n. 18
0
    def __init__(self):
        self.mScreenBuffer = ScreenBuffer()

        UART.setup(Sender.mUart)

        self.mSerial = serial.Serial(port=mUartDev, buadrate=mBaudRate)
        self.mSerial.close()
        self.mSerial.open()
        if self.mSerial.isOpen():
            self.mSerial.write("Beaglebone serial is open.")
Esempio n. 19
0
 def setup_bbb_uart(self):
     # Is this necessary if I don't want to use it myself??
     UART.setup(self.uart)
     self.ser = serial.Serial(port=self.tty, baudrate=9600)
     self.ser.close()
     self.ser.open()
     if self.ser.isOpen():
         return True
     else:
         return False
Esempio n. 20
0
def __main__():
    UART.setup("UART1")
    UART.setup("UART4")
    GPS1 = serial.Serial('/dev/ttyO1', 4800)
    GPS4 = serial.Serial('/dev/ttyO4', 4800)
    while (1):
        if GPS1.inWaiting() == 1:
            parse(GPS1.readline(), 1)
        if GPS4.inWaiting() == 1:
            parse(GPS4.readline(), 4)
Esempio n. 21
0
 def __init__(self, uart_num, baud=9600):
     fstring = "UART" + str(uart_num)
     uart_bus.setup(fstring)
     device = "/dev/ttyO" + str(uart_num)
     self.ser = serial.Serial(device,
                              baud,
                              parity=serial.PARITY_NONE,
                              stopbits=serial.STOPBITS_ONE,
                              bytesize=serial.EIGHTBITS,
                              timeout=1)
Esempio n. 22
0
def __main__():
	UART.setup("UART1")
	UART.setup("UART2")
	GPS1 = serial.Serial('/dev/ttyO1', 4800)
	GPS2 = serial.Serial('/dev/ttyO2', 4800)
	while(1):
		if GPS1.inWaiting() ==0:
			parse(GPS1.readline())	 
		if GPS2.inWaiting() ==0:
			parse(GPS2.readline())
Esempio n. 23
0
	def __init__(self, port=1):
		threading.Thread.__init__(self)

		UART.setup(("UART%i" % port))

		self.serial = serial.Serial(port=("/dev/ttyO%i" % port), baudrate=115200, timeout=0.1)
		self.serial.close()
		self.serial.open()

		self.serial.write("Started\r\n")
Esempio n. 24
0
    def __init__(self):
        self.mScreenBuffer = ScreenBuffer()

        UART.setup(Sender.mUart)

        self.mSerial = serial.Serial(port = mUartDev, buadrate = mBaudRate)
        self.mSerial.close()
        self.mSerial.open()
        if self.mSerial.isOpen():
            self.mSerial.write("Beaglebone serial is open.")
Esempio n. 25
0
 def __init__(self, option, logger):
     self._option = option
     if logger is None:
         self._logger = util.getdefaultlogger()
     else:
         self._logger = logger
     self._rbuf = ""
     self._wbuf = ""
     if "BBB" in option and option["BBB"] is True:
         import Adafruit_BBIO.UART as UART
         UART.setup("UART1")
Esempio n. 26
0
 def initialize_UART(self, uart_port_str, ser_port_str):
     print("Initializing motor controller UART")
     try:
         uart.setup(uart_port_str)
         self.ser = serial.Serial(port=ser_port_str, baudrate=9600, timeout=1)
         self.ser.close()
         self.ser.open()
         print("Successfully initialized UART")
     except Exception as e:
         print("error in opening uart.")
         print(e)
Esempio n. 27
0
def get_ph():
    print 'we are in get_ph'
    uart.setup('UART2')
    ser = serial.Serial(port = '/dev/ttyO2', baudrate=38400)
    print 'opened serial port'
    ser.open()
    ser.write('R\r')
    data = ser.read()
    print 'ph received raw as %s' % data
    ser.close()
    uart.cleanup()
    return data
def main():

    """Entry point to nabaztag_client application.

    Initialises the Serial port, starts all application threads, and initiates the websocket connection
    """

    # Serial setup
    UART.setup("UART1")
    serial = pyserial.Serial(port=SERIAL, baudrate=RATE)

    serial_queue = Queue.Queue()
    update_queue = Queue.Queue()

    serial_write_thread = SerialWriter(
        serial,
        serial_queue,
        name="serialwrite"
    )

    serial_read_thread = SerialReader(
        serial,
        update_queue,
        name="serialread"
    )

    update_thread = UpdateThread(
        POST_URL.format(
            host=HOST,
            port=PORT,
            identifier=getid(INTERFACE)
        ),
        update_queue,
        name="postupdate"
    )

    serial_write_thread.start()
    serial_read_thread.start()
    update_thread.start()

    websocket_thread = WSClient(
        WS_URL.format(
            host=HOST,
            port=PORT,
            identifier=getid(INTERFACE)
        ),
        serial_queue,
        update_queue,
        name="websocket"
    )

    websocket_thread.connect()
    websocket_thread.run_forever()
Esempio n. 29
0
    def __init__(self,
                 timeout=0,
                 serial_input_type='MP',
                 verbose_flag=False,
                 game=None):
        self.timeout = timeout
        self.serialInputType = serial_input_type
        self.verboseFlag = verbose_flag
        self.game = game

        # Variables
        self.receiveList = []
        self.packet = ''
        self.ETNpacketList = []

        # Prepare for ETN packet inspection
        self.sp = app.serial_IO.serial_packet.SerialPacket(self.game)

        # Mulit-platform support
        platform = app.utils.Platform.platform_detect()
        if platform == 2:
            import Adafruit_BBIO.UART as UART
            import serial
            UART.setup('UART1')
            port_name = '/dev/ttyO1'
        elif platform == 1:
            import serial
            port_name = '/dev/ttyS0'
        else:
            print("Don't work on windows yet")
            return  # Needed to skip the rest of __init__

        # Select input type
        if self.serialInputType == 'MP':
            self.previousLowByte = None
            self.maxBytes = 10
            self.timeout = 0
        elif self.serialInputType == 'ASCII':
            self.maxBytes = 250
            self.timeout = 0.008

        # Setup serial port
        print('port_name', port_name)
        self.ser = serial.Serial(port=port_name,
                                 baudrate=38400,
                                 bytesize=8,
                                 timeout=self.timeout)

        # TODO: Do I need these 3 lines?
        self.ser.close()
        self.ser.open()
        self.ser.flushInput()
Esempio n. 30
0
def openUart():
        """
        Opens UART1 (TX = 24, RX = 26). Returns true if successful.
        """

        UART.setup("UART1")
        ser = serial.Serial(port = "/dev/ttyO1", baudrate=9600, timeout=_TIMEOUT)

        # Reset port
        ser.close()
        ser.open()

        return ser
Esempio n. 31
0
    def __init__(self,
                 timeout=0,
                 serialInputType='MP',
                 verbose=False,
                 game=None):
        self.serialInputType = serialInputType
        self.verbose = verbose
        self.game = game
        PLATFORM = platform_detect()

        if PLATFORM == 2:
            import Adafruit_BBIO.GPIO as GPIO
            import Adafruit_BBIO.UART as UART
            import serial
            UART.setup('UART1')
            portName = '/dev/ttyO1'
        elif PLATFORM == 1:
            import RPi.GPIO as GPIO
            import serial
            portName = '/dev/ttyS0'
        else:
            self.ser = "Don't work on windows yet"
            print self.ser
            return

        if self.serialInputType == 'MP':
            self.previousLowByte = None
            self.maxBytes = 10
            self.bufferSize = 0
        elif self.serialInputType == 'ASCII':
            timeout = 0.008
            self.maxBytes = 1024
            self.bufferSize = 0

        print 'portName', portName
        self.ser = serial.Serial(port=portName,
                                 baudrate=38400,
                                 bytesize=8,
                                 timeout=timeout)
        self.ser.close()
        self.ser.open()
        self.receiveList = []
        self.packet = ''
        self.ETNpacketList = []
        self.sp = Serial_Packet()
        self.sp.ETNFlag = False
        self.sp.game = self.game
        self.sp.decodePacket = 'from serial ETN check'
        self.sp.MPserial = True

        self.ser.flushInput()
    def setup( self ):
        """
        setup - sets up the serial line on the beaglebone board
        """
        serial_port = None

        UART.setup( self.config[Constants.XbeeConfiguration.xbee_beaglebone_black_uart] )

        port = self.config[Constants.XbeeConfiguration.xbee_beaglebone_port]
        baudrate = int( self.config[Constants.XbeeConfiguration.xbee_beaglebone_baudrate] )
        timeout = int( self.config[Constants.XbeeConfiguration.xbee_beaglebone_timeout] )

        serial_port = Serial( port, baudrate, timeout=timeout )
        return serial_port
Esempio n. 33
0
def modem_init():

    print "Setting up UART1..."
    UART.setup("UART1")
    print "Setting up UART2..."
    UART.setup("UART2")
    print "Setting up UART4..."
    UART.setup("UART4")
    print "Setting up UART5..."
    UART.setup("UART5")

    print "Initializing GPIO(s)"

    GPIO.setup("P9_12", GPIO.OUT)  # CELL_ENABLE
    GPIO.setup("P9_23", GPIO.OUT)  # CELL_RESET
    GPIO.setup("P8_12", GPIO.OUT)  # CELL_ONOFF

    GPIO.output("P9_12", GPIO.LOW)
    GPIO.output("P9_23", GPIO.LOW)
    GPIO.output("P8_12", GPIO.LOW)

    time.sleep(3)

    print "Setting CELL_ON/OFF HIGH"
    GPIO.output("P8_12", GPIO.HIGH)
    time.sleep(5)
    print "Wait (5)s..."
    print "Setting CELL_ON/OFF LOW"
    GPIO.output("P8_12", GPIO.LOW)
    def __init__(self):
        #VRCSR protocol defines  
        self.SYNC_REQUEST  =  0x5FF5
        self.SYNC_RESPONSE =  0x0FF0
        self.PROTOCOL_VRCSR_HEADER_SIZE = 6
        self.PROTOCOL_VRCSR_XSUM_SIZE   = 4
        
        #CSR Address for sending an application specific custom command
        self.ADDR_CUSTOM_COMMAND  = 0xF0

        #The command to send.
        #The Propulsion command has a payload format of:
        # 0xAA R_ID THRUST_0 THRUST_1 THRUST_2 ... THRUST_N 
        # Where:
        #   0xAA is the command byte
        #   R_ID is the NODE ID of the thruster to respond with data
        #   THRUST_X is the thruster power value (-1 to 1) for the thruster with motor id X
        self.PROPULSION_COMMAND   = 0xAA

        #flag for the standard thruster response which contains 
        self.RESPONSE_THRUSTER_STANDARD = 0x2
        #standard response is the device type followed by 4 32-bit floats and 1 byte
        self.RESPONSE_THRUSTER_STANDARD_LENGTH = 1 + 4 * 4 + 1 

        #The propulsion command packets are typically sent as a multicast to a group ID defined for thrusters
        self.THRUSTER_GROUP_ID    = 0x81
        
        #default to 0 thrust for motor 
        self.thrust = [0,0]
        
        #default to 0 motor node for responses
        self.motor_response_node = 0
       
        #deault for send_motor_command
        self.send_motor_command = False
  
        #open the serial port
        UART.setup("UART4")
        try:        
            self.port = serial.Serial(port = "/dev/ttyO4",baudrate=115200)
            self.port.timeout = 1
        except IOError:
            print ("Error:  Could not open serial port: " + args.portname)     
            sys.exit()
        
        #setup GPIO
        rec_output_enable_pin="P9_12"
        GPIO.setup(rec_output_enable_pin, GPIO.OUT)
        #set receiver output enable to enable
        GPIO.output(rec_output_enable_pin, GPIO.LOW)
Esempio n. 35
0
def readEMI():
	UART.setup("UART1")
	ser = serial.Serial(port = "/dev/ttyO1", baudrate=460800, timeout = 1)
	ser.close()
	ser.open()
	
	if ser.isOpen():
		while(1):
			ser.write('1')
			data = ser.read(4096)
			if len(data) == 4096:
				data = 20*np.log10(1000*np.fromstring(data, dtype = np.float32)/2048)
				print data
			else:
				print("fail to get emi")
Esempio n. 36
0
	def task(self):
		UART.setup(self.pin)
		self.out=''
		self.serial_port = serial.Serial(port = "/dev/ttyO1", baudrate = self.baudrate)
		self.serial_port.open()
		while not self.stop.isSet():
			try:
				self.serial_port.write(''.join([chr(int(''.join(c), 16)) for c in zip(self.command[0::2],self.command[1::2])]))
				self.out = self.serial_port.read(self.byte)
				now = datetime.datetime.now()
				val = str(self.out) + " : " + str(now.minute) + " : " + str(now.second) + " : " + str(now.microsecond)
				print val
				if self.isLogging:
					log_file.write(val)
				time.sleep(self.rate)
Esempio n. 37
0
    def __init__(self, inName, inDefaultPriority=3, baudrate=38400, **kwargs):
        # boilerplate bookkeeping
        sensorState.Sensor.__init__(self,
                                    inName,
                                    inSensorThreadProc=self.__threadProc,
                                    inSensorThreadProcKWArgs=kwargs,
                                    inDefaultPriority=3)

        self.baudrate = baudrate

        self.R_encoderPort = "/dev/ttyO2"
        self.R_UART = "UART2"
        UART.setup(self.R_UART)

        self.R_encoderCom = serial.Serial(port=self.R_encoderPort,
                                          baudrate=self.baudrate)
Esempio n. 38
0
def readEMI():
    UART.setup("UART1")
    ser = serial.Serial(port="/dev/ttyO1", baudrate=460800, timeout=1)
    ser.close()
    ser.open()

    if ser.isOpen():
        while (1):
            ser.write('1')
            data = ser.read(4096)
            if len(data) == 4096:
                data = 20 * np.log10(
                    1000 * np.fromstring(data, dtype=np.float32) / 2048)
                print data
            else:
                print("fail to get emi")
Esempio n. 39
0
    def __init__(self):
        self.sensor = 0
	self.buzz = "P9_14"	
        self.angle = [180,90,180,90,180,90] #Save stepper motor angle for reaching each container
        self.initStepperMotor()
	self.initFluidMotor()
	ADC.setup()
	UART.setup("UART1")
	self.ser = serial.Serial(port="/dev/ttyO1",baudrate=115200)
	self.ser.close()
	self.ser.open()
	GPIO.setup(self.buzz, GPIO.OUT)
	GPIO.output(self.buzz,GPIO.LOW)
	self.weight = "0.0"
	t = threading.Thread(target=self.serialThread)
	t.start()
Esempio n. 40
0
    def __start(self):
        # print("DELAY =START ...3")
        time.sleep(3)

        UART.setup(self.UART)

        # print("OPERATION =RESET_PULLDOWN\n")
        GPIO.setup(self.GPIO_RESET, GPIO.OUT, GPIO.PUD_DOWN)
        GPIO.output(self.GPIO_RESET, GPIO.HIGH)
        time.sleep(1)
        GPIO.output(self.GPIO_RESET, GPIO.LOW)
        time.sleep(1)
        GPIO.output(self.GPIO_RESET, GPIO.HIGH)

        self.serialPort = serial.Serial(port=self.SERIAL_PORT,
                                        baudrate=self.SERIAL_BAUD)
Esempio n. 41
0
File: NMDA.py Progetto: opobla/nmpw
def init_resources(args):
	UART.setup("UART1")
	UART.setup("UART2")
	# Initialize the Serial Port
	port=init_port(args.serial_port_control, args_baudrate=921600)

	# Initialize the Serial Port for the barometer if one is needed.
	#  TODO Pass the sps baudrate as parameter or leave it as it is now
	port_sensors=init_port(args.serial_port_sensors, args_baudrate=2400) #  TODO change the baudrate

	# Initialize the Database connection
	conn=init_database(args.database)

	# Initialize the Sensors Manager
	sensors_manager=SensorsManager('Sensor Manager', bar_type=args.barometer_type, hvps_type=args.hvps_type, port_control=port, port_data=port_sensors, analog_hvps_corr=args.analog_hvps_corr)

	return port, port_sensors, conn, sensors_manager
Esempio n. 42
0
    def __init__(self, name: str) -> None:

        # Initialize parameters
        self.name = name

        # Initialize logger
        logname = "DeviceIO({})".format(name)
        self.logger = Logger(logname, __name__)

        # Verify io exists
        self.logger.debug("Verifying io stream exists")

        UART.setup("UART1")
        self.ser = serial.Serial(port = "/dev/ttyO1", baudrate=9600)

        self.open()
        self.close()
Esempio n. 43
0
def listen(q):
    UART.setup("UART2")

    with serial.Serial(port="/dev/ttyO2", baudrate=9600) as ser:
        print('Connected to GPS: %s' % ser.name)
        while True:
            sentence = ser.readline()
            # remove \r\n
            sentence = sentence[:-2]

            if sentence[0] == '$':
                try:
                    gps_data = parser.parse(sentence)

                    if gps_data.is_valid and gps_data.sentence_name != 'VTG':
                        q.put(gps_data)
                except:
                    pass
Esempio n. 44
0
    def collect_uart(self, iterations=5):
        import Adafruit_BBIO.UART as UART
        import serial

        UART.setup("UART1")

        ser = serial.Serial(port="/dev/ttyO1", baudrate=9600)
        ser.close()
        ser.open()

        for _ in range(0, iterations):
            min_val = 0
            max_val = 0
            sum_val = 0

            result = float(ser.readline().decode().strip())
            print('writing {}'.format(result))
            self.write_to_db(result)
Esempio n. 45
0
 def init(self):
     UART.setup(self.name)
     if self.name.lower() == 'uart1':
         self.port = serial.Serial(port='/dev/ttyO1',
                                   baudrate=self.baudrate)
     elif self.name.lower() == 'uart2':
         self.port = serial.Serial(port='/dev/ttyO2',
                                   baudrate=self.baudrate)
     elif self.name.lower() == 'uart3':
         self.port = serial.Serial(port='/dev/ttyO3',
                                   baudrate=self.baudrate)
     elif self.name.lower() == 'uart4':
         self.port = serial.Serial(port='/dev/ttyO4',
                                   baudrate=self.baudrate)
     elif self.name.lower() == 'uart5':
         self.port = serial.Serial(port='/dev/ttyO5',
                                   baudrate=self.baudrate)
     else:
         print 'Port: %s is not support' % self.name
Esempio n. 46
0
def f_ser_lcd_init():
    ''' serial lcd init '''

    UART.setup(LCD_SER_GPIO)
    dev_ser_lcd = serial.Serial(port=LCD_SER, baudrate=9600)
    dev_ser_lcd.close()
    dev_ser_lcd.open()
    if dev_ser_lcd.isOpen():
        print '[i] oled serial is now open'

        oled = digole_serial.oledSerial(LCD_SER)
        oled.timeout = 1
        oled.open
        oled.clearScreen()
        oled.drawStr(0, 1, 'Test TEXT')
        oled.drawLine(0, 0, 159, 127)
        print 'log h/t end ' + datetime.now().strftime('%Y-%m-%d %H:%M')
        oled.close()
        sys.exit(0)
Esempio n. 47
0
	def __init__(self,jsonObj):
		json_string = json.dumps(jsonObj)
		decoded = json.loads(json_string)
		self.rate =  decoded["rate"];
		self.protocol = decoded["protocol1"];
		#self.baudrate = decoded["baudrate"]
		self.byte1 = "8"#decoded["byte1"]
		self.command = "31"
		self.pin = "UART1";
		self.numb = Uart.number;
		Uart.number = Uart.number + 1;
		self.arr = [];
		UART.setup(self.pin)
		self.out=''
		self.serial_port = serial.Serial(port = "/dev/ttyO1", baudrate = int("9600",10))
		#self.serial_port.close()
		self.serial_port.open()
		self.stop = threading.Event()
		self.sensor_thread = threading.Thread(target = self.task)
		self.sensor_thread.start()
    def __init__(self):
		self.sensor = 0
		self.buzz = "P9_14"	
		self.angle = [90,90,60,60,60] #Save stepper motor angle for reaching each container
		self.weight = "0.0"				# Weight variable updated by thread
		self.ingredient = []

		self.initStepperMotor()			# Initialize the stepper motor pins
		self.initFluidMotor()			# Initialize the fluid motor pins
		ADC.setup()
		UART.setup("UART1")				# Initialize the UART to communicated with Arduino
		self.ser = serial.Serial(port="/dev/ttyO1",baudrate=115200)
		self.ser.close()
		self.ser.open()
		GPIO.setup(enable,GPIO.OUT)
		GPIO.output(enable, GPIO.HIGH)
		GPIO.setup(self.buzz, GPIO.OUT)	# Disable the buzzer pin initially
		GPIO.output(self.buzz,GPIO.LOW)
		t = threading.Thread(target=self.serialThread)
		t.start()
Esempio n. 49
0
 def __init__(self, jsonObj):
     json_string = json.dumps(jsonObj)
     decoded = json.loads(json_string)
     self.rate = decoded["rate"]
     self.protocol = decoded["protocol1"]
     #self.baudrate = decoded["baudrate"]
     self.byte1 = "8"  #decoded["byte1"]
     self.command = "31"
     self.pin = "UART1"
     self.numb = Uart.number
     Uart.number = Uart.number + 1
     self.arr = []
     UART.setup(self.pin)
     self.out = ''
     self.serial_port = serial.Serial(port="/dev/ttyO1",
                                      baudrate=int("9600", 10))
     #self.serial_port.close()
     self.serial_port.open()
     self.stop = threading.Event()
     self.sensor_thread = threading.Thread(target=self.task)
     self.sensor_thread.start()
	def __init__(self, queue_input, stopevent, sel_uart, occupe):
		#Les liaisons valides sont les liaisons 1,2,4
		if(sel_uart not in [1,2,4]):
				return "Erreur : la liaison série spécifiée n'est pas valide"
		#Initialisation du thread lui-même
		threading.Thread.__init__(self)
		#Les informations à émettre sur la liaison série
		self.input = queue_input
		#variable écoutant l'arrêt du thread par le controleur
		self.stoprequest = stopevent

		#Variable empechant l'empiêtement des classes Série (pas de lecture quand envoi, et pas d'envoi quand lecture)
		self.occupe = occupe
		### Liaison série
		#On choisit la liaison série spécifiée, sinon la liaison série 1 par défaut
		UART.setup("UART"+str(sel_uart))

		#Ouverture de la liaison série
		#le parametre stopbits DOIT etre égal à 1, le mettre à deux entraine une incompréhension par le controleur des moteurs des ordres à envoyer
		self.ser = serial.Serial(port = "/dev/ttyO"+str(sel_uart), baudrate=38400,bytesize=8, stopbits=1,timeout=None)
		#On ferme la liaison série instanciée, afin de ne pas occuper constamment le canal
		self.ser.close()
Esempio n. 51
0
def readUI_u(q,q_emi):
	UART.setup("UART4")
	ser = serial.Serial(port = "/dev/ttyO4", baudrate=460800, timeout = 1)
	ser.close()
	ser.open()
	data_s = []
	if ser.isOpen():
		while(1):
			ser.write('1')
			data = ser.read(276)
			if len(data) == 276:
				data = np.fromstring(data, dtype = np.float32)
				data_s.append(data)
				if len(data_s) == 4:
					while q_emi.get(True) != 1:
						time.sleep(0.1)
					data_s.append(q_emi.get(True))
					data_s.append(time.time())
					q.put(data_s)
					data_s = []
					#print("ui_emi 2 pipe")
			else:
				print("fail to get u......i........")
Esempio n. 52
0
def readUI_u(q, q_emi):
    UART.setup("UART4")
    ser = serial.Serial(port="/dev/ttyO4", baudrate=460800, timeout=1)
    ser.close()
    ser.open()
    data_s = []
    if ser.isOpen():
        while (1):
            ser.write('1')
            data = ser.read(276)
            if len(data) == 276:
                data = np.fromstring(data, dtype=np.float32)
                data_s.append(data)
                if len(data_s) == 4:
                    while q_emi.get(True) != 1:
                        time.sleep(0.1)
                    data_s.append(q_emi.get(True))
                    data_s.append(time.time())
                    q.put(data_s)
                    data_s = []
                    #print("ui_emi 2 pipe")
            else:
                print("fail to get u......i........")
Esempio n. 53
0
def init_resources(args):
    UART.setup("UART1")
    UART.setup("UART2")
    # Initialize the Serial Port
    port = init_port(args.serial_port_control, args_baudrate=921600)

    # Initialize the Serial Port for the barometer if one is needed.
    #  TODO Pass the sps baudrate as parameter or leave it as it is now
    port_sensors = init_port(args.serial_port_sensors,
                             args_baudrate=2400)  #  TODO change the baudrate

    # Initialize the Database connection
    conn = init_database(args.database)

    # Initialize the Sensors Manager
    sensors_manager = SensorsManager('Sensor Manager',
                                     bar_type=args.barometer_type,
                                     hvps_type=args.hvps_type,
                                     port_control=port,
                                     port_data=port_sensors,
                                     analog_hvps_corr=args.analog_hvps_corr)

    return port, port_sensors, conn, sensors_manager
Esempio n. 54
0
    def __init__(self, acceleration=1):
        """
        Input: int(acceleration = acceleration of the motors, defaults to 1)
        Output: N/A
        
        Initializes Serial (UART) communication to motor controllers

        Sets up motor controller PID coefficients
        Specifies what the encoder readings should be when the motors are receiving max voltage in order to scale speeds correctly
        """
        UART.setup("UART1")
        UART.setup("UART2")

        self.front_motors = Roboclaw(0x80, "/dev/ttyO1")
        self.back_motors = Roboclaw(0x81, "/dev/ttyO2")

        self.encoderResolution = 1024
        self.maxPulsesPerSecond = mechInfo.maxPPS  # Units of pulses per second. 100% of power is given at this encoder reading
        self.acceleration = self.__revToPulses(acceleration)  # Units of revolutions per second, default = 1

        self.p = int(1.0 * 65536)
        self.i = int(0.5 * 65536)
        self.d = int(0.25 * 65536)
        self.front_motors.set_m1_pidq(self.p, self.i, self.d, self.maxPulsesPerSecond)
        self.front_motors.set_m2_pidq(self.p, self.i, self.d, self.maxPulsesPerSecond)
        self.back_motors.set_m1_pidq(self.p, self.i, self.d, self.maxPulsesPerSecond)
        self.back_motors.set_m2_pidq(self.p, self.i, self.d, self.maxPulsesPerSecond)

        self.encoderPulsesFrontLeft = 0
        self.encoderPulsesFrontRight = 0
        self.encoderPulsesBackLeft = 0
        self.encoderPulsesBackRight = 0

        self.frontAngle = 0
        self.backAngle = 0

        self.readEncoderDistanceTraveled()  # Clears junk output from this function
Esempio n. 55
0
def setup_radio():
	spione.mode=0#SPI1 mode 0 at 2Mhz
	spione.msh=2000000
	spione.open(1,0) 
	UART.setup("UART4")#USART4 TX is used for direct modulation (RTTY at 200 baud), dts file altered to allow RX4, GPIO0_30 to be used for CTS
	ser=serial.Serial(port = "/dev/ttyO4", baudrate=200)
	ser.open()#Open the USART4 port as ser
	GPIO.setup("GPIO0_30",GPIO.IN)#This is the CTS pin, high==CTS
	GPIO.setup("GPIO1_14",GPIO.IN)#The IRQ pin, low==IRQ
	GPIO.setup("GPIO1_15",GPIO.OUT)#This is the SDN pin, high==shutdown
	GPIO.output("GPIO1_15",GPIO.HIGH)
	GPIO.setup("GPIO0_27",GPIO.OUT)#This is the nSEL pin, low==selected
	GPIO.output("GPIO0_27",GPIO.HIGH)
	time.sleep(0.005)#5ms sleep at bootup to allow everything to reset
	GPIO.output("GPIO1_15",GPIO.LOW)#Take the silabs out of shutdown mode
	#divide VCXO_FREQ into its bytes, MSB first
	x3 = (VCXO_FREQ // 0x1000000)&0xFF
	x2 = ((VCXO_FREQ - x3 * 0x1000000) // 0x10000)&0xFF
	x1 = ((VCXO_FREQ - x3 * 0x1000000 - x2 * 0x10000) // 0x100)&0xFF
	x0 = ((VCXO_FREQ - x3 * 0x1000000 - x2 * 0x10000 - x1 * 0x100))&0xFF 
	boot_config=[0x02, 0x01, 0x01, x3, x2, x1, x0]
	send_cmd_receive_answer( 1, boot_config)
	# Clear all pending interrupts and get the interrupt status back
	get_int_status_command = [0x20, 0x00, 0x00, 0x00]
	send_cmd_receive_answer( 9,  get_int_status_command)
	# Read the part info
	partinfo=send_cmd_receive_answer( 8, [0x01])
	# This is useful to check if the device is functional - sanity check
	print(partinfo)
	# Setup the GPIO pin, note that GPIO1 defaults to CTS, but we need to reset and set GPIO0 to TX direct mode mod input
	gpio_pin_cfg_command = [0x13, 0x04, 0x00, 0x01, 0x01, 0x00, 0x11, 0x00] # Set GPIO0 input, 1 CTS, rest disabled, NIRQ unchanged, 
	#SDO=SDO, Max drive strength
	send_cmd_receive_answer( 8, gpio_pin_cfg_command)
	set_frequency(active_freq)
	set_modem()
	set_deviation(active_shift)
Esempio n. 56
0
def server_app():
    global buffer
    UART.setup("UART1")
    ser = serial.Serial(port = "/dev/ttyO1", baudrate=115200)
    ser.close()
    print "server started ..."
    ser.open()
    while ser.isOpen():
        past = time.clock()
        node_num = 1
        while node_num < 5:
            packet = create_read_packet(node_num)
            ser.write(packet)
            print "sent a packet"

            # sleep for a quarter of a second
            period = 0.25 - (time.clock() - past)
            past = time.clock()
            period = max(min(period, 0.25), 0);
            time.sleep(period)

            str_ans = ''
            buf_size = ser.inWaiting()
            if buf_size > 0:
                str_ans = ser.read(buf_size)
        
            ans = [ord(ch) for ch in list(str_ans)]
            
            packet = Packet(ans)	
            if packet.is_valid:
                node_num += 1
                packet.save()
            print packet.json()
                
    print '........................connection...closed.........................'
    ser.close() 
""" Public python modules """
import serial
import numpy as np
import time
""" DIY Modules (placed in the same dir.)"""
import sensor
import control
""" Instances """
timeSTMP0 = control.Control()
timeSTMP1 = control.Control()
ctrlRoll = control.Control()
ctrlPitch = control.Control()
""" Overlay DTO using pyBBIO """
PWM.start("P9_14", 10.9, 50, 0)  # PWM.start(pin, duty, freq, polarity)
PWM.start("P9_16", 9.4, 50, 0)  # PWM.start(pin, duty, freq, polarity)
UART.setup("UART1")  # IMU
ADC.setup()  # ADC
""" Set port and baud rate """
ser = serial.Serial(port="/dev/ttyO1", baudrate=115200)
ser.close()
ser.open()
if ser.isOpen():
    """ Position initialization for the static test """
    time.sleep(0.5)
    mot1_pos = 10.9  # PWM_mot1 with interceptor Stroke 0%
    mot2_pos = 9.4  # PWM_mot2 with interceptor Stroke 0%
    PWM.set_duty_cycle("P9_14", mot1_pos)
    PWM.set_duty_cycle("P9_16", mot2_pos)
    time.sleep(0.5)
    """ Set gain of a PID controllers """
    KD = 50