Exemplo n.º 1
0
def main():
	print "opening"
	#board = BOARDS['arduino_mega']

	if os.path.exists(tty):
		board = ArduinoMega(tty, baudrate=57600)#, target=0)
		#time.sleep(3)
		
		#print "VERSION",board.get_firmata_version()
		## Prints some details to STDOUT
		#print "pyFirmata version:  %s"      % str(pyfirmata.__version__ )
		#print "Hardware:           %s"      % str(board                 )
		#print "Firmata version:    %s"      % str(board.firmata_version )
		#print "Firmware:           %s"      % str(board.firmware        )
		#print "Firmware version:   %s"      % str(board.firmware_version)
		#time.sleep(3)
		board.string_write("1234567890123567890")#from python. please echo")
		#board.string_write("abcdefghijklmn")#from python. please echo")
		#print "Firmata firmware name:  %s" % board.get_firmware()
		#print "Firmata firmware:\t%i.%i"   % (board.get_firmata_version()[0], board.get_firmata_version()[1])
		#time.sleep(10)
		
		try:
			while True:
				while board.sp.inWaiting() > 0:
					board.iterate()
				#print "sleeping"
				time.sleep(.5)
		except KeyboardInterrupt:
			sys.exit(0)
		except:
			sys.exit(1)
Exemplo n.º 2
0
def CriaPinos(mini = 2, maxi = 9,tipo = 'p', minis = 10, maxis = 12, tipos = 's'):      #TIPO: O:OUTPUT | I:INPUT | P:PWM
    
    arduino = ArduinoMega('COM13')
    
    for p in range(mini,maxi):
        AP["pino" + str(p)] = arduino.get_pin('d:{}:{}'.format(p,tipo))
    for s in range(minis,maxis):
        AS["pino" + str(s)] = arduino.get_pin('d:{}:{}'.format(s,tipos))
Exemplo n.º 3
0
class FirmataThread(threading.Thread):
     def __init__(self,widget):
         super(FirmataThread, self).__init__()
         self.board = ArduinoMega('/dev/ttyACM0')
         self.it = util.Iterator(self.board)
         self.it.start()
         self.board.analog[0].enable_reporting()
         self.board.analog[1].enable_reporting()
         self.board.analog[2].enable_reporting()
         self.board.analog[3].enable_reporting()
         self.board.analog[4].enable_reporting()
         self.board.analog[5].enable_reporting()
         self.stopNow = False
         self.ws = 0
         self.widget = widget
         print "ArduinoMEGA ready to operate"
         #self.connectWS()
         #self.max1 = 0.2
         #self.min1 = 0.1
         #self.max2 = 0.2
         #self.min2 = 0.1
     
     def connectWS(self):
		try:
			self.ws = create_connection("ws://192.168.1.220:33033/ws")
			print "Websocket created"
		except:
			print "Could not create connection"
			self.ws = 0
			
     
     def run(self):
         oldValue = [-10,-10,-10,-10,-10,-10]
         while ( not self.stopNow) :
			
			for sensor in range(6):
				value = self.board.analog[sensor].read()
				if (value==None):
					print "Coulde not read value form sensor ",sensor
					return
				value = (float(value) - 0.5) * 2  # - 0.5)*2 # to -1..1; for sensor 0.5 is neutral neutral now inhaling positive, exhaling negative
				value = int(value *100) / 100.0 # leave just 2 decimals
				#TODO: ümarda nii, et suurus oleks 1 komakoht (-10..10)? , saada ws ainult, kui on muutunud
				#print value, float(value), v1
				
				if (value!=oldValue[sensor] ):
					oldValue[sensor] = value
					valueLabel[sensor].setText(str(value))
					if (self.ws!=0):
						self.ws.send("blower,"+str(sensor+1)+ "," + str(value) )
				
			time.sleep(0.25)   
     
     def stop(self):
		 self.stopNow = True
		 self.board.exit()
		 if (self.ws!=0):
			self.ws.close
Exemplo n.º 4
0
 def __init__(self, widget):
     super(FirmataThread, self).__init__()
     self.board = ArduinoMega('/dev/ttyACM0')
     self.it = util.Iterator(self.board)
     self.it.start()
     self.board.analog[0].enable_reporting()
     self.board.analog[1].enable_reporting()
     self.stopNow = False
     self.widget = widget
     print "ArduinoMEGA ready to operate"
