Beispiel #1
0
def robotSetup():
    try:
        connection = SerialManager()
        a = ArduinoApi(connection = connection)
    except:
        print("Failed to connect to Arduino")
        sys.exit()

    a.pinMode(STDBY1, a.OUTPUT)
    a.pinMode(STDBY2, a.OUTPUT)

    FR = Motor(AI1, AI2, APWM)
    FR.setupMotor(a)

    BR = Motor(BI1, BI2, BPWM)
    BR.setupMotor(a)

    FL = Motor(CI1, CI2, CPWM)
    FL.setupMotor(a)

    BL = Motor(DI1, DI2, DPWM)
    BL.setupMotor(a)

    a.digitalWrite(STDBY1, a.HIGH)
    a.digitalWrite(STDBY2, a.HIGH)
    
    robot = Robot(FR, BR, FL, BL, a)

    return robot
Beispiel #2
0
def connect(request):
    try:
        connection = SerialManager()
        a = ArduinoApi(connection = connection)
        ledState = a.LOW

        if request.method == 'POST':
            connect = request.POST.get('connect')
            if connect == 'on':
                value = True
                status = True
                ledState = a.HIGH
            else:
                value = False
                status = False
                ledState = a.LOW

            Bulb.objects.all().update(connect=value, status=status)
            bulbs = Bulb.objects.all()
            for bulb in bulbs:
                ledPin = bulb.port_connect
                ledPin1 = bulb.port
                a.pinMode(ledPin, a.OUTPUT)
                a.pinMode(ledPin1, a.OUTPUT)
                a.digitalWrite(ledPin, ledState)
                a.digitalWrite(ledPin1, ledState)
        return redirect('/bulbs')
    except:
        return redirect('/error/103')
class SmartHomeIntentHandler():
    EQUIPMENTS = ["light", "fan"]
    EQUIPMENT_TO_PIN_MAP = {
        "fan": 8,
        "lights": 7,
        "light": 7
    }

    def __init__(self, intent):
        self.intent = intent
        if Util.is_system_mac():
            return

        # initialize raspberry pi
        connection = SerialManager(device='/dev/ttyACM0')
        self.arduino_conn = ArduinoApi(connection=connection)
        self.equipment = self.intent["EquipmentKeyword"]
        self.state = self.intent["OnOffKeyword"]

    def get_pin(self):
        return self.EQUIPMENT_TO_PIN_MAP[self.equipment]

    def handle(self):
        print(self.equipment)
        print(self.state)
        if Util.is_system_mac():
            return

        pin = self.get_pin()
        state_to_set = self.arduino_conn.LOW if self.state == "on" else self.arduino_conn.HIGH  # NoQA

        self.arduino_conn.pinMode(pin, self.arduino_conn.OUTPUT)
        self.arduino_conn.digitalWrite(pin, state_to_set)
Beispiel #4
0
 def off(self):
     threading.Thread(target=self.alert.ledOff).start()
     if self.boardID == 2:  # Board is Raspberry Pi
         try:
             GPIO.output(int(self.pin), True)
             notify = "{}-{} Off".format(self.appliance, self.device_name)
             notifyLCD = "{}".format(self.device_name)
             print(notify)
             self.updateState(0)
             self.alert.display2(notifyLCD, "Off")
             return True
         except Exception as e:
             print("Process Raspberry Pi failed {}".format(str(e)))
             return False
     elif self.boardID == 1:  # Board is Arduino
         try:
             conn = SerialManager()
             a = ArduinoApi(conn)
             a.pinMode(int(self.pin), a.OUTPUT)
             a.digitalWrite(int(self.pin), a.HIGH)
             notify = "{}-{} Off".format(self.appliance, self.device_name)
             notifyLCD = "{}".format(self.device_name)
             print(notify)
             self.updateState(0)
             self.alert.display2(notifyLCD, "Off")
             return True
         except Exception as e:
             print("Failed to connect to Arduino {}".format(str(e)))
             return False
Beispiel #5
0
def main():
    try:
        connection = SerialManager()
        a = ArduinoApi(connection=connection)
        m = Measure(connection=connection)
    except:
        print("Faild to connect to Arduino Firas")

    # setup the pinMode as is we were in the arduino IDE

    a.pinMode(2, a.OUTPUT)
    a.pinMode(3, a.OUTPUT)
    a.pinMode(4, a.OUTPUT)
    a.pinMode(5, a.OUTPUT)

    try:
        while True:
            forward(a)
            if distance(m, 6, 7) < 30:
                print("right")
                reverse(a)
                right(a)
            elif distance(m, 8, 9) < 30:
                print("left")
                reverse(a)
                left(a)

    except:
        print("Faild2 ")
        a.digitalWrite(2, a.LOW)
        a.digitalWrite(3, a.LOW)
        a.digitalWrite(4, a.LOW)
        a.digitalWrite(5, a.LOW)
Beispiel #6
0
def checked(request, id):
    bulb = Bulb.objects.get(pk=id)
    port = bulb.port
    ledPin = port
    try:
        connection = SerialManager()
        a = ArduinoApi(connection = connection)
        a.pinMode(ledPin, a.OUTPUT)
        ledState = a.LOW
        if request.method == 'POST':
            status = request.POST.get('status')
            if status == 'on':
                ledState = a.HIGH
                status = True
            else:
                ledState = a.LOW
                status = False

            Bulb.objects.select_related().filter(pk=id).update(status=status)
            a.digitalWrite(ledPin, ledState)
        return redirect('/bulbs')
    except:
        return redirect('/error/103')
Beispiel #7
0
class Motor():
  # Works as setup()
  def __init__(self, device):
    self.devicePath = device
    self.connection = SerialManager(device=self.devicePath)
    self.arduino = ArduinoApi(connection=self.connection)
    self.RPM1 = 100
    self.RPM2 = 100
    self.RPM3 = 100

    # Motor pins
    self.dir1=7
    self.pwm1=6

    self.dir2=12
    self.pwm2=9

    self.dir3=13
    self.pwm3=11

    # Setup pinmodes
    self.arduino.pinMode(self.dir1, self.arduino.OUTPUT)
    self.arduino.pinMode(self.pwm1, self.arduino.OUTPUT)
    self.arduino.pinMode(self.dir2, self.arduino.OUTPUT)
    self.arduino.pinMode(self.pwm2, self.arduino.OUTPUT)
    self.arduino.pinMode(self.dir3, self.arduino.OUTPUT)
    self.arduino.pinMode(self.pwm3, self.arduino.OUTPUT)
    
  def moveMotor(self, direction):
    if direction=='u':
      self.upMotor()
    elif direction=='d':
      self.downMotor()
    elif direction=='o':
      self.openMotor()
    elif direction=='c':
      self.closeMotor()
   # elif direction=='x':
    #  exit()
  def upMotor(self):
    self.arduino.digitalWrite(self.dir1, self.arduino.HIGH)
    self.arduino.digitalWrite(self.dir2, self.arduino.HIGH)
    
    self.arduino.analogWrite(self.pwm1, self.RPM1)
    self.arduino.analogWrite(self.pwm2, self.RPM1)
    time.sleep(1)
    self.arduino.analogWrite(self.pwm1, 0)
    self.arduino.analogWrite(self.pwm2, 0)

  def downMotor(self):
    self.arduino.digitalWrite(self.dir1, self.arduino.LOW)
    self.arduino.digitalWrite(self.dir2, self.arduino.LOW)
    self.arduino.analogWrite(self.pwm1, self.RPM1)
    self.arduino.analogWrite(self.pwm2, self.RPM2)
    time.sleep(1)
    self.arduino.analogWrite(self.pwm1, 0)
    self.arduino.analogWrite(self.pwm2, 0)


  def openMotor(self):
    self.arduino.digitalWrite(self.dir3, self.arduino.HIGH)
    self.arduino.analogWrite(self.pwm3, self.RPM3)
    time.sleep(1)
    self.arduino.analogWrite(self.pwm3, 0)

  def closeMotor(self):
    self.arduino.digitalWrite(self.dir3, self.arduino.LOW)
    self.arduino.analogWrite(self.pwm3, self.RPM3)
    time.sleep(1)
    self.arduino.analogWrite(self.pwm3, 0)
