def __init__(self): self.volts = float(5) self.result_voltage = 'nan' self.output = 'nan' self.output0 = 'nan' self.output1 = 'nan' self.port_a0 = 'nan' self.port_a1 = 'nan' self.message = "DAQ status update" self.board = Arduino('/dev/ttyUSB0') self.board.digital[13].write(1) self.it = util.Iterator(self.board) self.it.start() self.analog_0 = self.board.get_pin('a:0:i') self.analog_1 = self.board.get_pin('a:1:i') print("Stable Serial port timer") sleep(4)
def __init__(self, port='/dev/ttyUSB0'): ### base ---------------------- self.port = port self.board = Arduino(self.port) ### data --------------------- self.analog = {} self.samplingRate = 10 ### setup -------------------- self.board.samplingOn(100 / self.samplingRate)
def open_serial(self): self.message = "Testing running now..." self.board = Arduino('/dev/ttyUSB0') self.board.digital[13].write(1) self.it = util.Iterator(self.board) self.it.start() print("Measure will start") sleep(3) self.analog_0 = self.board.get_pin('a:0:i') self.analog_1 = self.board.get_pin('a:1:i') sleep(2) # self.result() # self.result_a1() return "Serial open successful"
def init_arduino(self): try: self.board = Arduino(Arduino.AUTODETECT) except: # pop-up window msg = QMessageBox() msg.setWindowTitle("arduino control") msg.setIcon(QMessageBox.Critical) msg.setText("problem to find the device") x = msg.exec_() self.iterator = util.Iterator(self.board) self.iterator.start() self.leftMagnet = self.board.get_pin('d:11:p') # digital ('d:13:o') self.rightMagnet = self.board.get_pin('d:10:p') # digital ('d:12:o')
def __init__(self): self.main_quest = None # noinspection PyBroadException try: self.board = Arduino('COM11') self.board.samplingOn(50) self.mirror_pin: Pin = self.board.digital[ZombieController.PIN_MIRROR] self.sparks_pin: Pin = self.board.digital[ZombieController.PIN_SPARKS] self.button_pin: Pin = self.board.analog[ZombieController.PIN_BUTTON] self.button_pin.mode = INPUT self.button_pin.register_callback(self.big_red_button_pressed) self.button_pin.enable_reporting() self.board_missing = False except Exception: logging.error("Arduino in ZombieBox is not responding!!!") self.board_missing = True
def main(): # 操作するArduinoを決定 board = Arduino(Arduino.AUTODETECT) # digital_8をデジタルピンのoutputに設定 digital_8 = set_pin(board, pin=8, mode="output", data="digital") # time.sleep(2) while True: # LEDを点灯 digital_8.high() time.sleep(0.5) # LEDを消灯 digital_8.low() time.sleep(0.5)
def checkArduinoIsConnected(): ports = list(serial.tools.list_ports.comports()) if len(ports) > 0: port = str(ports[0]).split(' ')[0] arduino = serial.Serial(port) board = Arduino(port) if board: status = True else: status = False else: status = False return {"status": status, "board": board}
def main(): # 操作するArduinoを決定 board = Arduino(Arduino.AUTODETECT) # pwm_10をデジタルピンのpwmに設定 pwm_10 = set_pin(board, pin=10, mode="pwm", data="digital") dt = 0.1 while True: # LEDを点灯 pwm_10.pwm((math.sin(math.pi * dt) + 1.0) / 2) time.sleep(0.05) dt += 0.1 # dt増やしてくとメモリが怖いので1周したら0に戻す if dt == 2.0: dt = 0.0
def switch_on_off(msg): port = find_port() if port != None: if len(msg) > 0: board = Arduino(port) # Arduino.AUTODETECT if msg == "on": board.digital[13].write(1) board.exit() return "LED Light is on" elif msg == "off": board.digital[13].write(0) board.exit() return "LED Light is off" else: board.exit() return help() return help() else: return "Arduino is not connected"
def main(): # 操作するArduinoを決定 board = Arduino(Arduino.AUTODETECT) # サンプリング周期を10msに固定 board.samplingOn(10) # pin8 をアナログピンのinputに設定 digital_8 = set_pin(board, pin=8, mode="i", data="digital") time.sleep(2) while True: # センサから取得した値を0~1024(int)で出力 print(digital_8.read()) time.sleep(0.5) # アナログピンのサンプリングを終了する board.samplingOff()
class AnalogPrinter: def __init__(self): # sampling rate: 50Hz self.samplingRate = 100 self.timestamp = 0 self.board = Arduino(PORT) def start(self): self.board.analog[0].register_callback(self.myPrintCallback) self.board.samplingOn(1000 / self.samplingRate) self.board.analog[0].enable_reporting() def myPrintCallback(self, data): print("%f,%f" % (self.timestamp, data)) self.timestamp += (1 / self.samplingRate) def stop(self): self.board.samplingOff() self.board.exit()
class Reader: class Analog: def __init__(self, pin, _board): ### base ---------------- self._board = _board self.timestamp = 0 ### data----------------- self.pin = pin self.value = 0 self.callback = None ### --------------------- def print_value(self, data): print("%f,%f" % (self.timestamp, data)) self.timestamp += (1 / self.samplingRate) self.set_value(data) def set_value(self, data): self.value = data def __init__(self, port='/dev/ttyUSB0'): ### base ---------------------- self.port = port self.board = Arduino(self.port) ### data --------------------- self.analog = {} self.samplingRate = 10 ### setup -------------------- self.board.samplingOn(100 / self.samplingRate) ### void setup ------------------------------------------------------------- def start(self, pin=0, callback=None): self.analog[pin] = self.Analog(pin, self.board) if callback: self.analog[pin].callback = callback else: self.analog[pin].callback = self.analog[pin].set_value self.board.analog[pin].register_callback(self.analog[pin].callback) self.board.analog[pin].enable_reporting() ### void draw -------------------------------------------------------------- def stop(self): self.board.samplingOff() self.board.exit()
from pyfirmata2 import Arduino from time import sleep import matplotlib.pyplot as plt signal = [] def my_cb(data): # print(data) signal.append(data) #pass board = Arduino(Arduino.AUTODETECT) board.samplingOn(10) # ms board.analog[0].register_callback(my_cb) board.analog[0].enable_reporting() lenPin = board.get_pin('d:3:p') lum = 0 delta_lum = 0.05; for t in range(50): sleep(0.5) if lum > 1.0 or lum < 0: delta_lum = -delta_lum lum += delta_lum lenPin.write(lum) lenPin.write(0)
class DaqMain: try: def __init__(self): self.volts = float(5) self.result_voltage = 'nan' self.output = 'nan' self.output0 = 'nan' self.output1 = 'nan' self.port_a0 = 'nan' self.port_a1 = 'nan' self.message = "DAQ status update" self.board = Arduino('/dev/ttyUSB0') self.board.digital[13].write(1) self.it = util.Iterator(self.board) self.it.start() self.analog_0 = self.board.get_pin('a:0:i') self.analog_1 = self.board.get_pin('a:1:i') print("Stable Serial port timer") sleep(4) def open_serial(self): self.message = "Testing running now..." self.board = Arduino('/dev/ttyUSB0') self.board.digital[13].write(1) self.it = util.Iterator(self.board) self.it.start() print("Measure will start") sleep(3) self.analog_0 = self.board.get_pin('a:0:i') self.analog_1 = self.board.get_pin('a:1:i') sleep(2) # self.result() # self.result_a1() return "Serial open successful" def analog_volts(self): self.result_voltage = ((self.analog_0 * self.volts) / 1) # print("%.2f" % self.result_voltage) self.output = ("%.2f" % self.result_voltage) # return str(self.output) def result(self): while True: self.board.digital[13].write(1) # print(self.analog_0.read()) self.port_a0 = self.analog_0.read() self.result_voltage = ((self.port_a0 * self.volts) / 1) print("%.2f" % self.result_voltage) self.output0 = ("%.2f" % self.result_voltage) self.status_voltage_range_a0() return 'ANALOG A0' def result_a1(self): while True: self.board.digital[13].write(0) self.port_a1 = self.analog_1.read() self.result_voltage = ((self.port_a1 * self.volts) / 1) print("%.2f" % self.result_voltage) self.output1 = ("%.2f" % self.result_voltage) sleep(1) self.status_voltage_range_a1() return 'ANALOG A1' def status_voltage_range_a0(self): if 3.9 <= float(self.output0) <= 5: return 'PASS A0' else: return 'FAIL A0' def status_voltage_range_a1(self): if 3.9 <= float(self.output1) <= 5: return 'PASS A1' else: return 'FAIL A1' def close_port(self): self.board.exit() except serial.SerialException: print("Serial Port Error: Code 000") except TypeError: print("code 002 Serial stooped") except AttributeError: print("Serial port code 000") except Exception as e: print(e)
#this is a sample code for testing arduino pin by python....took help from a site.. from pyfirmata2 import Arduino from time import sleep board = Arduino(Arduino.AUTODETECT) switch1 = board.digital[9] switch2 = board.digital[10] switch3 = board.digital[11] switch4 = board.digital[13] switches = switch1, switch2, switch3, switch4 def test_on(*relays): [relay.write(1) for relay in relays] [print('{} is turned on'.format(relay)) for relay in relays] def on(relays): [relay.write(1) for relay in relays] [print('{} is turned on'.format(relay)) for relay in relays] def off(): [switch.write(0) for switch in switches] test_on(switch1, switch2, switch3, switch4) sleep(10) off()
# our callback where we filter the data def callBack(data): y = f.filter(data) y = gain * y realtimePlotWindow.addData(y) if y >= 0.70: # Turn on/off the green and red leds according to the signal received. LED_green.write(y / 1.5) LED_red.write(0) else: LED_green.write(0) LED_red.write((1 - y) / 1.5) # Get the Ardunio board board = Arduino('\\.\COM3') # Define digital pins D5 and D9 as analog (PWM) outputs LED_green = board.get_pin('d:5:p') LED_red = board.get_pin('d:9:p') # Set the sampling rate in the Arduino board.samplingOn(1000 / samplingRate) # Register the callback which adds the data to the animated plot board.analog[0].register_callback(callBack) # Enable the callback board.analog[0].enable_reporting() # show the plot and start the animation
def start_luz(self): self.board = Arduino(PORT) self.board.analog[2].register_callback(self.myPrintCallback_3) self.board.samplingOn(1000 / self.samplingRate) self.board.analog[2].enable_reporting()
class AnalogPrinter: def __init__(self): # sampling rate: 10Hz self.samplingRate = 10 self.timestamp = 0 self.gas = 0 self.flama = 0 self.luz = 0 def start_gas(self): self.board = Arduino(PORT) self.board.analog[0].register_callback(self.myPrintCallback) self.board.samplingOn(1000 / self.samplingRate) self.board.analog[0].enable_reporting() def start_flama(self): self.board = Arduino(PORT) self.board.analog[1].register_callback(self.myPrintCallback_2) self.board.samplingOn(1000 / self.samplingRate) self.board.analog[1].enable_reporting() def start_luz(self): self.board = Arduino(PORT) self.board.analog[2].register_callback(self.myPrintCallback_3) self.board.samplingOn(1000 / self.samplingRate) self.board.analog[2].enable_reporting() def myPrintCallback(self, data): data1 = data * (5 / 1023) * 1000 self.timestamp += 1 / self.samplingRate if data1 <= 0.2: print(f"{round(self.timestamp, 2)}, {round(data1,2)} El valor del sensor es menor al muestreo",) self.board.digital[2].write(0) print("no hay gas") self.gas = 0 else: print(f"{round(self.timestamp, 2)}, {round(data1,2)} El valor del sensor es menor al muestreo",) self.board.digital[2].write(1) print("aqui hubo gas!") self.gas = 1 def myPrintCallback_2(self, data): data1 = data * (5 / 1023) * 1000 self.timestamp += 1 / self.samplingRate if data1 >= 2: print(f"{round(self.timestamp, 2)}, {round(data1,2)} El valor del sensor es mayor al muestreo",) self.board.digital[3].write(0) self.flama = 1 print("no hay fuego") else: print(f"{round(self.timestamp, 2)}, {round(data1,2)} El valor del sensor es menor al muestreo",) self.board.digital[3].write(1) print("fuego!!") self.flama = 1 def myPrintCallback_3(self, data): data1 = data * (5 / 1023) * 1000 self.timestamp += 1 / self.samplingRate if data1 >= 1: print(f"{round(self.timestamp, 2)}, {round(data1,2)} El valor del sensor es menor al muestreo",) self.board.digital[4].write(0) if self.gas == 1 : self.board.digital[2].write(1) if self.flama == 1: self.board.digital[3].write(1) if self.luz == 1: self.board.digital[4].write(1) if self.luz == 1 and self.gas == 1 and self.flama == 1: self.board.digital[5].write(1) else: print(f"{round(self.timestamp, 2)}, {round(data1,2)} El valor del sensor es mayor al muestreo",) self.board.digital[4].write(1) self.luz = 1 if self.gas == 1 : self.board.digital[2].write(1) if self.flama == 1: self.board.digital[3].write(1) if self.luz == 1 and self.gas == 1 and self.flama == 1: self.board.digital[5].write(1) def stop(self): self.board.samplingOff() self.board.exit()
from pyfirmata2 import Arduino #import library from pyfirmata2 to detect Arduino import time #time library to be able setup lenght of led lighting board = Arduino(Arduino.AUTODETECT) #detect Arduino with Autodetect print("...Arduino detected") #print statement #1 print("...Blink test started") #print statement #2 while True: #while this statement is true execute script hereunder print("...Blink LED 1st time") #print statement blink 1st time board.digital[13].write(1) time.sleep(2) #light up led number 13 for 2 seconds board.digital[13].write(0) time.sleep(1) #light off led number 13 for 1 seconds print("...Blink LED 2nd time") #print statement blink 2nd time board.digital[13].write(1) time.sleep(2) #light up led number 13 for 2 seconds board.digital[13].write(0) time.sleep(1) #light off led number 13 for 1 seconds print("...Blink LED 3rd time") #print statement blink 3rd time board.digital[13].write(1) time.sleep(2) #light up led number 13 for 2 seconds board.digital[13].write(0) time.sleep(1) #light off led number 13 for 1 seconds print("...Blink LED 4th time") #print statement blink 4th time board.digital[13].write(1) time.sleep(2) #light up led number 13 for 2 seconds board.digital[13].write(0) time.sleep(1) #light off led number 13 for 1 seconds print("...Blink test successfull!") #print statement #3 exit() #exit script
class arduino_control(threading.Thread): def __init__(self, threadID, name, time_oscillate, external_pointer_board, current_adruino_1, current_adruino_2): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.current_adruino_1 = current_adruino_1 self.current_adruino_2 = current_adruino_2 self.flag_arduino_working = True self.time_oscillate = time_oscillate self.init_arduino() self.external_pointer_board = external_pointer_board print(self.current_adruino_1, self.current_adruino_2, self.current_adruino_2 / 5.0) # voltages and currents arduino : # [ 0.15007188 -0.02560927] [ 0.1796672 -0.0954898] max_voltage = 5.0 # Volt # ratio between gate voltage to current by expereiment. average of both electroagnets : slope_electromagnet = (0.15007188 + 0.1796672) / 2 # this is the the 'b' in the 'y=a*x+b' : # bais_electromagnet = -(0.02560927 + 0.0954898) / 2 self.voltage_on_gate_1 = (self.current_adruino_1 / max_voltage) self.voltage_on_gate_2 = (self.current_adruino_2 / max_voltage) ''' This function is implements the oscillations, that is the frequency of the oscillations. pin1 = the pin the we conent to electromagnet 1. pin2 = the pin the we conent to electromagnet 2. ''' def oscillate(self, pin1, pin2): print("oscillate 1") time.sleep(self.time_oscillate) print("oscillate 2") pin1.write(self.current_adruino_1 / 5.0) # 1 print("oscillate 3") pin2.write(0) time.sleep(self.time_oscillate) pin1.write(0) pin2.write(self.current_adruino_2 / 5.0) # 1 print("loop") ''' This function implements the loop as it is in the original arduino. leftMagnet = the pin the we conent to electromagnet 1. rightMagnet = the pin the we conent to electromagnet 2. ''' def arduinoLoop(self, leftMagnet, rightMagnet): while (self.flag_arduino_working): self.oscillate(leftMagnet, rightMagnet) # 0.5 ''' Here we initialze the connection with the arduino. ''' def init_arduino(self): try: self.board = Arduino(Arduino.AUTODETECT) except: # pop-up window msg = QMessageBox() msg.setWindowTitle("arduino control") msg.setIcon(QMessageBox.Critical) msg.setText("problem to find the device") x = msg.exec_() self.iterator = util.Iterator(self.board) self.iterator.start() self.leftMagnet = self.board.get_pin('d:11:p') # digital ('d:13:o') self.rightMagnet = self.board.get_pin('d:10:p') # digital ('d:12:o') ''' This function returns the last port that was connected to the computer. ''' def find_com_port(self): myports = [tuple(p) for p in list(serial.tools.list_ports.comports())] return myports[-1][0] ''' Turn on the arduino (loop). ''' def run(self): # turn on print("arduino turn on") self.flag_arduino_working = True self.arduinoLoop(self.leftMagnet, self.rightMagnet) ''' Turn off the arduino (loop). ''' def exit2(self): # turn_off print("arduino turn off") self.flag_arduino_working = False time.sleep(1) self.board.exit()
output = filterDC.dofilter(data) output = filterLP.dofilter(output) # send jump key operation to control the game if output >= 0.04: keyboard.press(Key.space) keyboard.release(Key.space) #print("SpaceJump") realtimePlotWindow.addData(data, ) realtimePlotWindow2.addData(output) # Get the Ardunio board. board = Arduino('COM3') # Set the sampling rate in the Arduino board.samplingOn(1000 / samplingRate) # Register the callback which adds the data to the animated plot board.analog[3].register_callback( callBack) # analog pin a3 of Arduino connects to z-axis of the sensor # Enable the callback board.analog[3].enable_reporting() # show the plot and start the animation plt.show() # needs to be called to close the serial port # board.exit()
def __init__(self): self.board = Arduino(ConfigArduino.USB_PATH ) if ConfigArduino.USB_PATH != '' else Arduino( Arduino.AUTODETECT)
# Create an instance of an animated scrolling window # To plot more channels just create more instances and add callback handlers below realtimePlotWindow = RealtimePlotWindow() # sampling rate: 100Hz samplingRate = 100 # called for every new sample which has arrived from the Arduino def callBack(data): # send the sample to the plotwindow # add any filtering here: # data = self.myfilter.dofilter(data) realtimePlotWindow.addData(data) # Get the Ardunio board. board = Arduino(PORT) # Set the sampling rate in the Arduino board.samplingOn(1000 / samplingRate) # Register the callback which adds the data to the animated plot board.analog[0].register_callback(callBack) # Enable the callback board.analog[0].enable_reporting() # show the plot and start the animation plt.show() # needs to be called to close the serial port board.exit()
class ZombieController(object): PIN_MIRROR = 2 PIN_BUTTON = 0 PIN_SPARKS = 13 PIN_DATA_MIRROR_ON = 0 PIN_DATA_MIRROR_OFF = 1 def __init__(self): self.main_quest = None # noinspection PyBroadException try: self.board = Arduino('COM11') self.board.samplingOn(50) self.mirror_pin: Pin = self.board.digital[ZombieController.PIN_MIRROR] self.sparks_pin: Pin = self.board.digital[ZombieController.PIN_SPARKS] self.button_pin: Pin = self.board.analog[ZombieController.PIN_BUTTON] self.button_pin.mode = INPUT self.button_pin.register_callback(self.big_red_button_pressed) self.button_pin.enable_reporting() self.board_missing = False except Exception: logging.error("Arduino in ZombieBox is not responding!!!") self.board_missing = True def reset(self): if self.board_missing: return self.button_pin.enable_reporting() def mirror(self, turn_on=True): if self.board_missing: return self.mirror_pin.write(0 if turn_on else 1) def blink(self): if self.board_missing: return self.sparks_pin.write(1) self.board.pass_time(0.05) self.sparks_pin.write(0) def sparkle(self): if self.board_missing: return for i in range(20): self.sparks_pin.write(random.randint(0, 1)) self.board.pass_time(0.02) self.sparks_pin.write(0) def register_in_lua(self, main_quest): self.main_quest = main_quest return self def big_red_button_pressed(self, data): if data > 0.02: print(f"Activated on {data}") # self.button_pin.disable_reporting() if self.main_quest: self.main_quest['on_zombie_activated'](self.main_quest)
from flask import Flask, render_template, request, redirect, url_for from time import sleep from threading import Thread import serial import time from pyfirmata2 import Arduino PIN = 13 board = Arduino('/dev/ttyACM0') app = Flask(__name__) @app.route('/', methods=['POST', 'GET']) def hello_world(): if request.method == 'POST': if request.form['submit'] == 'Turn on': print('TURN ON') elif request.form['submit'] == 'Turn Off': print('TURN OFF') else: pass return render_template('index.html') @app.route('/turnon', methods=['GET', 'POST']) def turn_on(): board.digital[PIN].write(1) return redirect(url_for('status'))
def connect_firmata(self): print("Connecting to arduino... ") self.arduino = Arduino(self.com_port) print(" ... connected")
Plot1.addData(ch0) Plot3.addData(ch0_filtered) if ch0_filtered > THRESHOLD: board.digital[yellow_LED].write(1) ch1 = board.analog[1].read() if ch1: Plot2.addData(ch1) ch1_filtered = abs(IIR_Y.dofilter(ch1)) Plot4.addData(ch1_filtered) if ch1_filtered > THRESHOLD: board.digital[red_LED].write(1) # Get the Ardunio board. board = Arduino(PORT) # Set the sampling rate in the Arduino board.samplingOn(1000 / Fs) # Register the callback which adds the data to the animated plot board.analog[0].register_callback(callBack) # Enable the callback board.analog[0].enable_reporting() board.analog[1].enable_reporting() # showing all the windows app.exec_() # needs to be called to close the serial port
def __init__(self): # sampling rate: 50Hz self.samplingRate = 100 self.timestamp = 0 self.board = Arduino(PORT)
import scipy.signal as signal """ # ------------- Initialization of the Script ------------- - fs : sampling frequency, defined for every application and limited by the system specifications. - PORT : communication port, detected automatically so we don't have to care about the specific COM port. - app : global QT application object for plotting. - running = signals to all threads in endless loops that we'd like to run these """ fs = 100 PORT = Arduino.AUTODETECT app = QtGui.QApplication(sys.argv) running = True board = Arduino(PORT) # Get the Arduino board. board.samplingOn(1000 / fs) # Set the sampling rate in the Arduino class IIR2Filter(object): """ given a set of coefficients for the IIR filter this class creates an object that keeps the variables needed for the IIR filtering as well as creating the function "filter(x)" with filters the input data. Attributes: @:param coefficients: input coefficients of the IIR filter as an array of 6 elements where the first three coefficients are for the FIR filter part of the IIR filter and the last three coefficients are for the IIR part of the IIR filter. """ def __init__(self, coefficients): self.myCoefficients = coefficients
def callBack(data): #channel 0 data sent to the plotwindow t.sampleCount += 1 #increments number of samples counted if t.time() >= 10: #if 10 seconds have passed print(t.sampleCount, "= number of samples taken in 10 seconds") t.reset() #resets the timer and sample count to 0 data = (data - 0.1) * 400 #removes offset and converts voltage to pressure qtPanningPlot1.addData(data) ch1 = board.analog[1].read() # 1st sample of 2nd channel might arrive later so need to check if ch1: # filtering channel 1 samples here: ch1 = filt.filter(data) qtPanningPlot2.addData(ch1) PORT = Arduino.AUTODETECT #Get the Ardunio board. board = Arduino(PORT) board.samplingOn(1000 / samplingRate) # Set the sampling rate in the Arduino # Register the callback which adds the data to the animated plot t.start() board.analog[0].register_callback( callBack) #The function "callback" is called when data has arrived board.analog[0].enable_reporting() #Enable the callback board.analog[1].enable_reporting() app.exec_() #showing all the windows board.exit() #needs to be called to close the serial port print("finished")