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
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
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)
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')
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)
class Control(): def __init__(self, pin, name=None, connection=default_connection, analog_pin_mode=False, key=None, redis_conn=None): self.pin = pin if key is None: raise Exception('No "key" Found in Control Config') else: self.key = key.replace(" ", "_").lower() if name is None: self.name = self.key.replace("_", " ").title() else: self.name = name self.analog_pin_mode = analog_pin_mode self.connection = connection self.api = ArduinoApi(connection) try: self.r = redis_conn if redis_conn is not None else redis.Redis( host='127.0.0.1', port=6379) except KeyError: self.r = redis.Redis(host='127.0.0.1', port=6379) return def init_control(self): #Initialize the control here (i.e. set pin mode, get addresses, etc) self.api.pinMode(self.pin, self.api.INPUT) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured return self.read_pin() def read_raw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def read_pin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if self.analog_pin_mode else self.api.digitalRead( self.pin) return data def emitEvent(self, data): message = {'event': 'ControlUpdate', 'data': {self.key: data}} print(message["data"]) self.r.publish('controls', json.dumps(message))
def water_read_moisture(pin='A0'): air = 580 water = 277 connection = SerialManager() a = ArduinoApi(connection=connection) a.pinMode(pin, 'INPUT') moisture_read = ((a.analogRead(pin) * -1) + air) / 3.05 return moisture_read
def setup_arduino(): ''' Setup arduino connection :return: Arduino API object used to control Arduino UNO ''' a = None try: connection = SerialManager() a = ArduinoApi(connection=connection) a.pinMode(Util.ledPin, a.OUTPUT) except: # arduino_present = False # print("Arduino device not found") pass return a
def main(): connect_broker() connection = SerialManager(device='/dev/ttyACM0') a = ArduinoApi(connection=connection) a.pinMode(PIN, a.INPUT) try: client.loop_start() while True: value = a.analogRead(PIN) client.publish("messwerte/test", str(value), qos=1) print "value:" + str(value) sleep(1) except: client.loop_stop() print("publisher stopped")
def establish_connection(): global a # Establish connection to Arduino try: connection = SerialManager() a = ArduinoApi(connection=connection) print "Connection established!" except: print "Connection Error!" # Setup Pinmodes try: a.pinMode(relais, a.OUTPUT) a.pinMode(smoke, a.INPUT) print "PinModes set!" except: print "Could not set PinModes!" return True
class Control(): def __init__(self, pin, name='Control', 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_control(self): #Initialize the control here (i.e. set pin mode, get addresses, etc) self.api.pinMode(self.pin, self.api.INPUT) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured return self.readPin() def readRaw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def readPin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if self.analog_pin_mode else self.api.digitalRead( self.pin) return data def emitEvent(self, data): message = {'event': 'ControlUpdate', 'data': {self.key: data}} print(message["data"]) variables.r.publish('controls', json.dumps(message))
def move(): Motor1A = 2 Motor1B = 3 Motor2A = 4 Motor2B = 5 # Connecting to the Arduino try: connection = SerialManager() arduino = ArduinoApi(connection = connection) except: print "Failed to connect to the arduino" arduino.pinMode(Motor1A,arduino.OUTPUT) arduino.pinMode(Motor1B,arduino.OUTPUT) arduino.pinMode(Motor2A,arduino.OUTPUT) arduino.pinMode(Motor2B,arduino.OUTPUT) print "Going forwards" arduino.digitalWrite(Motor1A,arduino.LOW) arduino.digitalWrite(Motor1B,arduino.HIGH) arduino.digitalWrite(Motor2A,arduino.LOW) arduino.digitalWrite(Motor2B,arduino.HIGH) sleep(2) # Stop the motors from moving (kill all power) arduino.digitalWrite(Motor1A,arduino.LOW) arduino.digitalWrite(Motor2A,arduino.LOW) arduino.digitalWrite(Motor1B,arduino.LOW) arduino.digitalWrite(Motor2B,arduino.LOW) print "end" return "hello pi"
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')
class MotorController: """ Controller of the motors through arduino and probably through H-Bridge Used from different parts of the programme. It only gets the command to start or stop some mouvements """ def __init__(self): """ Creation of connection to the arduino through nanpy and initialisation of the used Pins """ try: connection = SerialManager() self.asdw_m = ArduinoApi(connection=connection) print("failed to upload") except: print("didn't worked") self.asdw_m.pinMode(l_turn, self.asdw_m.OUTPUT) self.asdw_m.pinMode(back_d, self.asdw_m.OUTPUT) self.asdw_m.pinMode(r_turn, self.asdw_m.OUTPUT) self.asdw_m.pinMode(forward_d, self.asdw_m.OUTPUT) def drive_forward(self): self.asdw_m.digitalWrite(forward_d, self.asdw_m.HIGH) def drive_back(self): self.asdw_m.digitalWrite(back_d, self.asdw_m.HIGH) def turn_right(self): self.asdw_m.digitalWrite(r_turn, self.asdw_m.HIGH) def turn_left(self): self.asdw_m.digitalWrite(l_turn, self.asdw_m.HIGH) # part to stop the mouvement or the turn def stop_drive(self): self.asdw_m.digitalWrite(back_d, self.asdw_m.LOW) self.asdw_m.digitalWrite(forward_d, self.asdw_m.LOW) def stop_turn(self): self.asdw_m.digitalWrite(l_turn, self.asdw_m.LOW) self.asdw_m.digitalWrite(r_turn, self.asdw_m.LOW) def d_motor_off(self): pass def w_motor_off(self): pass
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) 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
from nanpy import (ArduinoApi, SerialManager) from time import sleep ledpin = 13 try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print("failed connection") a.pinMode(ledpin, a.OUTPUT) try: while _ in range(3): a.digitalWrite(ledpin, a.HIGH) print("on") sleep(1) a.digitalWrite(ledpin, a.LOW) print("off") sleep(1) except: a.digitalWrite(ledpin, a.LOW)
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.
#!/usr/bin/python from nanpy import (ArduinoApi, SerialManager) from time import sleep from time import time from measure import Measure #trigpin=4 #echopin=3 trigpin = 2 echopin = 3 try: connection = SerialManager() a = ArduinoApi(connection=connection) a.pinMode(trigpin, a.OUTPUT) a.pinMode(echopin, a.INPUT) m = Measure(connection=connection) print("Connected to Arduino") except: print("Failed to connect") while True: distance = m.getMeasure(trigpin, echopin) if distance > 0: print(distance) sleep(.25)
except: try: 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")
#!/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() a = ArduinoApi(connection=connection) a.pinMode(13, a.OUTPUT) for i in range(10000): a.digitalWrite(13, (i + 1) % 2) sleep(0.2)
# 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) )
import serial from nanpy import (ArduinoApi, SerialManager) ser = serial.Serial('/dev/ttyS0', 9600) connection = SerialManager() a = ArduinoApi(connection=connection) led = 4 a.pinMode(led, a.OUTPUT) while True: read_serial = ser.readline().decode().strip() if str(read_serial) == 'on': a.digitalWrite(led, a.HIGH) write_serial = ser.write(b'Led is ON\r\n') print("Led is ON") elif str(read_serial) == 'off': a.digitalWrite(led, a.LOW) write_serial = ser.write(b'Led is OFF\r\n') print("Led is OFF")
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)
Y_DIR_PIN = 6 Z_DIR_PIN = 7 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:
from nanpy import (ArduinoApi, SerialManager) from time import sleep ledPin = 7 btnPin = 8 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 functions are for live monitoring, duplicate info in each log file #after 90 days, timer will continue to decrement until light timer goes to 0, this will take a very long time import os import time import serial from serial import SerialException from threading import Timer from nanpy import SerialManager from nanpy import ArduinoApi connection = SerialManager(device='/dev/ttyACM0') a = ArduinoApi(connection=connection) a.pinMode(13, a.OUTPUT) #board status LED a.pinMode(2, a.OUTPUT) #relay output 1, for lights a.pinMode( 3, a.OUTPUT ) #relay output 2, for lights, not used unless needed due to 10 Amp limit a.pinMode(4, a.OUTPUT) #pump output 1 a.pinMode(5, a.OUTPUT) #pump output 2 os.chdir('/home/pi/Documents/plant_logs') list = os.listdir('/home/pi/Documents/plant_logs') number_files = len(list) print number_files file_count = number_files + 1 print file_count day_counter = 0 now = time.strftime("%c") time_increment = number_files * 300 time_decrement = (number_files - 45) * 300 light_timer = 36000 light_timer2 = 50400 # 14400 = 4 hours
a = ArduinoApi(connection=connection) except: print("Failed to connect Arduino") config = { "apiKey": "AIzaSyDuDlz-k6BxOvOJIcKOPNOPV611rr54Njo", "authDomain": "raspberrypi-89fd5.firebaseapp.com", "databaseURL": "https://raspberrypi-89fd5.firebaseio.com", "storageBucket": "raspberrypi-89fd5.appspot.com" } firebase = pyrebase.initialize_app(config) auth = firebase.auth() user = auth.sign_in_with_email_and_password("*****@*****.**", "Kalyan@bvcoe") 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)
#Hand Part # 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 a.pinMode(11,a.OUTPUT) #dir a.pinMode(12,a.OUTPUT) #step #Finger 2 a.pinMode(2,a.OUTPUT) #dir a.pinMode(6,a.OUTPUT) #step #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #Stepper motor Motor power cotrol function a.pinMode(29,a.OUTPUT) #Stepper motor Base power on/off a.pinMode(30,a.OUTOUT) #Stepper motor Shoulder power on/off a.pinMode(31,a.OUTPUT) #Stepper motor Elbow power on/off #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #Body part function of the robotic arm control and sensory #Base function for the robotic arm b.pinMode(2,b.OUTPUT) # dir b.pinMode(3,b.OUTPUT) # step #Shoulder function for the robotic arm
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)
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-'),
app = Flask(__name__) led = 13 sensor = 24 swch = 12 ledState = False swchState = 0 try: connection = SerialManager() ard = ArduinoApi(connection) # pinMode setup for arduino ard.pinMode(led, ard.OUTPUT) ard.pinMode(swch, ard.INPUT) ard.pinMode(sensor, ard.INPUT) except: print("Failed To Connect to Arduino") @app.route('/') def home(): try: estadoLuz = ard.digitalRead(led) temp = ard.analogRead(sensor) except: estadoLuz = "Debugging" temp=69
laser = ArduinoApi(connection=connectLaser) except: print("Laser connection failed!") # Parameter setup valveDelay = 70 # unit: (msec) sensor = [2, 3, 4, 5, 6, 7, 8, 9] rewardPort = ['A0', 'A1', 'A2', 'A3'] idx_sensor = 1 idValve = 1 state = 1 trial_current = 0 state_valve1 = state_valve2 = state_valve3 = state_valve4 = False for index in range(0, 8): m.pinMode(sensor[index], m.INPUT) for index in range(0, 4): m.pinMode(rewardPort[index], m.OUTPUT) def valve_open(index_valve): m.digitalWrite(rewardPort[index_valve], m.HIGH) sleep(valveDelay / 1000) m.digitalWrite(rewardPort[index_valve], m.LOW) def trigger_laser(time_pulseon, time_pulseoff): laser.digitalWrite('A0', laser.HIGH) sleep(time_pulseon) laser.digitalWrite('A0', laser.LOW) sleep(time_pulseoff)
#!/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)
buttonState = 0 numPins = len(servoPins) currentServo = 0 currentAngle = 0 servo = [] try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print("Failed to connect to Arduino") #Setup arduino pins like in arduino IDE a.pinMode(buttonPin, a.INPUT) for m in servoPins: servo.append(Servo(m)) try: while True: buttonState = a.digitalRead(buttonPin) print(" Button State: {} Current Servo: {} Current Angle: {}".format( buttonState, currentServo, currentAngle)) if buttonState: servo[currentServo].write(0) currentAngle = 0 currentServo += 1 if currentServo > numPins: currentServo = 0 sleep(1)
s.sendmail(email, address_to_send, msg.as_string()) s.quit() camera = picamera.PiCamera() val = 0; sensor = 0 try: connection = SerialManager() a = ArduinoApi(connection = connection) except: print("failed to connect") a.pinMode(sensor, a.INPUT) while True: val = a.analogRead(sensor) print(val) sleep(0.1) if val > 200: camera.capture('image.jpg') sleep(0.1) SendSpMail('image.jpg')
#Conversions from: http://wiki.seeed.cc/Grove_Starter_Kit_Plus/ from nanpy import (ArduinoApi, SerialManager) from time import sleep import math #Connect to Arduino. Automatically finds serial port. connection = SerialManager() a = ArduinoApi(connection=connection) sensor = 14 #A0 on shield B = 3975 #B value of the thermistor (Grove Starter Kit information) a.pinMode(sensor, a.INPUT) #Setup sensor while True: total = 0 #Each set of readings start with a total of 0 #Get all the readings: for i in range(0, 24): reading = a.analogRead(sensor) #Get reading resistance = ((1023 - reading) * 10000 / reading) #Find resistance log = math.log10(resistance / 10000) temp = (1 / (log / B + 1 / 298.15) - 273.15) #Find temperature readings[i] = temp #Place temp reading in i space of array sleep(0.1) #Time between readings #Add the readings: for i in range(0, 24): total += readings[i]
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)
res = requests.get(url, headers=heads) message = json.loads(res.text) if (message["status"] == "success"): # Get the data into a list. devices = message["data"] # Make sure you are connected to the Arduino! try: con = SerialManager("/dev/ttyACM0") a = ArduinoApi(connection=con) for device in devices: if (device["sensor"] == False): # This is an output device. SET the values! a.pinMode(device["port"], a.OUTPUT) type_values = device["type_values"] for type_value in type_values: name = type_value["name"] device_values = device["device_values"] a.analogWrite(device["port"], device_values[name]) elif (device["sensor"] == True): sensor = device["type"] if (sensor == "dht22"): dht = DHT(device["port"], DHT.DHT22) type_values = device["type_values"] for type_value in type_values: name = type_value["name"] device_values = device["device_values"] if (name == "temperature"):
#!/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)
readingsGND = [ 0 ] * 300 # samples of the <span id="result_box" class="" lang="en"><span class="hps">virtual</span> <span class="hps alt-edited">ground</span></span> SumSqGND = 0 SumSqVClamp = 0 total = 0 totalI = 0 try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print("failed to connect to Arduino") a.pinMode(PinVClamp, a.INPUT) a.pinMode(PinVirtGND, a.INPUT) '''try: for x in range(0,199): readingsVClamp.append(0) readingsGND.append(0) print ("Our button State is: {}".format(readingVclamp[x])) except: print("Unable to clear sampling space") ''' try: while True: SumSqGND = 0 SumSqVClamp = 0 total = 0 totalI = 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
#!/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)
#!/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)