Beispiel #8
0
from nanpy import (ArduinoApi, SerialManager)
from time import sleep

connection = SerialManager()
a = ArduinoApi(connection = connection)

a.pinMode(4, a.OUTPUT)

while True:
	serial = raw_input("Enter :")
	if serial == "1":
		print ("Led is ON")
		a.digitalWrite(4, a.HIGH)
	elif serial == "0":
		print ("Led is OFF")
		a.digitalWrite(4, a.LOW)
# R = 100 k  et C = 4,7 µF

from nanpy import ArduinoApi           # Gestion Arduino
from nanpy import SerialManager        # Gestion port série
from time import sleep 
import matplotlib.pyplot as plt        # Gestion du tracé de courbe

port = SerialManager(device='/dev/ttyACM0')     # Sélection du port série (exemple : device = 'COM6')
uno = ArduinoApi(connection=port)               # Déclaration de la carte Arduino

uno.pinMode(8, uno.OUTPUT)      # Paramétrage de la broche 8 en sortie
x = []                          # Abscisse
y = []                          # Ordonnée

# Décharge du condensateur avant les mesures
uno.digitalWrite(8,0)           # Broche 8 à OV
sleep(2)                        # pendant 2 s

# Début de la charge du condensateur
uno.digitalWrite(8,1)           # Broche 8 à 5V   
for i in range(40):             # Boucle pour les mesures
    x.append(i)                 # Remplissage de x
    y.append(uno.analogRead(0)) # Mesure sur A0 et remplissage de y
    sleep(0.05)                 # Temporisation
    
# Décharge du condesateur après mesures
uno.digitalWrite(8,0)           # Broche 8 à 0V  

port.close()                    # Fermeture du port série

# Tracé de la courbe
Beispiel #10
0
        connection = SerialManager(device='/dev/ttyACM0')
        arduino = ArduinoApi(connection=connection)
    except:
        try:
            connection = SerialManager(device='/dev/ttyACM1')
            arduino = ArduinoApi(connection=connection)
        except:
            try:
                connection = SerialManager(device='/dev/ttyACM3')
                arduino = ArduinoApi(connection=connection)
            except:
                print "Could not connect to the arduino using /dev/ttyACM0, /dev/ttyACM1, /dev/ttyACM2 or /dev/ttyACM3"

arduino.pinMode(13, arduino.OUTPUT)
arduino.pinMode(8, arduino.OUTPUT)
arduino.digitalWrite(13,1)
arduino.digitalWrite(8,0)

time.sleep(3)



cap1 = cv2.VideoCapture(1)
cap2 = cv2.VideoCapture(0)

#enter = raw_input("To take left picture, press enter.")
_, imgL = cap1.read()
imgL = cv2.resize(imgL,(320,240))
#enter = raw_input("To take right picture 2, press enter")
_, imgR = cap2.read()
imgR = cv2.resize(imgR,(320,240))
Beispiel #11
0
from nanpy import (ArduinoApi, SerialManager)
from time import sleep

connection = SerialManager()
ard = ArduinoApi(connection = connection)

db = MySQLdb.connect("localhost", "root", "elect1", "SensorData")
curs=db.cursor()


ard.pinMode (13, ard.OUTPUT)

for i in range(10000):
	ard.digitalWrite(13, (i+1) % 2)
	sleep(0.2)
Beispiel #12
0
ledStat = False
btnstat = 0

try:
    connection = serialManager()
    a = ArduinoApi(connection=connection)
except:
    print("fail to connect to ardinno")

# Setup t
a.pinMode(ledPin, a.OUTPUT)
a.pinMode(btnPin, a.INPUT)

try:
    while True:
        btnStat - a.digitalRead(btnPin)
        print("btn state is : {}".format(btnStat))
        if btnStat:
            if ledStat:
                a.digitalWrite(ledPin, a.LOW)
                ledstat = False
                print("leeed offff")
                sleep(1)
            else:
                a.digitalWrite(ledPin, a.HIGH)
                ledState = True
                print("leeed onnnn")
                sleep(1)
except:
    a.digitalWrite(ledPin, a.LOW)
# startTime is how long from program initation until it should start (this is a holdover from the C code, since the RasPi should be able to do all the clockwork on its own. I may change this eventually)
startTime = 0
duration = 1200 #20 minutes
endOfDays = startTime + duration
# Frequency for each light, organized as an array. The first entry corresponds to the "first" set of lights
freq = [5,0,5,0]
shuffle = [1, 0, 3, 2]
# Similar for pulse width (except this is in milliseconds)
pulseWidth = [5,0,5,0]
flipTime = 600 # 10 minutes
flip = True
hasStarted = False
# This is like the void setup() method in C
for pin in range(pinStart,pinEnd):
    a.pinMode(pin, a.OUTPUT)
    a.digitalWrite(pin,a.HIGH)
a.pinMode(indicator,a.OUTPUT)

# Define the process by which lights flick on and off
# number = pin number
# freq = frequency for that pin (in Hz)
# width = duration of a single flash
# cycles = number of times you want to repeat this
def flashLights(number, freq, width, cycles):
    if not freq == 0:
        for i in range(0,cycles):
            a.digitalWrite(number,a.LOW)
	    t_ = time.time()
#            wp.delay( float(width/timescale) )
	    wp.delayMicroseconds( 1000*(width/timescale) )
            a.digitalWrite(number,a.HIGH)
Beispiel #14
0
event_id = settings.get('Instapush', 'INSTAPUSH_EVENT_NAME')
threshold = settings.getfloat('Fridge', 'THRESHOLD')
notify_every_x_seconds = settings.getfloat('Fridge', 'NOTIFY_EVERY_X_SECONDS')
write_log_every_x_measurements = 50

# Startup arduino connection
connection = SerialManager(device=device)
connection.open()
arduino = ArduinoApi(connection=connection)
temperature_sensors = DallasTemperature(connection=connection, pin=pin_temp)
temperature_sensors.setResolution(12)


# Mute sound by default
arduino.pinMode(pin_sound, arduino.OUTPUT)
arduino.digitalWrite(pin_sound, 0)

# Initial values
last_alert = time.time()
threshold_reached = False
write_log_counter = 0

while True:
    temperature_sensors.requestTemperatures()
    temp = temperature_sensors.getTempC(0)  # Fetches the temperature on the first DS18B20 found on the pin.

    print temp

    if temp < -100 or temp == 0:
        # Bad reading, lets skip this result.
        continue
Beispiel #15
0
#a.pinMode(13, a.OUTPUT)
#a.digitalWrite(13, a.HIGH)
#while True:≈
#a.digitalWrite(13, a.HIGH)
#time.sleep(0.01)
#a.digitalWrite(13, a.LOW)
#time.sleep(0.01)