Exemplo n.º 5
0
class FirmataThread(threading.Thread):
     def __init__(self,widget):
         super(FirmataThread, self).__init__()
         self.board = ArduinoMega('/dev/ttyACM0')
         self.it = util.Iterator(self.board)
         self.it.start()
         self.board.analog[0].enable_reporting()
         self.board.analog[1].enable_reporting()
         self.stopNow = False
         self.widget = widget
         print "ArduinoMEGA ready to operate"
         #self.max1 = 0.2
         #self.min1 = 0.1
         #self.max2 = 0.2
         #self.min2 = 0.1
	
     def run(self):
         while ( not self.stopNow) :
			v1 = self.board.analog[0].read()
			v2 = self.board.analog[1].read()
			#if (v1>self.max1 and v1<1): # find relative value between max and min of the session bit interesting
				#self.max1 = v1
			#if (v1<self.min1 and v1>0):
				#self.min1 = v1
			
			#if (v2>self.max2 and v2<1):
				#self.max2 = v2
			#if (v1<self.min2 and v2>0):
				#self.min2 = v2
			max = 0.6
			min = 0.2
			if (v1<min):
				v1 = min
			if (v1>max):
				v1 = max
			if (v2<min):
				v2 = min
			if (v2>max):
				v2 = max	
			rel1 = (v1-min) / (max-min)
			rel2 = (v2-min) / (max-min)
			#print rel1,rel2
			valueLabel1.setText(str(rel1))
			valueLabel2.setText(str(rel2))
			sendUdpMessage("sensor,skin1,"+str(rel1))
			sendUdpMessage("sensor,skin2,"+str(rel2))
			time.sleep(0.25)   
     
     def stop(self):
		 self.stopNow = True
		 self.board.exit()
Exemplo n.º 6
0
class FirmataThread(threading.Thread):
    def __init__(self, widget):
        super(FirmataThread, self).__init__()
        self.board = ArduinoMega('/dev/ttyACM0')
        self.it = util.Iterator(self.board)
        self.it.start()
        self.board.analog[0].enable_reporting()
        self.board.analog[1].enable_reporting()
        self.stopNow = False
        self.widget = widget
        print "ArduinoMEGA ready to operate"
        #self.max1 = 0.2
        #self.min1 = 0.1
        #self.max2 = 0.2
        #self.min2 = 0.1

    def run(self):
        while (not self.stopNow):
            v1 = self.board.analog[0].read()
            v2 = self.board.analog[1].read()
            #if (v1>self.max1 and v1<1): # find relative value between max and min of the session bit interesting
            #self.max1 = v1
            #if (v1<self.min1 and v1>0):
            #self.min1 = v1

            #if (v2>self.max2 and v2<1):
            #self.max2 = v2
            #if (v1<self.min2 and v2>0):
            #self.min2 = v2
            max = 0.6
            min = 0.2
            if (v1 < min):
                v1 = min
            if (v1 > max):
                v1 = max
            if (v2 < min):
                v2 = min
            if (v2 > max):
                v2 = max
            rel1 = (v1 - min) / (max - min)
            rel2 = (v2 - min) / (max - min)
            #print rel1,rel2
            valueLabel1.setText(str(rel1))
            valueLabel2.setText(str(rel2))
            sendUdpMessage("sensor,skin1," + str(rel1))
            sendUdpMessage("sensor,skin2," + str(rel2))
            time.sleep(0.25)

    def stop(self):
        self.stopNow = True
        self.board.exit()
Exemplo n.º 7
0
    def connect(self, port: str, board: str="uno") -> None:
        """
        Initialize a connection with the arduino.

        Parameters
        ----------
        port : str
            Computer serial port to which the arduino is connected
        board : str, optional
            | The type of the arduino that is being used:
            | ``uno``: `Arduino Uno <https://store.arduino.cc/products/arduino-uno-rev3>`_
            | ``mega``: `Arduino Mega <https://store.arduino.cc/products/arduino-mega-2560-rev3>`_
            | ``due``: `Arduino Due <https://store.arduino.cc/products/arduino-due>`_
            | ``nano``: `Arduino Nano <https://store.arduino.cc/products/arduino-nano>`_
        """
        self.port = port

        if board == "uno":
            self.board = Arduino(self.port)
        elif board == "mega":
            self.board = ArduinoMega(self.port)
        elif board == "due":
            self.board = ArduinoDue(self.port)
        elif board == "nano":
            self.board = ArduinoNano(self.port)
        else:
            raise UnknownBoardException("Unknown board " + board)
        self.it = util.Iterator(self.board)
        self.it.start()
Exemplo n.º 8
0
    def __init__(self, lc, addr, debug=True):
        self.lc = lc
        self.board = None
        self.lights = []

        #
        # pin 53 used as placeholder because we don't support buzzers yet
        #                  (r,  y,  g,  b )
        self.lights.append((22, 23, 24, 53))
        self.lights.append((25, 26, 27, 53))
        self.lights.append((28, 29, 30, 53))
        self.lights.append((31, 32, 33, 53))
        self.lights.append((34, 35, 36, 53))
        self.lights.append((37, 38, 39, 53))
        self.lights.append((40, 41, 42, 53))
        self.lights.append((43, 44, 45, 53))
        if addr is not None:
            self.board = ArduinoMega(addr)
            for r, y, g, b in self.lights:
                self.board.digital[r].write(1)
                self.board.digital[y].write(1)
                self.board.digital[g].write(1)
                self.board.digital[b].write(1)

        self.debug = debug
