Example #1
0
        #Send pump rate to pumpo
        pump.write(pumpRate)

        #Sends color to LED
        for i in range(0, 3):
            lights[i].write(colors[i] / 256)
        time.sleep(0.1)


# Main function
if __name__ == '__main__':
    from sys import argv

    # Setting up the board,
    # Use whatever serial port you are plugged into (what you choose in Arudino)
    board = pyfirmata.Arduino('/dev/cu.usbserial-14510')
    it = pyfirmata.util.Iterator(board)
    it.start()

    # Getting all the pins we need
    buttonOne = board.get_pin('d:7:i')
    buttonTwo = board.get_pin('d:6:i')
    knob = board.get_pin('a:0:i')
    pump = board.get_pin('d:3:p')

    lightGreen = board.get_pin('d:11:p')
    lightBlue = board.get_pin('d:10:p')
    lightRed = board.get_pin('d:9:p')

    lights = [lightRed, lightGreen, lightBlue]
Example #2
0
    def __init__(self, arduino_do_pin):
        arduino = pyfirmata.Arduino(self.get_com_port())
        self.it = pyfirmata.util.Iterator(arduino)
        self.it.start()

        self.digital_output = arduino.get_pin(f"d:{str(arduino_do_pin)}:o")
def main():

    #camera setup
    camera = PiCamera()
    camera.resolution = (320, 240)
    camera.framerate = 32
    rawCapture = PiRGBArray(camera, size=(320, 240))

    time.sleep(2)

    board = pyfirmata.Arduino('/dev/ttyUSB0')
    pin4 = board.get_pin('d:4:o')
    pin5 = board.get_pin('d:5:o')
    pin6 = board.get_pin('d:6:p')
    pin9 = board.get_pin('d:9:o')
    pin10 = board.get_pin('d:10:o')
    pin11 = board.get_pin('d:11:p')

    pin4.write(1)
    pin5.write(0)
    pin6.write((float(0.6)))  #right
    pin9.write(1)
    pin10.write(0)
    pin11.write(float(0.6))  #left

    stdscr = curses.initscr()
    curses.cbreak()
    stdscr.keypad(1)

    right_count = 0
    left_count = 0
    up_count = 0
    down_count = 0
    up = np.array([1, 0, 0, 0])
    right = np.array([0, 1, 0, 0])
    left = np.array([0, 0, 1, 0])
    down = np.array([0, 0, 0, 1])

    stdscr.refresh()
    key = ''
    for frame in camera.capture_continuous(rawCapture,
                                           format="bgr",
                                           use_video_port=True):
        if key == ord('q'):
            np.save("training_data/input" + str(frame_count - 1), image)
            break

        #get image from stream
        image = frame.array
        key = stdscr.getch()
        stdscr.addch(20, 25, key)
        stdscr.refresh()
        if key == curses.KEY_UP:
            pin6.write((float(0.6)))  #right
            pin11.write(float(0.6))  #left
            stdscr.addstr(2, 10, "Up")
            storeData(image, up)
            prev = up
            up_count += 1
        elif key == curses.KEY_RIGHT:
            stdscr.addstr(2, 10, "Right")
            pin6.write((float(0.15)))  #right
            pin11.write(float(0.6))  #left
            storeData(image, right)
            prev = right
            right_count += 1
        elif key == curses.KEY_LEFT:
            stdscr.addstr(2, 10, "Left")
            pin6.write((float(0.6)))  #right
            pin11.write(float(0.15))  #left
            storeData(image, left)
            prev = left
            left_count += 1
        elif key == curses.KEY_DOWN:
            stdscr.addstr(2, 10, "Down")
            pin6.write((float(0)))  #right
            pin11.write(float(0))  #left
            storeData(image, down)
            prev = down
            down_count += 1
        stdscr.addstr(4, 10, str(up_count))
        stdscr.addstr(5, 10, str(right_count))
        stdscr.addstr(6, 10, str(left_count))
        stdscr.addstr(7, 10, str(down_count))
        rawCapture.truncate(0)

    curses.endwin()
Example #4
0
import pyfirmata

board = pyfirmata.Arduino("COM3")

print('connected to: ' + str(board))
pin = board.get_pin('d:3:p')  # Digital : pin:3 : p:PWM
print('connected to: ' + str(pin))
while True:
    pin.write(0)
    print('ON')
    board.pass_time(1)
    pin.write(1)
    print('OFF')
    board.pass_time(1)
import pyfirmata
import time
import requests