a.pinMode(IN1, a.OUTPUT)
a.pinMode(IN2, a.OUTPUT)
a.pinMode(IN3, a.OUTPUT)
a.pinMode(IN4, a.OUTPUT)
a.pinMode(ENA, a.OUTPUT)
a.pinMode(ENB, a.OUTPUT)
a.digitalWrite(ENA, a.HIGH)
a.digitalWrite(ENB, a.HIGH)

while True:
    #a.digitalWrite(13, a.HIGH)
    #time.sleep(1)
    #a.digitalWrite(13, a.LOW)
    #time.sleep(1)
    a.digitalWrite(IN1, a.LOW)
    a.digitalWrite(IN2, a.HIGH)  # left wheel goes forward
    a.digitalWrite(IN3, a.LOW)
    a.digitalWrite(IN4, a.HIGH)  # right wheel goes forward
    time.sleep(0.5)
    a.digitalWrite(IN1, a.LOW)
    a.digitalWrite(IN2, a.LOW)  #left wheel holds still
    a.digitalWrite(IN3, a.LOW)
Beispiel #16
0
db = firebase.database()

a.pinMode(12, a.OUTPUT)
a.pinMode(11, a.OUTPUT)
a.pinMode(35, a.OUTPUT)
a.pinMode(7, a.OUTPUT)
a.pinMode(10, a.OUTPUT)
a.pinMode(9, a.OUTPUT)
a.pinMode(8, a.OUTPUT)
a.pinMode(2, a.OUTPUT)
a.pinMode(39, a.OUTPUT)
a.pinMode(3, a.OUTPUT)
a.pinMode(5, a.OUTPUT)

while True:
    a.digitalWrite(39, a.LOW)
    a.digitalWrite(3, a.LOW)
    a.digitalWrite(5, a.LOW)
    t = 0.15
    users = db.get().val()
    for i, (key, value) in enumerate(users.items()):
        print(str(key) + str(value))
        if (str(key) == "q"):
            if (value == 1):
                a.digitalWrite(12, a.HIGH)
                time.sleep(t)
                a.digitalWrite(12, a.LOW)
            if (value == 2):
                a.digitalWrite(11, a.HIGH)
                time.sleep(t)
                a.digitalWrite(11, a.LOW)
Beispiel #17
0
#!/usr/bin/env python

# Author: Andrea Stagi <*****@*****.**>
# Description: keeps your led blinking on 2 boards
# Dependencies: None

from nanpy import (ArduinoApi, SerialManager)
from time import sleep


device_1 = '/dev/tty.usbmodem1411'
device_2 = '/dev/tty.usbmodem1431'

connection_1 = SerialManager(device=device_1)
connection_2 = SerialManager(device=device_2)

a1 = ArduinoApi(connection=connection_1)
a1.pinMode(13, a1.OUTPUT)

a2 = ArduinoApi(connection=connection_2)
a2.pinMode(13, a2.OUTPUT)

for i in range(10000):
    a1.digitalWrite(13, (i + 1) % 2)
    sleep(1)
    a2.digitalWrite(13, (i + 1) % 2)
    sleep(1)

Beispiel #18
0
X_STP_PIN = 2
Y_STP_PIN = 3
Z_STP_PIN = 4

delayTime = 30  #Delay between each pause (uS)
stps = 6400  # steps in one revolution

try:
    connection = SerialManager()
    duino = ArduinoApi(connection=connection)

    #VOID SETUP
    duino.pinMode(X_DIR_PIN, duino.OUTPUT)
    duino.pinMode(X_STP_PIN, duino.OUTPUT)

    duino.pinMode(Y_DIR_PIN, duino.OUTPUT)
    duino.pinMode(Y_STP_PIN, duino.OUTPUT)

    duino.pinMode(Z_DIR_PIN, duino.OUTPUT)
    duino.pinMode(Z_STP_PIN, duino.OUTPUT)

    duino.pinMode(EN, duino.OUTPUT)
    duino.digitalWrite(EN, duino.LOW)

    while True:
        game_loop()

except:
    print("Connection to Arduino failed")
Beispiel #19
0
class DriveModule():
    def __init__(self):
        # self.gpio17 = rpilib.GPIOrtx('17')
        # self.gpio18 = rpilib.GPIOrtx('18')
        # self.gpio22 = rpilib.GPIOrtx('22')
        # self.gpio23 = rpilib.GPIOrtx('23')
        try:
            connection = SerialManager()
            self.a = ArduinoApi(connection=connection)
        except:
            print('Failed to connect to Arduino!')

        self.ENA = 10
        self.ENB = 5
        self.IN1 = 9
        self.IN2 = 8
        self.IN3 = 7
        self.IN4 = 6

    def online(self):
        print('online')
        # self.gpio17.export()
        # self.gpio17.setDirection('out')

        # self.gpio18.export()
        # self.gpio18.setDirection('out')

        # self.gpio22.export()
        # self.gpio22.setDirection('out')

        # self.gpio23.export()
        # self.gpio23.setDirection('out')
        self.a.pinMode(self.IN1, self.a.OUTPUT)
        self.a.pinMode(self.IN2, self.a.OUTPUT)
        self.a.pinMode(self.ENA, self.a.OUTPUT)
        self.a.digitalWrite(self.ENA, self.a.HIGH)
        self.a.pinMode(self.IN3, self.a.OUTPUT)
        self.a.pinMode(self.IN4, self.a.OUTPUT)
        self.a.pinMode(self.ENB, self.a.OUTPUT)
        self.a.digitalWrite(self.ENB, self.a.HIGH)

    def offline(self):
        # self.gpio17.unexport()
        # self.gpio18.unexport()
        # self.gpio22.unexport()
        # self.gpio23.unexport()
        self.a.digitalWrite(self.ENA, self.a.LOW)
        self.a.digitalWrite(self.ENB, self.a.LOW)

    def stop(self):
        # self.gpio17.writeValue('0')
        # self.gpio18.writeValue('0')
        # self.gpio22.writeValue('0')
        # self.gpio23.writeValue('0')
        self.a.digitalWrite(self.IN1, self.a.LOW)
        self.a.digitalWrite(self.IN2, self.a.LOW)
        self.a.digitalWrite(self.IN3, self.a.LOW)
        self.a.digitalWrite(self.IN4, self.a.LOW)


    def drive_forward(self):
        print('drive_forward')
        # self.gpio18.writeValue('1')
        # self.gpio22.writeValue('1')
        self.a.digitalWrite(self.IN1, self.a.LOW)
        self.a.digitalWrite(self.IN2, self.a.HIGH)
        self.a.digitalWrite(self.IN3, self.a.HIGH)
        self.a.digitalWrite(self.IN4, self.a.LOW)
        time.sleep(1)
        self.stop()

    def drive_backward(self):
        # self.gpio17.writeValue('1')
        # self.gpio23.writeValue('1')
        self.a.digitalWrite(self.IN1, self.a.HIGH)
        self.a.digitalWrite(self.IN2, self.a.LOW)
        self.a.digitalWrite(self.IN3, self.a.LOW)
        self.a.digitalWrite(self.IN4, self.a.HIGH)
        time.sleep(1)
        self.stop()

    def steer_left(self):
        # self.gpio17.writeValue('1')
        # self.gpio22.writeValue('1')
        self.a.digitalWrite(self.IN4, self.a.HIGH)
        time.sleep(0.1)
        self.a.digitalWrite(self.IN4, self.a.LOW)
        # self.gpio17.writeValue('0')
        # self.gpio22.writeValue('0')

    def steer_right(self):
        # self.gpio18.writeValue('1')
        # self.gpio23.writeValue('1')
        self.a.digitalWrite(self.IN1, self.a.HIGH)
        time.sleep(0.1)
        self.a.digitalWrite(self.IN1, self.a.LOW)
