Exemple #1
0
    def set_buttons(self):

        btn_switch1 = QPushButton('1', self)
        btn_switch1.clicked.connect(Arduino.switch1_on())
        btn_switch1.resize(btn_switch1.sizeHint())
        btn_switch1.move(100, 100)

        btn_switch2 = QPushButton('2', self)
        btn_switch2.clicked.connect(Arduino.switch2_on())
        btn_switch2.resize(btn_switch2.sizeHint())
        btn_switch2.move(100, 150)

        btn_switch3 = QPushButton('3', self)
        btn_switch3.clicked.connect(Arduino.switch3_on())
        btn_switch3.resize(btn_switch3.sizeHint())
        btn_switch3.move(100, 200)

        btn_switch4 = QPushButton('4', self)
        btn_switch4.clicked.connect(Arduino.switch4_on())
        btn_switch4.resize(btn_switch4.sizeHint())
        btn_switch4.move(100, 250)

        btn_switch5 = QPushButton('5', self)
        btn_switch5.clicked.connect(Arduino.switch5_on())
        btn_switch5.resize(btn_switch5.sizeHint())
        btn_switch5.move(200, 100)

        btn_switch6 = QPushButton('6', self)
        btn_switch6.clicked.connect(Arduino.switch6_on())
        btn_switch6.resize(btn_switch6.sizeHint())
        btn_switch6.move(200, 150)

        btn_switch7 = QPushButton('7', self)
        btn_switch7.clicked.connect(Arduino.switch7_on())
        btn_switch7.resize(btn_switch7.sizeHint())
        btn_switch7.move(200, 200)

        btn_switch8 = QPushButton('8', self)
        btn_switch8.clicked.connect(Arduino.switch8_on())
        btn_switch8.resize(btn_switch8.sizeHint())
        btn_switch8.move(200, 250)

        btn_all_off = QPushButton('ON', self)
        #btn_all_off.setCheckable(True)
        btn_all_off.clicked.connect(Arduino.switch_on())
        btn_all_off.resize(btn_all_off.sizeHint())
        btn_all_off.move(350, 125)

        btn_all_on = QPushButton('OFF', self)
        btn_all_on.clicked.connect(Arduino.switch_off())
        btn_all_on.resize(btn_all_on.sizeHint())
        btn_all_on.move(350, 225)

        qbtn = QPushButton('Quit', self)
        qbtn.clicked.connect(Arduino.close)
        qbtn.clicked.connect(QApplication.instance().quit)
        qbtn.move(200, 350)
        qbtn.setToolTip('Click to Quit')
Exemple #2
0
class Controller(object):
    def __init__(self, port, baud ):
        self._port = port
        self._baud = baud
        self._steppers = []
        self._arduino = None

    def connect(self):
        self._serial = serial.Serial(self._port,self._baud)
        self._serial.open()
        self._arduino = Arduino(self._serial)

    def addStepper(self, stepper):
        self._steppers.append(stepper)

    def attachStepper(self, pin, step):
        stepper = Stepper(pin,step)
        self._arduino.definePin(pin,'step')
        self._steppers.append(stepper)


    def stepAllUp(self):
        for stepper in self._steppers:
            self._arduino.stepPin(stepper._pin, stepper._step)
Exemple #3
0
from multiprocessing import Process, Queue
from threading import Thread
import sys
import time
import math
import re

# astar = A_Star.AStar(500)
# start = (0, 0)
# end = (2, 3)
# path = astar.solve(start, end)
n = dirX = dirY = 0
grid = 500
trig = 0

serArduino = Arduino.Serial('raspi', 'usb')
serOdroid = Arduino.Serial('raspi', 'gpio')
robot = move()

mqtt.set("192.168.0.112", "Jasmine")
queue = Queue()

# Receive Data from Base Station
R0 = robotCode = 0
data1 = data2 = data3 = data4 = data5 = 0

# Variable Process
find1=find2=point1=point2=point3=0

# Receive Data from Arduino
encoX = encoY = angleZ = ball = 0
Exemple #4
0
 def connect(self):
     self._serial = serial.Serial(self._port,self._baud)
     self._serial.open()
     self._arduino = Arduino(self._serial)
Exemple #5
0
 def initialize_arduino(self):
     self.arduino = Arduino()
     print 'Initialized Arduino'