board = pyfirmata.Arduino('COM8')


import time

def executeSomething():
    #code here
    board.digital[8].write(1)
    currentHum = requests.get('https://pi2-ephec.herokuapp.com/data/last?potId=1')
    minHum = requests.get('https://pi2-ephec.herokuapp.com/data/humidityThreshold?potId=1')
    arrosageAutYesOrNo = requests.get('https://pi2-ephec.herokuapp.com/users/getLearningMode?id=32')
    # print(x.status_code)
    # print(x.json())
    oneOrZero = arrosageAutYesOrNo.json()
    currentHumNum = currentHum.json()
    minHumNum = minHum.json()

    print(oneOrZero[0]["learningMode"])
    print(minHumNum.get("humidity"))
    print(currentHumNum[0]["dataHumidity"])
    learningMode = oneOrZero[0]["learningMode"]
    humidityMin = minHumNum.get("humidity")
    humidtyFromPlant = currentHumNum[0]["dataHumidity"]
    if ((humidityMin > humidtyFromPlant) and (learningMode == 1)):  # Mode auto activer et allume la pompe quelque seconde
        board.digital[8].write(0)
        print("ok")
import time  # Required to timestamp & delay functions
from random import shuffle
import numpy as np
# We want to collect experimental data
# describing the response of the measured T to the changes
# in the control input
# change the duty cycle (DC) of the PWM
# 
# import matplotlib.pyplot as plt
# import matplotlib.animation as animation #Required to live plot
#from pylive import live_plotter
import pyfirmata  # facilitates communication with Arduino https://pyfirmata.readthedocs.io/en/latest/
from progress.bar import ChargingBar  # required to display a charging bar

portName = 'COM3'
arduino = pyfirmata.Arduino(portName)

it = pyfirmata.util.Iterator(arduino)
it.start()

start_time = time.time()

input_pin = arduino.get_pin('a:0:i') #analog, input to the computer
input5V_pin = arduino.get_pin('a:1:i') #analog, input to the computer
output_pin = arduino.get_pin('d:6:p') #digital, PWM mode, from the computer

def read_voltage(pin):
    outputs = []
    for i in range(10):
        time.sleep(.1)
        outputs.append(pin.read())
Example #7
0
# for UI:
import PySimpleGUI as sg
# for working with Arduino:
import pyfirmata as pf
# any preferred appearance of the UI:
theme = 'DarkBlack1'
# set the theme:
sg.theme(theme);
del theme
# Boolean to check connection
connected = False
# Variable to keep board's type and dictionaries for ports
board_type = " "
digital_ports = pwm_ports_values = pwm_ports = dict()
gitoverflow = [
    [sg.T("Github: Muhammadrasul446", size=(28, 1))],
    [sg.T("Stackoverflow: user:13490404", size=(28, 1))]
]
twittedin = [
    [sg.T("Twitter: A_M_R_4_4_6", size=(28, 1))],
    [sg.T("Linkedin: 6644821a9", size=(28, 1))]
]
# Window layout for selecting boards
select_win_lay = [
    [sg.T('Select your board:')],
    [sg.Button("Nano/Uno/Leonardo")],
    [sg.Button("Mega/Mega2560")]
]
window = sg.Window("Select your board", select_win_lay)
# keep the window open:
Example #8
0
#!/usr/bin/env python
# encoding: utf-8

import pyfirmata
import time

import sys
import paho.mqtt.client as mqtt # 第一步,导入我们需要的包

board=pyfirmata.Arduino('/dev/ttyUSB0') # 初始化设备,这个地方设备名称上可能不同,有可能是/dev/ttyACM0

led_pin = board.get_pin('d:10:o') # 初始化端口,d代表数字的,10代表10号端口,o代表输出的意思

print("端口初始化!")

def output_level(): # 控制LED的函数
    try:
        while True:
            led_pin.write(1)
            time.sleep(0.5)
            led_pin.write(0)
            time.sleep(0.5)
    except KeyboardInterrupt:
        pass

# mqtt中的四个回调方法
def on_connect(mqttc,obj,flag,rc):
    print("rc : "+str(rc))

