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()
Exemplo n.º 2
0
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()
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"
    myFilter = IIR2Filter(coeff[0])

# Create two instances of Qt plots
qtPlot1 = QtPanningPlot("Arduino 1st channel")
qtPlot2 = QtPanningPlot("Arduino 2nd channel")


# This function is called for every new sample which has arrived from the Arduino
def callBack(data):
    qtPlot1.addData(data)
    ch1 = board.analog[1].read()
    if ch1:
        filteredData = myFilter.filter(ch1)
        qtPlot2.addData(filteredData * 10)


# 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()

# Show all windows
app.exec_()

# Close the serial port
board.exit()

print("Execution Finished")
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)
Exemplo n.º 6
0
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()
Exemplo n.º 7
0
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()
Exemplo n.º 8
0
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")
            )  # Call the addandfilter function to commence the filtering

    lowpass = sig.butter(
        N=2, Wn=0.5 / 50, btype='lowpass', output='sos'
    )  # Butterworth filter to create a lowpass with 0.5 Hz cutoff
    lowpass1 = sig.butter(
        N=2, Wn=1 / 50, btype='lowpass', output='sos'
    )  # Butterworth filter to create a lowpass with 1 Hz cutoff

    iir = IIRFilters.IIRFilter(
        lowpass)  # Send the sos coefficients to the filter
    iir2 = IIRFilters.IIRFilter(
        lowpass)  # Send the sos coefficients to the filter
    iir3 = IIRFilters.IIRFilter(
        lowpass1)  # Send the sos coefficients to the filter
    iir4 = IIRFilters.IIRFilter(
        lowpass1)  # Send the sos coefficients to the filter

    board = Arduino(PORT)  # Initialize board to look up for pins
    board.samplingOn(1000 /
                     samplingRate)  # Set the sampling rate for the board
    board.analog[0].register_callback(
        callBack)  # Register the callBack to a Port
    board.analog[0].enable_reporting()  # Enable port reporting for pin 0
    board.analog[1].enable_reporting()  # Enable port reporting for pin 1
    board.analog[2].enable_reporting()  # Enable port reporting for pin 2
    form.Portshow(str(board))  # Call the function to show the Port
    app.exec_()  # Execute our application
    board.exit()  # Close the board
    print("DONE")