def __init__(self, port,baudrate): tt = time.strftime("%m-%d_%H.%M",time.localtime(time.time())) # get current file absolutely path modulepath=os.path.dirname(os.path.realpath(__file__)) self.log_config(modulpath) os_version = sys.platform self.baudrate= baudrate self.bytesize = 8 self.parity = 'N' self.stopbits = 1 self.timeout = 1 self.writeTimeout = 10 if os_version == 'win32': self.port = port else: self.port = os.path.join('/dev', port) self.com = Serial(self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, timeout=self.timeout, writeTimeout=self.writeTimeout) # self.open() self.dev_name = self.get_dev_name() try: self.name = self.dev_name.split(',')[1] except IndexError as e: raise "Equipment not found: %s" % (str(self.port))) self.log.info(self.dev_name)
def run(self): stop = False # Create the Serial port logging.info("run: Creating the Serial port.") try: self.serial_port = Serial.Serial(serial_name = self.serial_name, baud_rate = self.baud_rate, bsl_mode = self.bsl_mode) except: return # If using the serial port to sniff if (self.sniffer_mode == "serial"): # Create the TUN interface logging.info("run: Creating the TUN interface.") try: self.tun_interface = TunInterface.TunInterface(tun_name = self.tun_name) except: # Stop the serial port self.serial_port.stop() return # Start the Serial port print("- Serial: Listening to port %s at %s bps." % (self.serial_name, self.baud_rate)) self.serial_port.start() # Start the TUN interface print("- Tun: Injecting packets to interface %s." % self.tun_name) self.tun_interface.start() # Define the IEEE 802.15.4 channel stop = self.set_radio_channel() # Run until stopped by user while (not stop): try: if (self.sniffer_mode == "serial"): # Try to receive a packet from the Serial port stop, packet, length = self.serial_port.receive() # If a packet is successfully received if (packet): logger.info("run: Received a message with %s bytes.", length) # Inject the packet to the TUN interface self.tun_interface.inject(packet) else: time.sleep(0.5) except (KeyboardInterrupt): # Define the IEEE 802.15.4 channel stop = self.set_radio_channel() # Stop the serial port self.serial_port.stop() # If using the serial port to sniff if (self.sniffer_mode == "serial"): # Stop the TUN interface self.tun_interface.stop()
def Main(): NeoModule.obj = NeoModule.NeoModule("COM20", "20") port = NeoModule.obj.port print(port) data = NeoModule.obj.send() print(data) Serial.obj = Serial.Serial(port, 9600, data) #NeoModule.obj.display() Serial.obj.read()
def program(port=None, baudrate=None): global finished # Create and start Serial manager serial = Serial.Serial(name=port, baudrate=baudrate, timeout=timeout) serial.start() # Create MQTT client mqtt = MqttClient.MqttClient(mqtt_address, mqtt_port) mqtt.start() print("Starting program at port {} with bauds {}.".format(port, baudrate)) # Repeat until finish condition while (not finished): # Try to receive a Serial message message, length = serial.receive(timeout=timeout) # If we received a message if (length > 0): try: message = bytearray(bytes(message)) eui48, counter, t, h, p, l, rssi = struct.unpack( '>6sIhhhhb', message) t = t / 10.0 h = h / 10.0 p = p / 10.0 l = l / 10.0 print( "Counter={}, Temperature={}, Humidity={}, Pressure={}, RSSI={}" .format(counter, t, h, p, rssi)) except: logger.error("program: Error unpacking.") try: # Create MQTT message mqtt_message = json.dumps({ "address": eui48, "counter": counter, "temp": t, "humidity": h, "pressure": p, "rssi": rssi }) # Send MQTT message mqtt.send_message(mqtt_topic, mqtt_message) except: logger.error("program: Error sending MQTT packet.") if (finished): # Stop the serial port serial.stop()
def __init__(self, ip='localhost', port=27017, table="employees", method=CONNECTED_DB): if method == CONNECTED_DB: self.db = DB.DB(ip, port, table) elif method == CONNECTED_TCP: self.socket = Socket(host=ip, port=port) self.method = method self.serial = Serial.Serial() self.data = None self.serial.setData(self.serial.ALERT_OFF)
def main(argc,argv): while True: if argc >= 2: serial = Serial.Serial(argv[1],int(argv[2])) else: serial = Serial.Serial('/dev/ttyACM0',115200) if serial.Available() == True: break #else: #print "Could not open serial port." time.sleep(1.0) while True: try: string = serial.Receive() if not(string in ""): print string except KeyboardInterrupt: print "Finished." sys.exit(0)
def __init__(self, serial_port=None, serial_baudrate=None, serial_timeout=0.1): self.serial_port = serial_port self.serial_baudrate = serial_baudrate self.serial_timeout = serial_timeout # Create serial port self.serial = Serial.Serial(name=self.serial_port, baudrate=self.serial_baudrate, timeout=self.serial_timeout) # Call parent init ABC.__init__(self) threading.Thread.__init__(self)
def __init__(self): self.gpgga_info = "$GPGGA," self.ser = Serial("/dev/ttyUSB0", baudrate = 115200 ) self.GPGGA_buffer = 0 self.NMEA_buff = 0 self.lat_in_degrees = 0 self.long_in_degrees = 0 self.nmea_latitude = 0 #extract latitude from GPGGA string self.nmea_longitude = 0 self.nmea_n_s=014 self.nmea_e_w=0 self.pointA =0 self.pointB =0 self.lat_1=0 self.long_1=0 self.lat_2=0 self.long_2=0
def serial(posisi): ser = Serial('/dev/ttyUSB0',) ser.baudrate = 115200 while 1: if (posisi == '1'): ser.write(str(1).encode()) print('kiri, 101') time.sleep(0.1) ser.write(str(0).encode()) time.sleep(0.1) ser.write(str(1).encode()) elif (posisi == '2'): print('kiri, nyala 1010 x') ser.write(str(1).encode()) time.sleep(0.1) ser.write(str(0).encode()) ser.write(str(1).encode()) time.sleep(0.1) ser.write(str(0).encode()) elif (posisi == '3'): ser.write(str(1).encode()) time.sleep(0.1) ser.write(str(0).encode()) time.sleep(0.1) ser.write(str(1).encode()) time.sleep(0.1) ser.write(str(0).encode()) time.sleep(0.1) ser.write(str(1).encode()) time.sleep(0.1) ser.write(str(0).encode()) print(ser.readline()) return 0
def __init__(self, port,baudrate): tt = time.strftime("%m-%d_%H.%M",time.localtime(time.time())) # get current file absolutely path modulepath=os.path.dirname(os.path.realpath(__file__)) self.log_config(modulpath) os_version = sys.platform self.baudrate= baudrate self.bytesize = 8 self.parity = 'N' self.stopbits = 1 self.timeout = 1 self.writeTimeout = 10 if os_version == 'win32': self.port = port else: self.port = os.path.join('/dev', port) self.com = Serial(self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, timeout=self.timeout, writeTimeout=self.writeTimeout)
#Code used for testning in M3 import cv2 assert float(cv2.__version__.rsplit('.', 1)[0]) >= 3 import numpy as np import Calibrater import Serial ser = Serial.Serial('COM9', 115200) def find_pixels(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONUP: print("X:" ,x, "Y:",y) global xCoordinate global yCoordinate xCoordinate = x yCoordinate = y def heighCorrection2(x, y, ledheight, cameraheight, xStart, ystart): t = (cameraheight - ledheight)/cameraheight vx = x - 200 vy = 400 - y - 37 xreal = xStart + t*vx yreal = ystart + t*vy return [xreal, yreal] cv2.namedWindow('image') cv2.setMouseCallback('image', find_pixels) lower_red = np.array([0,100,100], np.uint8) upper_red = np.array([10, 255, 255], np.uint8)
import Serial import time mySerial = Serial.Serial() # mySerial needs a few seconds to establish connection time.sleep(5) while (1): data = raw_input("> ") mySerial.write(data) time.sleep(0.01) #mySerial.read() #time.sleep(2) response = mySerial.read() print(response)
def init(self): self.serial = Serial.Serial(self.serial_port, self.serial_baudrate) self.serial.start()
def run(self): stop = False # Create the Serial port logging.info("run: Creating the Serial port.") try: self.serial_port = Serial.Serial(serial_name = self.serial_name, baud_rate = self.baud_rate) except: return # Start the Serial port print("- Serial: Listening to port %s at %s bps." % (self.serial_name, self.baud_rate)) self.serial_port.start() ringlen = 1600 rb_x = deque(np.zeros(ringlen, dtype='f'), ringlen) rb_y = deque(np.zeros(ringlen, dtype='f'), ringlen) rb_z = deque(np.zeros(ringlen, dtype='f'), ringlen) fig = plt.figure() ax1 = plt.subplot(3, 1, 1) ax2 = plt.subplot(3, 1, 2) ax3 = plt.subplot(3, 1, 3) ax1.grid(True) ax2.grid(True) ax3.grid(True) ax1.set_ylim([-1.5, 1.5]) ax2.set_ylim([-1.5, 1.5]) ax3.set_ylim([-1.5, 1.5]) graph1, = ax1.plot(rb_x) graph2, = ax2.plot(rb_y) graph3, = ax3.plot(rb_z) file = "output.log" f = open(file,'w') plt.show(block=False) while (not stop): stop, packet, length = self.serial_port.receive() if (length > 0): # Unpack the values elements = length/2 values = struct.unpack('<' + 'h' * elements, packet) # Iterate over values and append to buffer for x, y, z in zip(*[iter(values)]*3): # Conver to Gs x = x / 256.0 y = y / 256.0 z = z / 256.0 # Append to ringbuffer rb_x.append(x) rb_y.append(y) rb_z.append(z) # Write to log file f.write(str(x) + "," + str(y) + "," + str(z) + "\n") f.flush() # Update the graph data graph1.set_ydata(rb_x) graph2.set_ydata(rb_y) graph3.set_ydata(rb_z) # Update the plot fig.canvas.draw() # Close the file f.close() # Stop the serial port self.serial_port.stop()
I11_ = Zeros(3, 3) I11_[2, 2] = Jz11 I21_ = Zeros(3, 3) I21_[2, 2] = Jz21 I1__ = [I11_, I21_] I12_ = Zeros(3, 3) I12_[2, 2] = Jz12 I22_ = Zeros(3, 3) I22_[2, 2] = Jz22 I2__ = [I12_, I22_] """ Gravidade """ gamma_ = Zeros(3, 1) gamma_[1] = -9.8 """ Cadeias Seriais """ RR1 = Serial(dof, l_, lg1_, m1_, I1__, gamma_, fDH_RR) RR2 = Serial(dof, l_, lg2_, m2_, I2__, gamma_, fDH_RR) RR_ = [RR1, RR2] """ Efetuador """ EndEffector = EfetuadorTranslacional(0, gamma_, 0, 0, 0, False) """ Parametros da arquitetura do mecanismo Paralelo """ angulos1_ = Zeros(3, 1) angulos2_ = Zeros(3, 1) angulos2_[0, 0] = pi angulos2_[1, 0] = pi angulos__ = [angulos1_, angulos2_] l0 = 0.05 origem1_ = Zeros(3, 1) origem1_[0, 0] = l0 origem2_ = -origem1_
def on_enter(self): ser.Serial.port = self.textInput.text ser.Serial().open_communication()
"Class that detects a blue led on the screen and sends it coordinates " "over USB-port" import cv2 import numpy as np import Calibrater import Serial assert float(cv2.__version__.rsplit('.', 1)[0]) >= 3 ser = Serial.Serial('COM9', 115200) #initiate the serial communication img_size = (400, 400) img_draw = np.ones(img_size) * 255 oldCoordinateX = 0 oldCoordinateY = 0 "Returns the clicked pixel on the image" def find_pixels(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONUP: print("X:", x, "Y:", y) global xCoordinate global yCoordinate xCoordinate = x yCoordinate = y "Correction for the height of camera, " def heighCorrection2(x, y, ledheight, cameraheight, xStart, ystart, offset):
def program(dbClient, port=None, baudrate=None): global finished # Create and start Serial manager serial = Serial.Serial(name=port, baudrate=baudrate, timeout=timeout) serial.start() print("Starting program at port {} with bauds {}.".format(port, baudrate)) # Repeat until finish condition while not finished: # Try to receive a Serial message message, length = serial.receive(timeout=timeout) statistics = serial.get_statistics() # If we received a message if (length > 0): message = bytearray(bytes(message)) _, deviceID, counter, txMode, txCounter, csmaRetries, csmaRSSI, pkt_type, _, rssi, _ = unpack( ">c6sIBBBbB16sbc", message) data = [ { "measurement": "transmissionData", "tags": { "deviceID": chr(deviceID[0]) }, "fields": { "counter": counter, "txMode": txMode, "txCounter": txCounter, "csmaRetries": csmaRetries, "csmaRSSI": csmaRSSI, "rssi": rssi, "pkt_type": pkt_type } }, { "measurement": "serialStatistic", "tags": { "deviceID": chr(deviceID[0]) }, "fields": { "rx_bad_frames": 0, #statistics["rx_bad_frames"], "rx_good_frames": 0, #statistics["rx_good_frames"], "rx_total_frames": 0, #statistics["rx_total_frames"], } } ] print( f'deviceID: {chr(deviceID[0])}, counter: {counter}, txMode: {txMode}, txCounter: {txCounter}, csmaRetries: {csmaRetries}, csmaRSSI: {csmaRSSI}, rssi: {rssi}, pkt_type: {pkt_type}' ) #\n\tRX bad {statistics["rx_bad_frames"]}, RX good {statistics["rx_good_frames"]}, RX total {statistics["rx_total_frames"]}') try: # Write data into Influxdb # dbClient.write_points(data) pass except Exception as e: logging.error(e) if finished: # Stop the serial port serial.stop() # Close db connection dbClient.close()
# coding=UTF8 from copy import deepcopy import Serial import time import vision as vs import random SER = Serial.Serial() time.sleep(2) #wait until the serial connection is open def false_decision(): return random.random() < 0.15 # ath the moment deactivated class Board: def __init__(self, other=None): self.player = 'X' self.opponent = 'O' self.empty = '.' self.size = 3 self.fields = {} self.depth = 0 for y in range(self.size): for x in range(self.size): self.fields[x, y] = self.empty #initializing the field # copy constructor if other: self.__dict__ = deepcopy( other.__dict__ ) #when another board is passed at the instantiation of a board,
* */ import processing.serial.*; Serial port; // Create object from Serial class float val, val2; // Data received from the serial port float[] values, values2, values3; float threshold = 512; float distance; float spread = 1; void setup() { size(640, 480); // Open the port that the board is connected to and use the same speed (9600 bps) println(Serial.list()); port = new Serial(this, Serial.list()[1], 115200); values = new float[width]; values2 = new float[width]; values3 = new float[width]; smooth(); PFont font; font = loadFont("Gautami-30.vlw"); textFont(font); } void serialEvent(Serial myPort) { String myString = myPort.readStringUntil('|'); //the ascii value of the "|" character if( myString != null ) { myString = trim(myString); //remove whitespace around our values
#Code moved to Positioning! import Serial serial = Serial('COM7', 115200)
f = open('coordinates.txt', 'w') iterations = 0; for i in range(im_outline.shape[0]): for j in range(im_outline.shape[1]): if (iterations == 0): previousXBlack = i previousYBlack = y xblacks = np.append(xblacks, i) yblacks = np.append(xblacks, j) print>>f, i, j iterations = iterations + 1 if (im_outline[i,j] == 0): if ((abs(previousXBlack - i) > 5) or (abs(previousYBlack - j) > 5)): xblacks = np.append(xblacks, i) yblacks = np.append(xblacks, j) print>>f, i, j previousXBlack = i previousYBlack = j print>>f, "!" ser = Serial('/dev/ttyACM0', 9600, timeout=3) ser.write(coordinates.txt)