def on_message(mqttc,obj,msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
import pyfirmata

board = pyfirmata.Arduino("/dev/ttyUSB0)")

button = board.get_pin('d:2:i')

it = pyfirmata.util.Iterator(board)
it.start()

button.enable_reporting()

while True:
    if str(button.read()) == 'True':
        print "Pressed!"
    board.pass_time(1)
# Moisture Sensor - Student
# Author: Matt Cook
# Written for Wyoming EPSCoR Summer Coding Camp
# Created May 25, 2016
# Version 1.0

# Incomplete file for handling the Moisture Sensor on the Arduino

# Import libraries to interact with Arduino
import sys
import time
import pyfirmata

# Setup the translator for how we talk to the Arduino
board = pyfirmata.Arduino("/dev/tty.usbmodem1411")

it = pyfirmata.util.Iterator(board)
it.start()

# Set what "wet" is and store that in a variable


# Set which pin we will use to monitor moisture levels


# Enable the analog pin of our choice to report what it is observing


# Loop through this process
while True:
    # Wait a little so we can see the values a little more clearly.  This way we can see what is happening more easily.
Example #11
0
    def __init__(self, comport_arduino, startsteps, sensitivity, invertx: bool,
                 run_test: str):
        # Handle input parameters
        self.port = comport_arduino
        self.startcount = startsteps
        self.init_pos = 0
        self.sensitivity = float(sensitivity)
        if self.sensitivity > 1:
            self.sensitivity = 0.5
            logger.info("Invalid sensitivity entered: new value = {}".format(
                self.sensitivity))
        self.invert_x_axis = invertx
        self.test = run_test

        # Setup Arduino and Stepper Motors
        self.board = pyfirmata.Arduino(self.port)
        time.sleep(1)
        self.motors = []
        self.default_motor_setup()
        self.dirpull = {
            0: [0, 1],
            1: [0],
            2: [0, 3],
            3: [3],
            4: [2, 3],
            5: [2],
            6: [1, 2],
            7: [1],
        }

        self.dirpush = {
            0: [2, 3],
            1: [2],
            2: [1, 2],
            3: [1],
            4: [0, 1],
            5: [0],
            6: [0, 3],
            7: [3],
        }

        # motor vectors that code for the directions in the x-y space of the needle
        self.motorvec = {
            0: np.array([1, 1]),
            1: np.array([-1, 1]),
            2: np.array([-1, -1]),
            3: np.array([1, -1]),
        }
        """
        FESTO section
        !!! to use FESTO:    first upload "FESTO_controlv3.lua" to the T7 with Kipling 3 software
                            then close the connection with Kipling 3 software
        """
        # config
        self.config_object = ConfigParser()
        self.config_object.read('config.ini')
        festo = self.config_object["FESTO"]

        self.init_FESTO_pos = int(festo["initial_pos"])
        self.init_FESTO_speed = float(festo["initial_speed"])
        self.FESTO_stepsize = int(festo["step_size"])

        self.AIN0addr = 0  # position (0-10V)
        self.DAC0addr = 1000  # speed ref.signal (2.5V)
        self.DAC1addr = 1002  # speed out signal (-2.5 - 2.5V)
        self.initialpos_addr = 46000
        self.targetpos_addr = 46002
        self.speed_addr = 46004
        self.enable_addr = 46008
        self.f_datatype = ljm.constants.FLOAT32
        self.i_datatype = ljm.constants.UINT16

        self.offsetV = 2.5  # (offsetV+2.5V on DAC1 = 25 mm/s)
        self.offV = 0.0299544557929039  # low voltage that T7 can certainly output
        self.maxpos = 50  # mm
        self.minpos = 3  # mm
        self.currentpos = self.init_FESTO_pos

        try:
            FESTO_handle = ljm.openS("ANY", "USB", "ANY")
        except ljm.LJMError as error:
            FESTO_handle = None
            logger.error(
                "No FESTO_handle: thus not able to use the FESTO functions \n Error presented: "
                + str(error))

        if FESTO_handle is not None:
            self.FESTO_handle = FESTO_handle
            # Set initial positions (keep target pos at init_FESTO_pos at the start)
            ljm.eWriteAddress(self.FESTO_handle, self.initialpos_addr,
                              self.f_datatype, self.init_FESTO_pos)
            ljm.eWriteAddress(self.FESTO_handle, self.targetpos_addr,
                              self.f_datatype, self.init_FESTO_pos)
            # Set speed
            ljm.eWriteAddress(self.FESTO_handle, self.speed_addr,
                              self.f_datatype, self.init_FESTO_speed)
            logger.success(
                "FESTO connected, handle is available, init is set, current position ="
                + str(
                    ljm.eReadAddress(self.FESTO_handle, self.AIN0addr,
                                     self.f_datatype)))
            time.sleep(0.3)

            # Enable init LUA program
            ljm.eWriteAddress(self.FESTO_handle, self.enable_addr,
                              self.f_datatype, 1)
            logger.success("FESTO moving to initial position")
        else:
            logger.error(
                "Something went wrong when creating a FESTO Handle. Check if all adresses are correct in needle.py"
            )
            self.FESTO_handle = None
    return [clampMotor(int(left1 * 180)), clampMotor(int(right1 * 180))]


# funtion for calculating correct camera values from application joystick
def cameraValues(tilt):
    return clampCamera(int((tilt + 1) * 90))


### INIT ####################################

#check free space for the first time
update_free_space()

# initializing Arduino board
print 'Setting up board...'
board = pyfirmata.Arduino(serialPort)
it = util.Iterator(board, 0.05)  #object board, interval
it.start()
print 'Setup complete.'

# create server, listening on default port
try:
    server = liblo.Server(defaultListenPort)
    lastTime = time.time()  # save time for disconnect detection purposes
except liblo.ServerError, err:
    print str(err)
    sys.exit()

# register method for taking camera, front, back, left and right motor values, all float between -1, 1
server.add_method("/signal", 'hfffffffii', signal_callback)
Example #13
0
        self.on = on

    def run(self):
        while True:
            with self.lock:
                if self.on:
                    self.led.write(1)
                else:
                    self.led.write(0)
            time.sleep(1)


if __name__ == "__main__":

    serial_port = '/dev/cu.usbmodem14101'

    arduino = pyfirmata.Arduino(serial_port)

    lock = RLock()
    led = arduino.get_pin('d:13:o')

    led_on = LedBlinker(led, True, lock)
    led_off = LedBlinker(led, False, lock)

    led_on.start()
    time.sleep(0.5)
    led_off.start()

    led_on.join()
    led_off.join()
Example #14
0
import pyfirmata

DELAY = 0.5
brightness = 0

board = pyfirmata.Arduino("/dev/ttyACM0")

led = board.get_pin('d:11:p')

# increase
for i in range(0, 10):
    brightness = brightness + 0.1
    print "Setting brightness to %s" % brightness
    led.write(brightness)
    board.pass_time(DELAY)

# decrease
for i in range(0, 10):
    print "Setting brightness to %s" % brightness
    led.write(brightness)
    brightness = brightness - 0.1
    board.pass_time(DELAY)

board.exit()
Example #15
0
 def start(self):
     self.board = pyfirmata.Arduino(self.tty)
     self.iter8 = pyfirmata.util.Iterator(self.board)
     self.iter8.start()
Example #16
0
	return


def refresh():
	ax1.clear()
	return


def set_mean():
	return m


#-------------------------------------------
# Arduino
port = '/dev/ttyACM0' # puerto donde esta conectado el arduino (hay que cambiarlo dependiendo del pc)
board = pyfirmata.Arduino(port) # crea objeto como arduino en puerto anterior

it = pyfirmata.util.Iterator(board) # para que el buffer no haga overflow
it.start()

A0 = board.get_pin('a:0:i')
A1 = board.get_pin('a:1:i')
A2 = board.get_pin('a:2:i')
A3 = board.get_pin('a:3:i')
D5 = board.get_pin('d:5:p') # pwm motor 1
D6 = board.get_pin('d:6:p') # pwm motor 2


#-----------------------------------------------------
# Gui
root = Tk()
import pyfirmata
import time as t
import requests
import sys
import datetime

board = pyfirmata.Arduino('/dev/cu.usbmodem14201')

it = pyfirmata.util.Iterator(board)
it.start()

board.analog[0].mode = pyfirmata.INPUT


def get_humidity():
    t.sleep(3)
    humidity = board.analog[0].read()
    humidity = round(humidity * 1023)
    print(humidity)
    return humidity


def post_humidity(humidity, status, time):
    r = requests.post(
        'https://node-red-hyw-frej.eu-gb.mybluemix.net/humidity_endpoint',
        json={
            "humidity": humidity,
            "status": status,
            "time": time
        })
    print("post status: " + str(r.status_code))
Example #18
0
import pyfirmata

board = pyfirmata.Arduino('/dev/tty.usbserial-1410')
servo_pin = board.get_pin('d:9:s')

while True:
    angle = input("Enter rpm val:")
    angle = int(angle)
    servo_pin.write(angle)
Example #19
0
#!/usr/bin/python
import pyfirmata #pt legatura cu Arduino # Creeaza un obiect Arduino pe portul specificat 
import random
import time
board = pyfirmata.Arduino('/dev/ttyACM0') #Pinii Arduino pt motoare (ca variabile) 
PIN_stanga_inainte = board.get_pin('d:5:p') #pinul digital 5 = pwm 
PIN_stanga_inapoi = board.get_pin('d:3:p') 
PIN_dreapta_inainte = board.get_pin('d:6:p') 
PIN_dreapta_inapoi = board.get_pin('d:9:p') # Pornim un thread Iterator care sa se ocupe de datele pe serial (pt analog) 
left=0;
right=0;
max_speed=900.0;

def mergi(stanga, dreapta): 
    if(stanga > 0):      
	    PIN_stanga_inapoi.write(0)      
	    PIN_stanga_inainte.write(stanga/max_speed) 
    else:      
	    PIN_stanga_inapoi.write(-stanga/max_speed)      
	    PIN_stanga_inainte.write(0)    
	    if(dreapta > 0):      
	        PIN_dreapta_inapoi.write(0)      
	        PIN_dreapta_inainte.write(dreapta/max_speed)    
	    else:      
	        PIN_dreapta_inapoi.write(-dreapta/max_speed)      
	        PIN_dreapta_inainte.write(0) 
#while (1):      
#    if(random.random()  < 0.5):
#        left+=random.random()*150/10;
#        mergi(-left,-left) #inainte
#        time.sleep(0.001)
Example #20
0
#!/usr/bin/env python3.4
# Author: Jonathan Rotter & Danny Kong & Yiluo Li

import time
import pyfirmata

# idk what this is
port = '/dev/ttyACM0'

# Setup pyFirmata
board = pyfirmata.Arduino(port)

# Setup an iterator for safety
iter8 = pyfirmata.util.Iterator(board)
iter8.start()

# Locate pins
pin2 = board.get_pin('d:2:s')
pin3 = board.get_pin('d:3:s')
pin4 = board.get_pin('d:4:s')
pin5 = board.get_pin('d:5:s')
pin6 = board.get_pin('d:6:s')
pin7 = board.get_pin('d:7:s')
pin8 = board.get_pin('d:8:s')
pin9 = board.get_pin('d:9:s')
pin10 = board.get_pin('d:10:s')
pin12 = board.get_pin('d:12:s')


# functions for setting pins
def move2(a):
import pyfirmata
import keyboard
import time
import tkinter as tk
import numpy as np

try:
    board = pyfirmata.Arduino(
        'COM7')  #On définit la carte Arduino qui est branchée sur le port COM8
    iter8 = pyfirmata.util.Iterator(
        board)  #On accepte de soutirer des infos à la carte
    iter8.start(
    )  #On démarre la lecture des données (itérative cad qu'on actualise la lecture des données)

    dt = board.get_pin('d:3:i')
    clk = board.get_pin('d:4:i')
    sw = board.get_pin('d:2:i')
except:
    board, dt, clk, sw = None, None, None, None

app = tk.Tk()
text1 = tk.Label(app, text='0', fg='black')
text1.place(x=10, y=10)
text2 = tk.Label(app, text='0', fg='black')
text2.place(x=10, y=50)
text_sw = tk.Label(app, text='0', fg='blue')
text_sw.place(x=100, y=10)
text3 = tk.Label(app, text='0', fg='red')
text3.place(x=10, y=100)

count = 0
Example #22
0
    if conn:
        print("Closing conn")
        conn.close()
    if sock:
        print("Closing sock")
        sock.close()
    exit(0)


if len(sys.argv) != 2:
    print("Usage: raspberry.py <port>")
    exit()

signal.signal(signal.SIGINT, signal_handler)

board = pyfirmata.Arduino('/dev/ttyACM0')

it = pyfirmata.util.Iterator(board)
it.start()

blue = board.get_pin('d:7:o')
red = board.get_pin('d:6:o')
green = board.get_pin('d:5:o')

button = board.get_pin('a:0:i')
state = button.read()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("172.18.131.47", int(sys.argv[1])))
sock.listen(1)
# all the imports
import speech_recognition as sr
import pyfirmata as pf
import pyttsx3 as p3

# arduino
board = pf.Arduino('COM8')
board.digital[13].mode = pf.OUTPUT
board.digital[13].mode = pf.OUTPUT


# voice
engine = p3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[0].id)
engine.setProperty('voice', voices[0].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def takecommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Listening...')
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print('Recognizing...')
        query = r.recognize_google(audio, language='en-in')