Exemple #6
0
def Check() :
    global Distance
    global Command_Running, Current_Command, Command_Start
    global Delay_Time
    global Turn_Delta_Angle, delta_angle_current, turn_active
    global Turn_To_Angle, Turn_To_Direction, have_direction
    global HEADING_DELTA, heading_direction, adjusting_heading
    global Speed_Setting, accel_setting, SPEED_DELTA, SPEED_UNIT, _adjust_speed, cur_time, prev_time, prev_error
    global _course_set

    if _course_set : # a course can be set without command_Running being true
        cur_dir = GPS.Direction
        turn_direction = ''
        if cur_dir == GPS.invalid_Direction : # wait for valid direction
            return
        if cur_dir + HEADING_DELTA < heading_direction or cur_dir - HEADING_DELTA > heading_direction :
            # Find the direction the golf cart should turnto ( 360 - 0 condition checking )
            if cur_dir + HEADING_DELTA < heading_direction and heading_direction - cur_dir < 180 :
                turn_direction = 'right'
            elif cur_dir + HEADING_DELTA < heading_direction and heading_direction - cur_dir > 180 :
                turn_direction = 'left'
            elif cur_dir - HEADING_DELTA > heading_direction and cur_dir - heading_direction < 180 :
                turn_direction = 'left'
            elif cur_dir - HEADING_DELTA > heading_direction and cur_dir - heading_direction > 180 :
                turn_direction = 'right'
            writeLog(LOG_DETAILS, "Command course is executing a turnto," + str(heading_direction) + "," + turn_direction + ";")
            Execute('turnto,'+str(heading_direction)+','+turn_direction+';')
            return
        else :
            _course_set = False
            writeLog(LOG_DETAILS, "Command course is executing a heading," + str(Distance) + ";")
            Execute('heading,'+str(Distance)+';')
            return

    if not Command_Running :
        return

    '''if _adjust_speed :
        cur_speed = GPS.Speed
        prev_time = cur_time
        cur_time = time.time()
        dt = cur_time - prev_time
        error = Speed_Setting - cur_speed
        integral = integral + error * dt
        derivative = (error - prev_error) / dt
        manipulated_value = PROPORTIONAL_GAIN * error + INTEGRAL_GAIN * integral + DERIVATIVE_GAIN * derivative
        prev_error = error
        Arduino._serial_cmd(Arduino._Commands["speed"], manipulated_value)
        writeLog(LOG_DETAILS, "Current Speed : " + repr(cur_speed) + " with an Accel value of : " + repr(accel_setting))'''

    if Current_Command == 'sstop' :
        if GPS.Connected and GPS.Speed == 0.0 :
            Command_Running = False
            Arduino._serial_cmd(Arduino._Commands["brake"], 0) # releases the brake
        if Command_Start + Delay_Time < time.time() :
            Command_Running = False
            Arduino._serial_cmd(Arduino._Commands["brake"], 0) # releases the brake
    elif Current_Command == 'hstop' :
        # I don't know if I have the correct brake status here
        if GPS.Connected and GPS.Speed == 0.0 and Arduino.Brake == 3:
            Command_Running = False
            Arduino._serial_cmd(Arduino._Commands["brake"], 0) # releases the brake
        if Command_Start + Delay_Time < time.time() :
            Command_Running = False
            Arduino._serial_cmd(Arduino._Commands["brake"], 0) # releases the brake
    elif Current_Command == 'turnto' :
        cur_dir = GPS.Direction
        if have_direction == True :
            if Turn_To_Angle - HEADING_DELTA < cur_dir and cur_dir < Turn_To_Angle + HEADING_DELTA :
                Arduino._serial_cmd(Arduino._Commands["steer"], 0)
                if turn_active :
                    Arduino._serial_cmd(Arduino._Commands["speed"], 0)
                    turn_active = False
                Command_Running = False
        else :
            if GPS.Direction != GPS.invalid_Direction :
                have_direction = True
    elif Current_Command == 'forward' :
        distance = GPS.haversine(Start_Lat, Start_Long, GPS.Latitude, GPS.Longitude)
        if distance > Distance :
            Command_Running = False
            Arduino._serial_cmd(Arduino._Commands["speed"], 0)
    elif Current_Command == 'heading' :
        if not have_direction :
            if GPS.Direction != GPS.invalid_Direction :
                have_direction = True
                heading_direction = GPS.Direction
            else :
                return 
        distance = GPS.haversine(Start_Lat, Start_Long, GPS.Latitude, GPS.Longitude)
        cur_dir = GPS.Direction
        if distance > Distance :
            Command_Running = False
            Arduino._serial_cmd(Arduino._Commands["speed"], 0)
            Arduino._serial_cmd(Arduino._Commands["steer"], 0)
        if cur_dir - heading_direction > HEADING_DELTA and not adjusting_heading : # veering right
            Arduino._serial_cmd(Arduino._Commands["steer"], -_degrees)
            adjusting_heading = True
        elif -cur_dir + heading_direction > HEADING_DELTA and not adjusting_heading: # veering left
            Arduino._serial_cmd(Arduino._Commands["steer"], _degrees)
            adjusting_heading = True
        # assumes check() is often enough to stop turn before veering opposite way
        elif -cur_dir + heading_direction < HEADING_DELTA and cur_dir - heading_direction < HEADING_DELTA : 
            Arduino._serial_cmd(Arduino._Commands["steer"], 0)
            adjusting_heading = False
    elif Current_Command == 'course' :
        return
    elif Current_Command == 'delay' :
        if Command_Start + Delay_Time < time.time() :
            Command_Running = False
    else :
        writeLog(LOG_ERROR, 'Unrecognized command')
        Command_Running = False