Beispiel #20
0
class Motor:
    def __init__(self, trip_meter):
        # these values might need to be adjusted
        self.max_speed  = 0.55
        min_voltage = 1.0
        self.correction_interval = 0.01
        self.proportional_term_in_PID = 1.25
        self.derivative_term_in_PID = 0.01
        # these values might change
        self.pin_right_forward = 6
        self.pin_right_backward = 11
        self.pin_left_forward = 5
        self.pin_left_backward = 10
        self.pin_motor_battery = 7
        ##################################################
        # Values after this should not need to be changed.
        ##################################################
        
        self.trip_meter = trip_meter
        
        self.min_value = math.floor(min_voltage / 5.0 * 255)
        
        try:
            self.connection = SerialManager(device='/dev/ttyACM2')
            self.arduino = ArduinoApi(connection=self.connection)
        except:
            try:
                self.connection = SerialManager(device='/dev/ttyACM0')
                self.arduino = ArduinoApi(connection=self.connection)
            except:
                try:
                    self.connection = SerialManager(device='/dev/ttyACM1')
                    self.arduino = ArduinoApi(connection=self.connection)
                except:
                    try:
                        self.connection = SerialManager(device='/dev/ttyACM3')
                        self.arduino = ArduinoApi(connection=self.connection)
                    except:
                        print "Could not connect to the arduino using /dev/ttyACM0, /dev/ttyACM1, /dev/ttyACM2 or /dev/ttyACM3"
            
        self.arduino.pinMode(self.pin_right_forward, self.arduino.OUTPUT)
        self.arduino.pinMode(self.pin_right_backward, self.arduino.OUTPUT)
        self.arduino.pinMode(self.pin_left_forward, self.arduino.OUTPUT)
        self.arduino.pinMode(self.pin_left_backward, self.arduino.OUTPUT)
        self.arduino.pinMode(self.pin_motor_battery, self.arduino.OUTPUT)
        
        self.arduino.pinMode(13, self.arduino.OUTPUT)
        self.arduino.digitalWrite(13, 1)

        self.arduino.digitalWrite(self.pin_motor_battery, 0)
        
        self.power = 0.0
        self.turn = 0.0
        self.right_forward_value = 0
        self.right_backward_value = 0
        self.left_forward_value = 0
        self.left_backward_value = 0
        self.previous_right_forward_value = 0
        self.previous_right_backward_value = 0
        self.previous_left_forward_value = 0
        self.previous_left_backward_value = 0
        self.right_speed = 0.0
        self.left_speed = 0.0
        self.stopped = True
    
        self.motor_control_thread = threading.Thread(target = self.motor_control_loop)
        self.motor_control_thread.setDaemon(True)
        self.motor_control_thread.start()

    def motor_control_loop(self):
        while True:
            self.true_right_speed = self.trip_meter.get_right_speed() * 100.0 / self.max_speed
            self.true_left_speed = self.trip_meter.get_left_speed() * 100.0 / self.max_speed
            
            if (self.right_speed > 0.0):
                self.right_backward_value = 0
                next_previous_right_forward_value = self.right_forward_value
                self.right_forward_value += self.proportional_term_in_PID * (self.right_speed - self.true_right_speed) - self.derivative_term_in_PID * (self.right_forward_value - self.previous_right_forward_value) / self.correction_interval
                self.previous_right_forward_value = next_previous_right_forward_value
            elif (self.right_speed < 0.0):
                self.right_forward_value = 0
                next_previous_right_backward_value = self.right_backward_value
                self.right_backward_value += self.proportional_term_in_PID * (-self.right_speed - self.true_right_speed) - self.derivative_term_in_PID * (self.right_backward_value - self.previous_right_backward_value) / self.correction_interval
                self.previous_right_backward_value = next_previous_right_backward_value
            else:
                self.right_forward_value = 0
                self.right_backward_value = 0
                self.previous_right_forward_value = 0
                self.previous_right_backward_value = 0
            
            if (self.left_speed > 0.0):
                self.left_backward_value = 0
                next_previous_left_forward_value = self.left_forward_value
                self.left_forward_value += self.proportional_term_in_PID * (self.left_speed - self.true_left_speed) - self.derivative_term_in_PID * (self.left_forward_value - self.previous_left_forward_value) / self.correction_interval
                self.previous_left_forward_value = next_previous_left_forward_value
            elif (self.left_speed < 0.0):
                self.left_forward_value = 0
                next_previous_left_backward_value = self.left_backward_value
                self.left_backward_value += self.proportional_term_in_PID * (-self.left_speed - self.true_left_speed) - self.derivative_term_in_PID * (self.left_backward_value - self.previous_left_backward_value) / self.correction_interval
                self.previous_left_backward_value = next_previous_left_backward_value
            else:
                self.left_forward_value = 0
                self.left_backward_value = 0
                self.previous_left_forward_value = 0
                self.previous_left_backward_value = 0
            
            if (not self.stopped):
                if (self.right_forward_value < 0):
                    self.right_forward_value = 0.0
                elif (self.right_forward_value > 255):
                    self.right_forward_value = 255
                if (self.right_backward_value < 0.0):
                    self.right_backward_value = 0.0
                elif (self.right_backward_value > 255):
                    self.right_backward_value = 255
                if (self.left_forward_value < 0.0):
                    self.left_forward_value = 0.0
                elif (self.left_forward_value > 255):
                    self.left_forward_value = 255
                if (self.left_backward_value < 0.0):
                    self.left_backward_value = 0.0 
                elif (self.left_backward_value > 255):
                    self.left_backward_value = 255
                self.arduino.analogWrite(self.pin_right_forward, self.right_forward_value)
                self.arduino.analogWrite(self.pin_right_backward, self.right_backward_value)
                self.arduino.analogWrite(self.pin_left_forward, self.left_forward_value)
                self.arduino.analogWrite(self.pin_left_backward, self.left_backward_value)
                
            time.sleep(self.correction_interval)


    def stop(self):
        self.stopped = True
        self.right_speed = 0.0
        self.left_speed = 0.0
        self.right_forward_value = 0
        self.right_backward_value = 0
        self.left_forward_value = 0
        self.left_backward_value = 0
        self.arduino.analogWrite(self.pin_right_forward, 0)
        self.arduino.analogWrite(self.pin_right_backward, 0)
        self.arduino.analogWrite(self.pin_left_forward, 0)
        self.arduino.analogWrite(self.pin_left_backward, 0)

    def turn_off(self):
        self.arduino.digitalWrite(self.pin_motor_battery, 1)
        self.stop()

    # 'right_speed' is a number between -100 and 100, where 100 is full speed forward on the right wheel
    def set_right_speed(self, right_speed):
        self.right_speed = right_speed
        self.stopped = False
        if (self.right_speed == 0):
            self.right_forward_value = 0
            self.right_backward_value = 0
        elif (self.right_speed > 0):
            self.right_forward_value = self.right_speed / 100.0 * (255 - self.min_value) + self.min_value
            self.right_backward_value = 0
        elif (self.right_speed < 0):
            self.right_forward_value = 0
            self.right_backward_value = -self.right_speed / 100.0 * (255 - self.min_value) + self.min_value

    # 'left_speed' is a number between -100 and 100, where 100 is full speed forward on the left wheel
    def set_left_speed(self, left_speed):
        self.left_speed = left_speed
        self.stopped = False
        if (self.left_speed == 0):
            self.left_forward_value = 0
            self.left_backward_value = 0
        elif (self.left_speed > 0):
            self.left_forward_value = self.left_speed / 100.0 * (255 - self.min_value) + self.min_value
            self.left_backward_value = 0
        elif (self.left_speed < 0):
            self.left_forward_value = 0
            self.left_backward_value = -self.left_speed / 100.0 * (255 - self.min_value) + self.min_value
