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 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()
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
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
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()
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.")
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())
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)
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")
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
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)
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()
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 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
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)
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
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 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)
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")
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()
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
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
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)
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()
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()
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........")
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
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()
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)
##################################################################### # ScreenBuffer.py # # This file contains a Python class called ScreenBuffer which holds # the pixel color values of a screen. # # Resources: # BBB UART: https://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/uart ##################################################################### #!/usr/bin/python import Adafruit_BBIO.UART as UART import serial from ScreenBuffer import ScreenBuffer UART.setup(uart) # This class is used to send the data in a ScreenBuffer across UART # byte by byte. class Sender: # The UART which we use. # RX -> P9_26 # TX -> P9_24 mUart = "UART1" mUartDev = "/dev/tty01" mBaudRate = 9600 # Serial object which interfaces to the UART. mSerial = ""
current_servo_y = min(current_servo_y, 10) current_servo_y = max(current_servo_y, 5) print x, y, x_err, y_err, current_servo_x, current_servo_y #check if we're on target #valid = sqrt(x_err**2 + y_err**2) < size valid = 1 #Initialize Servo PWM control PWM.start(x_servo, current_servo_x, 50, 0) PWM.start(y_servo, current_servo_y, 50, 0) print "started servo" + x_servo print "started servo" + y_servo """ #Initialize UART for laser data UART.setup("UART1") ser = serial.Serial(port = "/dev/ttyO1", baudrate=115200,timeout=1) ser.close() ser.open() t = threading.Thread(target=take_measurements) t.daemon = True t.start() """ cap = cv2.VideoCapture(-1) cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 160) cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 120) before_cap = time.time()
""" Public python modules """ import serial import numpy as np import time """ pyBBIO """ import Adafruit_BBIO.UART as UART import Adafruit_BBIO.PWM as PWM """ Developed Modules (placed in the same dir.)""" import sensor import control """ Instances """ timeSTMP0 = control.Control() timeSTMP1 = control.Control() ctrlRoll = control.Control() """ Overlay DTO using pyBBIO """ UART.setup("UART1") # IMU """ Set port and baud rate """ ser = serial.Serial(port="/dev/ttyO1", baudrate=115200) ser.close() ser.open() if ser.isOpen(): """ Set gain of a PID controllers """ KD = 0.03 ctrlRoll.ctrlGain(0, 0, KD) # pidGain(KP, KI, KD) """ Error matrices initialization """ rollEr = np.matrix('0.0 0.0;1 1') #[t0 e0; t1 e1] """ initial time stamp """ timeSTMP0.timeSTMP() """ Open .dat file to record values """ f = open('controlTest.dat', 'w') f.write(
import Adafruit_BBIO.UART as UART import serial import pynmea2 import time import Adafruit_BBIO.GPIO as GPIO import os permission_command = "sudo chmod 777 /dev/ttyO0" sudoPassword = "******" os.system('echo %s|sudo -S %s' % (sudoPassword, permission_command)) UART.setup("PB-UART0") GPIO.setup("P1_35", GPIO.OUT) GPIO.output("P1_35", GPIO.LOW) time.sleep(1) GPIO.output("P1_35", GPIO.HIGH) GPIO.setup("P1_34", GPIO.IN) #GPIO.setup("", ) ser = serial.Serial(port="/dev/ttyO0", baudrate=9600) ser.close() ser.open() while (1): if GPIO.input("P1_34"): print("P1_34 is HIGH")
import Adafruit_BBIO.UART as UART import serial from dronekit import connect, VehicleMode # Constants # ---------------------------------------------------------------------------- UART_NAME = 'UART1' PORT = '/dev/ttyO1' BAUDRATE = 57600 # ---------------------------------------------------------------------------- # Main code UART.setup(UART_NAME) print 'Connecting to vehicle on %s' % PORT vehicle = connect(ip=PORT, wait_ready=True, baud=BAUDRATE) # Get some vehicle attributes (state) print 'Get some vehicle attribute values:' print 'GPS: %s' % vehicle.gps_0 print 'Battery: %s' % vehicle.battery print 'Last Heartbeat: %s' % vehicle.last_heartbeat print 'Is Armable?: %s' % vehicle.is_armable print 'System status: %s' % vehicle.system_status.state print 'Mode: %s' % vehicle.mode.name # settable while (True): try:
def initializePorts(self): UART.setup(self.uartPort) self.serialConn = serial.Serial(port=self.port, baudrate=self.baudrate)
class TheBase(Thread): #The X, Y, and Phi coordinates (X,Y,PHI) initially set to zero. Xcurrent = 0.0 Ycurrent = 0.0 PHIcurrent = 0.0 #Length of wheel base (inches) lengthOfWheelBase = 15 #These variabels keep track of the number of pulses received during a time interval LWPulses = 0 RWPulses = 0 #Set up the base motors #Ser1 is assuming to be the left motor #Ser2 is assuming to be the right motor UART.setup("UART1") UART.setup("UART2") ser1 = serial.Serial(port = "/dev/ttyO1", baudrate=9600) ser2 = serial.Serial(port = "/dev/ttyO2", baudrate=9600) #Make sure to close any previous open serial connections #Then open them for this purpose ser1.close() ser2.close() ser1.open() ser2.open() #Setup tackle sensor GPIO.setup("P9_23", GPIO.OUT) GPIO.add_event_detect("P9_23", GPIO.RISING) #Server IP, port, and socket to send position data to serverIP = "127.0.0.1" serverPort = 4489 Disconnected = False serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #Socket to listen for commands from the server theSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #The mode this thread class will run i.e. "Receive" or "Send" job = "Receive" #A variable to tell if it's done running the thread Done = False #Constructor #If for constructing the Quarterback, create the object without any parameters since it'll be the reference #If for any other robot, such as the Receiver, then type in the coordinates it'll start off with respect to the Quarterback def __init__(self, x = 0.0, y = 0.0, phi = 0.0): Thread.__init__(self) self.Xcurrent = x self.Ycurrent = y self.PHIcurrent = phi #Displays the robot's current coordinates def displayCoordinates(self): print self.Xcurrent print self.Ycurrent print self.PHIcurrent #This method will take a the speed data received from the socket #And from it, it will differentiate if it will go straight forward #Or backwards. It'll also know when to turn and it which direction #For going straight forward or backward, the data will contain a value #in the format of 'S255'. def driveBaseMotors(self, speedData): if self.ser1.isOpen() and self.ser2.isOpen(): if speedData[0] == "S": #Go straight backward or forward #Logic to drive motors, one is reversed which is right one i = 0 while True: if speedData[i] == "X": break else: i += 1 self.ser1.write(speedData[0:i] + "\n\r") self.ser2.write("S" + str(-1*int(speedData[i+1:])) + "\n\r" ) elif speedData[0] == "T": #Turn robot according to how much the thumbstick is pushed #Logic to turn #Logic for turning clockwise if int(speedData[1:]) > 0: self.ser1.write("S" + speedData[1:] + "\n\r") self.ser2.write("S0 \n\r") else: #Logic for turning counterclockwise self.ser1.write("S0 \n\r") self.ser2.write("S" + speedData[1:] + "\n\r") elif self.ser1.isOpen() and not self.ser2.isOpen(): print "Ser1 is opened but not Ser2!" elif not self.ser1.isOpen() and self.ser2.isOpen(): print "Ser2 is opened but not Ser1!" else: print "Both Ser1 and Ser2 are not opened!" #These next two method checks how many pulses are received at a certain time interval from the encoders #and will save the number of pulses to LWPulses and RWPulses variables def getLeftWheelPulses(self): #Try to get pulses from the Left encoder try: #Logic to do it, LWPulses = ..... self.LWPulses = 5 print "Got Left Wheel Pulse" except Exception as inst: print type(inst) print inst.args print inst else: #Anything else to do with encoder doen="Done" #For right wheel def getRightWheelPulses(self): #Try to get pulses from the Right encoder try: #Logic to do it, RWPulses = ..... self.RWPulses = 5 print "Got Right Wheel Pulse" except Exception as inst: print type(inst) print inst.args print inst else: #Anything else to do with encoder doen="Done" #This method will use the number of pulses received during a time interval (using LWPulses and RWPulses variables) #to update the position of the robot def updatePosition(self): #Delta Distance Right Wheel (dDRW), Delta Distance Left wheel (dDLW), and Delta Distance Center of Robot (dDCR) - (initially zero change) dDRW = 0.0 dDLW = 0.0 dDCR = 0.0 #Get number of pulses for both left and right encoders and determine distance traveled dDLW = 0.012 * self.LWPulses dDRW = 0.012 * self.RWPulses #Determine the distance traveled with respect to the center of the robot dDCR = (dDLW + dDRW)/2 #Update orientation of robot first self.PHIcurrent = self.PHIcurrent + (dDRW - dDLW) / self.lengthOfWheelBase #Then X and Y coordinates #self.Xcurrent = self.Xcurrent + dDCR*math.sin(-self.PHIcurrent) #self.Ycurrent = self.Ycurrent + dDCR*math.cos(self.PHIcurrent) self.Xcurrent += dDCR*math.cos(self.PHIcurrent) self.Ycurrent += dDCR*math.sin(self.PHIcurrent) #Clean up delta changes dDRW = dDLW = dDCR = 0 #Testing self.Xcurrent += .0003 self.Ycurrent += .0001 self.PHIcurrent += .0002 #Send new coordinates to server self.sendCoordinates() #This method will send the current (X,Y,PHI) coordinates to the server def sendCoordinates(self): #Logic to send coordinates coordinates = "{0:.4f}".format(self.Xcurrent) + "X" + "{0:.4f}".format(self.Ycurrent) + "X" + "{0:.4f}".format(self.PHIcurrent) + "X" self.serverSocket.sendto(coordinates, (self.serverIP, self.serverPort)) #This method will set up the IP and port the robot will be listening from def setupListenSocket(self, ip, port): self.theSocket.bind((ip, port)) def setupSendSocket(self, ip, port): self.serverIP = ip self.serverPort = port #This method will retreive the command from the server def retreiveCommands(self): data, addr = self.theSocket.recvfrom(32) if data[0] == "S" or data[0] == "T": self.driveBaseMotors(data) elif data[0] == "B": print "Button: ", data[1:] elif data[0] == "D": self.Done = True else: print "Unknown data" def run(self): if self.job == "Receive": while(!self.Done): print "Receiving joystick input" self.testForTackle() self.retreiveCommands() elif self.job == "Send": while(!self.Done): print "Sending position data" self.updatePosition() def testForTackle(self): if GPIO.event_detected("P9_23"): print "Tackled"
import Adafruit_BBIO.UART as UART import serial import time UART.setup("UART1") # RX P9_26 TX P9_24 ser = serial.Serial(port="/dev/ttyO1", baudrate=9600) buffer = "" while True: oneByte = ser.read(1) if oneByte == b"\r": # method should return bytes ## continue ## print(buffer) dist = buffer print(dist) ## ser.reset_input_buffer() ## time.sleep(0.001) # rest else: try: buffer += oneByte.decode("ascii") except UnicodeDecodeError as e: print('UnicodeDecodeError: ', e) ser.close()
# uart.cleanup() # not yet supported? def mapVals(val, inMin, inMax, outMin, outMax): toRet = float(outMin + (float(outMax - outMin) * (float(val - inMin) / float(inMax - inMin)))) # return clamp(toRet, outMin, outMax) return toRet def clamp(val, tmin, tmax): if val > tmax: val = tmax if val < tmin: val = tmin return val uart.setup("UART2") printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5) printer.begin() printer.upsideDownOn() printer.feed(3) printer.print(parse('i am awake and I am BLOCKS (presence)')) printer.feed(1) rPast = 0 rMax = 0 # all-time max sensor reading rMin = 100000 # all-time min sensor reading WINDOW_SIZE = 30 # size of moving-window avg noop = 0 # number of intervals passed without a trigger noop_threshold = 480 emission_threshold = 5 # changed this for vcnl4000, used to be 0.7 while True:
#!/usr/bin/python from gps import * #interface with gpsd import subprocess #allows for starting the gpsd service import time #for sleep timing import sys #for exiting when there is no fix import Adafruit_BBIO.UART as UART #Adafruit BeagleBobe UART libraries UART.setup("UART1") #initialize the SERIAL1 or UART1 interface pins #TODO: Setup gps on uart2 instead of uart1 #this ensures that the gpsd service is running #the gpsd service provides the python gps module with input from the physical module #gpsd must be configured using "gpsd -n /dev/ttyO1 -F var/run/gpsd.sock" #prior to running this code try: subprocess.check_output(["pgrep", "gpsd"]) except subprocess.CalledProcessError: #gpsd isn't running yet, start it up subprocess.check_output(["systemctl", "start", "gpsd.service"]) gps_in = gps(mode=WATCH_ENABLE) #read data in from the gpsd interface library no_fix_count = 5 #limit the time spent waiting for a fix in this test while True: #run until a keyboard-interupt gps_in.next() print "fix mode: ", gps_in.fix.mode if (gps_in.fix.mode != 1): #a fix.mode value of 1 indicated no gps fix #have a gps fix, print the data or make it available in a global data structure print "time: ", gps_in.fix.time, "latitude: ", gps_in.fix.latitude, ", longitude: ", gps_in.longitude, "altitude: ", gps_in.fix.altitude print "total number of satellites tracked: ", len(gps_in.satellites)
def test_setup_uart_multiple(self): if kernel >= '4.1.0': pass else: UART.setup("UART1") UART.setup("UART1")
def LOG_TO_FILE(GPS="", Acel="", temp=""): now = datetime.datetime.now() Time_Stamp = (now.strftime("%Y-%m-%d %H:%M:%S")) file = open("LOG_file.txt", "a") file.write( "\nTime: {} GPS: {} Temp: {} Accelerometer: {}" .format(Time_Stamp, GPS, temp, Acel)) file.close() # Setup ADC.setup() UART.setup("UART1") #Opens the Uart comunication bus Nr.1 ser = serial.Serial('/dev/ttyO1', 9600) accel = Adafruit_ADXL345.ADXL345(address=0x53, busnum=2) GPIO.setup("P8_8", GPIO.OUT) GPIO.setup("P8_10", GPIO.OUT) GPIO.setup("P8_12", GPIO.IN) accel.enable_freefall_detection(8, 40) # defult TH = 9 and TIME = 20 (The scale factor is 5 ms/LSB) # THIS WILL TURN ON FREE-FALL MODE AND INT1 will go HIGH if TRUE(fall) # The scale factor is 62.5 mg/LSB. Threshold 5 to 10 and The fall time 20 to 70 #accel.disable_freefall_detection() # This is to disable the freefall detect try: commands.getstatusoutput( 'cp GPS_Template.KML GPS_log.KML') # Delete LOG-file and copy template
def init(self): UART.setup("UART1") os.system("echo BB-UART1 > /sys/devices/bone_capemgr.9/slots")
import Adafruit_BBIO.UART as uart import serial from time import sleep from math import * from sabertooth import * uart.setup("UART1") """ ser = serial.Serial(port = "/dev/ttyO1", baudrate=38400) ser.close() ser.open() power = 0 while ser.isOpen(): power = power + 1 if power > 127: power = 0 data = bytearray([128, 0, power, (128 + 0 + power) & 127 ]) ser.write(data) print data sleep(.05) """ time = 0 motors = [Sabertooth(i) for i in xrange(4)] try: while True: for i in xrange(4): motors[i].write(sin(time + (pi/2 * i))) time += .05
import Adafruit_BBIO.UART as UART import serial import time import Adafruit_BBIO.GPIO as GPIO UART.setup("PB-UART1") #U0 Tx and Rx on PB UART.setup("PB-UART2") #CLK and MOSI on SPI0 serB = serial.Serial(port="/dev/ttyO2", baudrate=9600) serA = serial.Serial(port="/dev/ttyO1", baudrate=9600) serA.close() serB.close() serB.open() serA.open() my_messages = ["what\n", "is\n", "love?\n"] while True: serA.write("bee movie\n".encode('ascii')) serB.write("zee movie\n".encode('ascii')) time.sleep(1) print("Trying to check if serial is open") if serB.isOpen(): print("Serial B is open") if serB.in_waiting > 0: print("Serial B is waiting") if serB.isOpen() and serB.in_waiting > 0: line = serB.readline().decode('ascii') print("the line is", line) time.sleep(0.1)
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 # Debug #============================================================================== if __name__ == "__main__": myserial = BBBserial('UART1') print myserial.name print myserial.baudrate print myserial.status # print myserial._BAUDRATES try: while (1): if myserial.port.isOpen(): print 'Sending Data:' myserial.port.write('Hello') else: print 'Port is closed' time.sleep(1) except KeyboardInterrupt: print 'EXIT' myserial.port.close() UART.cleanup() # print(dir(serial))
import serial # this library used to communicate in serial import Adafruit_BBIO.UART as UART #to acces serial ports UART.setup( "UART1") # this set is activating the pin name UART1 which has tx and rx # now we need to activate connection btw our board and gps module GPS = serial.Serial('/dev/ttyO1', 9600) while (1): while GPS.inWaiting( ) == 0: # it waits for data....if no data comes from gps it does nothingbut if data comes it send to board pass NMEA = GPS.readline( ) #this fucntion reads all NMEA values (google about NMEA ) print(NMEA)
def test_setup_uart_wrong_name(self): with pytest.raises(ValueError): UART.setup("UART7")
#!/usr/bin/python import Adafruit_BBIO.UART as UART import Adafruit_BBIO.GPIO as GPIO import serial, time, os.path, struct, fcntl, os, zlib ##Set up Connection UART.setup("UART4") GPIO.setup("P9_15", GPIO.OUT) GPIO.output("P9_15", GPIO.HIGH) GPIO.setup("P8_33", GPIO.OUT) GPIO.output("P8_33", GPIO.LOW) ser = serial.Serial(port = "/dev/ttyO4", baudrate=9600, timeout = 3) ser.flushInput() ser.flushOutput() #SETUP FILE LOCATIONS save_path = '/root/' #Config Files Fan_Name = os.path.join(save_path, "fan_config.txt") Temp_Name = os.path.join(save_path, "temp_config.txt") OD_Name = os.path.join(save_path, "OD_config.txt") Fluid_Name = os.path.join(save_path, "fluid_config.txt") Pause_Name = os.path.join(save_path, "paused.txt") #Data Files Temp_Data = os.path.join(save_path, "temp_data.txt") OD_Data = os.path.join(save_path, "OD_data.txt") ser.close()
def test_setup_adc(self): UART.setup("UART1")
GPIO.setup(Ultra1E, GPIO.IN) GPIO.setup(Ultra1T, GPIO.OUT) GPIO.setup(Ultra2E, GPIO.IN) GPIO.setup(Ultra2T, GPIO.OUT) GPIO.setup(Ultra3E, GPIO.IN) GPIO.setup(Ultra3T, GPIO.OUT) GPIO.setup(Ultra4E, GPIO.IN) GPIO.setup(Ultra4T, GPIO.OUT) GPIO.output(Ultra1T, GPIO.LOW) GPIO.output(Ultra2T, GPIO.LOW) GPIO.output(Ultra3T, GPIO.LOW) GPIO.output(Ultra4T, GPIO.LOW) UART.setup("UART1") ser = serial.Serial(port="/dev/ttyO1", baudrate=9600) ser.open() def translate(value, leftMin, leftMax, rightMin, rightMax): # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin # Convert the left range into a 0-1 range (float) valueScaled = float(value - leftMin) / float(leftSpan) # Convert the 0-1 range into a value in the right range. return rightMin + (valueScaled * rightSpan)
def test_setup_adc_multiple(self): UART.setup("UART1") UART.setup("UART1")
# See page 11: #http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Co$ gprmc = nmea.GPRMC() mag_addr = 0x1E config_register = 0x01 X_msb = 0x03 X_lsb = 0x04 Z_msb = 0x05 Z_lsb = 0x06 Y_msb = 0x07 Y_lsb = 0x08 i2c = Adafruit_I2C(mag_addr) UART.setup("UART2") ser = serial.Serial(port="/dev/ttyO2", baudrate=9600) ser.close() ser.open() ADC.setup() # Based on observation of high and low raw readings of the accelerometer X 3.6 V. Then took the average of each. zeroOffsetZ = 1.672 zeroOffsetX = 1.595 zeroOffsetY = 1.614 #The sensitivity or conversion factor is the average for each axis of the accelerometer minus low raw reading. conversionFactorZ = 0.322 conversionFactorY = 0.325
#you MUST run setup somewhere before running other functions #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! import Adafruit_BBIO.UART as UART import serial buff = "3" ser = serial.Serial(port="/dev/ttyO5", baudrate=9600) def setup(): ser.close() ser.open() print("Serial is open!") def loadRead(): buff = ser.readline() buff = int(buff) return buff if __name__ == "__main__": UART.setup("UART5") setup() print("beginning Loadcell loop") while True: buff = loadRead() print(buff)
Program that will be used for loss prevention device. See Code flow diagram. -------------------------------------------------------------------------- """ import sys import Adafruit_BBIO.UART as UART import serial import pynmea2 import time import os # Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client #UART1 is the bluetooth module UART.setup("PB-UART4") #UART2 is the GPS module UART.setup("PB-UART2") # ------------------------------------------------------------------------ # Constants # ------------------------------------------------------------------------ # None # ------------------------------------------------------------------------ # Global variables # ------------------------------------------------------------------------ # None
import Adafruit_BBIO.UART as UART import serial import io import time UART.setup('UART1') ser = serial.Serial(port='/dev/ttyO1', baudrate=115200, timeout=2, xonxoff=False) command = "get humidity" ser.write(command.encode()) #ser.flushInput() if (ser.isOpen()): line = ser.readline() print(line)
CENTER1 = CENTER0 - CENTER_DIFF DEFAULT_TURN_SPEED = 100 # slower: 50 DEFAULT_SEC_FOR_90_DEGREE_TURN = 1.4 # slower: 2.9 # END Section tunable parameters ################################################################################ # Setup sensor pins ADC.setup() U_SONIC = "P9_40" IR_L = "P9_39" IR_R = "P9_38" IR_D = "P9_37" # Motor controller UART UART.setup("UART1") # P9_24 # Motor contoller constants START_SIG = "\xAA" CHAN0 = "\x00" CHAN1 = "\x01" NUM_OF_TARGETS = "\x02" ser = serial.Serial(port="/dev/ttyO1", baudrate=9600) ser.close() ser.open() if ser.isOpen(): print "Sending commands..."
import Adafruit_BBIO.UART as uart import serial uart.setup("UART5") ser = serial.Serial(port="/dev/ttyO4", baudrate=9600, timeout=15) print("\n") card = ser.read(12) print(card[1:]) if (card[1:] == "06008E52BF6"): print("access granted") import open.py else: print("Denied")
import socket import select import sys import os import Adafruit_BBIO.GPIO as GPIO import threading import Adafruit_BBIO.UART as UART # TO USE UART OF ADAFRUIT. import serial #FOR SERIAL COMMUNICATION SERIAL LIBRARY OF PYTHON IS INCLUDED #########################This part is for initializing the GPIO later to be converted in module################################ outpin = "P9_12" #gives a name to the P9_12 pin GPIO.setup(outpin, GPIO.OUT) #sets the outpin to output pin ############################################################################################################################### ##########################UART INITIALIZATION ################################################################################ UART.setup('UART1') #UART1 HAS BEEN SETUP FOR SERIAL COMMUNICATION ser = serial.Serial(port="/dev/ttyO1", baudrate=115200, timeout=0.5) ############################################################################################################################## ##########################This part is for intializing the client and connecting it to a server################################ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if len(sys.argv) != 3: print "Correct usage: script, IP address, port number" exit() IP_address = str(sys.argv[1]) Port = int(sys.argv[2]) server.connect((IP_address, Port)) print 'server_msg' + server.recv(2048) ############################################################################################################################# ###########################This part is regarding signaling and list and tuples related to that##############################
import sqlite3 import time import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial # import Adafruit_DHT as dht from datetime import datetime # Initial the dht device, with data pin connected to: UART.setup("UART1") # RX - P9_26, TX - P9_24 # learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/uart GPIO.setup("P8_11", GPIO.IN) # dhtDevice = dht.DHT11 ser = serial.Serial(port="/dev/ttyO1", baudrate=9600) # <- 9600 na arduino też ser.close() ser.open() cols = ["P8_7", "P8_8", "P8_9", "P8_10"] rows = ["P8_15", "P8_16", "P8_17", "P8_18"] keys = (("1", "2", "3", "A"), ("4", "5", "6", "B"), ("7", "8", "9", "C"), ("*", "0", "#", "D")) def klawiatura(): while True: for i, row in enumerate(rows): GPIO.output(row, GPIO.HIGH) for j, col in enumerate(cols): if GPIO.input(col): return keys[i][j]