Exemple #7
0
    print(Data.menu[drink].drinkIngredients)
    print(Data.menu[drink].recipeRatio)

    #converts ratios to volume and prints
    Data.menu[drink].setRecipeVolume()
    print(Data.menu[drink].recipeVolume)

    #converts volume to instructions for arduino and prints
    Data.menu[drink].setRecipeInstructions()
    print(Data.menu[drink].recipeInstructions)

    #print amount of standard Menu[Drink]s
    print(Data.menu[drink].getStndDrink())

    #sends Recipe instructions to the arduino
    Arduino.sendDrink(Data.menu[drink].recipeInstructions, "/dev/tty.usbmodem142101")
else: # gets data for a new custom drink
    custom = input('Drink not on menu, would you like to create a custom drink (y/n? ').lower()
    if (custom == 'y'):
        cup = input('Cup Type(ml): ').lower() #gets the cup type/volume
        fill = input('how full would you like your drink(%): ').lower() #gets the percentage fill of the cup

        # gets an ingredient list and ratio
        ingredients = {}
        ingredient = input('Ingredient: ').lower()
        amount = input('Amount as a ratio: ').lower()
        ingredients[ingredient] = amount
        while (ingredient != ''):
            ingredient = input('Ingredient: ').lower()
            amount = input('Amount as a ratio: ').lower()
            ingredients[ingredient] = amount
import Arduino
import time
import Database

db = Database.Database()

cfgdir = 'config/'
fmaincfg = open(cfgdir + 'main.cfg', 'r')

arduinos = []
n = int(fmaincfg.readline())
for i in range(0, n):
    arduinos.append(Arduino.Arduino(fmaincfg.readline().rstrip()))

while True:
    for arduino in arduinos:
        data = arduino.read()
        db.insert(data, arduino.name)
    time.sleep(3)
Exemple #9
0
import sys
import time
import Arduino

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('localhost', 10000)
print('starting up on ', server_address)
sock.bind(server_address)

# Listen for incoming connections
sock.listen(10)

ser = Arduino.openSerial()
if (ser == 'X'):
    exit

while True:
    try:
        # Wait for a connection
        print('waiting for a connection')
        connection, client_address = sock.accept()

        print('connection from ', client_address)

        data = connection.recv(1)
        print('received from client:' + str(ord(data.decode())))
        Arduino.writeSerial(ser, data)
        time.sleep(.2)
'''
Created on Mar 4, 2020

@author: Collin Bradford for PERCS
'''

import Arduino
import Run
import time
from DataLogger import DataLogger

COM_PORT = "COM4"
BAUD_RATE = 115200

mainBoard = Arduino.Arduino(COM_PORT, BAUD_RATE)
mainBoard.printConnectionInformaion()

print()
print("Starting tests...")
print()

print("Setting sample size to 6")
mainBoard.setChannelCount(6)
print("Sample size set. Message from board: " + mainBoard.readLine())

print("Setting sample frequency to 50")
mainBoard.setSampleFrequency(50)
print("Sample frequency set. Message from board: " + mainBoard.readLine())

print("Setting sample average size to 1")
mainBoard.setSampleAverageSize(1)
Exemple #11
0
# test script for Recognition
import Arduino
import kairos_face
kairos_face.settings.app_id = "1efff1b3"
kairos_face.settings.app_key = "95817e68b6633112a23d0589b76a73f1"
try:
    recog = kairos_face.recognize_face(file="lastface.jpg",
                                       gallery_name="whitelist")
    print('Found in gallery')
    try:
        found = recog['images'][0]['transaction']['status']
        person = recog['images'][0]['transaction']['subject_id']
        confidence = recog['images'][0]['transaction']['confidence']
        print(found)
        print("The person is " + person + " with %d percent confidence." %
              (confidence * 100))
        if confidence >= 0.65:
            try:
                Arduino.openDoor()
            except Arduino.SerialError:
                print "Unable to open door!"
    except ValueError:
        err = recog['Errors']
        print("the following errors were recieved -")
        for i in err:
            print i
