Esempio n. 1
0
import time
import json
import redis
from nanpy import (ArduinoApi, SerialManager)

default_connection = SerialManager()


# Base sensor class to extend all other arduino sensors from.
class Sensor():
    def __init__(self,
                 pin,
                 name='Sensor',
                 connection=default_connection,
                 analog_pin_mode=False,
                 key=None):
        self.pin = pin
        self.name = name
        self.key = key.replace(
            " ", "_").lower() if key is not None else self.name.replace(
                " ", "_").lower()
        self.analog_pin_mode = analog_pin_mode
        self.connection = connection
        self.api = ArduinoApi(connection)
        return

    def init_sensor(self):
        #Initialize the sensor here (i.e. set pin mode, get addresses, etc)
        pass

    def read(self):
Esempio n. 2
0
import time
import datetime
import json
import redis
from .sensor import Sensor
from nanpy import (ArduinoApi, SerialManager)
import sys
sys.path.append('..')

import variables

default_connection = SerialManager(device='/dev/ttyUSB0')
#r = redis.Redis(host='127.0.0.1', port=6379)


class LightSensor(Sensor):
    def __init__(self,
                 pin,
                 name=None,
                 key=None,
                 connection=default_connection,
                 redis_conn=None):
        super().__init__(pin,
                         name=name,
                         key=key,
                         connection=connection,
                         redis_conn=redis_conn)
        return

    def init_sensor(self):
        # read data using pin specified pin
Esempio n. 3
0
        return a.analogWrite(PWM1, 0), a.digitalWrite(
            Motor1_1, a.LOW), a.digitalWrite(Motor1_2, a.LOW), a.analogWrite(
                PWM2, 0), a.digitalWrite(Motor2_1, a.LOW), a.digitalWrite(
                    Motor2_2, a.LOW), a.analogWrite(PWM3, 0), a.digitalWrite(
                        Motor3_1, a.LOW), a.digitalWrite(
                            Motor3_2,
                            a.HIGH), a.analogWrite(PWM4, 0), a.digitalWrite(
                                Motor4_1,
                                a.LOW), a.digitalWrite(Motor4_2, a.HIGH)

    else:
        #print("No such command")
        return 0


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)
Esempio n. 4
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)
Esempio n. 5
0
#!/usr/local/bin/python3
from nanpy import (ArduinoApi, SerialManager)
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

sensorConnection = SerialManager(device='/dev/ttyUSB0')
A = ArduinoApi(connection=sensorConnection)

laserL = 14
laserR = 15
laserF = 16
laserB = 17

TuSonicL1 = 7
EuSonicL1 = 11

TuSonicL2 = 12
EuSonicL2 = 13

TuSonicR1 = 15
EuSonicR1 = 16

TuSonicR2 = 18
EuSonicR2 = 22

