def write(name_file, start_nm, end_nm, speed_nm, com, q_bar, q_str, q_stop, mode, direct): print(direct) # np.save(direct + '\\' + name_file, [1, 2, 3, 4, 5]) speed_nm1 = speed_nm old_l = 0 stop = False q_str.put('Scan starting') speed_nm = speed_nm * 1.0625 s = Serial(com, baudrate=500000, timeout=1) ### Настройка сериал порта time.sleep(4) ############################################### time_scan = ( (end_nm - start_nm) / speed_nm) * 60 ### Расчетное время сканирования print(time_scan) s.read_all() ### Считываем все из порта time.sleep(4) s.write(b"s") ### Отправка команды микрокотроллеру для старта # started = s.readline().strip() q_str.put('Get ready') while True: started = s.readline().strip() print("started") if started.endswith(b"started"): print("started") break try: stop = q_stop.get_nowait() if stop == True: print('Stop') break except Empty as end_scan: print(end_scan) ############################################### Проверка ответной команды от микроконтроллера о страте # if not started.endswith(b"started"): # print(started) # s.close() # raise RuntimeError("Couldn't start reading!") # else: # print("Started") ############################################### cur = b"" a = bytearray() q_str.put('Scaning') start_scan = time.time() end_scan = 0 if stop != True: while True: try: end_scan = time.time() if end_scan - start_scan >= time_scan: break l = (int(end_scan - start_scan) * 100) / time_scan if l != old_l: q_bar.put(l) cur = s.read(70) a.extend(cur) old_l = l stop = q_stop.get_nowait() if stop == True: print('Stop') break except Empty as end_scan: print(end_scan) in_buf = s.in_waiting print(in_buf) cur = s.read(in_buf) a.extend(cur) print(s.in_waiting) s.write(b"e") ### Отправка команды микрокотроллеру для завершения stopped = s.readline().strip() s.close() ############################################### Проверка ответной команды от микроконтроллера о заерщении if stop != True: if not stopped.endswith(b"stopped"): print("Uncorrect stop!") else: print("Succesfully stopped.") print("Elapsed", end_scan - start_scan) q_str.put('Scan end, start correct') print('Scan end, start correct') ############################################### Проверка на плохие(поломанные) данные, если нашли то "выбрасываем" bytes_ = [0b00100010, 0b00100000, 0b00100100] d = bytearray() i = 0 while i < len(a): pack = a[i:i + 7] if len(pack) == 7: c = pack[0] in bytes_ if c == True: d.extend(pack) else: while not a[i] in bytes_: i += 1 i += 7 dtype = np.dtype([('signals', 'uint8'), ('value', 'uint16'), ('time', 'uint32')]) data = np.frombuffer(d, dtype) diff = np.diff(data['time']) ind = np.where(diff < np.median(diff) * 2) data = data[ind] np.save(direct + '//' + name_file, data) time.sleep(1) q_str.put('Mathematical processing') if mode == 'Dual beam mode': mat_c.mat_calculations(start_nm, speed_nm1, name_file, q_str, direct) if mode == 'Single beam mode': s_mar_c.mat_calculations(start_nm, speed_nm1, name_file, q_str, direct)
if __name__ == "__main__": main() #preprae database with open('database.json') as f: cha_arr = json.load(f) if file_name in cha_arr: print('\n') print('+------------------------------------------------------------+') print('| Name already exist. The program has been terminated :( |') print('+------------------------------------------------------------+') sys.exit(0) s = Serial(port='COM3', baudrate=1000000, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, xonxoff=False, rtscts=False) print("Configured") while True: #mcu_feedback = s.readline().decode() # mcu_feedback = ser.read(1) b1, b2, b3 = b'\x00', b'\x00', b'\x00' RGB = True img = np.zeros((64, 64, 3)).astype(np.uint8) while True: b1, b2, b3 = b2, b3, s.read(1)
def on_start(self): if self._device is None: from serial import Serial self._device = Serial(port=settings.MIXER_EXT_PORT, timeout=0.2)
# Empty line = EOF if len(row) == 0: break # Lines containing 112 elements are legit elif len(row) == 112: a.append(row) # Return image as numpy array return np.array(a).astype('float') if __name__ == '__main__': # Open serial connection to Arduino stony = Serial(PORT, BAUD, timeout=2) # Get pattern-noise image F = getimage( stony, 'Cover the lens and hit any key to acquire pattern noise ...') # Get actual image I = getimage(stony, 'Uncover the lens and hit any key to take a snapshot ...') # Subtract pattern noise from image and display result image = F - I plt.imshow(np.flipud(image), cmap='gray') plt.show()
import pickle import csv from random import shuffle import serial from serial import Serial from time import sleep from values import ARDUINO_PORT, BAUD_RATE import csv lookup = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] arduino = Serial(ARDUINO_PORT, BAUD_RATE, timeout=0.1) print("Loading model") loaded_model = pickle.load(open('classification.sav', 'rb')) print("Model loaded") def getBytes(msg): return bytes(msg, 'utf-8') print("Starting . . . ") sleep(1) arduino.write(getBytes("5")) sleep(1) while True:
def open(self): if self._dev is not None: raise RuntimeError('Device has already been opened.') self._dev = Serial(port=self._devpath, timeout=10)
sys.stderr.write( 'missing serial port (probably /dev/tty.usbserial-something)\n' ) sys.exit(1) if len(maybes) > 1: sys.stderr.write( 'not sure which serial port to use. likely candidates:\n{}\n'. format('\n'.join( map( lambda m: '{}\t{}\t{}'.format(m.device, m.description, m.manufacturer), maybes)))) sys.exit(1) port = maybes[0].device s = Serial(port, 9600) sleep(2) t = s.read(s.in_waiting) print(t) # print('check load bolex') # check_load_bolex(s) # sleep(0.3) # print('check bolex reel') # check_bolex_reel(s) print('check capture') check_capture(s) # print('check advance')
from serial import Serial, SerialException import time cxn = Serial("/dev/ttyACM1", baudrate=9600) time.sleep(2) while True: cmd = input("Select your Speed (0-10): ") if cmd == 'exit': cxn.write(0) cxn.close() exit() else: cmd = int(cmd) cxn.write([cmd]) print 'Python: ' + str(cmd) while cxn.inWaiting() < 1: pass msg = cxn.readline() # print "Arduino: " + msg file = open('data', 'a') file.write(msg) file.close()
import time as tm from collections import namedtuple import matplotlib.pyplot as plt from serial import Serial zero_time = tm.time() session_data = dict() Datapoint = namedtuple('data', ['time', 'voltage', 'temperature']) with Serial(port='/dev/tty.usbserial-14630', baudrate=9600, timeout=5) as port0: for _ in range(250): print('In while') data_0 = port0.readline().strip() #print('data_0 read: ', data_0) data_1 = port0.readline().strip() #print('data_1 read: ', data_1) if data_0[0] == 'V': #print('V') voltage = float(data_1[2:]) temperature = float(data_0[2:]) else: #print('Not V') voltage = float(data_0[2:]) temperature = float(data_1[2:]) #print('data recognized') time = tm.time() - zero_time session_data[time] = Datapoint(time, voltage, temperature) print(session_data[time]) tm.sleep(0.15) print('-'*15) print(len(session_data))
#send data # EN--X2--Y2--X1--Y1--ST # OEN STOP all # OST START # EN - end # ST - start data packet # CR -color RED # CB - color BLUE # CG - color Green # S1 - side one # S2 - side two # S3 - side three # S4 - side four s = Serial('com4', 9600) def set_DT(i, x, y): s.writelines(i, '.', x, ':', y) def set_ST(): s.writelines('ST') def set_OST(): s.writelines('OST') def set_OEN():
# establish wireless connect to onboard RaspberryPi wireless_ip = "10.0.0.2" routered_ip = "192.168.1.2" serverAddressPort = (routered_ip, 20001) bufferSize = 128 UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) # establish serial connection to Arduino # reading inputs from GoBilda transmitter # Check using arduino ide: Tools --> Port --> ser = Serial('/dev/cu.usbmodem144301', 115200) print(ser.name) if ser.is_open: while True: time.sleep(0.010) values = ser.readline() channels = values.split() if len(channels) < 6: continue L_X = int(channels[3]) L_Y = invert_channel(int(channels[2])) R_X = invert_channel(int(channels[0]))
def get_socket(self): """ Creates Pyserial object :return: serial object """ return Serial(port=self.port, **self.serial_settings)
def __init__(self, *args, **kwargs): super(Updater, self).__init__(*args, **kwargs) self.usb = Serial('/dev/ttyUSB0') self.a = 0 self.b = 0
from struct import pack, unpack def send_location(ser): x = int(input("Enter a number from 0 to 980 for x axis: ")) y = int(input("Enter a number from 0 to 850 for y axis: ")) z = int(input("Enter a number from 0 to 7000 for z axis: ")) location = pack("<3H", x, y, z) ser.write(location) def read_crgb(ser): crgb = ser.read(8) colours = unpack("<4H", crgb) return colours def crgb_2_rgb(raw): GAMMA = 2.2 return tuple((int(((val / raw[0])**GAMMA) * 255) for val in raw[1:])) if __name__ == "__main__": ser = Serial("/dev/ttyACM0", 9600) while True: send_location(ser) raw = read_crgb(ser) print(crgb_2_rgb(raw))
cursorclass=MySQLdb.cursors.DictCursor, charset='utf8') cursor = conn.cursor() print "connected" shell = win32com.client.Dispatch("WScript.Shell") def checkCard(cardid_hex): print "card id is " + cardid_hex cursor.execute("SELECT `username` FROM `rfid` WHERE `card_id`=%(cardid)s", {'cardid': cardid_hex}) result = cursor.fetchone() print result shell.SendKeys(result['username'] + "{enter}") while True: try: io = Serial('COM4', 9600, timeout=1) while True: try: p = Packet(ISO14443A.Request) reply = p.execute(io) p = Packet(ISO14443A.Anticollision) reply = p.execute(io) cardid = reply.data if cardid: cardid_hex = "".join(map(lambda x: "%.2X" % x , cardid)) if cardid_hex != prevcardid: prevcardid = cardid_hex checkCard(cardid_hex) else: prevcardid = None time.sleep(0.1)
def connect_with_baudrate(baudrate): return Serial(port=port, baudrate=baudrate, timeout=self.timeout, writeTimeout=self.write_timeout)