Exemplo n.º 9
0
def readdatafromArduino(stop):
    global datafromfile
    # load default values from
    file = open("/var/www/html/lifeboxdata", "r")
    datafromfile = file.read().split("|")
    # remove
    board = ArduinoMega('/dev/ttyACM0')
    it = util.Iterator(board)
    it.start()
    for i in range(0, 11):
        board.analog[i].enable_reporting()
    while not stop:
        #for i in range (0,11):
        #if board.analog[i].read() is not None:
        #print("Pin:"+str(i)+" Value:"+str(int(board.analog[i].read()*1000)))
        if board.analog[i].read() is not None:
            #datafromfile[16] = board.analog[8].read() # plants life expectancy
            #datafromfile[20] = board.analog[10].read() # plants energy generation
            print("Value:" + str(int(board.analog[9].read() * 1000)))
            datafromfile[17] = int(
                map(int(board.analog[9].read() * 1000), 0, 1000, 1,
                    2000))  # plants nearborn chances
            print("Return:" + str(datafromfile[17]))
            #datafromfile[6] = board.analog[3].read() # sp1 gathering
            #datafromfile[5] = board.analog[2].read() # sp1 efficency
            #datafromfile[0] = board.analog[0].read() # sp1 life exp
            #datafromfile[1] = board.analog[1].read() # sp1 nearborn chances
            #datafromfile[14] = board.analog[7].read() # sp2 gathering
            #datafromfile[13] = board.analog[6].read() # sp2 efficency
            #datafromfile[8] = board.analog[4].read() # sp2 life exp
            #datafromfile[9] = board.analog[5].read() # sp2 nearborn chances
        time.sleep(1)
Exemplo n.º 10
0
 def __init__(self):
     self.logicMatrix = []
     self.initialize_matrix()
     self.board = ArduinoMega(PORT, baudrate=RATE)
     super().__init__(self.board, PIN_DATA_IN, PIN_LOAD, PIN_CLOCK)
     self.clear()
     self.layout = []
     self.build_layout()
Exemplo n.º 11
0
 def __init__(self,widget):
     super(FirmataThread, self).__init__()
     self.board = ArduinoMega('/dev/ttyACM0')
     self.it = util.Iterator(self.board)
     self.it.start()
     self.board.analog[0].enable_reporting()
     self.board.analog[1].enable_reporting()
     self.stopNow = False
     self.widget = widget
Exemplo n.º 12
0
class FirmataThread(threading.Thread):
     def __init__(self,widget):
         super(FirmataThread, self).__init__()
         self.board = ArduinoMega('/dev/ttyACM0')
         self.it = util.Iterator(self.board)
         self.it.start()
         self.board.analog[0].enable_reporting()
         self.board.analog[1].enable_reporting()
         self.stopNow = False
         self.widget = widget
	
     def run(self):
         while ( not self.stopNow) :
			v1 = self.board.analog[0].read()
			v2 = self.board.analog[1].read()
			#print v1,v2
			valueLabel1.setText(str(v1))
			valueLabel2.setText(str(v2))
			time.sleep(0.1)    
     
     def stop(self):
		 self.stopNow = True
		 self.board.exit()
Exemplo n.º 13
0
    def __init__(self, cfg):
        # load the config
        self.cfg = cfg
        self.board = ArduinoMega(cfg['ARDUINO_PORT'])

        # iterator thread for reading analog pins
        # self.iter = util.Iterator(self.board)
        # self.iter.start()
        # print("iterator running.")

        # set the select pins as arduino digital pins
        self.s_pin_num = cfg['MUX_SELECT_PINS']
        self.s_pins = [self.board.get_pin('d:' + str(self.s_pin_num[0]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[1]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[2]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[3]) + ':o')]
        # set the signal pin
        # self.sig_pin = self.board.get_pin('d:' + str(cfg['MUX_SIG_PIN']) + ':o')

        # TODO: add some stuff to separate digital and analog pins
        self.sig_pin = self.board.get_pin('a:0:i')

        print("Mux connected.")
Exemplo n.º 14
0
def readPotDatafromArduino(stop):
    global potData
    board = ArduinoMega(sys.argv[2])
    it = util.Iterator(board)
    it.start()
    for i in range(0, 11):
        board.analog[i].enable_reporting()
    while not stop:
        for i in range(0, 11):
            time.sleep(0.2)
            prevalue = potData[i]
            potData[i] = board.analog[i].read()
            if potData[i] is not None:
                potData[i] = potData[i] * 1023
            else:
                potData[i] = prevalue
Exemplo n.º 15
0
    def __init__(self, addr, debug=True):
        self.board = None
        self.pins = []

        # green
        #
        self.pins.append((23, 24, 22, 2))
        self.pins.append((26, 27, 25, 3))
        self.pins.append((29, 30, 28, 4))
        self.pins.append((32, 33, 31, 5))
        self.pins.append((35, 36, 34, 6))
        self.pins.append((38, 39, 37, 7))
        self.pins.append((41, 42, 40, 8))
        self.pins.append((44, 45, 43, 9))
        if addr is not None:
            self.board = ArduinoMega(addr)
            for b in self.pins:
                self.board.digital[b[3]].mode = pyfirmata.SERVO
                for c in range(3):
                    self.board.digital[b[c]].write(True)

        self.debug = debug