GPIO.setup(TuSonicL1, GPIO.OUT)
GPIO.setup(EuSonicL1, GPIO.IN)
GPIO.setup(TuSonicL2, GPIO.OUT)
GPIO.setup(EuSonicL2, GPIO.IN)
Esempio n. 6
0
settings.read(
    os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.cfg'))

# Load settings
device = settings.get('Arduino', 'SERIAL_PORT')
pin_sound = settings.getint('Arduino', 'PIN_SOUND')
pin_temp = settings.getint('Arduino', 'PIN_TEMPERATURE')
app_id = settings.get('Instapush', 'INSTAPUSH_APP_ID')
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:
Esempio n. 7
0
"""
#########  Raspberry - Arduino setup  ############
"""
from nanpy import (ArduinoApi, SerialManager)
from time import sleep
from datetime import datetime

try:
    connectMain = SerialManager(device='/dev/ttyACM1')
    m = ArduinoApi(connection=connectMain)
except:
    print("Main connection failed!")

try:
    connectLaser = SerialManager(device='/dev/ttyACM2')
    l = ArduinoApi(connection=connectLaser)
except:
    print("Laser connection failed!")

"""
##############  Main Arduino code  ###############
"""
valveDelay = 70
reward = False
sensor = [2, 3, 4, 5, 6, 7, 8, 9]
rewardPort = ['A0', 'A1', 'A2', 'A3']
idSensor = 0
idValve = 0
nTrial = 0
totalTrial = 90
            continue
        if distance < 0:
            print("Invalid input!! PLEASE INPUT A POSTIVE NUMBER")
            continue
        elif distance > 155:
            print("Excedes the range, PLEASE INPUT A VALUE BELOW 155 INCH")
            continue
        else:
            break
    return distance


distance = InputDistance()
#SETUP
try:
    connection = SerialManager('COM3')
    board = ArduinoApi(connection=connection)
except:
    print("Connection Failed")
    sys.exit(1)
my_led = [(0, 0, 0)] * 360


#Start Animation
def lineAnim(b, x):
    one = random.randint(0, 256)
    two = random.randint(0, 256)
    three = random.randint(0, 256)
    my_led[b] = (0, 0, 0)
    my_led[b + x] = (one, two, three)
    time.sleep(0.01)
Esempio n. 9
0
 def connect(self):
     attempts = 3
     conn = None
     if self.config.get('use_wifi', False):
         while attempts > 0 and self.main_thread_running.is_set():
             try:
                 print('\033[1;36m{0}\033[0;0m -> Connecting...         \t'.
                       format(self.config["name"], (3 - attempts)))
                 attempts -= 1
                 conn = SocketManager(
                     host=str(self.config.get('address', 'mudpi.local')))
                 # Test the connection with api
                 self.api = ArduinoApi(connection=conn)
             except (SocketManagerError, BrokenPipeError,
                     ConnectionResetError, socket.timeout) as e:
                 print(
                     '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m           '
                     .format(**self.config))
                 if attempts > 0:
                     print('{name} -> Preparing Reconnect...  \t'.format(
                         **self.config))
                 else:
                     print(
                         '{name} -> Connection Attempts...\t\033[1;31m Failed\033[0;0m           '
                         .format(**self.config))
                 conn = None
                 self.resetConnection()
                 time.sleep(15)
             except (OSError, KeyError) as e:
                 print(
                     '[{name}] \033[1;33m Node Not Found. (Is it online?)\033[0;0m'
                     .format(**self.config))
                 conn = None
                 self.resetConnection()
                 time.sleep(15)
             else:
                 print(
                     '{name} -> Wifi Connection \t\t\033[1;32m Success\033[0;0m                 '
                     .format(**self.config))
                 for worker in self.workers:
                     worker.connection = conn
                 self.node_connected.set()
                 self.node_ready.set()
                 break
     else:
         while attempts > 0 and self.main_thread_running.is_set():
             try:
                 attempts -= 1
                 conn = SerialManager(
                     device=str(self.config.get('address', '/dev/ttyUSB1')))
             except SerialManagerError:
                 print(
                     '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m           '
                     .format(**self.config))
                 if attempts > 0:
                     print('{name} -> Preparing Reconnect...  \t'.format(
                         **self.config),
                           end='\r',
                           flush=True)
                 else:
                     print(
                         '{name} -> Connection Attempts...\t\033[1;31m Failed\033[0;0m           '
                         .format(**self.config))
                 self.resetConnection()
                 conn = None
                 time.sleep(15)
             else:
                 if conn is not None:
                     print(
                         '[{name}] Serial Connection \t\033[1;32m Success\033[0;0m         '
                         .format(**self.config))
                     for worker in self.workers:
                         worker.connection = conn
                     self.node_connected.set()
                     self.node_ready.set()
                 break
     return conn
# -*- coding: utf-8 -*-
# Mesure de la tension aux bornes d'un condensateur (version simple)
# 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("A0", uno.OUTPUT)  # Paramétrage de la broche 8 en sortie
uno.digitalWrite("A0", 1)
from Autonomouscameraman import gpidd
'''
import microgear.client as microgear  # microgear unit function for the IoT
import time
import logging  # logging data
import csv
import pandas  # Pandas importer function for the system data transfer
import os  # Operating system to control the software to open when needed
sensor1 = 0  # Back sensor of the autonomouse car
sensor2 = 0  # Front sensor of the autonomouse car
sensor3 = 0  # Activation sensors for the robot
# Data key set function and value
Data_1_key = " "
Data_2_value = " "
try:
    connection = SerialManager()
    motorunit = ArduinoApi(connection=connection)  #Connection astrablished
except:
    print("Motor unit control ")
# Beacon function input for the positioning of the robot
try:
    connection1 = SerialManager(
        "/dev/ttyUSB0", 115200)  # Serial input of the Third wireless MCU
    Wmcu = ArduinoApi(connection=connection1)  # Connection connected
except:
    print("Wireless message reciever MCU connection lost")

#try:
#  sensor_msg = serial.Serial("/dev/ttyUSB0",115200)
#except:
#   print("Sensor read message error please check the sensor unit")
engine = pyttsx.init()
#voices = engine.getProperty('voices')
#for voice in voices:
#    engine.setProperty('voice',voice.id)
#   print voice.id
# Servo input function
servo = Servo(2)  # Finger 1
servo2 = Servo(3)  # Finger 2
servo3 = Servo(4)  # Finger 3
servo4 = Servo(5)  # Finger 4
servo5 = Servo(6)  # Finger 5
servo6 = Servo(9)  # Finger 6

try:
    Handfinger = SerialManager(
        '/dev/ttyACM0',
        115200)  # Hand serial checker and hand shake connection
    Handcontrol = ArduinoApi(connection=Handfinger)
    engine.say("Hardware serial connected 100 percent")
    engine.runAndWait()
    for i in progressbar.progressbar(range(100)):
        time.sleep(0.02)
except:
    print("Connection error please check the serial communication")
try:
    Sensorserial = serial.Serial(
        "/dev/ttyUSB0", 115200)  # Serial communication for the sensors serial
    engine.say("Sensors serial connected 100 percent")
    engine.runAndWait()
    for i in progressbar.progressbar(range(100)):
        time.sleep(0.02)
Esempio n. 13
0
# -*- coding: utf-8 -*-
from nanpy import ArduinoApi, SerialManager
import time

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

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

#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)
#!/usr/bin/env python 
# Author :Mr.Chanapai Chuadchum 
# Project name :RoboticArm Kinematic Sim Con 'RKSC system'
# Describetion: Use with Jetson Tk1 and Vision System function on the CUDA 
import numpy as np # Numpy function for the math and matrix calculation function 
import matplotlib.pyplot as plt  
from nanpy import (ArduinoApi,SerialManager)
from nanpy import Servo
from nanpy import serial_manager 
from nanpy import CapacitiveSensor # Capacitive sensor input 
from nanpy import DHT,DallasTemperature 
from nanpy.arduinotree import ArduinoTree # Arduino Tree function 
import time # Time control delaytion
#Connection of the System on the serial communication system 
connection = SerialManager('/dev/ttyACM0',115200)  # Serial communication via MCU function 
a = ArduinoApi(connection=connection) # Connection with the serial magnager 
connectionBody = SerialManager('/dev/ttyACM1',115200) # Serial sensing and control 
b = ArduinoApi(connection=connectionBody) # The Body and sensing connection for the system of therobotic arm 
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
          # Servo part for the robotic arm 
servo3e = Servo(3)  
servo3u = Servo(4)
servo1u = Servo(5) 
servo1e = Servo(8)
servo2u = Servo(9) 
servo2e = Servo(10)  
          # Servo for the robotic wrist of the arm 
servoWrist= Servo(43) # Wrist servo  
servowristrotate = Servo(44) # Wrist rotate servo 
 # Stepper motor at the finger
#Finger 1 
Esempio n. 15
0
# FRONT BACK RIGHT LEFT
motorState = [False, False, False, False]


def resetAllMotors():
    for i in range(len(motorState)):
        motorState[i] = False


# The motors pins are pinOffset + 0, pinOffset + 1, pinOffset + 2, pinOffset + 3
pinOffset = 7

# Connect to arduino
try:
    connection = SerialManager("/dev/ttyUSB0")
    a = ArduinoApi(connection=connection)
except:
    print("Failed to connect to arduino!")


def motor():
    print("Motor thread Started!")
    while True:
        for i in range(len(motorState)):
            if motorState[i]:
                a.digitalWrite(pinOffset + i, a.HIGH)
            else:
                a.digitalWrite(pinOffset + i, a.LOW)

Esempio n. 16
0
#!/usr/bin/env python
import rospy
from flask import Flask, render_template, request
from nanpy import (ArduinoApi, SerialManager)
from time import sleep
#from flask website
from nanpy import Stepper
import time
import RPi.GPIO as GPIO
from std_msgs.msg import String

app = Flask(__name__)  #placeholder for current module (app.py)
#instance of flask app
MOTOR_AMOUNT = [0, 1, 2, 3, 4]
try:  #trying to establish connection to the arduino
    connection = SerialManager(
        device='/dev/ttyACM0')  #automatically finds the arduino connected
    a = ArduinoApi(connection=connection)  #instance of the arduinoapi object
except:
    print("Failed to connect to Arduino")

#* 0 = Thumb
#* 1 = Pinky
#* 2 = Ring
#* 3 = Middle
#* 4 = Index

GPIO.setmode(GPIO.BCM)

Motor1A = 16  #DC motor pins
Motor1B = 20
Motor1E = 21
from nanpy import SerialManager
from nanpy.hx711 import Hx711

connection = SerialManager(device='COM3')

scale = Hx711(60, 59, connection)

print("Put nothing on the scale.")
input("Press Enter to continue")

offset = scale.averageValue()

print("Put 500g on the scale.")
input("Press Enter to continue")

averageValue = scale.averageValue()
ratio = (averageValue - offset) / 500

print("gram: " + str(averageValue))
print("ratio: " + str(ratio))

scale.setOffset(offset)
scale.setScale(ratio)

while True:
    print(scale.getGram())

Esempio n. 18
0
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(12, a.OUTPUT)
a.pinMode(11, a.OUTPUT)
a.pinMode(10, a.OUTPUT)
a.pinMode(9, a.OUTPUT)


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

    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text="Blue", callback_data='/blue'),
            InlineKeyboardButton(text="Red", callback_data='/red')
        ],
        [
            InlineKeyboardButton(text="Green", callback_data='/green'),
            InlineKeyboardButton(text="Yellow", callback_data='/yellow')
        ]
    ])

    bot.sendMessage(
        chat_id,
        'Press a button to change the status of the corresponding LED',
        reply_markup=keyboard)
Esempio n. 19
0
from nanpy import ArduinoApi, SerialManager
arduino = ArduinoApi(connection=SerialManager())


class AnalogIn():
    def __init__(self, pin, name=None):
        self.pin = pin
        arduino.pinMode(self.pin, arduino.INPUT)
        if name:
            self.name = name
        else:
            self.name = "Pin {}".format(pin)

    def read(self):
        return arduino.analogRead(self.pin)
Esempio n. 20
0
 def connectMotor(self):
     try:
         connection = SerialManager(self.devicePath)  #CHANGE THIS
         self.motorSerial = ArduinoApi(connection=connection)
     except Exception as e:
         raise e
angleDegY = 0
angleDegZ = 0
c = 0
  # Gyro scope address
    #Register
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                     #Hardware connection part 
try: 
    hardware = pyfirmata.ArduinoMega('/dev/ttyACM0') # Hardware try connection 
except: 
    print("Hardware STM32 not found !")
    print("Prepare for seccond protocol ....")
    try: 
       connection = SerialManager()  # Firmware update hardware serial finder 
       catbot = ArduinoApi(connection=connection) 
    except:    
        print("All hardware fail connection")
                    
                    # GPS 
try: 
    gps = serial.Serial("/dev/ttyS0",115200) #GPS connection 
except: 
    print("GPS device notfound !")  
x = str(gps.read(1200))
pos1 = x.find("$GPRMC")
pos2 = x.find("\n",pos1)
loc = x[pos1:pos2]
data = loc.split(',')
Esempio n. 22
0
Uses the nanpy library (https://github.com/nanpy/nanpy), which controls
a slave Arduino processor. The sensors are connected to the Arduino.

Both digital (1/0 output) and analogue (0-1023 ouput) sensors may be
be connected to the Arduino. To use this, Nanpy firmware needs to be
flashed onto the Arduino to allow Python to be used.

Note -This sensor class can only be used with sensors which send their output
straight to the  Arduino pins. For sensors which use I2C or SPI, with their
own registers, a library to use them has to be written separately.
"""

from thingflow.base import OutputThing, IndirectOutputThingMixin

from nanpy import ArduinoApi, SerialManager
ardApi = ArduinoApi(connection=SerialManager(device='/dev/ttyACM0'))


class ArduinoSensor(OutputThing, IndirectOutputThingMixin):
    """Sensor connected to Arduino. Output is analogue(1/0) or digital output(0 - 1023). Nanpy firmware needs to be flashed onto Arduino.
    """
    def __init__(self, sensor_id, AD):
        """sensor_id is port number, AD is True/False for Analogue/Digital
        """
        super().__init__()
        self.sensor_id = sensor_id
        self.AD = AD
        ardApi.pinMode(sensor_id, ardApi.INPUT)

    def sample(self):
        if self.AD:
# -*- coding: utf-8 -*-
# Mesure de la tension aux bornes d'un condensateur (version simple)
# 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
Esempio n. 24
0
#!/usr/bin/env python

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

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

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

#a.pinMode(8, a.OUTPUT)
pin = int(input('Enter Pin: '))
delay = float(input('Enter Delay: '))

while True:
    a.digitalWrite(pin, a.LOW)
    sleep(delay)
    a.digitalWrite(pin, a.HIGH)
Esempio n. 25
0
#!/usr/bin/env python
from nanpy import(ArduinoApi,SerialManager) # Hardware serial control  
from nanpy import Servo   # Servo controller 
import Tkinter
import math 
from Tkinter import* # Import GUI function for error port alert 
connection = SerialManager('/dev/ttyACM0',115200) # Serial connection 
a = ArduinoApi(connection=connection)
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
def RunServo(event): 
     Bases.write(Base.get())
     print(Base.get())
def RunServo1(event): 
     Shoulders.write(Shoulder.get())
     print(Shoulder.get())
def RunServo2(event):
     Elbows.write(Elbow.get())
     print(Elbow.get())
def RunServo3(event):
     WristRots.write(WristRot.get())
     print(WristRot.get())
def RunServo4(event):
     Wrists.write(Wrist.get())
     print(Wrist.get())
def RunServo5(event):
     Grippers.write(Gripper.get())
     print(Gripper.get())        
def kinematicbase(event):  # get the base angle to control kinematic function
     AngleBaseoutput = math.degrees(math.atan(y.get()/x.get())) #base
     Base.write(AngleBaseoutput)
def Shoulder(event):   # manipulator control function of Shouldr 
Esempio n. 26
0
# PINS 0, 1 and 11 broken
PINS = {
    'direction': 4,
    'step': 5,
    'sleep': 6,
    'dispense': 3,
    'reset': 2,
    'photocell': 5,  # A5
    'limit': 7,
    'ms1': 9,
    'ms2': 10,
    'ms3': 12,
    'gate': 13
}

CONNECTION = SerialManager(device='/dev/ttyUSB0')
A = ArduinoApi(connection=CONNECTION)
SERVO = Servo(PINS['gate'])
JOBS = []
SCHED = sched.scheduler(time.time, time.sleep)


def toggle(a):
    time.sleep(SLEEP_TIME)  # .75
    if a.digitalRead(PINS['sleep']) == a.HIGH:
        print("Sleeping")
        a.digitalWrite(PINS['sleep'], a.LOW)
    elif a.digitalRead(PINS['sleep']) == a.LOW:
        print("Awake")
        a.digitalWrite(PINS['sleep'], a.HIGH)
Esempio n. 27
0
import snowboydecoder
import sox
import rospkg
from time import sleep
from std_msgs.msg import Bool
from std_msgs.msg import String
import os
from nanpy import ArduinoApi
from nanpy import SerialManager
from nanpy import Servo

import logging
logging.basicConfig(level=logging.DEBUG)
SERVO_PAN = 7
SERVO_TILT = 8
connection = SerialManager(device='/dev/ttyACM0')
panservo=Servo(SERVO_PAN)
tiltservo=Servo(SERVO_TILT)
panservo.write(40)
tiltservo.write(55)
sleep(1)
panservo.write(40)
tiltservo.write(55)
sleep(1)
panservo.write(40)
tiltservo.write(55)

r = sr.Recognizer()
rospack = rospkg.RosPack()
FORMAT = pyaudio.paInt16
CHANNELS = 1
Esempio n. 28
0
from nanpy import (ArduinoApi, SerialManager)
from time import sleep

import threading

batteryPin = 'A5'
#connection = SerialManager('COM5')
connection = SerialManager('/dev/ttyACM0')
a = ArduinoApi(connection=connection)
eps = 0.0048828125

#Setup
a.pinMode(batteryPin, a.INPUT)

#Loop
batteryLevel = a.analogRead(batteryPin)
converted = (batteryLevel * 12) / 5

if converted > 13:
    print('100')
elif converted >= 12.75 and converted < 13:
    print('90')
elif converted >= 12.50 and converted < 12.75:
    print('80')
elif converted >= 12.30 and converted < 12.50:
    print('70')
elif converted >= 12.15 and converted < 12.30:
    print('60')
elif converted >= 12.05 and converted < 12.15:
    print('50')
elif converted >= 11.95 and converted < 12.05:
Esempio n. 29
0
#!/usr/local/bin/python3
from nanpy import (ArduinoApi, SerialManager)
import time

motorConnection = SerialManager(device=/dev/ttyUSB0)
A = ArduinoApi(connection=motorConnection)

mLeft1 = 'input1'
mLeft2 = 'input2'
eLeft = 'Enable1'

mRight1 = 'input3'
mRight2 = 'input4'
eRight = 'Enable2'

A.pinMode(mLeft1, A.OUTPUT)
A.pinMode(mLeft2, A.OUTPUT)
A.pinMode(eLeft2, A.OUTPUT)

A.pinMode(mRight1, A.OUTPUT)
A.pinMode(mRight2, A.OUTPUT)
A.pinMode(eRight, A.OUTPUT)

Esempio n. 30
0
#!/usr/bin/env python
# coding: utf8

from datetime import datetime
from time import sleep

import sys
from MeteorClient import MeteorClient
from nanpy import (ArduinoApi, SerialManager)
from nanpy.hx711 import Hx711
from nanpy.RGBLED import RGBLED

import configuration

connection = SerialManager(device=configuration.SERIAL_PORT)

led = RGBLED(configuration.LED_R_PINS[0], configuration.LED_G_PINS[0],
             configuration.LED_B_PINS[0], connection)
for i in range(1, len(configuration.LED_R_PINS)):
    led.addLED(configuration.LED_R_PINS[i], configuration.LED_G_PINS[i],
               configuration.LED_B_PINS[i])

led.setColor(0, 0, 255)

arduino = ArduinoApi(connection=connection)
arduino.pinMode(configuration.PUMP_PIN, arduino.OUTPUT)
for pin in configuration.VALVE_PINS:
    arduino.pinMode(pin, arduino.OUTPUT)

scale = Hx711(configuration.LOAD_CELL_DOUT_PIN,
              configuration.LOAD_CELL_SCK_PIN, connection)
from nanpy import DallasTemperature, SerialManager

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

sensors = DallasTemperature(connection=connection, pin=2)
n_sensors = sensors.getDeviceCount()

print("There are %d devices connected on pin %d" % (n_sensors, sensors.pin))
addresses = []

for i in range(n_sensors):
    addresses.append(sensors.getAddress(i))

sensors.setResolution(12)

while True:
    sensors.requestTemperatures()
    for i in range(n_sensors):
        temp = sensors.getTempC(i)
        print("Device %d (%s) temperature, in Celsius degrees is %0.2f" % (i, addresses[i], temp))
        print("Let's convert it in Fahrenheit degrees: %0.2f" % DallasTemperature.toFahrenheit(temp))
    print("\n")
Esempio n. 32
0
from nanpy import (ArduinoApi, SerialManager, OneWire)

connection = SerialManager(device='/dev/ttyACM0')
connection.baudrate=9600
#a = ArduinoApi(connection=connection)
#a.pinMode(13, a.OUTPUT)
#a.digitalWrite(13,a.HIGH)

connection.write("5")