def main(): signal.signal(signal.SIGINT, signal_handler) parser = argparse.ArgumentParser(description='%s version %s' % (__progname__, __version__), prog=__filename__) parser.add_argument('--port', '-p', help='Serial port device (default: COM1)', default='COM1') parser.add_argument('--tact', '-t', help='Time Activation ms (0-off, default: 600 ms)', type=arg_auto_int, default=600) parser.add_argument('--fldr', '-f', help='Filename floader (default: floader.bin)', default='floader.bin') parser.add_argument('--baud', '-b', help='UART Baud Rate (default: 230400)', type=arg_auto_int, default=230400) subparsers = parser.add_subparsers(dest='operation', help='Run ' + __filename__ + ' {command} -h for additional help') parser_read_flash = subparsers.add_parser('rf', help='Read Flash to binary file') parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int) parser_read_flash.add_argument('size', help='Size of region', type=arg_auto_int) parser_read_flash.add_argument('filename', help='Name of binary file') parser_burn_flash = subparsers.add_parser( 'we', help='Write file to Flash with sectors erases') parser_burn_flash.add_argument('address', help='Start address', type=arg_auto_int) parser_burn_flash.add_argument('filename', help='Name of binary file') parser_write_flash = subparsers.add_parser( 'wf', help='Write file to Flash without sectors erases') parser_write_flash.add_argument('address', help='Start address', type=arg_auto_int) parser_write_flash.add_argument('filename', help='Name of binary file') parser_erase_sec_flash = subparsers.add_parser( 'es', help='Erase Region (sectors) of Flash') parser_erase_sec_flash.add_argument('address', help='Start address', type=arg_auto_int) parser_erase_sec_flash.add_argument('size', help='Size of region', type=arg_auto_int) parser_erase_all_flash = subparsers.add_parser('ea', help='Erase All Flash') args = parser.parse_args() print('================================================') print('%s version %s' % (__progname__, __version__)) print('------------------------------------------------') print('Open %s, %d baud...' % (args.port, args.baud)) try: serialPort = serial.Serial(args.port, args.baud, \ serial.EIGHTBITS,\ serial.PARITY_NONE, \ serial.STOPBITS_ONE) serialPort.setRTS(False) serialPort.setDTR(False) # time.sleep(0.01) serialPort.flushInput() serialPort.flushOutput() serialPort.reset_input_buffer() serialPort.reset_output_buffer() except: print('Error: Open %s, %d baud!' % (args.port, args.baud)) sys.exit(1) warn = 0 serialPort.timeout = 33 * 12 / args.baud + 0.001 #-------------------------------- # Test Floader Already: Send BAD CMD # 1F 34 56 78 79 BC -> 9F 34 56 78 50 7C ? byteSent = serialPort.write(crc_blk(b'\x1f\x34\x56\x78')) read = serialPort.read(33) if read != crc_blk(b'\x9f\x34\x56\x78'): #-------------------------------- # Open Floader try: stream = open(args.fldr, 'rb') size = os.path.getsize(args.fldr) except: serialPort.close print('Error: Not open input file <%s>!' % args.fldr) sys.exit(2) if size < 8: stream.close serialPort.close print('Error: File size = %d!' % size) sys.exit(3) #-------------------------------- # Stop CPU|: [0x0602]=5 serialPort.write(sws_code_end()) blk = sws_wr_addr(0x0602, b'\x05') serialPort.write(blk) if args.tact != 0: #-------------------------------- # issue reset-to-bootloader: # RTS = either RESET (active low = chip in reset) # DTR = active low print('Reset module (RTS low)...') serialPort.setDTR(True) serialPort.setRTS(True) time.sleep(0.05) print('Activate (%d ms)...' % args.tact) tact = args.tact / 1000.0 for _ in range(5): byteSent += serialPort.write(blk) serialPort.setRTS(False) for _ in range(5): byteSent += serialPort.write(blk) serialPort.setDTR(False) byteSent = serialPort.write(blk) t1 = time.time() while time.time() - t1 < tact: for _ in range(5): serialPort.write(blk) time.sleep(0.001) serialPort.flushOutput() serialPort.flushInput() serialPort.reset_input_buffer() #-------------------------------- # Set SWS speed low: [0x00b2]=50 byteSent = serialPort.write(sws_code_end()) x = int(32000000 / args.baud) if x > 127: x = 127 byteSent += serialPort.write(sws_wr_addr(0x00b2, bytearray([x]))) #-------------------------------- # Test read bytes [0x00b2] byteSent += serialPort.write(sws_rd_addr(0x00b2)) byteRead = len(serialPort.read(byteSent + 33)) # print(byteRead, byteSent) if byteRead != byteSent: byteSent = 0 warn += 1 print('Warning: Wrong RX-TX connection?') # Start read serialPort.write(b'\xff') read = serialPort.read(33) byteRead = len(read) if byteRead == 1 and read[0] == b'\xff': print('Warning: Pin RX no connection to the module?') warn += 1 else: print('Connection...') # stop read byteSent = serialPort.write(sws_code_end()) serialPort.read(33) #-------------------------------- # Load floader.bin binWrite = 0 rdsize = 0x100 addr = 0x40000 print('Load <%s> to 0x%04x...' % (args.fldr, addr)) while size > 0: print('\r0x%04x' % addr, end='') data = stream.read(rdsize) if not data: # end of stream print('send: at EOF') break byteSent += serialPort.write(sws_wr_addr(addr, data)) serialPort.reset_input_buffer() binWrite += len(data) addr += len(data) size -= len(data) stream.close print('\rBin bytes writen:', binWrite) print('CPU go Start...') byteSent += serialPort.write(sws_wr_addr(0x0602, b'\x88')) # cpu go Start time.sleep(0.07) serialPort.flushInput() serialPort.flushOutput() serialPort.reset_input_buffer() serialPort.reset_output_buffer() time.sleep(0.07) # print('COM bytes sent:', byteSent) print('------------------------------------------------') # print('Get version floader...') byteSent = serialPort.write(crc_blk(b'\x00\x00\x00\x00')) read = serialPort.read(10) if len(read) == 6 and read[0] == 0 and crc_chk(read): cid = read[2] | (read[3] << 8) ver = read[1] if cid == 0 and ver == 0: print('Error: Check connection to the module!') serialPort.close sys.exit(10) if cid == 0x5562: chip = 'TLSR8253' else: chip = '?' print('ChipID: 0x%04x (%s), Floader ver: %x.%x' % (cid, chip, (ver >> 4) & 0x0f, ver & 0x0f)) else: print('Error get version floader!') serialPort.close sys.exit(4) # print('Get Flash Info...') byteSent = serialPort.write(crc_blk(b'\x05\x00\x00\x00')) read = serialPort.read(10) if len(read) == 6 and read[0] == 5 and crc_chk(read): jedecid = (read[1] << 16) | (read[2] << 8) | read[3] if jedecid == 0xffffff: print('Power Off in the module, Reset and Restart!') serialPort.close sys.exit(5) elif jedecid == 0: print('Error: Check connection to the module!') serialPort.close sys.exit(10) else: print('Flash JEDEC ID: %06x, Size: %d kbytes' % (jedecid, ((1 << read[3]) >> 10))) else: print('Error get version floader!') serialPort.close sys.exit(6) print('------------------------------------------------') if args.operation == 'rf': serialPort.timeout = 1024 * 12 / args.baud + 0.004 print('Read Flash from 0x%06x to 0x%06x...' % (args.address, args.address + args.size)) print('Outfile: %s' % args.filename) try: stream = open(args.filename, 'wb') except: print('Error: Not open Outfile file <%s>!' % args.filename) sys.exit(2) if not ReadBlockFlash(serialPort, stream, args.address, args.size): stream.close serialPort.close sys.exit(5) stream.close elif args.operation == 'wf' or args.operation == 'we': serialPort.timeout = 0.15 print('Inputfile: %s' % (args.filename)) try: stream = open(args.filename, 'rb') size = os.path.getsize(args.filename) except: serialPort.close print('Error: Not open input file <%s>!' % args.fldr) sys.exit(2) if size < 1: stream.close serialPort.close print('Error: File size = %d!' % size) sys.exit(3) offset = args.address & 0x00ffffff print('Write Flash data 0x%08x to 0x%08x...' % (offset, offset + size)) if not WriteBlockFlash(serialPort, stream, offset, size, bool(args.operation == 'we')): stream.close serialPort.close sys.exit(9) stream.close elif args.operation == 'es': serialPort.timeout = 0.15 count = int((args.size + FLASH_SECTOR_SIZE - 1) / FLASH_SECTOR_SIZE) size = (count * FLASH_SECTOR_SIZE) offset = args.address & (0xffffff ^ (FLASH_SECTOR_SIZE - 1)) print('Erase Flash %d sectors,\r\ndata from 0x%06x to 0x%06x ...' % (count, offset, offset + size)) if not EraseSectorsFlash(serialPort, offset, count): serialPort.close sys.exit(6) elif args.operation == 'ea': serialPort.timeout = 2.5 print('Erase All Flash ...') if not EraseAllFlash(serialPort): serialPort.close sys.exit(7) serialPort.close print('------------------------------------------------') if warn == 0: print('Done!') else: print('(%d) Warning' % warn) sys.exit(0)
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- # Dependence: # $ sudo apt-get install python-serial from __future__ import print_function import serial import time import sys ser = serial.Serial('/dev/ttyUSB1', 9600) starttime = time.time() before, now = 1, 1 s = 0 # serial read while True: # n = ser.inWaiting(); # if n: # rec = ser.read(n) # print(rec, end='') line = ser.readline() #print(line, end='') now = int(line) if now == 0 and before == 1: s += 1 nowtime = time.time() speed = 1 / (nowtime - starttime) print("Sum = %d, Speed = %f times/second" % (s, speed)) starttime = nowtime before = now ser.close()
import serial import time import struct import xbox speed = 0 delay = 0.1 maxSpeed = 50 minSpeed = 0 ser = serial.Serial( '/dev/serial/by-id/usb-FTDI_FT230X_Basic_UART_DN0393EE-if00-port0', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) ser.flush() while True: speed = input("Enter speed ") # string = raw_input("Enter string ") # val = chr(int(speed)) # for i in range(100): val = chr(speed) bytes_sent = ser.write(val + "\n") print("num_sent ", val) time.sleep(0.01) print("bytes_sent is: ", bytes_sent)
def Proc_7(f=1): startAdr = [] rangeAdr = [] rtuAddress = [] varname = [] timeOut = [] reg = [] unitCount = 1 for i in range(0, unitCount + 1): rtuAddress.append(i) reg.append(i) startAdr.append(i) rangeAdr.append(i) varname.append(i) timeOut.append(i) try: com = serial.Serial('1', 1, timeout=2, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) time.sleep(2) except Exception as e: pass x = 0 varname[x], rtuAddress[x], reg[x], startAdr[x], rangeAdr[x], timeOut[x] = ( 't', '1', '', '', '1', '1') while True: for i in range(0, unitCount): try: varNameData = m.getDataFromCounter(rtuAddress[i], com, 0) sock_udp.sendto( json.dumps({ 'name': varname[i], 'data': varNameData }).encode('utf-8'), server_address_udp) sock_udp_arch.sendto( json.dumps({ 'name': varname[i], 'data': varNameData }).encode('utf-8'), server_address_udp_arch) sock_udp_vk.sendto( json.dumps({ 'name': varname[i], 'data': varNameData }).encode('utf-8'), server_address_udp_vk) except Exception as e: varNameData = None sock_udp.sendto( json.dumps({ 'name': varname[i], 'data': 'Error' }).encode('utf-8'), server_address_udp) sock_udp_arch.sendto( json.dumps({ 'name': varname[i], 'data': 'Error' }).encode('utf-8'), server_address_udp_arch) sock_udp_vk.sendto( json.dumps({ 'name': varname[i], 'data': 'Error' }).encode('utf-8'), server_address_udp_vk) time.sleep(float(timeOut[x]))
import serial import time import csv arduino=serial.Serial('com4',9600) prevData = 0 time.sleep(5) dataFile = open('data.csv', 'w') with dataFile: while True: inData = arduino.readline() inString = inData.decode('utf-8') headers = inString.split(",") if headers[0] == "HBT": data = [int(headers[1])] print(data[0]) if (data[0]-prevData) > 1: print("Missed beat") prevData = data[0] writer = csv.writer(dataFile, lineterminator='\r') writer.writerow(data)
from tkinter import * import serial #-------------------------------Interface---------------------------------- serialString = "" bmp = "" serialPort = serial.Serial(port="COM1", baudrate=115200, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE) try: serialPort.isOpen() print('serial is open') except: print('error') exit() #TODO: input is ascci #TODO: Com port if (serialPort.isOpen()): try: while (1): #To find port = device manager -> Ports if (serialPort.in_waiting > 0): # Read data out of the buffer until a carraige return / new line is found serialString = serialPort.readline() bmp = serialString.decode("Ascii")
# import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import math import cv2 import numpy as np #Arcuo Detection Imports from cv2 import aruco import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd # for RPI version 1, use “bus = smbus.SMBus(0)” bus = smbus.SMBus(1) ser = serial.Serial("/dev/ttyACM1", 115200, timeout=1) #, writeTimeout = 3) ser.flush() # This is the address we setup in the Arduino Program address = 0x04 offset = 1 # Initialise I2C bus. i2c = busio.I2C(board.SCL, board.SDA) # Modify this if you have a different sized Character LCD lcd_columns = 16 lcd_rows = 2 # Initialise the LCD class lcd = character_lcd.Character_LCD_RGB_I2C(i2c, lcd_columns, lcd_rows) cap = cv2.VideoCapture(0) #camera.balanceExposure()
#!/usr/bin/env python # -*- coding: utf-8 -*- import serial import time import webbrowser import sys import urllib2 gps_serial = serial.Serial(sys.argv[1], 9600) # args: Serial device, baudrate def to_degrees(lats, longs): """ converts the raw values of latitude and longitude from gps module into the values required by the google maps to display the exact location. """ #NMEA format for latitude is DDMM.mmmm #so parsing values for degree, minutes, seconds form the raw value lat_deg = lats[0:2] lat_mins = lats[2:4] lat_secs = round(float(lats[5:]) * 60 / 10000, 2) lat_str = lat_deg + '[' + lat_mins + '(' + str(lat_secs) + ')' #NMEA format for longitude is DDDMM.mmmm #so parsing values for degree, minutes, seconds form the raw value lon_deg = longs[0:3] lon_mins = longs[3:5] lon_secs = round(float(longs[6:]) * 60 / 10000, 2)
import math def GetFirstFloatFromString (string, prefix ): stringAfterPrefix = string.split(prefix)[1] floatstring = stringAfterPrefix.split("~")[0] return float(floatstring) #def getValueFromPositionArrayOutlierRejected(arr): # i=0 # for val in arr: obj = bpy.context.selected_objects[0] ser = serial.Serial() scaleFactor = .005 NumAverages = 5 # print the values to the console print("Connecting to Rig...") #print("bool state:", mytool.my_bool) #print("int value:", mytool.my_int) #print("float value:", mytool.my_float) #print("string value:", mytool.my_string) #print("enum state:", mytool.my_enum) # Prevent unsupported Execution in Local View modes space_data = bpy.context.space_data # Make variable scene that is current scene scene = bpy.context.scene
def __init__(self, device, baud=57600, type="ru5102"): self.connection = serial.Serial(device, baud) assert type in TYPES self.type = type
import os import sys import time import serial from datetime import datetime # commands fire = "<FIR>" stop = "<STP>" # send STP when target is found up = "<UPP>" down = "<DWN>" left = "<LFT>" right = "<RGT>" home = "<HOM>" # send HOM when target has been hit/no bad target in sight arduino_port_tur = "/dev/ttyACM0" arduino_baudrate_tur = 9600 tur_write = serial.Serial(port=arduino_port_tur, baudrate=arduino_baudrate_tur) t_end = time.time() + 2 while time.time() < t_end: tur_write.write(up.encode('utf-8')) t_end = time.time() + 2 while time.time() < t_end: tur_write.write(down.encode('utf-8'))
#if char == self.EOM and self.started: #self.started = False ##msg = self.buffer.split(';') ##ack = '<' + msg[1] + ';' + msg[0] + ';' + 'ACK' + '>' ; ##s.write(ack.encode()) ##print("GOT MESSAGE: " + self.buffer + ' Replying ' + ack) ##print(" ***: " + self.buffer) #self.log.log("INCOMING>>" + self.buffer) #elif char == self.SOM: #self.started = True #self.buffer = "" #elif self.started: #self.buffer += char serialPort = serial.Serial() serialPort.port = '/dev/ttyUSB1' serialPort.baudrate = 115200 def _start(): if serialPort.isOpen(): serialPort.close() serialPort.open() serial_worker = serial.threaded.ReaderThread(serialPort, myESPNOW()) serial_worker.start() mySock.server(myESPNOW.socket) mySock.on_message(handler) while True:
import serial ser = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=3.0) ser.open() string = 'Hello from Raspberry Pi' print 'INIT MESSAGE: "%s"' % string ser.open() # ser.write('%s\n' % string) try: while True: incoming = ser.readline().strip() if len(incoming)>0: print 'Received %s' % incoming else: print 'Nothing received' except: ser.close()
#argv = parse_arguments() #if argv.num == 0: # out_dir = to_dir+str(argv.num)+"/" #else: # out_dir = to_dir+str(argv.num)+"/" #print"\n\n File writting to "+ out_dir+"\n\n" #to_dir = "data/" out_dir = "" num_files = len( [f for f in os.walk(out_dir).next()[2] if f[-4:] == ".csv"]) num_files = 0 #= len([f for f in os.walk(out_dir).next()[2] if f[-4:] == ".csv"]) count = num_files + 1 exit = 0 listen = 0 ser = serial.Serial(serial_port, baud_rate) while exit < 1: print("Ready to record!!!") out_line = "" line = ser.readline() line = line.decode( "utf-8") #ser.readline returns a binary, convert to string if "START" in line: listen = 1 print("Start writing digit ") #+str(argv.num)) #print "Start writing digit "+str(argv.num) while (listen > 0): line = ser.readline() line = line.decode( "utf-8") #ser.readline returns a binary, convert to string if "STOP" in line:
#!/usr/bin/env python #turn sound Mute import sys import serial port = serial.Serial('/dev/ttyUSB0', baudrate=9600, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=5) port.open #this is the code sent to the projector. Replace it for your model port.write("\%\x34\x30\x76") received = port.read(8) print received # newline is printed port.close
import re import os ''' http://www.softree.com/Tips_Techniques/T-039/Nmea_0183_Import_example.pdf NMEA data format $GPRMC, 103804.374 ,A,0411.8650,N,10326.3480,E,0.00,3.85,010304,,*03 103804.374 - Time of fix 10:38:04.374 UTC A - Navigation receiver warning A = OK, V = warning 0411.8650,N - Latitude 4 deg. 11.8650 min. North 10326.3480,E - Longitude 103 deg. 26.3480 min East 0.0 - Speed over ground, Knots etc... ''' #os.system("echo uart1 > /sys/devices/bone_capemgr.9/slots") serial = serial.Serial("/dev/ttyO2", baudrate=9600) resp = "" while True: while (serial.inWaiting() > 0): resp += serial.read() if "\r\n" in resp: if "$GPRMC" in resp: print resp.strip() data = resp.split(',') info = data[3] + " " + data[4] + " " + data[5] + " " + data[6] print "GPS lat, long: " + info + "\r\n" resp = ""
def onChoseSerialPort(self, event): """ picks up the newly selected port and attempts to connect to a peripheral device via it """ self.logger.debug('Choosing serial port.') # ignore the None option if self.portChoice.GetStringSelection() != 'None': try: # don't re-open a working stream if self.portChoice.GetStringSelection() != self.currentPort: # close any open ports if present if self.portOpen: self.currentSerialConnection.close() self.currentSerialConnection = serial.Serial( port=self.portChoice.GetStringSelection(), baudrate=self.BaudRate, timeout=2, stopbits=self.currentStopBits, parity=self.currentParity, bytesize=self.currentByteSize) self.logger.debug('Checking {}'.format( self.currentSerialConnection)) if self.checkConnection( ): # Try to connnect to the user-selected port. self.portOpen = True self.currentPort = self.portChoice.GetStringSelection() self.logger.info('Connected to port {}'.format( self.currentPort)) # To verify the setting of the serial connection details. self.logger.debug( 'baud={},stop bits={},parity={},byte size={}'. format( self.currentSerialConnection.baudrate, self.currentSerialConnection.stopbits, self.currentSerialConnection.parity, self.currentSerialConnection.bytesize, )) else: # Something's wrong, couldn't connect. wx.MessageBox( 'Cannot connect to port {}.'.format( self.portChoice.GetStringSelection()), 'Error', wx.OK | wx.ICON_ERROR) self.logger.error( 'Could not connect to port {}'.format( self.portChoice.GetStringSelection())) self.currentSerialConnection = 0 self.portOpen = False self.updatePorts() self.portChoice.SetSelection( 0) # Go back to 'None' selection. except BaseException as unknonwError: wx.MessageBox( 'Unknown problem occurred while establishing connection using the chosen port!', 'Error', wx.OK | wx.ICON_ERROR) self.currentSerialConnection = 0 self.portOpen = False self.updatePorts() self.portChoice.SetSelection(0) # Go back to 'None' selection. self.logger.error( 'Failed to connect to a port due to {}.'.format( unknonwError)) # if None is chosen then close the current port else: self.disconnect()
def __init__(self, portname, baudrate, protocol): """Initializes port by resetting device and gettings supported PIDs. """ logger.info("Initializing ELM327: PORT=%s BAUD=%s PROTOCOL=%s" % ( portname, "auto" if baudrate is None else baudrate, "auto" if protocol is None else protocol, )) self.__status = OBDStatus.NOT_CONNECTED self.__port = None self.__protocol = UnknownProtocol([]) # ------------- open port ------------- try: self.__port = serial.Serial(portname, \ parity = serial.PARITY_NONE, \ stopbits = 1, \ bytesize = 8, timeout = 10) # seconds except serial.SerialException as e: self.__error(e) return except OSError as e: self.__error(e) return # ------------------------ find the ELM's baud ------------------------ if not self.set_baudrate(baudrate): self.__error("Failed to set baudrate") return # ---------------------------- ATZ (reset) ---------------------------- try: self.__send(b"ATZ", delay=1) # wait 1 second for ELM to initialize # return data can be junk, so don't bother checking except serial.SerialException as e: self.__error(e) return # -------------------------- ATE0 (echo OFF) -------------------------- r = self.__send(b"ATE0") if not self.__isok(r, expectEcho=True): self.__error("ATE0 did not return 'OK'") return # ------------------------- ATH1 (headers ON) ------------------------- r = self.__send(b"ATH1") if not self.__isok(r): self.__error("ATH1 did not return 'OK', or echoing is still ON") return # ------------------------ ATL0 (linefeeds OFF) ----------------------- r = self.__send(b"ATL0") if not self.__isok(r): self.__error("ATL0 did not return 'OK'") return # by now, we've successfuly communicated with the ELM, but not the car self.__status = OBDStatus.ELM_CONNECTED # try to communicate with the car, and load the correct protocol parser if self.set_protocol(protocol): self.__status = OBDStatus.CAR_CONNECTED logger.info("Connected Successfully: PORT=%s BAUD=%s PROTOCOL=%s" % ( portname, self.__port.baudrate, self.__protocol.ELM_ID, )) else: logger.error("Connected to the adapter, but failed to connect to the vehicle")
#!/usr/bin/env python2.7 #andres leon: this script is called from the main sollarcontrollerdata_mysqlxx.py and gets data from the #current sensor which is connected to its own Arduino board. it delivers a json dataset that the other #scripts can decipher and use. import json import serial import sys import time ser = serial.Serial('/dev/ttyUSB2', 115200) for x in range(1,3): jsondata = str(ser.readline().strip()) #print ("'" + jsondata + "'") raw = 0.0 zero_point = 0.0 current = 0.0 avgSamples = 0.0 jsondata = "" try: print( str( ser.readline().strip() ) ) except Exception as e: print str("ERROR!")
import logging import os logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) from PyCRC.CRCCCITT import CRCCCITT import struct def calcCRC(data): crc = CRCCCITT("FFFF").calculate(bytes(data)) b = bytearray(struct.pack(">H", crc)) return b print(calcCRC(b'0')) with serial.Serial('COM6', 921600) as s: h = HDLC(s) h.sendFrame(b'0') POLYNOMIAL = 0x1021 PRESET = 0xffff def _initial(c): crc = 0 c = c << 8 for j in range(8): if (crc ^ c) & 0x8000: crc = (crc << 1) ^ POLYNOMIAL else: crc = crc << 1 c = c << 1
PORT = "/dev/ttyACM0" fig = plt.figure() ax = fig.add_subplot(111) ax.set_ylim(0, 250) #ax.set_xlim(0, 250) x = np.arange(0, 2 * np.pi, 0.01) # x-array line = ax.plot(x, np.sin(x)) distances = [] # TODO: adjust this based on the time between inputs distances_max_len = 20 ser = serial.Serial(PORT, 9600) def reading_to_distance(x): return (0.0 if x == 0 else 1000 / math.sqrt(x)) # Adds a new distance reading to the distances array. If # the array has more than the distances_max_len, remove # its first element. def add_new_distance(distance): distances.append(distance) if len(distances) > distances_max_len: distances.pop(0)
import serial import time from light_controller import LightController import face_controller import subprocess as sp import picamera import pickle import os import signal print('libs loaded') port = serial.Serial('/dev/ttyAMA0', baudrate=9600) camera = picamera.PiCamera() fc = face_controller.FaceController(camera) os.system("xte 'mousemove 0 600'") if port.is_open: print("/dev/ttyAMA0 is open") lc = LightController() stop = 0 # possibly have a flag that will terminate any routine def take_picture(): pid = os.fork() if pid == 0: # in child process lc.pic_countdown() os._exit(0) else:
def run(self): """ The main loop of the daemon. """ #Variaveis globais porta = "/dev/ttyACM0" velocidade = 57600 urlFiware = "http://35.199.66.232:8080/webservice/coleta/add" #CHAVES DE CANAL COLMEIA1 = 'ODQHRWU1WIPGH2CK' COLMEIA2 = 'Z63X9L46JZFPDUWZ' COLMEIA3 = 'NCFLS5NZV3MPWKAU' try: #Conexao com porta serial conexao = serial.Serial(porta, velocidade) #Limpa o buffer da porta serial para nao ler valores errados conexao.flushInput() while 1: leitura = conexao.readline() # leitura = "1 24 54 12 12" valores = leitura.split(' ') if leitura != "" and len(valores) == 5: headers = {'Content-Type': 'application/json'} #Preparacao dos dados para enviar data1 = open('/etc/smartbee/json.json', 'r') data = data1.read() data1.close() #Alterar o atributos principais do JSON #IdColmeia data = data.replace('$1', valores[0]) #Temperatura data = data.replace('$2', valores[1]) #Umidade data = data.replace('$3', valores[2]) #Tensao Sensores data = data.replace('$4', valores[3]) #Tensao Repetidores data = data.replace('$5', valores[4]) #Consertando erros no arquivo JSON data = json.dumps(data) data = data.replace('\\n', '') data = data.replace('\\', '') data = data.replace('\"{', '{') data = data.replace('r\"}]}]', '\"}]}]') data = data.replace('}\"', '}') status_requisicao = '' with open('/etc/smartbee/json.txt', 'a') as arq: arq.write(data + '\n') with open('/etc/smartbee/leituras.txt', 'a') as arq: arq.write(leitura + '\n') status_requisicao = '' #ENVIANDO REQUISICAO PARA THINKSPEAK id_key = '' if (valores[0] == 1): id_key = COLMEIA1 elif (valores[0] == 2): id_key = COLMEIA2 elif (valores[0] == 3): id_key = COLMEIA3 try: r = requests.post(urlFiware, headers=headers, data=data) #ENVIA ATUALIZACAO DE VALORES THINKSPEAK url = "http://api.thingspeak.com/update?api_key=%s&field1=%s&field2=%s&field3=%s&field4=%s" % ( id_key, valores[1], valores[2], valores[3], valores[4], valores[5]) r = requests.get(url) except requests.exceptions as err: with open('/var/log/smartbee/smartbee_err.log', 'a') as arq: arq.write(str(err) + '\n') except Exception as err: with open('/var/log/smartbee/smartbee_err.log', 'a') as arq: arq.write(str(err) + '\n') except Exception as err: with open('/var/log/smartbee/smartbee_err.log', 'a') as arq: arq.write(str(err) + '\n')
if __name__ == '__main__': parser = argparse.ArgumentParser(description='Calibrate the encoder on a motor controller board.') parser.add_argument('serial', type=str, help='Serial port') parser.add_argument('--baud_rate', type=int, help='Serial baud rate') parser.add_argument('board_id', type=int, help='Board ID') parser.add_argument('file_name', type=str, help='File name to record data') parser.add_argument('--steps', type=int, help='Number of steps') parser.add_argument('--delay', type=float, help='Delay between steps') parser.set_defaults(baud_rate=COMM_DEFAULT_BAUD_RATE, duty_cycle=0.6, steps=50, delay=0.1, file_name='') args = parser.parse_args() # # Data collection # ser = serial.Serial(port=args.serial, baudrate=args.baud_rate, timeout=0.1) time.sleep(0.1) client = BLDCControllerClient(ser) client.enterBootloader([args.board_id]) time.sleep(0.2) try: print (client.enumerateBoards([args.board_id])) except: print("Failed to receive enumerate response") time.sleep(0.2) client.leaveBootloader([args.board_id]) time.sleep(0.2) # Wait for the controller to reset ser.reset_input_buffer()
#!/usr/bin/python # coding: utf -8 #加上這行才能key中文 要import urllib2 import urllib2 import cv2.cv as cv import sys import serial import time arduino = serial.Serial('/dev/ttyUSB0', 9600) #set arduino serial port cv.NamedWindow("color_tracking", 1) #创建一个矩形,来让我们在图片上写文字,参数依次定义了文字类型,高,宽,字体厚度等。 font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 4) #capture = cv.CaptureFromCAM(0) #capture = cv.CaptureFromCAM(1) capture = cv.CaptureFromCAM(2) #width = 160 #leave None for auto-detection #height = 120 #leave None for auto-detection width = 640 #leave None for auto-detection height = 480 #leave None for auto-detection middle_w = 2 #Cross Center width 十字中心歸零校正,數字越大線往左 middle_h = 2 #Cross Center height 十字中心歸零校正,數字越大線往上 cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, width) cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, height) while True: img = cv.QueryFrame(capture) cv.Smooth(img, img, cv.CV_BLUR, 3)
def BootModeFWUpgrade(dut_port, device, path): cyfm_file = read_into_buffer(path) if dut_port < 0: return -1 if device == "8020": address = 0x90000000 cmdBOOTERASE = cmdBOOTERASE_8020 if device == "8040": address = 0x100000 cmdBOOTERASE = cmdBOOTERASE_8040 dut_port = int(dut_port) comport = serial.Serial("COM" + str(dut_port), 115200, timeout=60) if (cyfm_file[0] != 0x0A or cyfm_file[1] != 0x11): terminate_program("Fail, cyfm file invalid: 01", 1) out = open("temp_file", "wb") out.write(cyfm_file[12:]) # extract .gz file out.close() # wait for file closed while (out.closed == False): pass print("File closed") try: with gzip.open("temp_file", 'rb') as f: file_content = bytearray(f.read()) except: terminate_program("Fail, cyfm file invalid: 02", 1) # verify MD5 file_md5 = hashlib.md5(file_content[16:]).digest() if (file_md5 != file_content[0:16]): terminate_program("Fail, cyfm file invalid: 03", 1) print("Verify MDS") firmware_file = list(file_content[16:]) # firmware to be loaded firmware_length = len(firmware_file) f.close() # wait for file closed while (f.closed == False): pass os.remove("temp_file") # 鍙戦�丮ONVER send_command(comport, cmdMONVER) time.sleep(0.02) print("MONVER") #FLASH瑙i攣 send_command(comport, cmdFLASHUNLOK) time.sleep(0.1) print("Flash unlock") # 鍙戦�丼ETFRQ send_command(comport, cmdSETFRQ) time.sleep(0.02) print("Set frequency") # 鍙戦�丅OOTERASE send_command(comport, cmdBOOTERASE) time.sleep(0.2) print("Boot erase") comport.reset_input_buffer() comport.reset_output_buffer() fw_update_boot(comport, firmware_file, firmware_length, address) comport.close() terminate_program("Firmware download completed!", 0) return 0
#set variables to hold serial port of microbit device ID and baud rate port = "/dev/ttyACM0" baud = 115200 #create variables for motors, any gpio will work however these are in the right order to sync motors motorA = Motor(forward=26, backward=19) motorB = Motor(forward=20, backward=16) #used to detect if robot is already in motion on = False while True: #set serial port config s = serial.Serial(port) s.baudrate = baud s.parity = serial.PARITY_NONE s.databits = serial.EIGHTBITS s.stopbits = serial.STOPBITS_ONE #read serial data and save to data variable data = s.readline() time.sleep(0.1) data = str(data) #find related word in data string #shake event to toggle move forward if "shake" in data: if on == False: motorA.forward()
# get steering value(delta) row_delta = get_steering_value(vp, image.shape[0], image.shape[1]) return result, ROI_img, int(row_delta) def interact_ser(_str, _ard): _ard.write(_str.encode()) tmp = _ard.readline() print(tmp.decode()) capture = cv2.VideoCapture(1) capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) port = 'COM15' ard = serial.Serial(port, 9600) tmp = deque([]) while cv2.waitKey(33) != ord('q'): try: ret, frame = capture.read() img, ROI_img, delta = conv_img_to_delta(frame) tmp.append(delta) if len(tmp) > 10: tmp.popleft() delta = int(sum(tmp) / len(tmp)) if len(tmp) >= 10: #if abs(delta) < 2: # delta =0 serial_deque = deque([]) if delta < 0: delta = abs(delta)
import serial import pynmea2 ser = serial.Serial('/dev/serial0', 9600, timeout=1) while True: data = ser.readline() print(data) msg = pynmea2.parse(data.str()) print(msg)