示例#1
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')
示例#2
0
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):
        #Read the sensor(s), parse the data and store it in redis if redis is configured
        pass

    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 analog_pin_mode else self.api.digitalRead(self.pin)
        return data
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)
示例#4
0
    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
示例#5
0
  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)
示例#6
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)
示例#7
0
  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)
示例#8
0
    def connect(self):
        # close old connection if exists
        if self.serialManager:
            self.serialManager.close()

        # make new connection
        self.serialManager = SerialManager()
        self.a = ArduinoApi(connection=self.serialManager)
    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"]
示例#10
0
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))
示例#11
0
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
示例#12
0
def main(pir_pin=2,inactiveDuration=10,outdir="."):
    """
    *Parameters*
    > `pir_pin<int>`: the GPIO signal pin (in BCM mode) of the PIR motion sensor
    > `inactiveDuaration<int>`: specifies when the camera should stop recording after no motion has been detected
    > `outdir<str>`: the path to the desired directory of which to save the video files
    """
    # === Local Variables ===
    camera = PiCamera()

    # === setup Arduino ===
    connection = SerialManager()
    a = ArduinoApi(connection=connection)

    # === start main loop ===
    while True:
        # === sense PIR motion ===
        motionDetected = a.digitalRead(pir_pin)
        print(motionDetected)

        # === condition ===
        if  motionDetected:
            print("started recording...")

            # === start recording ===
            # Set-up camera
            camera.resolution = (1024,768)

            # Start camera
            camera.start_preview()

            # Camera warm-up time
            time.sleep(2)

            # Determine output filename
            outfilename = datetime.datetime.now().strftime("%m-%d-%Y-%H-%M-%S") + ".h264"

            # Start Recording
            camera.start_recording(outdir+"/"+outfilename)

            while motionDetected:

                # record for duration
                time.sleep(inactiveDuration)

                # detected motion
                motionDetected = a.digitalRead(pir_pin)

            # Stop Recording
            camera.stop_recording()
            print("recording finished")
示例#13
0
    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)
示例#14
0
 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
示例#15
0
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
示例#16
0
    def init(self):
        Logger.log(
            LOG_LEVEL["info"],
            '{name} Relay Worker {0}...\t\t\033[1;32m Initializing\033[0;0m'.
            format(self.key))
        self.api = self.api if self.api is not None else ArduinoApi(connection)
        self.pin_state_off = self.api.HIGH if self.config[
            'normally_open'] is not None and self.config[
                'normally_open'] else self.api.LOW
        self.pin_state_on = self.api.LOW if self.config[
            'normally_open'] is not None and self.config[
                'normally_open'] else self.api.HIGH
        self.api.pinMode(self.config['pin'], self.api.OUTPUT)
        # Close the relay by default, we use the pin state we determined based on the config at init
        self.api.digitalWrite(self.config['pin'], self.pin_state_off)
        time.sleep(0.1)

        # Feature to restore relay state in case of crash  or unexpected shutdown. This will check for last state stored in redis and set relay accordingly
        if (self.config.get('restore_last_known_state', None) is not None and
                self.config.get('restore_last_known_state', False) is True):
            if (self.r.get(self.key + '_state')):
                self.api.digitalWrite(self.config['pin'], self.pin_state_on)
                Logger.log(
                    LOG_LEVEL["warning"],
                    'Restoring Relay \033[1;36m{0} On\033[0;0m'.format(
                        self.key))

        self.relay_ready = True
        return
示例#17
0
def ConnectArduino():
    try:
        connection = SerialManager(device='/dev/ttyACM0')
        ConnectArduino.a = ArduinoApi(connection=connection)
        print("\n\nConnection Successful...\n\n")
    except:
        print("\n\nFailed to connect...\n\n")
示例#18
0
    def __init__(self, size=60, crossover=0.8, elitism=0.1, mutation=0.03):
        self.elitism = elitism
        self.mutation = mutation
        self.crossover = crossover
        self.population = []

        self.connection = SerialManager()
        self.a = ArduinoApi(connection=self.connection)
        for r in range(12):
            self.a.pinMode(r, self.a.OUTPUT)

        for i in range(size):
            self.population.append(Chromosome.gen_random())
        self._setFitness()
        self.population = list(sorted(self.population,
                                      key=lambda x: x.fitness))
def connectMotor():
    global Motor
    try:
        connection = SerialManager("/dev/ttyACM0")  #CHANGE THIS
        Motor = ArduinoApi(connection=connection)
    except Exception as e:
        print("Failed to connect to arduino!", e)
示例#20
0
    def arduino_api_scope(self):
        connection = SerialManager(device=self.arduino_port)
        arduino = ArduinoApi(connection=connection)

        try:
            yield arduino
        finally:
            connection.close()