Beispiel #21
0
#!/usr/bin/env python

from nanpy import ArduinoApi
from time import sleep
from nanpy.sockconnection import SocketManager
# import logging
# logging.basicConfig(level=logging.DEBUG)

PIN=2

connection = SocketManager()
a = ArduinoApi(connection=connection)

a.pinMode(PIN, a.OUTPUT)

for i in range(10000):
    a.digitalWrite(PIN, (i + 1) % 2)
    sleep(0.2)

Beispiel #22
0
from nanpy import ArduinoApi
from nanpy import SerialManager
from time import sleep

link = SerialManager(device='/dev/ttyACM0')
A = ArduinoApi(connection=link)

led = 13

# SETUP:
A.pinMode(led, A.OUTPUT)

# LOOP:
while True:
    A.digitalWrite(led, A.HIGH) # turn the LED on (HIGH is the voltage level)
    print "blink on"
    sleep(1) # use Python sleep instead of arduino delay
    A.digitalWrite(led, A.LOW) # turn the LED off by making the voltage LOW
    print "blink off"
    sleep(1)
Beispiel #23
0
class BoxGpio:
    _PARAM_PIN_CONTROLLER = "pin_controller"
    _PARAM_PIN_POWER = "pin_power"
    _PARAM_PIN_FAN = "pin_fan"
    _PARAM_BOARD_PIN_RESET = "pin_reset"

    def __init__(self, box_id, config_box):
        self.box_id = box_id
        self.config_box = config_box

        if not BoxGpio._PARAM_PIN_CONTROLLER in self.config_box:
            self.arduino = None
            logging.info(f"Box {self.box_id} has no pin controller")
        else:
            connection = SerialManager(
                device=self.config_box[BoxGpio._PARAM_PIN_CONTROLLER])
            self.arduino = ArduinoApi(connection=connection)

        self.set_power(False)
        self.set_fan(0)

    def set_power(self, on):
        if self.arduino == None:
            return
        if not BoxGpio._PARAM_PIN_POWER in self.config_box:
            return

        self._set_pin(self.config_box[BoxGpio._PARAM_PIN_POWER], not on)
        logging.info(f"Box {self.box_id} <- power={on}")

    def set_fan(self, val):
        if self.arduino == None:
            return
        if not BoxGpio._PARAM_PIN_FAN in self.config_box:
            return

        val = min(1, max(0, val))
        # TODO: this could be changed to pwm if required
        self._set_pin(self.config_box[BoxGpio._PARAM_PIN_FAN], False)
        logging.info(f"Box {self.box_id} <- fan={val}")

    def set_board_reset(self, board_name, reset):
        if self.arduino == None:
            return
        board = self.config_box['boards'][board_name]
        if not BoxGpio._PARAM_BOARD_PIN_RESET in board:
            # this is a hack
            if reset and self.board_cmd_exists(board_name, "poweroff"):
                self.exec_board_cmd(board_name, "poweroff")
                logging.info(f"Box {self.box_id} <- {board_name}.poweroff")
            return

        self._set_pin(board[BoxGpio._PARAM_BOARD_PIN_RESET], not reset)
        logging.info(f"Box {self.box_id} <- {board_name}.reset={not reset}")

    def board_cmd_exists(self, board_name, cmd_name):
        board_config = self.config_box['boards'][board_name]
        if not ("client_cmds" in board_config):
            return False
        return cmd_name in board_config["client_cmds"]

    def exec_board_cmd(self, board_name, cmd_name):
        cmd_seq = self.config_box['boards'][board_name]["client_cmds"][
            cmd_name]
        logging.info(
            f"Box {self.box_id} <- {board_name}.{cmd_name} - {cmd_seq}")
        for instr in cmd_seq:
            instr_p = instr.split(" ")
            assert len(instr_p) >= 1
            op = instr_p[0]
            par = instr_p[1:]
            if op == "sleep":
                assert len(par) == 1
                time.sleep(float(par[0]))
            elif op == "pin":
                assert len(par) == 2
                pin = int(par[0])
                assert par[1] == "true" or par[1] == "false"
                val = par[1] != "false"
                self._set_pin(pin, val)
            else:
                raise Exception(f"unknown instruction '{op}'")

    def _set_pin(self, pin, on):
        if self.arduino == None:
            raise Exception(f"no pin controller at {self.box_id}")

        if on:
            # on means floating! this is important!
            self.arduino.digitalWrite(pin, self.arduino.LOW)
            self.arduino.pinMode(pin, self.arduino.INPUT)
        else:
            self.arduino.pinMode(pin, self.arduino.OUTPUT)
            self.arduino.digitalWrite(pin, self.arduino.LOW)

        logging.debug(f"Box {self.box_id} <- pin{pin}={on}")
Beispiel #24
0
    connection = SerialManager()
    a = ArduinoApi(connection=connection)
except:
    print("Failed to connect to Arduino")

#setup the pin modes as if they were in the Arduino IDE
a.pinMode(enA, a.OUTPUT)
a.pinMode(enB, a.OUTPUT)
a.pinMode(in1, a.OUTPUT)
a.pinMode(in2, a.OUTPUT)
a.pinMode(in3, a.OUTPUT)
a.pinMode(in4, a.OUTPUT)

try:
    print("hello")
    a.digitalWrite(in1, a.HIGH)
    a.digitalWrite(in2, a.LOW)
    a.digitalWrite(in3, a.HIGH)
    a.digitalWrite(in4, a.LOW)
    a.analogWrite(enA, 150)
    a.analogWrite(enB, 150)
    #a.delay(5000)
    sleep(5)
    a.analogWrite(enA, 0)
    a.analogWrite(enB, 0)
    sleep(5)
except:
    print("u suck")
    a.digitalWrite(enA, a.LOW)
    a.digitalWrite(enB, a.LOW)
    a.digitalWrite(in1, a.LOW)
Beispiel #25
0
        b4 = a.digitalWrite(Motor3_1, a.HIGH)
        c4 = a.digitalWrite(Motor3_2, a.LOW)
        return a1, b1, c1, a2, b2, c2, a3, b3, c3
    else:

        return 1


try:
    connection = SerialManager()
    a = ArduinoApi(connection=connection)
except:
    print("Failed to connect to Arduino")

a.pinMode(PWM1, a.OUTPUT)
a.pinMode(Motor1_1, a.OUTPUT)
a.pinMode(Motor1_2, a.OUTPUT)
a.pinMode(PWM2, a.OUTPUT)
a.pinMode(Motor2_1, a.OUTPUT)
a.pinMode(Motor2_2, a.OUTPUT)
a.pinMode(PWM3, a.OUTPUT)
a.pinMode(Motor3_1, a.OUTPUT)
a.pinMode(Motor3_2, a.OUTPUT)

try:
    while True:
        command("forward")

except:
    a.digitalWrite(Motor1_2, a.HIGH)