except kairos_face.exceptions.ServiceRequestError:
    print('gallery not found')
except:
    print('ERROR!!')
Exemple #12
0
import time
import Arduino

    
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('localhost', 10000)
print('starting up on ', server_address)
sock.bind(server_address)

# Listen for incoming connections
sock.listen(10)

ser = Arduino.openSerial()
if( ser == 'X'):
    exit


while True:
    try:
      # Wait for a connection
      print('waiting for a connection')
      connection, client_address = sock.accept()
      
      print('connection from ', client_address)

      data = connection.recv(1)
      print('received from client:' + str(ord(data.decode())))
      Arduino.writeSerial(ser,data)
Exemple #13
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        self.voice = voiceRecognition()
        self.arduinoDisponible = False
        self._ConexionArduino()

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 801, 561))
        self.label.setStyleSheet("background:rgb(40, 40, 40)")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(0, 0, 271, 560))
        self.label_2.setStyleSheet("background:rgb(89, 89, 89)")
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QtCore.QRect(10, 10, 256, 196))
        self.graphicsView.setObjectName("graphicsView")
        self.btnReconocerVoz = QtWidgets.QPushButton(self.centralwidget)
        self.btnReconocerVoz.setGeometry(QtCore.QRect(10, 220, 251, 51))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.btnReconocerVoz.setFont(font)
        self.btnReconocerVoz.setObjectName("btnReconocerVoz")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(20, 310, 91, 101))
        self.label_3.setObjectName("label_3")
        self.label_3.setStyleSheet("border-image: url(ui/luzEner.jpg);")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(20, 420, 91, 101))
        self.label_4.setObjectName("label_4")
        self.label_4.setStyleSheet("border-image: url(ui/ventEner.jpg);")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(130, 350, 101, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_5.setFont(font)
        self.label_5.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(130, 450, 101, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_6.setFont(font)
        self.label_6.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_6.setObjectName("label_6")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(440, 30, 191, 51))
        font = QtGui.QFont()
        font.setPointSize(22)
        self.label_7.setFont(font)
        self.label_7.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_7.setObjectName("label_7")
        self.label_8 = QtWidgets.QLabel(self.centralwidget)
        self.label_8.setGeometry(QtCore.QRect(300, 110, 201, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_8.setFont(font)
        self.label_8.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_8.setObjectName("label_8")
        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setGeometry(QtCore.QRect(570, 110, 201, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_9.setFont(font)
        self.label_9.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_9.setObjectName("label_9")
        self.label_10 = QtWidgets.QLabel(self.centralwidget)
        self.label_10.setGeometry(QtCore.QRect(280, 330, 241, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_10.setFont(font)
        self.label_10.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_10.setObjectName("label_10")
        self.label_11 = QtWidgets.QLabel(self.centralwidget)
        self.label_11.setGeometry(QtCore.QRect(550, 330, 241, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_11.setFont(font)
        self.label_11.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_11.setObjectName("label_11")
        self.labelLucesHab1 = QtWidgets.QLabel(self.centralwidget)
        self.labelLucesHab1.setGeometry(QtCore.QRect(300, 170, 191, 151))
        self.labelLucesHab1.setText("")
        self.labelLucesHab1.setObjectName("labelLucesHab1")
        self.labelLucesHab2 = QtWidgets.QLabel(self.centralwidget)
        self.labelLucesHab2.setGeometry(QtCore.QRect(570, 170, 191, 151))
        self.labelLucesHab2.setText("")
        self.labelLucesHab1.setStyleSheet(
            "border-image: url(ui/bombApagado.jpg);")
        self.labelLucesHab2.setObjectName("labelLucesHab2")
        self.labelLucesHab2.setStyleSheet(
            "border-image: url(ui/fueraServ.jpg);")
        self.labelVentiladorHab1 = QtWidgets.QLabel(self.centralwidget)
        self.labelVentiladorHab1.setGeometry(QtCore.QRect(290, 380, 191, 151))
        self.labelVentiladorHab1.setText("")
        self.labelVentiladorHab1.setStyleSheet(
            "border-image: url(ui/ventiladorAp.jpg);")
        self.labelVentiladorHab1.setObjectName("labelVentiladorHab1")
        self.labelVentiladorHab2 = QtWidgets.QLabel(self.centralwidget)
        self.labelVentiladorHab2.setGeometry(QtCore.QRect(570, 380, 191, 151))
        self.labelVentiladorHab2.setText("")
        self.labelVentiladorHab2.setObjectName("labelVentiladorHab2")
        self.labelVentiladorHab2.setStyleSheet(
            "border-image: url(ui/fueraServ.jpg);")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.btnReconocerVoz.clicked.connect(self._ReconocerVoz)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.word = None
        self.s = socket.socket()
        self.s.connect(("localhost", 6000))

    def setWord(self, word):
        self.word = word
        if (self.word != "Acabo"):
            print(self.word)
            self.accion()

    def _ConexionArduino(self):
        try:
            if (not self.arduinoDisponible):
                self.arduino = Arduino("COM3", 9600)
                self.arduinoDisponible = True
        except:
            self.arduinoDisponible = False
            Speech("No esta conectado el Arduino").speech()

    def _ReconocerVoz(self):
        self._ConexionArduino()
        if (self.arduinoDisponible == True
                and self.arduino.RevisarConexionArduino() == True):
            VoiceThread(voiceRecognition(), self).start()
        else:
            Speech("No esta conectado el Arduino").speech()

    def accion(self):
        self._ConexionArduino()
        if (self.arduinoDisponible == True
                and self.arduino.RevisarConexionArduino() == True):
            imagevoicethread = VoiceRecordImage(self.graphicsView)
            imagevoicethread.start()
            self.s.send(self.word.encode("utf-8"))
            indice = int(self.s.recv(1024).decode("utf-8"))
            print("este es el indice", type(indice))
            if (indice >= 0):
                if (indice <= 1):
                    if (indice % 2 == 0):
                        self.arduino.EnviarDatos('L')
                        self.labelLucesHab1.setStyleSheet(
                            "border-image: url(ui/luzPrendida.jpg);")
                    else:
                        self.arduino.EnviarDatos('l')
                        self.labelLucesHab1.setStyleSheet(
                            "border-image: url(ui/bombApagado.jpg);")
                else:
                    if (indice % 2 == 0):
                        self.arduino.EnviarDatos('V')
                        self.labelVentiladorHab1.setStyleSheet(
                            "border-image: url(ui/ventiladorEncen.gif);")
                    else:
                        self.arduino.EnviarDatos('v')
                        self.labelVentiladorHab1.setStyleSheet(
                            "border-image: url(ui/ventiladorAp.jpg);")

        else:
            msg = QMessageBox()
            msg.setText("Verifique la conexión con el Arduino!!")
            msg.setWindowTitle("Mensaje")
            msg.exec()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.btnReconocerVoz.setText(_translate("MainWindow", "Reconocer Voz"))
        self.label_3.setText(_translate("MainWindow", ""))
        self.label_4.setText(_translate("MainWindow", ""))
        self.label_5.setText(_translate("MainWindow", "Luces"))
        self.label_6.setText(_translate("MainWindow", "Ventilador"))
        self.label_7.setText(_translate("MainWindow", "Primer Piso"))
        self.label_8.setText(_translate("MainWindow", "Luces Habitación 1"))
        self.label_9.setText(_translate("MainWindow", "Luces Habitación 2"))
        self.label_10.setText(
            _translate("MainWindow", "Ventilador Habitación 1"))
        self.label_11.setText(
            _translate("MainWindow", "Ventilador Habitación 2"))
Exemple #14
0
  Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""

from __future__ import division  # so that 1/3=0.333 instead of 1/3=0
from psychopy import visual, core, data, event, logging, sound, gui, hardware
from psychopy.constants import *  # things like STARTED, FINISHED
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import serial
from Arduino import *  #lukas

#kamil =====================================

arduino = Arduino()
try:
    arduino.connect()
except Exception as ex:
    print('vyjimka pri arduino.connect')
#arduino.blink()

sumascore = 0
#soucet score pro vypocet prumeru #kamil 25.1.2016
sumart = 0
#soucet reakcnich casu pro vypocet prumeru
pokusy = 0
#pocet zapocitanych trials
vynechanych = 0
#pocet nezmacknutych klaves = (trials bez zmacknute klavesy)
stlaceno = -1
from tkinter import ttk  #导入内部包
'''
    本实例演示了每秒从Arduino读取温度和湿度信息,写入Sqlite数据库dhtinfo表
    同时提供了在Treeview中显示最新数据的功能
    如果需要导出到Excel表中,请调用writeExcel函数
'''

id = 0
records = []

DBPath = 'DB.db'
timer = None
#cu= conn.cursor()

#IP地址和端口两个参数,需根据WIFI扩展板的实际IP和端口重新设置
arduino = Arduino.Arduino("192.168.1.200", 5000)


def timerfun():
    global id
    now = time.asctime(time.localtime(time.time()))
    if (vT.get() == 1):  #是否打钩
        temp = arduino.sendMessage('Temp', 0, 0)
        record = ['Temp', int(temp[3]), now]
        print(record)
        records.append(record)
        id += 1
    if (vH.get() == 1):  #是否打钩
        hum = arduino.sendMessage('Hum', 0, 0)
        record = ['Hum', int(hum[3]), now]
        print(record)
Exemple #16
0
def command(choice, usuario):
    id_pessoa = -1

    if choice == 1:
        id_pessoa = fazer_login(usuario)
        if id_pessoa != -1:
            print("Login Realizado Com Sucesso")
        else:
            print("Usuario Não Encontrado, Favor Realizar Cadastro")
        return id_pessoa
    elif choice == 2:
        arduinoUtil = Arduino()
        arduinoUtil.connectArduino()
        measuresData = arduinoUtil.readMeasures()
        humAir, tempAir, lum, humSoil = (measuresData.split(';'))
        if usuario == -1:
            print("Realize Login Para Continuar")
            return -1
        id_local = (
            input("Qual O Código Do Local Onde Está Sendo Feita A Medição? "))
        status = realizar_medida(tempAir, humAir, humSoil, lum, usuario,
                                 id_local)
        if status != -1:
            print("Medidas Inseridas Com Sucesso")
        else:
            print("Ocorreu Um Erro")
    elif choice == 3:
        id_pessoa = cadastrar_usuario()
        if id_pessoa != -1:
            print("Cadastro Realizado Com Sucesso")
        else:
            print("Ocorreu Um Erro")
        print("Seu Código De Usuário É: %s" % id_pessoa)
        return id_pessoa
    elif choice == 4:
        id_pessoa = atualizar_usuario()
        if id_pessoa != -1:
            print("Atualização Realizada Com Sucesso")
        else:
            print("Ocorreu Um Erro")
        return id_pessoa
    elif choice == 5:
        if usuario == -1:
            print("Realize Login Para Continuar")
            return -1
        id_local = cadastrar_local(usuario)
        if id_local != -1:
            print("Cadastro Realizado Com Sucesso")
        else:
            print("Ocorreu Um Erro")
        print("O Código Do Local É: %s" % id_local)
    elif choice == 6:
        if usuario == -1:
            print("Realize Login Para Continuar")
            return -1
        id_local = atualizar_local(usuario)
        if id_local != -1:
            print("Atualização Realizada Com Sucesso")
        else:
            print("Ocorreu Um Erro")
    elif choice == 7:
        if usuario == -1:
            print("Realize Login Para Continuar")
            return -1
        id_medida = (input("Qual O Código Do Medição A Ser Excluida? "))
        id_local = (input("Qual O Código Do Local Onde Foi Feita A Medição? "))
        status = excluir_medida(id_medida, usuario, id_local)
        if status != -1:
            print("Medida Excluida Com Sucesso")
        else:
            print("Ocorreu Um Erro")
    else:
        print('Comando Não Cadastrado')

    return id_pessoa
Exemple #17
0
def stop_it() :    
    Arduino.open(Arduino_Port)
    Arduino._serial_cmd(Arduino._Commands["speed"], 0)
    Arduino._serial_cmd(Arduino._Commands["steer"], 0)
"""

from __future__ import division  # so that 1/3=0.333 instead of 1/3=0
from psychopy import visual, core, data, event, logging, sound, gui
from psychopy.constants import *  # things like STARTED, FINISHED
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import serial
from Arduino import *  #lukas

#verze z 2.10.2014
# aby mi fungovalo strobe off i bez odpovedi, musel jsem vrati ISI 0.1 s po krizku

arduino = Arduino()
arduino.connect()
print arduino.is_open()
arduino.blink()
arduino_up = False
#status, jestli posledni puls nahoru

blokcislo = 0
ovocebylo = 0
ovocenalezeno = 0
reakcecas = 0
chciklavesu_default = 1
#jestli budu vyzadovat klavesy
chciklavesu = chciklavesu_default

# Store info about the experiment session
Exemple #19
0
    def __init__(self):
        self.board = Arduino("115200", port="/dev/tty.usbmodem142301")

        self.board.pinMode(13, "OUTPUT")
 def __init__(self, token):
     super(TelegramTutorial, self).__init__(token)
     self.serial = Arduino.start_communication()
Exemple #21
0
from Arduino import *

ar = Arduino("COM4")

ar.output([], [9])
ar.servoWrite(9, 180)
Exemple #22
0
def Execute(command) :
    global Command_Running, Current_Command, Command_Start
    global Delay_Time
    global Distance
    global Start_Lat, Start_Long
    global Turn_Delta_Angle, _degrees, turn_active
    global Turn_To_Angle, Turn_To_Direction
    global have_direction
    global heading_direction
    global Speed_Setting, accel_setting, SPEED_TERMINATE, _adjust_speed
    global _course_set

    command = command.strip();
    command = command.rstrip(';')
    parm = command.split(',')
    writeLog(LOG_NEW_COMMAND, parm)

    if not parm[0] in _Commands :
        writeLog(LOG_ERROR, "Unknown Command... Skipping");
        return
    
    Current_Command = parm[0]
    Command_Running = True
    Command_Start = time.time()

    if parm[0] == 'sstop' :
        Arduino._serial_cmd(Arduino._Commands["speed"], 0)
        Delay_Time = 5
    # hstop with arg of 1 applys brake, 0 release brakes
    elif parm[0] == 'hstop' :
        Arduino._serial_cmd(Arduino._Commands["speed"], 0)
        Arduino._serial_cmd(Arduino._Commands["brake"], parm[1])
        Delay_Time = 10
    #A turnto command can not be called as the first command or after a delay
    #as the GPS.Direction has to be set before the commands execute stage.
    elif parm[0] == 'turnto' : #format "turnto,compass_heading,turning_left_or_right;"
        try :
            if GPS.Direction == GPS.invalid_Direction :
                writeLog(LOG_ERROR, "Command turnto failed... must have a valid direction")
                Command_Running = False
                return
            Turn_To_Angle = int(parm[1])
            if parm[2] == 'right' :
                writeLog(LOG_DETAILS, "Turning Right")
                Arduino._serial_cmd(Arduino._Commands["steer"], _degrees*1.825)
            elif parm[2] == 'left' :
                writeLog(LOG_DETAILS, "Turning Left")
                Arduino._serial_cmd(Arduino._Commands["steer"], -_degrees*1.825)
            else :
                writeLog(LOG_ERROR, "Unknown turnto Direction... Skipping");
                Turn_To_Angle = 0
                Command_Running = False
                return
            if Arduino.Speed == 0 :
                Arduino._serial_cmd(Arduino._Commands["speed"], accel_setting)
                turn_active = True
            if GPS.Direction != 0 :
                have_direction = True
            Turn_To_Direction = parm[2]
            Arduino._serial_cmd(Arduino._Commands["speed"], accel_setting)
        except ValueError :
            Turn_To_Angle = 0
            Command_Running = False
            writeLog(LOG_ERROR, "Command turnto failed... Conversion fail");
    #A turndelta command can not be called as the first command or after a delay
    #as the GPS.Direction has to be set before the commands execute stage.
    #Formats turndelta parmaters into a turnto call and calls execute again
    elif parm[0] == 'turndelta' :
        try :
            if GPS.Direction == GPS.invalid_Direction :
                writeLog(LOG_ERROR, "Command turndelta failed... must have a valid direction")
                Command_Running = False
                return
            turn_direction = ''
            Turn_Delta_Angle = int(parm[1])
            delta_heading = GPS.Direction + Turn_Delta_Angle
            delta_heading = int(delta_heading)
            if delta_heading < 0 :
                delta_heading = 360 + delta_heading
            if delta_heading > 360 :
                delta_heading = delta_heading - 360
            if Turn_Delta_Angle > 0 :
                turn_direction = 'right'
            elif Turn_Delta_Angle < 0 :
                turn_direction = 'left'
            Execute('turnto,'+str(delta_heading)+','+turn_direction+';')           
        except ValueError :
            Turn_Delta_Angle = 0
            Command_Running = False
            writeLog(LOG_ERROR, "Command turndelta failed... Conversion fail");
    elif parm[0] == 'forward' :
        try :
            Distance = int(parm[1])
            Start_Lat = GPS.Latitude
            Start_Long = GPS.Longitude
            Arduino._serial_cmd(Arduino._Commands["speed"], accel_setting) #starts the golf cart moving
        except ValueError :
            Distance = 0
            Command_Running = False
            logWrite(LOG_ERROR, "Command forward failed... Conversion fail");
    elif parm[0] == 'heading' :
        try :
            Distance = int(parm[1])
            '''if GPS.Direction != GPS.invalid_Direction :
                have_direction = True
                heading_direction = GPS.Direction'''
            Start_Lat = GPS.Latitude
            Start_Long = GPS.Longitude
            Arduino._serial_cmd(Arduino._Commands["speed"], accel_setting) #starts the golf cart moving
        except ValueError :
            Distance = 0
            Command_Running = False
            writeLog(LOG_ERROR, "Command heading failed... Conversion fail")
    elif parm[0] == 'course' :
        try :
            Distance = int(parm[1])
            heading_direction = int(parm[2])
            if heading_direction > 360 or heading_direction < 0 :
                writeLog(LOG_ERROR, "Command course failed... direction not between 0 and 360")
                return
            _course_set = True
            Arduino._serial_cmd(Arduino._Commands["speed"], accel_setting) #starts the golf cart moving
        except ValueError :
            Distance = 0
            Command_Running = False
            _course_set = False
            logWrite(LOG_ERROR, "Command course failed... Conversion fail")
    elif parm[0] == 'speed' :
        try :
            Speed_Setting = float(parm[1])
            if Speed_Setting == SPEED_TERMINATE : #terminate control speed command
                _adjust_speed = False
                accel_setting = 1700
                Speed_Setting = 0
                return
            _adjust_speed = True
            #Arduino._serial_cmd(Arduino._Commands["speed"], Speed_Setting) #starts the golf cart moving
            accel_setting = Speed_Setting
            writeLog(LOG_DETAILS, "Set Speed to : " + repr(Speed_Setting))
        except:
            Speed_Setting = 0
            _adjust_speed = False
            writeLog(LOG_ERROR, "Command speed failed... Conversion fail")
    elif parm[0] == 'delay' :
        Delay_Time = int(parm[1])
    else :
        writeLog(LOG_ERROR, 'Unrecognized command')
        Command_Running = False
Exemple #23
0
import time
import json
from Arduino import *
from Database import *

with open('config/db.json') as data_file:
    dbCfg = json.load(data_file)
db = Database(dbCfg)

with open('config/main.json') as data_file:
    cfg = json.load(data_file)

if len(cfg['Arduinos']) > 4:
    raise ValueError('One RPI supports 4 Arduino at max;' +
                     str(len(cfg['Arduinos'])) + 'is provided')

arduinos = [Arduino(a) for a in cfg['Arduinos']]

while True:
    for arduino in arduinos:
        data = arduino.read()
        db.insert(data, arduino.name)
    time.sleep(3)
Exemple #24
0
from log import *
import GPS
import Arduino
import Server

url = 'http://157.182.184.52/~agc/command.php'
# GPS_Port = 'COM17'
GPS_Port = '/dev/ttyUSB0'
# Arduino_Port = 'COM6'
Arduino_Port = '/dev/ttyACM0'

def  poll():
    Server.Ping()
    GPS.Check()
    Arduino.Check()
    time.sleep(0.55)

# Ping the server once to get current Sequence
writeLog(LOG_ALWAYS, 'AGC Startup')
Server.open(url)
Arduino.open(Arduino_Port)
GPS.open(GPS_Port)

while(1):
    poll()
Exemple #25
0
 def __init__(self, token):
     super(TelegramBot, self).__init__(token)
     self.serial = Arduino.start_communication()
Exemple #26
0
import sys
from Arduino import *


port = 1234
server = None

# create server
try:
    server = liblo.Server(1234)
except liblo.ServerError, err:
    print str(err)
    sys.exit()


arduino = Arduino("/dev/ttyACM0")
arduino.init()


def updateNumber(path,number):
     print "number",number
     arduino.send("U"+str(number[0]))

def fallback(path, args, types, src):
    print "got unknown message '%s' from '%s'" % (path, src.url)
    for a, t in zip(args, types):
        print "argument of type '%s': %s" % (t, a)

server.add_method("/update", 'i', updateNumber)
server.add_method(None, None, fallback)
Exemple #27
0
    #               data      - the actual numeric float value of the reading
    # Example:
    #          ["HWT", 13123131231, 0.30]
    #
    queueMqttPub = Queue()

    # Setup Mqtt client thread
    mqtt_client = mqtt.mqtt(cfg,
                            publish_queue=queueMqttPub,
                            on_msg_queue=queueToArduino)
    mqtt_client.daemon = True
    mqtt_client.start()

    # setup Arduino thread
    arduino = Arduino.Arduino(cfg,
                              queueFromArduino=queueReadings,
                              queueToArduino=queueToArduino)

    # setup calculation thread
    threadCalc = Calc.Calc(cfg,
                           queueReadings=queueReadings,
                           queueResults=queueDB,
                           broadcast_queue=queueMqttPub)
    threadCalc.daemon = True
    threadCalc.start()

    # setup database thread
    updateDB = DB.UpdateDB(cfg, queueResults=queueDB)
    updateDB.daemon = True
    updateDB.start()