示例#21
0
    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)
示例#22
0
def ConnectArduino():  #establish connection with arduino
    try:
        connection = SerialManager(
            device='/dev/ttyACM0')  #change device path for multiple Arduinos
        ConnectArduino.a = ArduinoApi(connection=connection)
        print("\n\nConnection Successful...\n\n")
    except:
        print("\n\nFailed to connect...\n\n")
示例#23
0
    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
示例#24
0
 def __init__(self, en, in1, in2, a=ArduinoApi()):
     self.en = en
     self.in1 = in1
     self.in2 = in2
     self.a = a
     self.a.pinMode(en, a.OUTPUT)
     self.a.pinMode(in1, a.OUTPUT)
     self.a.pinMode(in2, a.OUTPUT)
示例#25
0
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")
示例#26
0
    def __init__(self, _lcd):
        threading.Thread.__init__(self)
        try:
            self.conn = SerialManager()
            self.a = ArduinoApi(self.conn)
        except:
            print("Failed to connect to Arduino.")

        self.analogIn = '******'
        self.mVperAmp = 66  # use 100 for 20A Module and 66 for 30A Module
        self.voltage = 0
        self.amps = 0
        self.rawValue = 0
        self.default = 510
        # Current = Voltage You Applied / The Resistance of your Load
        
        self.lcd = _lcd
示例#27
0
def connectToArduino():
    try:
        con = SerialManager(timeout=3)
        api = ArduinoApi(connection=con)
        return api
    except Exception as e:
        print "Failed to connect to Arduino"
        print e
        sys.exit(1)
示例#28
0
    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)
示例#29
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:
					Logger.log(LOG_LEVEL["debug"], '\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:
					Logger.log(LOG_LEVEL["warning"], '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m           '.format(**self.config))
					if attempts > 0:
						Logger.log(LOG_LEVEL["info"], '{name} -> Preparing Reconnect...  \t'.format(**self.config))
					else:
						Logger.log(LOG_LEVEL["error"], '{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:
					Logger.log(LOG_LEVEL["error"], '[{name}] \033[1;33m Node Not Found. (Is it online?)\033[0;0m'.format(**self.config))
					conn = None
					self.resetConnection()
					time.sleep(15)
				else:
					Logger.log(LOG_LEVEL["info"], '{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:
					Logger.log(LOG_LEVEL["warning"], '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m           '.format(**self.config))
					if attempts > 0:
						Logger.log(LOG_LEVEL["info"], '{name} -> Preparing Reconnect...  \t'.format(**self.config), end='\r', flush=True)
					else:
						Logger.log(LOG_LEVEL["error"], '{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:
						Logger.log(LOG_LEVEL["info"], '[{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
    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)
示例#31
0
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))
示例#32
0
文件: Motor.py 项目: task123/AutoTT
    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()
示例#33
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)
# -SCT (09/27/14)

# ACTUALLY possibly too slow to use for 5 ms pulses. This is a shame. digitalWrite takes like 8 or 9 ms

# nanpy is the package with the Arduino control via python
from nanpy import (ArduinoApi, SerialManager)
import time
import datetime
import multiprocessing
import os
import wiringpi2 as wp
# will automatically find the arduino
# if there's more than one Arduino and you want a specific location, write SerialManager('location') (not as a string)
connection = SerialManager()
# a is the name of our Arduino at location connection
a = ArduinoApi(connection=connection)
# Define the names of the pins that we're using to control the lights
indicator = 9
pinStart = 10
pinEnd = 14
numPins = pinEnd-pinStart

# timescale is 1000 if we're using milliseconds, 1000000 if we're using microseconds (this is just a quality of life change to make the code easy to deal with if the implementation changes; thanks Stephen from a year ago!)
timescale = 1

# 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]
示例#35
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)
示例#36
0
# 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:
    temperature_sensors.requestTemperatures()
    s.starttls()
    s.ehlo()
    s.login(email, email_password)
    print(address_to_send)
    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')

示例#38
0
文件: blink.py 项目: DarkSotM/nanpy
#!/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)

示例#39
0
#!/usr/bin/env python

import cv2
import numpy as np
import time
from nanpy import ArduinoApi
from nanpy import SerialManager

Q = np.loadtxt('Q_mat.txt')

try:
    connection = SerialManager(device='/dev/ttyACM2')
    arduino = ArduinoApi(connection=connection)
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)
示例#40
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)
示例#41
0
from flask import Flask, render_template, Blueprint, Response, request, json
from time import sleep
from nanpy import(ArduinoApi, SerialManager)


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)
示例#42
0
文件: Motor.py 项目: task123/AutoTT
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
示例#43
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)

示例#44
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)