Beispiel #26
0
class Car():
    def __init__(self, arduinoApi=None, serialPort="/dev/ttyACM0"):
        self.PINS = {
            "LEFT_SPEED": 11,  # ENA
            "RIGHT_SPEED": 5,  # ENB
            "IN1": 9,
            "IN2": 8,
            "IN3": 7,
            "IN4": 6,
        }

        if arduinoApi:
            self.api = arduinoApi
        else:
            connection = SerialManager(device=serialPort)
            self.api = ArduinoApi(connection=connection)

        for pin in self.PINS.values():
            self.api.pinMode(pin, self.api.OUTPUT)

        self.left_speed_raw = 0
        self.left_direction = 0
        self.right_speed_raw = 0
        self.right_direction = 0

    def write(self):
        self.write_speed()
        self.write_left_direction()
        self.write_right_direction()

    def write_speed(self):
        self.api.analogWrite(self.PINS["LEFT_SPEED"], self.left_speed_raw)
        self.api.analogWrite(self.PINS["RIGHT_SPEED"], self.right_speed_raw)

    def write_left_direction(self):
        # both pins LOW if left_direction == 0 aka. full stop
        self.api.digitalWrite(
            self.PINS["IN3"],
            self.api.LOW if self.left_direction > 0 else self.api.HIGH)
        self.api.digitalWrite(
            self.PINS["IN4"],
            self.api.LOW if self.left_direction < 0 else self.api.HIGH)

    def write_right_direction(self):
        # both pins LOW if right_direction == 0 aka. full stop
        self.api.digitalWrite(
            self.PINS["IN1"],
            self.api.LOW if self.right_direction > 0 else self.api.HIGH)
        self.api.digitalWrite(
            self.PINS["IN2"],
            self.api.LOW if self.right_direction < 0 else self.api.HIGH)

    # -100 <= left_speed <= 100
    # -100 <= right_speed <= 100
    # a value of 0 means stop
    def move(self, left_speed, right_speed, turn=0):
        # cmp(-123, 0) == -1
        # cmp(0, 0)    == 0
        # cmp(88, 0)   == 1
        # aka it mimicks the "sign" function from other languages (and basic math)
        self.left_direction = cmp(left_speed, 0)
        self.right_direction = cmp(right_speed, 0)

        # Because the wheels only start moving when the analog port has
        # value 'threshold' or up. In our case it was somewhere between
        # 80 and 90.
        threshold = float(85)

        # Make sure we don't f**k up with values outside [-100...100]
        left_speed = min(100, max(-100, left_speed))
        right_speed = min(100, max(-100, right_speed))

        # Here we map a value [0...100] to [threshold...255]
        self.left_speed_raw = round((float(abs(left_speed)) / 100.0) *
                                    (255.0 - threshold) + threshold)
        self.right_speed_raw = round((float(abs(right_speed)) / 100.0) *
                                     (255.0 - threshold) + threshold)

        if turn > 0:
            self.right_speed_raw = 0
            # self.left_speed_raw = min(255, self.left_speed_raw + turn * 4)
        elif turn < 0:
            self.left_speed_raw = 0
            # self.right_speed_raw = min(255, self.right_speed_raw - turn * 4)

        # write debug info
        print "left_speed %d" % (left_speed)
        print "right_speed %d" % (right_speed)
        print "self.left_speed_raw %d" % (self.left_speed_raw)
        print "self.right_speed_raw %d" % (self.right_speed_raw)
        print "self.left_direction %d" % (self.left_direction)
        print "self.right_direction %d" % (self.right_direction)
        print ""

        # Write values to the Bruce car
        self.write()

    def fullStop(self):
        self.move(0, 0, 0)