def setBoard(boardType, port):
  if boardType == 'arduino':
    board = Arduino(port)
  else:
    board = ArduinoMega(port)
  return board
Exemplo n.º 17
0
import RPi.GPIO as GPIO
from pyfirmata import Arduino, ArduinoMega, util
import time

GPIO.setmode(GPIO.BCM)

#def arduino board for onboard comms
board = ArduinoMega('/dev/ttyACM0')

#in1-4 are for the arduino to interface with motor controller
#these determine direction of current
in1pin = board.get_pin('d:22:o')
in2pin = board.get_pin('d:24:o')
in3pin = board.get_pin('d:26:o')
in4pin = board.get_pin('d:28:o')

#for arduino again, this is PWM to attain speed control
enablePin1 = board.get_pin('d:6:p')
enablePin2 = board.get_pin('d:7:p')

#determines encoder pins
input_A = 17
input_B = 22

input_C = 18
input_D = 23

GPIO.setup(input_A, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(input_B, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.setup(input_C, GPIO.IN, pull_up_down=GPIO.PUD_UP)
Exemplo n.º 18
0
# vim:fenc=utf-8
#
# Copyright © 2015 cameron <cameron@Megatron-Virtual>
#
# Distributed under terms of the MIT license.

"""
This is a second attempt to reading analog
"""

from pyfirmata import ArduinoMega, util
import time
import os

port = '/dev/ttyACM0'
board = ArduinoMega(port)
time.sleep(5)
it = util.Iterator(board)
it.start()
sensor = board.get_pin('a:0:i')

try:
    while True:
        value = sensor.read()
        print value
        print(type(value))
        time.sleep(1)
except KeyboardInterrupt:
    board.exit()
    os._exit()
Exemplo n.º 19
0
def CriaPinos(mini = 2, maxi = 13,tipo = 'p'):      #TIPO: O:OUTPUT | I:INPUT | P:PWM
    
    arduino = ArduinoMega('COM3')
    for i in range(mini,maxi):
        AP["pino" + str(i)] = arduino.get_pin('d:{}:{}'.format(i,tipo))
Exemplo n.º 20
0
#
# Copyright © 2015 cameron <www.candidcypher.com>
#
# Distributed under terms of the MIT license.

"""
This is an experiement to create a breathing LED using Firmata and an
Arduino
"""

from pyfirmata import ArduinoMega
from pyfirmata import OUTPUT, INPUT, PWM
import time

port = "/dev/ttyS3"
board = ArduinoMega(port)

ledPin = board.get_pin('d:2:p')


def increase_range(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step


def decrease_range(start, stop, step):
    down_step = start
    while down_step > stop:
        yield down_step
Exemplo n.º 21
0
    if w.serial_number == "558383437333512132D0":
        ArduinoMegaPort = w.device

    if w.serial_number == "5":
        ArduinoNanoPort = w.device

# print('Arduino Mega Port: ', ArduinoMegaPort)

pygame.init
clock = pygame.time.Clock()
useArduino = True

# Try to connect to the arduino board. If it fails, then we will use the keyboard.
# TODO: create something that finds which port the arduino is connected to...
try:
    arduino = ArduinoMega(ArduinoMegaPort)
    # arduino = ArduinoMega('/dev/ttyACM1')
    # arduino = ArduinoMega('/dev/ttyACM0')
    # arduino = ArduinoMega('COM7')
    time.sleep(0.2)
    iterator = util.Iterator(arduino)
    iterator.start()
    time.sleep(0.2)

    # Define all input pins
    PIN_ONE = arduino.get_pin("d:37:i")
    PIN_TWO = arduino.get_pin("d:36:i")
    PIN_THREE = arduino.get_pin("d:35:i")
    PIN_LEFT = arduino.get_pin("d:32:i")
    PIN_RIGHT = arduino.get_pin("d:31:i")
    PIN_UP = arduino.get_pin("d:34:i")
Exemplo n.º 22
0
import requests
import nmap
import RPi.GPIO as GPIO
from pyfirmata import ArduinoMega
from pyfirmata.util import Iterator

board = ArduinoMega('/dev/ttyACM0')
GPIO.setmode(GPIO.BCM)
GPIO.setup(26,GPIO.IN)
iterator = Iterator(board)
iterator.start()
pinTemp = board.get_pin('a:0:i')

backend = "http://192.168.1.4:5000"
nm = nmap.PortScanner()

devices = {}
temp = 42.0
lumi = 42.0
people = 0
opt_temp = 0.0


def optimal_temp():
	global opt_temp
	opt_temp = 1.0


def sensors():
	global pinTemp
	global temp
Exemplo n.º 23
0
from pyfirmata import ArduinoMega, util
import time
import pyfirmata
board = ArduinoMega('/dev/tty.usbmodem1441')
#board = ArduinoMega('COM8')
board.analog[0].mode = pyfirmata.INPUT
it = util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
while True:
    print(board.analog[0].read())
Exemplo n.º 24
0
from pyfirmata import ArduinoMega, util
from pyfirmata import SERVO
import time


board = ArduinoMega('com3')
board.digital[7].mode = SERVO
board.digital[6].mode = SERVO
window_width = 650
window_height = 400

def translate(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin

    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)

    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

def getValues():
    try:
        f = open('values.txt','r')
        values = f.read().split(':')
        f.close
        return values
    except:
        pass
Exemplo n.º 25
0
from pyfirmata import ArduinoMega, util
import pyfirmata, pyfirmata.util
import time
import pygame

from random import seed
from random import randint
from random import seed
from random import choice

# Initialize PyGame and PyFirmata

pygame.mixer.init()
board = ArduinoMega('COM7', baudrate=57600)
iterator = pyfirmata.util.Iterator(board)
iterator.start()
time.sleep(1)

# Button Pin Declarations

button2 = board.get_pin('d:2:i')
button4 = board.get_pin('d:4:i')
button6 = board.get_pin('d:6:i')
button8 = board.get_pin('d:8:i')
button10 = board.get_pin('d:10:i')
button12 = board.get_pin('d:12:i')

button30 = board.get_pin('d:30:i')
button32 = board.get_pin('d:32:i')
button34 = board.get_pin('d:34:i')
button36 = board.get_pin('d:36:i')
Arduino_SN = arduino_boards.Arduino_SN
ArduinoMega_SN = arduino_boards.ArduinoMega_SN

Arduinos = {}  # Initialize the board dictionary
for comport in comports():
    # print(comport.vid)			# 9025 (type: int)
    # print(comport.serial_number)	# "95530343235351605281" (type: str)
    # print(comport.device)			# "COM4" (type: str)
    # print(comport)				# "COM4 - USB Serial Device (COM4)" (type: class)
    SN = comport.serial_number

    if SN in ArduinoMega_SN.keys():
        board_name = ArduinoMega_SN[SN]
        print(board_name, ':', comport.device)
        # adding the 'timeout' to prevent raising wirteTimeout Error, it's None by default
        board = ArduinoMega(comport.device, timeout=0)
        # time.sleep(0.5)		# Wait for communication to get established
        Arduinos[board_name] = board

    elif SN in Arduino_SN.keys():
        board_name = Arduino_SN[SN]
        print(board_name, ':', comport.device)
        board = Arduino(comport.device)
        # time.sleep(0.5)		# Wait for communication to get established
        Arduinos[board_name] = board

# =================== assign pins for each board ====================
# Define each board
# uno_1 = Arduinos['Uno_1']
# mega_1 = Arduinos['Mega_1']
mega_2 = Arduinos['Mega_2']
Exemplo n.º 27
0
# vim:fenc=utf-8
#
# Copyright © 2015 cameron <cameron@Megatron-Virtual>
#
# Distributed under terms of the MIT license.

"""
This Python Script reads data from a soil moisture sensor
"""

from pyfirmata import ArduinoMega, util
from pyfirmata import INPUT
import time

port = "/dev/ttyACM0"
board = ArduinoMega(port)
sensor = board.get_pin("a:0:i")
# board.analog[0].mode = INPUT
it = util.Iterator(board)
it.start()
time.sleep(1)


def get_value():
    """
    This method takes an integer input for the pin to be read. Appropriate
    values range 0-15 for analog pins.
    """
    read_val = sensor.read()
    print(read_val)
    time.sleep(1.0)
Exemplo n.º 28
0
from pyfirmata import ArduinoMega, util
from sensor_controller.EventGenerator import EventGenerator
# from sensor_controller.MyColor import MyColor
import time


BLENDING_CONSTANT = 10

if __name__ == '__main__':
	

	"""
	Setup sensor input
	"""
	
	board = ArduinoMega(SERIAL_INPUT)
	eventGenerator = EventGenerator(board)
	cupXPin_r = board.get_pin('d:5:p')
	cupXPin_g = board.get_pin('d:7:p')
	cupXPin_b = board.get_pin('d:6:p')

	cupXColor = Color(rgb=(0.0, 0.0, 0.0))

	# Init
	board.digital[5].write(1)
	board.digital[6].write(1)
	board.digital[7].write(1)


	dt = 0.0
Exemplo n.º 29
0
# -*- coding: utf-8 -*-

import time
from pyfirmata import ArduinoMega, util
import pyfirmata

board = ArduinoMega('/dev/ttyUSB0')

RED=0
ORANGE=1
GREEN=2
SERVO=3

combinations = []
combinations.append((22, 23, 24, 2))
combinations.append((25, 26, 27, 3))
combinations.append((28, 29, 30, 4))
combinations.append((31, 32, 33, 5))
combinations.append((34, 35, 36, 6))
combinations.append((37, 38, 39, 7))
combinations.append((40, 41, 42, 8))
combinations.append((43, 44, 45, 9))

stime=.5
for combo in combinations:
    board.digital[combo[SERVO]].mode = pyfirmata.SERVO
while True:
    for i in range(3):
        for combo in combinations:
            board.digital[combo[i]].write(False)
            board.digital[combo[SERVO]].write(0)
"""

import cv2
import numpy as np
import pygame
from pygame.locals import *
import time
from pyfirmata import ArduinoMega, util

from OpenGL.GL import *
from OpenGL.GLU import *

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
body_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml')

board = ArduinoMega('COM4')
iterator = util.Iterator(board)
iterator.start()

S1 = board.get_pin('d:5:p')  #ght
D1 = board.get_pin('d:7:o')  #right
S2 = board.get_pin('d:4:p')  #ft
D2 = board.get_pin('d:6:o')  #left
time.sleep(1.0)


def left():
    for i in range(50):
        S1.write(i)
        D1.write(0)
        S2.write(i)  #left forward
Exemplo n.º 31
0
from SESCdraw import _DRAW
from SESCfunc import _FCM, _FCE, _PASS, _MIN, _MAX, _CEN, _MOV
from pyfirmata import ArduinoMega, util

MESA = "SIMULACAO"
INICIAR = True

mega = ArduinoMega('COM3')
iterator = util.Iterator(mega)
iterator.start()

DM_pin_YGOL_ENE = mega.get_pin('d:18:o')
DM_pin_YGOL_DIR = mega.get_pin('d:19:o')
DM_pin_YGOL_PAS = mega.get_pin('d:20:o')
DM_pin_RGOL_ENE = mega.get_pin('d:21:o')
DM_pin_RGOL_DIR = mega.get_pin('d:22:o')
DM_pin_RGOL_PAS = mega.get_pin('d:23:o')
FC_pin_MGOL_MIN = mega.get_pin('d:24:i')
FC_pin_MGOL_MAX = mega.get_pin('d:25:i')
FC_pin_EGOL = mega.get_pin('d:26:i')

DM_pin_YDEF_ENE = mega.get_pin('d:27:o')
DM_pin_YDEF_DIR = mega.get_pin('d:28:o')
DM_pin_YDEF_PAS = mega.get_pin('d:29:o')
DM_pin_RDEF_ENE = mega.get_pin('d:30:o')
DM_pin_RDEF_DIR = mega.get_pin('d:31:o')
DM_pin_RDEF_PAS = mega.get_pin('d:32:o')
FC_pin_MDEF_MIN = mega.get_pin('d:33:i')
FC_pin_MDEF_MAX = mega.get_pin('d:34:i')
FC_pin_EDEF = mega.get_pin('d:35:i')
Exemplo n.º 32
0
                   device_helpers)
except (SystemError, ImportError):
    import assistant_helpers
    import audio_helpers
    import browser_helpers
    import device_helpers

ASSISTANT_API_ENDPOINT = 'embeddedassistant.googleapis.com'
END_OF_UTTERANCE = embedded_assistant_pb2.AssistResponse.END_OF_UTTERANCE
DIALOG_FOLLOW_ON = embedded_assistant_pb2.DialogStateOut.DIALOG_FOLLOW_ON
CLOSE_MICROPHONE = embedded_assistant_pb2.DialogStateOut.CLOSE_MICROPHONE
PLAYING = embedded_assistant_pb2.ScreenOutConfig.PLAYING
DEFAULT_GRPC_DEADLINE = 60 * 3 + 5

port = '/dev/ttyACM0'
board = ArduinoMega(port)
sleep(1)
pin13 = board.get_pin('d:13:p')


class SampleAssistant(object):
    """Sample Assistant that supports conversations and device actions.

    Args:
      device_model_id: identifier of the device model.
      device_id: identifier of the registered device instance.
      conversation_stream(ConversationStream): audio stream
        for recording query and playing back assistant answer.
      channel: authorized gRPC channel for connection to the
        Google Assistant API.
      deadline_sec: gRPC deadline in seconds for Google Assistant API call.
Exemplo n.º 33
0
class Mux():
    muxChannel = [[0, 0, 0, 0], # channel 1
                  [1, 0, 0, 0], # channel 2
                  [0, 1, 0, 0], # channel 3
                  [1, 1, 0, 0], # channel 4
                  [0, 0, 1, 0], # channel 5
                  [1, 0, 1, 0], # channel 6
                  [0, 1, 1, 0], # channel 7
                  [1, 1, 1, 0], # channel 8
                  [0, 0, 0, 1], # channel 9
                  [1, 0, 0, 1], # channel 10
                  [0, 1, 0, 1], # channel 11
                  [1, 1, 0, 1], # channel 12
                  [0, 0, 1, 1], # channel 13
                  [1, 0, 1, 1], # channel 14
                  [0, 1, 1, 1], # channel 15
                  [1, 1, 1, 1]] # channel 16

    def __init__(self, cfg):
        # load the config
        self.cfg = cfg
        self.board = ArduinoMega(cfg['ARDUINO_PORT'])

        # iterator thread for reading analog pins
        # self.iter = util.Iterator(self.board)
        # self.iter.start()
        # print("iterator running.")

        # set the select pins as arduino digital pins
        self.s_pin_num = cfg['MUX_SELECT_PINS']
        self.s_pins = [self.board.get_pin('d:' + str(self.s_pin_num[0]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[1]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[2]) + ':o'),
                       self.board.get_pin('d:' + str(self.s_pin_num[3]) + ':o')]
        # set the signal pin
        # self.sig_pin = self.board.get_pin('d:' + str(cfg['MUX_SIG_PIN']) + ':o')

        # TODO: add some stuff to separate digital and analog pins
        self.sig_pin = self.board.get_pin('a:0:i')

        print("Mux connected.")

    def run(self):
        # TODO: Debugging
        for j in range(0, 5):
            for i in range(0, 3):
                print("channel: " + str(i))
                self.switch_mux(i, 1)

        # exit cleanly
        self.shutdown()

        return 0

    def switch_mux(self, channel, wait_s):
        """
        @about: switch mux signal pin to specified channel for specified time.
        @param: channel to switch the multiplexer to
        @param: wait_s delay time to stay at channel. sometimes the readings
                would take longer to "switch"
        """
        # write to selecter pins to specify the mux output channel
        for i in range(0, 4):
            self.s_pins[i].write(self.muxChannel[channel][i])

        time.sleep(wait_s)

        return 0

    def write_mux(self, channel, wait_s, pin_value):
        """
        @about: call switch mux to switch mux channel. Write to signal pin with
                pin_value.
        # TODO: used for debugging
        """
        # call switch_mux to change the mux channel
        self.switch_mux(channel, wait_s)

        # do something with the LED's
        self.sig_pin.write(pin_value)
        time.sleep(wait_s)
        self.sig_pin.write(0)

        return 0

    def read_analog_resistance(self):
        """
        @brief: (FOR DEBUGGING) read the analog input pin and calculate the resistance
                using a voltage divider
        """
        R_IN = 220.0
        V_IN = 5.0
        V_out = self.sig_pin.read() * V_IN # rescale it to the 5V bar
        R_out = (R_IN * V_out/V_IN) / (1.0 - (V_out/V_IN))
        print('R = %.2f' % R_out)

        return R_out

    def shutdown(self):
        """
        @brief: close connection to board.
        """
        self.board.exit()
        print('Closed connection to mux.')

        return 0
Exemplo n.º 34
0
from pyfirmata import ArduinoMega, util
import subprocess

bashCommand = "fuser -k /dev/ttyACM0"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()

check = True
pinArray = [512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512]

board = ArduinoMega('/dev/ttyACM0')
it = util.Iterator(board)
it.start()

# Start reporting for defined pins
for pin in range(0, 11):
    board.analog[pin].enable_reporting()
while (True):
    board.pass_time(2)
    f = open('controllerdata', 'w')
    index = 0
    for pin in range(0, 11):
        value = board.analog[pin].read()
        if value is not None:
            #f.write(str(int(value*1023)))
            pinArray[index] = int(value * 1023)
            if check:
                #print ("Analog Pin %i : %s" % (pin, int(value*1023)))
                print("Readings Ok, you can start Lifebox!")
                check = False
        #board.pass_time(0.2)
Exemplo n.º 35
0
from pyfirmata import Arduino, util
from pyfirmata import ArduinoMega
from pyfirmata import INPUT, OUTPUT, PWM
import RPi.GPIO as GPIO
import numpy as np
import argparse
import imutils
import cv2
import math
import pandas as pd
import matplotlib.pyplot as plt
import time
import serial  # import serial library
arduinoSerialData = serial.Serial('/dev/ttyACM0', 9600, timeout=10)

board = ArduinoMega('/dev/ttyACM0')
servoX = board.get_pin('d:3:s')
servoY = board.get_pin('d:2:s')
# for 1st Motor on ENA
ENA = 33
IN1 = 35
IN2 = 37

# set pin numbers to the board's
GPIO.setmode(GPIO.BOARD)

# initialize EnA, In1 and In2
GPIO.setup(ENA, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(IN1, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(IN2, GPIO.OUT, initial=GPIO.LOW)
Exemplo n.º 36
0
from time import sleep

# from pysine import sine
from pyfirmata import ArduinoMega
import time

upperbt = 60
lowerbt = 0
l = .3
h = .9
board = ArduinoMega('COM15')
servo1 = board.get_pin('d:7:s')  #
servo2 = board.get_pin('d:8:s')
servo3 = board.get_pin('d:6:s')  #
servo4 = board.get_pin('d:9:s')
servo5 = board.get_pin('d:5:s')  #
servo6 = board.get_pin('d:10:s')
servo7 = board.get_pin('d:4:s')  #
servo8 = board.get_pin('d:13:s')
servo9 = board.get_pin('d:2:s')  #
servo10 = board.get_pin('d:12:s')
servo11 = board.get_pin('d:3:s')  #
servo12 = board.get_pin('d:11:s')
airpin = board.get_pin('d:14:s')  # not used yet
# to initialize all values to zero angle
servo1.write(0)  #
servo2.write(0)
servo3.write(0)  #
servo4.write(0)
servo5.write(0)  #
servo6.write(0)
Exemplo n.º 37
0
def ir_mux(ir_name):
    logging.debug('Starting')

    # ------- connect to IR hardwares --------
    board_port = ir_port  # The port is from the USB port
    ir_board = ArduinoMega(
        board_port)  # Creat the Serial port for ArduinoMega board
    # first multiplexer, define switch and signal pins on boards
    PinS, PinSig = mux.DefinePin(ir_board, [30, 31, 32, 33], 3)
    # second multiplexer, define switch and signal pins on boards
    PinS2, PinSig2 = mux.DefinePin(ir_board, [40, 41, 42, 43], 4)
    logging.debug('connected to IR board')

    # ------- initialize hardwares and variables ------
    # start switches with connectin to channel 0
    mux.SwitchMUX(PinS, 0)
    mux.SwitchMUX(PinS2, 0)
    Data = {}  # Creat an empty dictionary
    num_of_data = 2000

    # ------ start Iterator to avoid serial overflow -----
    it = util.Iterator(
        ir_board)  # need this iteration otherwise pin just reporting 'None'
    it.start()
    time.sleep(0.5)

    # ------ start collect data ------
    for n in range(32):
        # logging.debug('IR channel '+str(n+1)+'...')
        print("IR channel " + str(n + 1) + "...")
        t = []
        v = []
        t0 = time.time()
        if n < 16:  # It's on the first mutiplexer
            mux.SwitchMUX(PinS, n)
            time.sleep(0.1)
            for m in range(num_of_data):
                t.append(time.time() - t0)
                v.append(
                    float(mux.Read(PinSig))
                )  # mux returns a string, need to transfer to float number
                time.sleep(0.000001)
            Data['Time' + str(n + 1)] = t
            Data['Chan' + str(n + 1)] = v

        else:  # switch to the second mutiplexer, need to re-define channel number
            m = n - 16
            mux.SwitchMUX(PinS2, m)
            time.sleep(0.1)
            for m in range(num_of_data):
                t.append(time.time() - t0)
                v.append(
                    float(mux.Read(PinSig2))
                )  # MUX returns a string, need to transfer to float number
                time.sleep(0.000001)
            Data['Time' + str(n + 1)] = t
            Data['Chan' + str(n + 1)] = v

    ir_board.exit()
    np.save(
        os.path.join(file_dir, ir_name), Data
    )  # use np.load(filename) to read data, and dict will be in .item()

    freq = []
    drops = []
    for i in range(32):
        time_title = 'Time' + str(i + 1)
        chan_title = 'Chan' + str(i + 1)
        time_stamp = Data[time_title]
        ir = Data[chan_title]
        ir = np.array(ir)  # convert list to array, for the following process

        rel_ir = -1 * ir + max(ir)
        cut_height = 0.3 * max(rel_ir)
        spec_cut_half = rel_ir - cut_height
        fwhm_index = np.where(np.diff(np.sign(spec_cut_half)))[0]
        peak_numbs = len(fwhm_index) / 2
        # time lapse between reading is 1ms, the unit below is ms
        liq_total_time = sum(counter > cut_height for counter in rel_ir)

        freq.append(peak_numbs / (time_stamp[-1] - time_stamp[0]))  # unit Hz
        drops.append(liq_total_time / peak_numbs)  # unit: ms/drop

    print('########### Droplet frequency is  ' + str(np.mean(freq)) +
          '  Hz ##############')
    print('########### Droplet size is  ' + str(np.mean(drops)) +
          '  ms/drop ##############')

    logging.debug('Exiting')
Exemplo n.º 38
0
#
# Copyright © 2015 cameron <cameron@Megatron-Virtual>
#
# Distributed under terms of the MIT license.

"""
This module starts to integrate the analog read of a sensor into PySide
"""

from PySide import QtGui, QtCore
from pyfirmata import ArduinoMega, util
import time

sensor_app = QtGui.QApplication([])
port = "/dev/ttyACM0"
board = ArduinoMega(port)
sensor = board.get_pin('a:0:i')
iterator = util.Iterator(board)
iterator.start()
time.sleep(1)


def get_value():
    read_val = sensor.read()
    corrected_val = 1 - read_val
    lcd.display(corrected_val)

lcd = QtGui.QLCDNumber()
lcd.setDigitCount(8)

timer = QtCore.QTimer()