class ArduinoSlave():
    """Arduino slave construction setup"""
    Motor1A = 2
    Motor1B = 3
    Motor2A = 4
    Motor2B = 5

    TrigPin = 9
    EchoPin = 10

    ultrasonic = ''
    distance = 0

    automatic_mode = False

    def __init__(self, connection_path):
        try:
            connection = SerialManager(connection_path)
            self.arduino = ArduinoApi(connection=connection)
            self.ultrasonic = Ultrasonic(self.EchoPin,
                                         self.TrigPin,
                                         False,
                                         connection=connection)
        except:
            print("Failed to connect to the arduino")

        # Motors set up
        self.arduino.pinMode(self.Motor1A, self.arduino.OUTPUT)
        self.arduino.pinMode(self.Motor1B, self.arduino.OUTPUT)
        self.arduino.pinMode(self.Motor2A, self.arduino.OUTPUT)
        self.arduino.pinMode(self.Motor2B, self.arduino.OUTPUT)

        # Sensor set up
        self.arduino.pinMode(self.TrigPin, self.arduino.OUTPUT)
        self.arduino.pinMode(self.EchoPin, self.arduino.INPUT)

    def startGetDistance(self):
        self.distance = self.ultrasonic.get_distance()
        print(self.distance)
        # if distance < 5:
        #     pass
        # else:
        #     pass

        return float(self.distance)
        # sleep(0.002)

    def automatic_control(self):
        if (self.startGetDistance() < 5):
            self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor1B, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor2A, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)
            sleep(0.5)
        else:
            self.arduino.digitalWrite(self.Motor1A, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor2A, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)
        return self.startGetDistance()

    def dists(self):
        count = 0
        while True:
            # distance test when moving forwards
            try:
                distance = self.startGetDistance()
                yield 'data: ' + str(distance) + '\n\n'
            except:
                yield 'data: there was an error!\n\n'
            count += 1

    def kill_motors(self):
        self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)

    def move_forwards(self, sense):
        self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)
        forwardsarrow.forwards()
        count = 0
        while True:
            gevent.sleep(0.01)
            self.arduino.digitalWrite(self.Motor1A, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor2A, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)

            # distance test when moving forwards
            try:
                distance = self.startGetDistance()
                print('distance retrieved successfully')
                raw_data = get_all_data(sense)
                raw_data['distance'] = distance
                yield 'data: %s\n\n' % json.dumps(raw_data)
            except:
                yield 'data: there was an error!\n\n'
            count += 1

    def move_backwards(self, sense):
        self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)
        backwardsarrow.backwards()
        count = 0
        while True:
            gevent.sleep(0.01)
            self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor1B, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor2A, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor2B, self.arduino.HIGH)
            try:
                distance = self.startGetDistance()
                raw_data = get_all_data(sense)
                raw_data['distance'] = distance
                yield 'data: %s\n\n' % json.dumps(raw_data)
            except:
                yield 'data: there was an error!\n\n'
            count += 1

    def move_right(self, sense):
        self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)
        count = 0
        while True:
            gevent.sleep(0.01)
            self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor1B, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor2A, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)
            try:
                distance = self.startGetDistance()
                raw_data = get_all_data(sense)
                raw_data['distance'] = distance
                yield 'data: %s\n\n' % json.dumps(raw_data)
            except:
                yield 'data: there was an error!\n\n'
            count += 1

    def move_left(self, sense):
        self.arduino.digitalWrite(self.Motor1A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2A, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
        self.arduino.digitalWrite(self.Motor2B, self.arduino.LOW)
        count = 0
        while True:
            gevent.sleep(0.01)
            self.arduino.digitalWrite(self.Motor1A, self.arduino.HIGH)
            self.arduino.digitalWrite(self.Motor1B, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor2A, self.arduino.LOW)
            self.arduino.digitalWrite(self.Motor2B, self.arduino.HIGH)
            try:
                raw_data = get_all_data(sense)
                distance = self.startGetDistance()
                raw_data['distance'] = distance
                yield 'data: %s\n\n' % json.dumps(raw_data)
            except:
                yield 'data: there was an error!\n\n'
            count += 1
Beispiel #28
0
# Setup the variable (LED)
LED = 13

# Attempt to connect the Arduino
try:
    # Connect and create the Arduino
    connection = SerialManager()
    a = ArduinoApi(connection = connection)
# Otherwise it failed to connect
except:
    # Print error message
    print("Error: Failed to connect to Arduino!")

# Setup the pinMode as if we were in the Arduino IDE
a.pinMode(LED, a.OUTPUT)

try:
    # Continuous loop
    while True:
        # Turn on the LED
        a.digitalWrite(LED, a.HIGH)
        # Wait one second
        sleep(1)
        # Turn off the LED
        a.digitalWrite(LED, a.LOW)
        # Wait one second
        sleep(1)
except:
    # Turn off the LED
    a.digitalWrite(LED, a.LOW)
Beispiel #29
0
connection = SerialManager()
a = ArduinoApi(connection=connection)

a.pinMode(8, a.OUTPUT)
a.pinMode(7, a.OUTPUT)
a.pinMode(13, a.OUTPUT)


def OFFstatus():
    a.digitalWrite(8, 0)
    a.digitalWrite(7, 0)
    a.digitalWrite(13, 0)


valid = True

for i in range(1000):
    OFFstatus()
    choice = int(input("Select color:"))
    if (choice == 1):
        a.digitalWrite(8, 1)
        a.digitalWrite(7, 1)
        a.digitalWrite(13, 1)
        print("Relays On")
    elif (choice == 2):
        a.digitalWrite(8, 0)
        a.digitalWrite(7, 0)
        a.digitalWrite(13, 0)
        print("Relays Off")
Beispiel #30
0
AI2 = 8
PWM = 9
stdby = 10

try:
    connection = SerialManager()
    a = ArduinoApi(connection = connection)
except:
    print("Failed to connect to Arduino")

#Setup
#a.pinMode(AI1, a.OUTPUT)
#a.pinMode(AI2, a.OUTPUT)
#a.pinMode(PWM, a.OUTPUT)
a.pinMode(stdby, a.OUTPUT)

m1 = Motor(AI1, AI2, PWM)
m1.setupMotor(a)

a.digitalWrite(stdby, a.HIGH)
try:
    while True:
        speed = input("Input speed: ")
        if speed == "exit":
            break
        m1.drive(int(speed), a)
except Exception as e:
    print(e)

m1.drive(0, a)
Beispiel #31
0
class Splitters(object):
    def __init__(self, uc_pin=7, ub_pin=8, pc_pin=12, pb_pin=13):

        # set member variables
        self.upstream_state = None
        self.phy_state = None
        self.uc_pin = uc_pin
        self.ub_pin = ub_pin
        self.pc_pin = pc_pin
        self.pb_pin = pb_pin

        # connect to the arduino device over serial connection
        self.connection = SerialManager()
        self.api = ArduinoApi(connection=self.connection)

        # initialize pins as output
        self.api.pinMode(self.uc_pin, self.api.OUTPUT)
        self.api.pinMode(self.ub_pin, self.api.OUTPUT)
        self.api.pinMode(self.pc_pin, self.api.OUTPUT)
        self.api.pinMode(self.pb_pin, self.api.OUTPUT)

    def print_state(self, pretty=False):

        if self.upstream_state is None or self.phy_state is None:

            print 'State unknown'

        else:

            print 'Upstream Connected:', self.upstream_state
            print 'PHY Connected:', self.phy_state
            if pretty:
                if self.upstream_state:
                    print state_banners.upstream_connected
                else:
                    print state_banners.upstream_bypass
                print state_banners.banner_center
                if self.phy_state:
                    print state_banners.phy_connected
                else:
                    print state_banners.phy_bypass

    def set_upstream(self, state):

        if state:
            self._flip_switch(self.uc_pin)
        else:
            self._flip_switch(self.ub_pin)
        self.upstream_state = state

    def set_phy(self, state):

        if state:
            self._flip_switch(self.pc_pin)
        else:
            self._flip_switch(self.pb_pin)
        self.phy_state = state

    def _flip_switch(self, relay_pin):

        self.api.digitalWrite(relay_pin, self.api.HIGH)
        time.sleep(1)
        self.api.digitalWrite(relay_pin, self.api.LOW)
import telepot
import time
from nanpy import ArduinoApi, SerialManager
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton

connection = SerialManager(device='COM3')  #or the port you are actually using
a = ArduinoApi(connection=connection)
a.pinMode(9, a.OUTPUT)
a.pinMode(10, a.OUTPUT)
a.pinMode(11, a.OUTPUT)
a.digitalWrite(9, 0)
a.digitalWrite(10, 0)
a.digitalWrite(11, 0)

r = 0
g = 0
b = 0


def on_chat_message(msg):  #create a customized keyboard
    content_type, chat_type, chat_id = telepot.glance(msg)

    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text="+", callback_data='/r+'),
            InlineKeyboardButton(text="+", callback_data='/g+'),
            InlineKeyboardButton(text="+", callback_data='/b+')
        ],
        [
            InlineKeyboardButton(text="-", callback_data='/r-'),
            InlineKeyboardButton(text="-", callback_data='/g-'),
Beispiel #33
0
app_secret = settings.get('Instapush', 'INSTAPUSH_APP_SECRET')
event_id = settings.get('Instapush', 'INSTAPUSH_EVENT_NAME')
threshold = settings.getfloat('Fridge', 'THRESHOLD')
notify_every_x_seconds = settings.getfloat('Fridge', 'NOTIFY_EVERY_X_SECONDS')
write_log_every_x_measurements = 50

# Startup arduino connection
connection = SerialManager(device=device)
connection.open()
arduino = ArduinoApi(connection=connection)
temperature_sensors = DallasTemperature(connection=connection, pin=pin_temp)
temperature_sensors.setResolution(12)

# Mute sound by default
arduino.pinMode(pin_sound, arduino.OUTPUT)
arduino.digitalWrite(pin_sound, 0)

# Initial values
last_alert = time.time()
threshold_reached = False
write_log_counter = 0

while True:
    temperature_sensors.requestTemperatures()
    temp = temperature_sensors.getTempC(
        0)  # Fetches the temperature on the first DS18B20 found on the pin.

    print temp

    if temp < -100 or temp == 0:
        # Bad reading, lets skip this result.
Beispiel #34
0
# 25200 = 7 hours
# 1200 = 20 minutes

print "Startup BIT, LED on Board will Turn on for 10 Seconds, then off if communication is established\n"
print "if LED does not flash, check connections, and try the following from a terminal\n"
print ">>cd /dev\n"
print ">>ls\n"
print "if dev/ttyACM0 is missing from the list, you need to try another port, communication is not established\n"
print("Current time %s" % now)

if number_files <= 45:
    with open('testwithboard' + str(file_count), 'w') as f:
        f.write("Current time %s" '\nTest Successful!' % now)
        f.write("it is day %s\n" % number_files)
        print("it is day %s\n" % number_files)
        a.digitalWrite(13, a.HIGH)
        a.digitalWrite(2, a.HIGH)
        a.digitalWrite(3, a.HIGH)
        a.digitalWrite(4, a.HIGH)
        a.digitalWrite(5, a.HIGH)
        f.write("Led is on\n")
        print("Led is on\n")
        time.sleep(10)
        a.digitalWrite(13, a.LOW)
        f.write("LED is OFF\n")
        print("LED is OFF\n")
        light_timer = light_timer + time_increment
        a.digitalWrite(2, a.LOW)
        a.digitalWrite(3, a.LOW)
        f.write("Digital Light Output 2 relay is closed, light should be on\n")
        print("Digital Light Output 2 relay is closed, light should be on\n")
Beispiel #35
0
#!/usr/bin/env python

from nanpy import ArduinoApi
from time import sleep
from nanpy.sockconnection import SocketManager
# import logging
# logging.basicConfig(level=logging.DEBUG)

PIN = 2

connection = SocketManager()
a = ArduinoApi(connection=connection)

a.pinMode(PIN, a.OUTPUT)

for i in range(10000):
    a.digitalWrite(PIN, (i + 1) % 2)
    sleep(0.2)
Beispiel #36
0
class Motor():
  # Works as setup()
  def __init__(self, device):
    self.devicePath = device
    self.connection = SerialManager(device=self.devicePath)
    self.arduino = ArduinoApi(connection=self.connection)
    self.RPM = 70
    self.turnPRM = 60

    # Motor pins
    self.dir11=7
    self.pwm11=5    #cytron 1
    self.dir21=2
    self.pwm21=3
    self.dir11=self.dir21
    self.pwm11=self.pwm21


    self.dir12=8
    self.pwm12=9      #cytron 2
    self.dir22=13
    self.pwm22=11

    # Setup pinmodes
    self.arduino.pinMode(self.dir11, self.arduino.OUTPUT)
    self.arduino.pinMode(self.pwm11, self.arduino.OUTPUT)
    self.arduino.pinMode(self.dir12, self.arduino.OUTPUT)
    self.arduino.pinMode(self.pwm12, self.arduino.OUTPUT)
    self.arduino.pinMode(self.dir21, self.arduino.OUTPUT)
    self.arduino.pinMode(self.pwm21, self.arduino.OUTPUT)
    self.arduino.pinMode(self.dir22, self.arduino.OUTPUT)
    self.arduino.pinMode(self.pwm22, self.arduino.OUTPUT)

  def moveMotor(self, direction):
    if direction=='f':
      self.forwardMotor()
    elif direction=='b':
      self.backwardMotor()
    elif direction=='l':
      self.leftMotor()
    elif direction=='r':
      self.rightMotor()
    elif direction=='s':
      self.resetAllMotors()
    elif direction=='x':
      exit()    
  
  def forwardMotor(self):
    self.arduino.digitalWrite(self.dir11, self.arduino.HIGH)
    self.arduino.digitalWrite(self.dir12, self.arduino.LOW)
    self.arduino.digitalWrite(self.dir21, self.arduino.HIGH)
    self.arduino.digitalWrite(self.dir22, self.arduino.LOW)

    self.arduino.analogWrite(self.pwm11, self.RPM)
    self.arduino.analogWrite(self.pwm12, self.RPM)
    self.arduino.analogWrite(self.pwm21, self.RPM)
    self.arduino.analogWrite(self.pwm22, self.RPM)

  def backwardMotor(self):
    self.arduino.digitalWrite(self.dir11, self.arduino.LOW)
    self.arduino.digitalWrite(self.dir12, self.arduino.HIGH)
    self.arduino.digitalWrite(self.dir21, self.arduino.LOW)
    self.arduino.digitalWrite(self.dir22, self.arduino.HIGH)

    self.arduino.analogWrite(self.pwm11, self.RPM)
    self.arduino.analogWrite(self.pwm12, self.RPM)
    self.arduino.analogWrite(self.pwm21, self.RPM)
    self.arduino.analogWrite(self.pwm22, self.RPM)

  def leftMotor(self):
    self.arduino.digitalWrite(self.dir11, self.arduino.HIGH)
    self.arduino.digitalWrite(self.dir12, self.arduino.HIGH)
    self.arduino.digitalWrite(self.dir21, self.arduino.HIGH)
    self.arduino.digitalWrite(self.dir22, self.arduino.HIGH)

    self.arduino.analogWrite(self.pwm11, self.turnRPM)
    self.arduino.analogWrite(self.pwm12, self.turnRPM)
    self.arduino.analogWrite(self.pwm21, self.turnRPM)
    self.arduino.analogWrite(self.pwm22, self.turnRPM)

  def rightMotor(self):
    self.arduino.digitalWrite(self.dir11, self.arduino.LOW)
    self.arduino.digitalWrite(self.dir12, self.arduino.LOW)
    self.arduino.digitalWrite(self.dir21, self.arduino.LOW)
    self.arduino.digitalWrite(self.dir22, self.arduino.LOW)

    self.arduino.analogWrite(self.pwm11, self.turnRPM)
    self.arduino.analogWrite(self.pwm12, self.turnRPM)
    self.arduino.analogWrite(self.pwm21, self.turnRPM)
    self.arduino.analogWrite(self.pwm22, self.turnRPM)

  def resetAllMotors(self):
    self.arduino.analogWrite(self.pwm11,0)
    self.arduino.analogWrite(self.pwm12,0)
    self.arduino.analogWrite(self.pwm21,0)
    self.arduino.analogWrite(self.pwm22,0)
firebaseUrl= 'https://raspberrypi-17a5b.firebaseio.com/'
firebaseRef=firebase.FirebaseApplication(firebaseUrl,None)
print "Firebase Url excepted"
try:
    while True:
##############current and power calculation
        for i in range(5):
            print "getting on/off from firebase"
            val1=int(firebaseRef.get('devices','device1'))
            #time.sleep(2);
            print str(val1)
            val2=int(firebaseRef.get('devices','device2'))
            #time.sleep(2);
            print str(val2)
            if(val1 == 1 and val2 == 1):
                a.digitalWrite(relay1,a.LOW)
                a.digitalWrite(relay2,a.LOW)
                print "Both relays are ON"
            elif(val1 == 0 and val2 == 1):
                a.digitalWrite(relay1,a.HIGH)
                a.digitalWrite(relay2,a.LOW)
                print "Relay 1 OFF & Relay 2 ON"
            elif(val1 == 1 and val2 == 0):
                a.digitalWrite(relay1,a.LOW)
                a.digitalWrite(relay2,a.HIGH)
                print "Relay 1 ON & Relay 2 OFF"
            elif(val1 == 0 and val2 == 0):
                a.digitalWrite(relay1,a.HIGH)
                a.digitalWrite(relay2,a.HIGH)
                print "Both relays are OFF"
            else:
Beispiel #38
0
#!/usr/bin/env python

# Author: Andrea Stagi <*****@*****.**>
# Description: keeps your led blinking
# Dependencies: None

from nanpy import (ArduinoApi, SerialManager)
from time import sleep
import logging
logging.basicConfig(level=logging.DEBUG)

connection = SerialManager(device=str(input('Enter Device Port: ')),
                           timeout=20)
a = ArduinoApi(connection=connection)

a.pinMode(13, a.OUTPUT)

for i in range(100):
    a.digitalWrite(13, (i + 1) % 2)
    sleep(0.2)
Beispiel #39
0
#!/usr/bin/env python

# Author: Andrea Stagi <*****@*****.**>
# Description: keeps your led blinking
# Dependencies: None

from nanpy import (ArduinoApi, SerialManager)
from time import sleep

device = '/dev/cu.usbmodem1411'
connection = SerialManager(device=device)
connection.open()
a = ArduinoApi(connection=connection)

a.pinMode(3, a.OUTPUT)
led_status = 1
while True:
    if led_status:
        led_status = 0
    else:
        led_status = 1
    a.digitalWrite(3, led_status)
    sleep(2)