Пример #1
0
    def __init__(self):
        self.db = Database() # classe database
        self.i2c = 0
        self.getBusValue() # Setta il corretto device
        self.A = {}
        self.P = {}
        self.mBoard = [] # matrive board
        self.mBoard_io = [] # matrice IO
        self.mProg = [] # matrice programma
        self.area_id = ()
        self.dir_root = os.path.dirname(os.path.abspath(__file__))
        self.initialize()

        """
        Example pigpio port
        """
        self.pi = pigpio.pi("localhost", 8888) # Instance host, port
        print dir(self.pi)
        print
        self.pi.write(16, False)
        print self.pi.read(16) # Read status if IO 16
        self.pi.write(16, True) # Write 1 to IO 16
        print self.pi.read(16)

        for n in range(32): # print mode of GPIO: 0 = INPUT  1 = OUTPUT, 2 = ALT5, 3 = ALT4, 4 = ALT0, 5 = ALT1, 6 = ALT2, 7 = ALT3
            print "GPIO n:%s, mode: %s" %(n, self.pi.get_mode(n))
Пример #2
0
    def init(self, switch_pin=None, clock_pin=None, data_pin=None, **kwargs):
        self._switch_pin = switch_pin
        self._clock_pin = clock_pin
        self._data_pin = data_pin
        self._state = 0
        self._gpio = pigpio.pi()
        self._data = None
        self._clock = None
        self._switch = None

        if self._switch_pin:
            self._gpio.set_glitch_filter(self._switch_pin, 2000)
            self._gpio.set_mode(self._switch_pin, pigpio.INPUT)
            self._gpio.set_pull_up_down(self._switch_pin, pigpio.PUD_UP)
            self._switch = self._gpio.callback(self._switch_pin, pigpio.EITHER_EDGE, self._switch_cb)

        if self._data_pin:
            self._gpio.set_mode(self._data_pin, pigpio.INPUT)
            self._data = self._gpio.callback(self._data_pin, pigpio.EITHER_EDGE, self._data_cb)

        if self._clock_pin:
            self._gpio.set_mode(self._clock_pin, pigpio.INPUT)
            self._clock = self._gpio.callback(self._clock_pin, pigpio.EITHER_EDGE, self._clock_cb)

        if self._data_pin and self._clock_pin:
            self._state = 2*self._gpio.read(self._clock_pin) + self._gpio.read(self._data_pin)

        self._values = []
Пример #3
0
def main():
    #Run pigpiod is called on getSensorData script

    #Init led flasher
    INDC_SPLY_OUTS	= 16
    INDC_HEALTH_RED	= 26
    INDC_HEALTH_GREEN	= 20
    INDC_HEALTH_BLUE	= 19

    #Supply voltage
    #Related to srCurrent
    #Normal off, error blinking

    #Health
    #Normal blinking green
    #Network error blinking red
    #Temp error blinking yellow
    #CPU utilization error blinking yellow
    try:
        pi = pigpio.pi()
        while True:
            #time.sleep(4)
            time.sleep(0.2)
            pi.write(23,1)
            time.sleep(0.2)
            pi.write(23,0)
    except:
        print 'Error init led flasher'
        pi.stop()
        sys.exit(1)
Пример #4
0
 def __init__(self, logger):
     self.logger = logger
     self.pi = pigpio.pi()
     # self.Pit-Config
     self.pit_type = None
     self.pit_gpio = None
     
     # public
     self.pit_min = 50
     self.pit_max = 200
     self.pit_inverted = False
     
     self.pit_startup_min = 25
     self.pit_startup_threshold = 0
     self.pit_startup_time = 0.5
     
     # Steuergröße
     self.pit_out = None
     
     # Wave-ID
     self.fan_pwm = None
     
     self.pit_io_pwm_thread = None
     self.pit_io_pwm_on = 0
     self.pit_io_pwm_off = 0
     self.pit_io_pwm_lock = threading.Lock()
     self.pit_io_pwm_end = threading.Event()
def main():
    #Run pigpiod is called on getSensorData script

    #Init charger control
    try:
        pi = pigpio.pi()
        while True:
            #Read from DB
            db = MySQLdb.connect("localhost","monitor","1234","smartRectifier")
            curs = db.cursor()
            cmd = "SELECT srVBat FROM sensorDataCurrent ORDER BY srVBat ASC LIMIT 1"
            curs.execute(cmd)
            value = curs.fetchone()
            vbat = value[0]
            db.close()
            print vbat
            #print type(vbat)
            
            #!!! Handler if vbat is NULL !!!
            if vbat is not None and vbat < 50:
                #charging
                pi.write(21,1)
                time.sleep(600)
                pi.write(21,0)
            time.sleep(30)
    except:
        print 'Error charger control'
        pi.stop()
        sys.exit(1)
Пример #6
0
  def __init__(self, servo=False, motor_trim_factor=1.0):
    self.pi = pigpio.pi('localhost')
    self.pi.set_mode(PIN_PUSHBUTTON, pigpio.INPUT)
    self.pi.set_mode(PIN_ENCODER_LEFT, pigpio.INPUT)
    self.pi.set_mode(PIN_ENCODER_RIGHT, pigpio.INPUT)
    self._cb = dict()
    self._cb_last_tick = dict()
    self._cb_elapse = dict()
    self._servo = servo
    self._motor_trim_factor = motor_trim_factor
    if self._servo:
      self.motor_control = self._servo_motor
    else:
        self.motor_control = self._pibrella_motor

    self._cb1 = self.pi.callback(PIN_PUSHBUTTON, pigpio.EITHER_EDGE, coderbot_callback)
    self._cb2 = self.pi.callback(PIN_ENCODER_LEFT, pigpio.RISING_EDGE, coderbot_callback)
    self._cb3 = self.pi.callback(PIN_ENCODER_RIGHT, pigpio.RISING_EDGE, coderbot_callback)
    for pin in self._pin_out:
      self.pi.set_PWM_frequency(pin, PWM_FREQUENCY)
      self.pi.set_PWM_range(pin, PWM_RANGE)

    self.stop()
    self._is_moving = False
    self.sonar = [sonar.Sonar(self.pi, PIN_SONAR_1_TRIGGER, PIN_SONAR_1_ECHO),
                  sonar.Sonar(self.pi, PIN_SONAR_2_TRIGGER, PIN_SONAR_2_ECHO),
                  sonar.Sonar(self.pi, PIN_SONAR_3_TRIGGER, PIN_SONAR_3_ECHO)]
    self._encoder_cur_left = 0
    self._encoder_cur_right = 0
    self._encoder_target_left = -1
    self._encoder_target_right = -1
Пример #7
0
 def __init__(self, address, port):
     super(PiGPIOInterface, self).__init__()
     self.hostname = address
     self.port = port
     self._logger = PytoLogging(self.__class__.__name__)
     self.pig = pigpio.pi(self.hostname,self.port)
     self._logger.info("creating pigpiod connection to %s on port %s " % (self.hostname, port))
Пример #8
0
 def __new__(cls, number, host='localhost', port=8888):
     try:
         return cls._PINS[(host, port, number)]
     except KeyError:
         self = super(PiGPIOPin, cls).__new__(cls)
         cls._PINS[(host, port, number)] = self
         try:
             self._connection = cls._CONNECTIONS[(host, port)]
         except KeyError:
             self._connection = pigpio.pi(host, port)
             cls._CONNECTIONS[(host, port)] = self._connection
         self._host = host
         self._port = port
         self._number = number
         self._pull = 'up' if number in (2, 3) else 'floating'
         self._pwm = False
         self._bounce = None
         self._when_changed = None
         self._callback = None
         self._edges = pigpio.EITHER_EDGE
         try:
             self._connection.set_mode(self._number, pigpio.INPUT)
         except pigpio.error as e:
             del cls._PINS[(host, port, number)]
             raise ValueError(e)
         self._connection.set_pull_up_down(self._number, self.GPIO_PULL_UPS[self._pull])
         self._connection.set_glitch_filter(self._number, 0)
         self._connection.set_PWM_range(self._number, 255)
         return self
Пример #9
0
 def ValueChange(self, instance, value):
     self.label_1.text = str(self.slide_1.value)
     try:
         p = pigpio.pi()
         p.set_servo_pulsewidth(18, 1500 + self.slide_1.value)
     except:
         pass
Пример #10
0
 def __init__(self):
     self.logger = logging.getLogger(__name__)
     self.gpio = pigpio.pi()
     if not self.gpio is None:
         self.__setup_pins()
     else:
         self.logger.critical("Failed to get GPIO!")
Пример #11
0
def raspberrypi_bridge():
    """
    Main function for the raspberry pi bridge
    :return:
    """
    # noinspection PyShadowingNames

    parser = argparse.ArgumentParser()
    parser.add_argument("-b", dest="board_number", default="1", help="Board Number - 1 through 10")
    parser.add_argument("-r", dest="router_ip_address", default="None", help="Router IP Address")

    args = parser.parse_args()

    pi = pigpio.pi()

    board_num = args.board_number
    router_ip_address = args.router_ip_address
    rpi_bridge = RaspberryPiBridge(pi, board_num, router_ip_address)
    try:
        rpi_bridge.run_raspberry_bridge()
    except KeyboardInterrupt:
        rpi_bridge.cleanup()
        pi.stop()
        sys.exit(0)

    # signal handler function called when Control-C occurs
    # noinspection PyShadowingNames,PyUnusedLocal,PyUnusedLocal
    def signal_handler(signal, frame):
        print("\nControl-C detected. See you soon.")
        sys.exit(0)

    # listen for SIGINT
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
Пример #12
0
def end_read(signal, frame):
    global continue_reading
    print("Ctrl+C captured, ending read.")
    continue_reading = False
    # GPIO.cleanup()
    pi = pigpio.pi()
    pi.stop()
Пример #13
0
    def __init__(self, config):
        '''
        '''

        self.config = config

        self.hours_pin = int(config.get('clockdriver', 'hour_pin'))
        self.mins_pin = int(config.get('clockdriver', 'min_pin'))
        self.seconds_pin = int(config.get('clockdriver', 'sec_pin'))

        # 
        self.gpio = pigpio.pi()

        #
        self.ds3231 = SDL_DS3231(0, int(config.get('clockdriver', 'ds3231addr'),0) )

        #
        self.msfdecoder = MSFDecoder( self.gpio, 
                                      int(config.get('clockdriver', 'msf_pin')),
                                      self.tick_callback,
                                      self.timesync_callback,
                                    )

        self.dial_update_scheduled = False

        self.running = True

        return
Пример #14
0
	def __init__(self):
		rospy.Subscriber('Green_led', Bool, self.green)
		rospy.Subscriber('White_led', Bool, self.white)
		#self.green_pub = rospy.Publisher("green_light", String, queue_size=1)
		#self.white_pub = rospy.Publisher("white_light", String, queue_size=1)

		self.pig = pigpio.pi()
		self.pig.set_mode(12, pigpio.OUTPUT)
		self.pig.set_mode(16, pigpio.OUTPUT)
		self.green_flag = 0

		rate = rospy.Rate(360) #Hz

		counter = 0

		while not rospy.is_shutdown():
			if self.green_flag == 0:
				self.pig.write(16, 0)
			elif self.green_flag == 1:
				if counter == 0 or counter == 1 or counter == 2 or counter == 3 or counter == 4 or counter == 5 or counter == 6 or counter == 7:  
					self.pig.write(16, 1)
				else:
					self.pig.write(16, 1) #self.pig.write(16, 0)
			counter += 1

			if counter > 23:
				#this resets the counter
				counter = 0
			rate.sleep()	
Пример #15
0
	def __init__(self):
		self.MAX_RETRIES = 5
		self.roomTemp = 0 #Init temp
		self.rasPiChannel = 1	#Numero de bus dans la raspberry
		self.omronAddress = 0x0a #Adresse du capteur dans la Rasp
		self.arraySize = 16 #Taille des donnees du capteur
		self.BUFFER_LENGTH=(self.arraySize * 2) + 3       # Taille du buffer
		self.piGPIO = pigpio.pi()
		self.piGPIOver = self.piGPIO.get_pigpio_version()
		self.i2cBus = smbus.SMBus(1) 
		time.sleep(0.1)                

			# initialize the device based on Omron's appnote 1
		self.retries = 0
		self.result = 0
		for i in range(0,self.MAX_RETRIES):
			time.sleep(0.05)                               # Wait a short time
			self.handle = self.piGPIO.i2c_open(self.rasPiChannel, self.omronAddress) # open Omron D6T device at address 0x0a on bus 1
			print self.handle
			if self.handle > 0:
				self.result = self.i2cBus.write_byte(self.omronAddress,0x4c)
			break
		else:
			print ''
			print '***** Omron init error ***** handle='+str(self.handle)+' retries='+str(self.retries)
			self.retries += 1
Пример #16
0
 def __init__(self,debug = 0,
             enc_plus = 16,
             enc_minus = 20,
             enc_button = 21,
             no_encoder = 0,
             encoder_object = None):
     #Set the encoder + and - pins and push switch pin
     self.enc_plus = enc_plus
     self.enc_minus = enc_minus
     self.enc_button = enc_button
     #Set the debug level
     self.debug = debug
     self.pos = 0
     self.pushed = 0
     self.no_encoder = no_encoder
     self.encoder_object = encoder_object #if not none, this is a curses object
     if (self.debug == 0):
         #Setup the rotary encoder module (lol idk what it does)
         self.pi = pigpio.pi()
         self.decoder = rotary_encoder.decoder(self.pi, self.enc_plus, self.enc_minus, self.callback)
         #Set the GPIO parameters for the push switch pin
         GPIO.setmode(GPIO.BCM)
         GPIO.setup(self.enc_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
     else:
         #self.screen = curses.initscr()
         # turn off input echoing
         #curses.noecho()
         # respond to keys immediately (don't wait for enter)
         #curses.cbreak()
         # map arrow keys to special values
         #self.screen.keypad(True)
         pass
Пример #17
0
  def __init__(self,
    port=DEFAULT_GPIO_TX,
    baudrate=DEFAULT_BAUD,
    serial_address=DEFAULT_ADDRESS,
    word_offset=DEFAULT_GPIO_WORD_OFFSET,
    stop_bits=DEFAULT_STOP_BITS):

    if SIM_MODE:
      print 'In sim mode.  Commands will not be sent to TXD.'

    # Create serial connection
    self._conn = pigpio.pi()
    # Initialize GPIO TX Pin
    self._conn.set_mode(port,pigpio.OUTPUT)
    self._conn.set_pull_up_down(port, pigpio.PUD_DOWN)

    # Define the settings required by pigpio api
    self._gpio_tx_port = port
    self._gpio_baud = baudrate
    self._gpio_offset = word_offset
    self._gpio_stop_bits = stop_bits

    # Initialize sabertooth
    time.sleep(3)
    self._write_bytes(bytearray([AUTO_BAUD_RATE_COMMAND]))

    self._serial_address = serial_address

    # Sabertooth requires you to define a min battery voltage upon startup
    self._send_packet(
      self._get_packet_for_command(
        MIN_VOLTAGE_COMMAND,10))
    def __init__(self, pins):

        assert len(pins) == 3

        self.PINS = pins
        self.MIN_SPEED = 1
        self.MAX_SPEED = 20

        self.interval = 1
        self.speed    = 1
        self.set_speed(self.MIN_SPEED)

        self.gpio = None
        self.gpio = pigpio.pi()

        self.stop_event = threading.Event()

        self.thread = None

        self.programs = {
            "off"    : self.off,
            "fade"   : self.fade,
            "flash"  : self.flash,
            "strobe" : self.strobe,
            "smooth" : self.smooth
        }
Пример #19
0
	def __init__(self):
		Pio._refcount += 1
		self._closed = False
		if not Pio._started:
			
			try:
				Pio.host
			except AttributeError:
				Pio.host = 'localhost'
				
			try:
				Pio.port
			except AttributeError:
				Pio.port = 8888
				
			# now see if daemon is running
			try:
				socket = soc.create_connection((Pio.host,Pio.port))
			except:
				dok = False
			else:
				socket.close()
				dok = True
			
			if not dok:
				self._closed = True
				raise RuntimeError('Cannot connect to pigpio daemon')
					
			Pio.pi = pg.pi(Pio.host,Pio.port)
			Pio._started = True
Пример #20
0
 def startPIGPIO(self):
    if sys.version_info[0] < 3:
        import commands
        status, process = commands.getstatusoutput('sudo pidof pigpiod')
        if status:  #  it wasn't running, so start it
            self.LogInfo ("pigpiod was not running")
            commands.getstatusoutput('sudo pigpiod')  # try to  start it
            time.sleep(0.5)
            # check it again        
            status, process = commands.getstatusoutput('sudo pidof pigpiod')
    else:      
        import subprocess
        status, process = subprocess.getstatusoutput('sudo pidof pigpiod')
        if status:  #  it wasn't running, so start it
            self.LogInfo ("pigpiod was not running")
            subprocess.getstatusoutput('sudo pigpiod')  # try to  start it
            time.sleep(0.5)
            # check it again        
            status, process = subprocess.getstatusoutput('sudo pidof pigpiod')
    
    if not status:  # if it was started successfully (or was already running)...
        pigpiod_process = process
        self.LogInfo ("pigpiod is running, process ID is {} ".format(pigpiod_process))
    
        try:
            pi = pigpio.pi()  # local GPIO only
            self.LogInfo ("pigpio's pi instantiated")
        except Exception as e:
            start_pigpiod_exception = str(e)
            self.LogError ("problem instantiating pi: {}".format(start_pigpiod_exception))
    else:
        self.LogError ("start pigpiod was unsuccessful.")
        return False
    return True
    def __init__(self):

        # Setup SPI
        self.spi = spidev.SpiDev()

        # -------------------------------
        # GPIO pin for bump switch setup
        # -------------------------------
        self.pi1 = pigpio.pi()
        self.pi1.set_mode(18, pigpio.INPUT)
        cb1 = self.pi1.callback(18, pigpio.RISING_EDGE, self.bumpSwitch_ISR)
        self.bumpSwitchPressed = False

        #---------------------
        # Color sensing setup 
        #---------------------
        # Setup Color Sensor Array
        self.bus = smbus.SMBus(1)
        self.addr = 0x70
        self.addr1 = 0x29

        # Initialize and calibrate color sensors
        self.initializeColorSensors()

        # Approximate rail cart RGB arrays
        self.redCartColor = [91, 86, 17]
        self.blueCartColor = [74, 69, 2]
        self.greenCartColor = [111, 97, 16]
        self.yellowCartColor = [99, 94, 26]
        self.railCartColorMatrix = [self.redCartColor, self.blueCartColor, self.greenCartColor, self.yellowCartColor]
Пример #22
0
def main():
    
    '''Entry point for script'''

    global precip_tick_count
    global precip_accu
 
    precip_tick_count = 0
    precip_accu       = 0


    #---------------------------------------------------------------------------
    # SET UP LOGGER
    #---------------------------------------------------------------------------
    logger = log.setup('root', '/home/pi/weather/logs/read_rain_gauge.log')

    logger.info('--- Read Rain Gauge Script Started ---')
    

    #---------------------------------------------------------------------------
    # LOAD DRIVERS
    #---------------------------------------------------------------------------
    try:
        pi = pigpio.pi()

    except Exception, e:
        logger.error('Failed to connect to PIGPIO ({error_v}). Exiting...'.format(
            error_v=e))
        sys.exit()
Пример #23
0
   def __init__(self, gpioA, gpioB,):


      self.pi = pigpio.pi()
      self.gpioA = gpioA
      self.gpioB = gpioB
      #self.callback = callback
      
      self.levA = 0
      self.levB = 0
      self.lastGpio = None

      self.pi.set_mode(gpioA, pigpio.INPUT)
      self.pi.set_mode(gpioB, pigpio.INPUT)

      self.pi.set_pull_up_down(gpioA, pigpio.PUD_UP)
      self.pi.set_pull_up_down(gpioB, pigpio.PUD_UP)
      
      
      """VARIABLES DE INTERRUPCION"""
      self.pos = 0
      self.tiempo_pasado = time.time()
      self.tiempo_actual = 0	
      self.velocidad = 0
      self.pid_posicion = pidp()
      self.status = 0
Пример #24
0
    def __init__(self):
        # Wecker parameter
        self.weckzeit = None          
        self.wecker_startzeit = None
        self.wecken_p = False
        
        self.dimm_dauer = 120 #sekunden
        self.nachleuchten = 1 #sekunden

        self.config_file = SCRIPT_DIR + "/config.json"
        
        # PWM Configuration
        self.pwm_start = 1000
        self.pwm_ende  = 2550

        self.pi = pigpio.pi()
        # setup pin as an output
        self.pi.set_mode(LED_PIN, pigpio.OUTPUT)
        # pi set frequency
        self.pi.set_PWM_frequency(LED_PIN, 1200)

        self.load_config()

        if(self.weckzeit):
            self.init_scheduler()
Пример #25
0
    def __init__(self, config_file, rgb_csv_file, logging_config_file=None):
        if logging_config_file is None:
            self.logging = logging.getLogger(self.__class__.__name__)
            logging.basicConfig(filename='hugh.log',level=logging.INFO)
        else:
            logging.config.fileConfig(logging_config_file, disable_existing_loggers=True)
            self.logging = logging.getLogger(self.__class__.__name__)
        
        self.pi = pigpio.pi() # local device GPIO

        # Config parsing
        self.timestamps = [0.0, 0.0] # when configuration files were last updated
        self.config_files = [ config_file, rgb_csv_file ]

        self.color_correction = None

        self.fade_through_black = None
        self.instant = None
        self.increment_count = None

        self.freq = None
        self.pins = None
        
        self.scp = ConfigParser.SafeConfigParser()
        self.configure()

        self.init_pins()
        self.set_frequency()
Пример #26
0
   def __init__(self, rasPiChannel=1, omronAddress=0x0a, arraySize=8):
      self.MAX_RETRIES = 5
      self.roomTemp = 0
      self.omronAddress = omronAddress
      self.arraySize = arraySize
      self.BUFFER_LENGTH=(arraySize * 2) + 3       # data buffer size 
      self.CRC_ERROR_BIT = 0x04                    # the third bit
      self.CRC = 0xa4 / (16/arraySize)                             # if you take the CRC of the whole word including the PEC, this is what you get
      self.piGPIO = pigpio.pi()
      self.piGPIOver = self.piGPIO.get_pigpio_version()
      self.i2cBus = smbus.SMBus(1)
      time.sleep(0.1)                # Wait
      
      # initialize the device based on Omron's appnote 1
      self.retries = 0
      self.result = 0
      for i in range(0,self.MAX_RETRIES):
         time.sleep(0.05)                               # Wait a short time
         self.handle = self.piGPIO.i2c_open(rasPiChannel, omronAddress) # open Omron D6T device at address 0x0a on bus 1
	 print self.handle
         if self.handle > 0:
            self.result = self.i2cBus.write_byte(self.omronAddress,0x4c)
            break
         else:
            print ''
            print '***** Omron init error ***** handle='+str(self.handle)+' retries='+str(self.retries)
            self.retries += 1
Пример #27
0
	def __init__(self, red_pin, green_pin, blue_pin, brightness=100):
		import pigpio
#		Disallow same pin for two colors
#		if red == green or red == blue or green == blue:
#			raise ValueError('The pin values cannot be the same')
		self.gpio = pigpio.pi()
		if red_pin in self.ALLOWED_PINS:
			self.red_pin = red_pin
		else:
			raise ValueError('Red pin must be one of: ' + str(self.ALLOWED_PINS))
		
		if green_pin in self.ALLOWED_PINS:
			self.green_pin = green_pin
		else:
			raise ValueError('Green pin must be one of: ' + str(self.ALLOWED_PINS))
		
		if blue_pin in self.ALLOWED_PINS:
			self.blue_pin = blue_pin
		else:
			raise ValueError('Blue pin must be one of: ' + str(self.ALLOWED_PINS))
			
		self.red_val = 0
		self.green_val = 0
		self.blue_val = 0
		self.set_brightness(brightness)
Пример #28
0
    def __init__(self):
        self.pin_motor_left_front = rospy.get_param('~pin_motor_left_front', 11)
        self.pin_motor_right_front = rospy.get_param('~pin_motor_right_front', 9)
        self.pin_motor_left_back = rospy.get_param('~pin_motor_left_back', 14)
        self.pin_motor_right_back = rospy.get_param('~pin_motor_right_back', 18)

        # in meter
        self.wheel_dist = rospy.get_param('~wheel_dist', 0.223)

        self.max_vel = rospy.get_param('~max_velocity', 255)
        self.min_vel = rospy.get_param('~min_velocity', 100)

        # in sec
        self.timeout = rospy.get_param('~timeout', 1)

        self.velocity_corr = rospy.get_param('~velocity_correction', 1.0)
        self.rotation_corr = rospy.get_param('~rotation_correction', 1.0)

        self.debug_mode = rospy.get_param('~debug_mode', False)

        try:
            if not self.debug_mode:
                self.pi = pigpio.pi()

                self.pi.set_mode(self.pin_motor_left_front, pigpio.OUTPUT)
                self.pi.set_mode(self.pin_motor_right_front, pigpio.OUTPUT)
                self.pi.set_mode(self.pin_motor_left_back, pigpio.OUTPUT)
                self.pi.set_mode(self.pin_motor_right_back, pigpio.OUTPUT)

                # switch them off for now
                self.pi.write(self.pin_motor_left_front, 0)
                self.pi.write(self.pin_motor_right_front, 0)
                self.pi.write(self.pin_motor_left_back, 0)
                self.pi.write(self.pin_motor_right_back, 0)
        except:
            print " Error: unable to set cmd vel!"
            # return

        self.vel_right = 0.0
        self.vel_left = 0.0
        self.last_msg = None
        self.enabled = False

        self.x = 0
        self.y = 0
        self.vx = 0
        self.vy = 0
        self.yaw = 0
        self.vyaw = 0
        self.last_time = None

        rospy.Subscriber("cmd_vel", Twist, self.cmd_cb)
        self.odom_pub = rospy.Publisher("/odom", Odometry, queue_size=10)
        self.tfbr = tf.TransformBroadcaster()

        while not rospy.is_shutdown():
            rospy.sleep(0.02)  # 50Hz
            self.check_timeout()
            self.publish_odometry()
Пример #29
0
    def Initialize(self):
        # Create an RFID object.
        self.pi = pigpio.pi()
        self.rfid = decoder(self.pi, self.data_low, self.data_high, self._RfidTagScanned)

        self.pi.set_mode(self.led, pigpio.OUTPUT)
        self.pi.set_mode(self.beep, pigpio.OUTPUT)
        self.pi.set_mode(self.lock, pigpio.OUTPUT)
Пример #30
0
 def initialize(self):
     if(pigpioLibraryFound):           
         self.emit(QtCore.SIGNAL('logEvent'),"servo initialized") 
         self.pi = pigpio.pi()
         self.setAngle(90)
         self.currentAngle = 90
         self.openLid()
         self.currentState = ScreenState.OPEN
Пример #31
0
#
#
# unit testing script for the ventilator
# controller class
#

import pigpio
from configs.gpio_map import *
from actuators.motor import Motor
from sensors.rotary_encoder import RotaryEncoder
from sensors.limit_switch import LimitSwitch
from sensors.power_switch import PowerSwitch
from ventilator_controller import VentilatorController

if __name__ == "__main__":
    encoder = RotaryEncoder(pigpio.pi(), ENCODER_B_PLUS_PIN,
                            ENCODER_A_PLUS_PIN)
    contact_switch = LimitSwitch(CONTACT_SWITCH_PIN)
    absolute_switch = LimitSwitch(ABSOLUTE_SWITCH_PIN)
    power_switch = PowerSwitch(POWER_SWITCH_PIN)

    # instantiate actuators
    motor = Motor(encoder)

    # instantiate controller
    controller = VentilatorController(motor, None, absolute_switch,
                                      contact_switch, power_switch)

    controller.start_homing()

    print("Start ventilation...")
Пример #32
0
 def __init__(self,gpio):
    self.gpio=gpio
    self.pi = pigpio.pi()
    if not self.pi.connected:
       exit()
    self.pi.set_servo_pulsewidth(gpio, MID_WIDTH)
Пример #33
0
import cv2 as cv
import time
import imutils
import argparse
from imutils.video import VideoStream
from imutils.video import FPS

#servo libraries
import RPi.GPIO as GPIO
import pigpio
import time

servo = 18 #GPIO 18 corresponds to pin 11 in reality

#Use pigpio to set a PWM
pwm = pigpio.pi()
pwm.set_mode(servo,pigpio.OUTPUT)
pwm.set_PWM_frequency(servo,50) #setting the PWM to 50hz, this is what the servo was designed for


#initialising servo ranges
maxServoPos = 2500 #Pulse width of 2500 microseconds
minServoPos = 500 #Pulse width of 500 microseconds
midServoPos = minServoPos+(maxServoPos-minServoPos)/2 #Middle of servo = 1500 microseconds

servoPos = midServoPos #initialising variable which will store servo values
pwm.set_servo_pulsewidth(servo,servoPos) #setting servo to 90 degreees initially

#initialising variables that store values for PID
integral = 0
prev_error = 0
def main():
	user =  "******"
	password = "******"
	host = ""
	localpi = pigpio.pi()

	power_pin = 0

	serial_passes = 0
	plugin_passes = 0
	serial_fails = 0
	plugin_fails = 0

	A_firmware = ""
	B_firmware = ""

	initial_run = True
	initial_plugins = 0
	current_plugins = 0
	trial_number = 0
	plugin_trial_number = 0
	returned_serial = ""

	#while A_firmware and B_firmware == "":
		#A_firmware = input("What's the normal firmware's git hash?:\n")
		#B_firmware = input("What's the alternate firmware's git hash?: \n")

	while host == "":

		host = input("What's the IP?\n")
		expected_serial = input("and what's the serial?\n")
		power_pin = int(input("What's the power pin to use?"))

	filename = (expected_serial + "logfile.txt")
	
	if exists(filename) != True:
		print("Creating a logfile...")
		target = open(filename, 'x')
		target.close()
		print("Logfile created!")

	elif exists(filename) == True:
		print("Appending to existing logfile.")

	while True:

		print("Trial #", trial_number)

		# Boot the oven


		localpi.write(power_pin, 1)
	# Wait for a ssh connection
		connected = False
		while connected == False:
			try:
				ssh = paramiko.SSHClient()
				ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
				ssh.connect(host, username = user, password = password)
				print("connected!")
				connected = True



			except:
				sleep(1)
				print("connecting...")

	# When connected, query the serial number and plug in events.

		returned_serial = check_serial(host)
		print("the serial is", returned_serial)

			#read the plugins
		current_plugins = check_plugins(host)
		print("the plugins are ", current_plugins)

	# If this is the initial run of the test, store the plug in events.

		if initial_run == True:
			print("this is an initial run of this test.\n")
			initial_plugins = current_plugins
			initial_run = False
	# Wait 1 minute.

		for i in range(1,90):
			print(i, "...")
			sleep(1)
	# On five second intervals, query the serial number and plug in events. Do this 6 times

		for i in range(1,2):
			print("Check #", i, "checking the serial...")
			check = check_serial(host)

			if check in expected_serial:
				print("The serial is correct")
				serial_passes += 1

	# If the serial is corrupted, fail
			elif check != expected_serial:
				print(check)
				print("Wrong serial! fail:(")
				serial_fails += 1
	# If the serial is blank, fail
			elif check == "":
				print("no serial. Fail:(")
				serial_fails += 1
	# On the 6th query, check the plugin events is correct.
			print("checking plugins...")
			check = check_plugins(host)
			
			sleep(5)


	# If plugin is incorrect, fail and restart the initial plugin events check
			if check == (initial_plugins +	plugin_trial_number):
				print("there are ", check, "plugins, which is expected. Pass!")
				plugin_passes += 1

			elif check != (initial_plugins + plugin_trial_number):
				print("there are ", check, "plugins. There should be: ", initial_plugins +	plugin_trial_number, "fail:(")
				plugin_fails += 1
				
				#reset the plugins 
				
				initial_plugins = 0
				plugin_trial_number = 0
				initial_run = True
				
			else:
				print("whoops. Check the initial plugin stuff")


	# Close the SSH connection
		ssh.close()
	# Print test conditions
		serial = "serial fails: ", serial_fails, "and passes: ", serial_passes 
		print(serial)
		plugins = "plugin fails: ", plugin_fails, "and passes: ", plugin_passes
		print(plugins)
	# Goto 1
		trial_number += 1
		print("Turning off the oven!")
		localpi.write(power_pin, 1)
		localpi.write(power_pin, 0)
		
		print("logging results...")
		log_file = open(filename, 'a+')
		log_file.write(str(serial))
		log_file.write(str(plugins))
		log_file.write("\n")
		log_file.close()

		
		
		for i in range(1,15):
			print(i, "...")
			sleep(1)
Пример #35
0
import time

#  GPIO.setmode(GPIO.BOARD)  # Sets the pin numbering system to use the physical layout

# Set up pin 12 for PWM
# GPIO.setup(12, GPIO.OUT)  # Sets up pin 12 to an output (instead of an input)
# pwm = GPIO.PWM(12, 50)  # Sets up pin 11 as a PWM pin | 50hz frequency

frequency = 50
period = 1.0 / frequency
lowestCycle = 0.0005 / period * 100
highestCycle = 0.0025 / period * 100
minAngle = 0
maxAngle = 180
gpioPin = 12  # GPIO pin connected to servo
pi = pigpio.pi()  # connect to GPIO
if not pi.connected:
    print("not connected")
    exit()

pi.set_mode(gpioPin, pigpio.OUTPUT)  # set pin to output mode
print(pi.set_PWM_frequency(gpioPin, frequency))  # set PWM frequency of pin
pi.set_PWM_range(gpioPin, 255)


def start():
    test = 6.8
    # pwm.start(test)  # Starts running PWM on the pin and sets it to 1
    # example = 0.0005 # 500us minimum

    # pwm.ChangeDutyCycle(test)
Пример #36
0
 def __init__(self):
     super(PinManager, self).__init__()
     self.gpio = pigpio.pi('0.0.0.0', 3000)
     self.initialize_pins()
Пример #37
0
#! /usr/bin/python

import RPi.GPIO as GPIO
import time
import pigpio
import sys

pi = pigpio.pi()

RedPin = 17

#start pigpiod deamon

pi = pigpio.pi()  #connect to Pi

#turnOn relay
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
GPIO.setwarnings(False)
GPIO.setup(23, GPIO.OUT)
GPIO.output(23, GPIO.LOW)

duty_s = sys.argv[1]
duty = int(duty_s)
duty_red = duty * 2.55

pi.set_PWM_dutycycle(RedPin, duty_red)

#stop pigpio

pi.stop()  #disconnect with Pi
Пример #38
0
import pigpio
import time

try:
    pi = pigpio.pi()
    GPIO_pin = 4

    pi.set_mode(GPIO_pin, pigpio.OUTPUT)
    pi = pigpio.pi()  # connect to local Pi

    freq = 30000  # Hz

    period = 1.0 / freq * 10**6

    print "period: %f" % period

    #ramp_time = 5 # sec

    #start_date = time.time()

    # final wave
    square = []
    square.append(pigpio.pulse(1 << GPIO_pin, 0, period / 2.0))
    square.append(pigpio.pulse(0, 1 << GPIO_pin, period / 2.0))

    pi.wave_clear()
    pi.wave_add_generic(square)

    wid0 = pi.wave_create()

    square = []
Пример #39
0
################################################################################
#   ir_led_test.py
#
#   First test of IR Remote with LED with PIGGPI
#
#   30.06.2019  Created by:  zhenya
################################################################################
import pigpio
import time

host_addr = '192.168.2.44'
gpio_pin  = 21
LED_pin   = 27	
count   = 0

pi = pigpio.pi(host_addr)

while True:
    
    tr = pi.event_trigger(21)
    print(tr)
    time.sleep(1)
    
#if pi.wait_for_event(gpio_pin, 10):
#   print("event detected")
#else:
#   print("wait for event timed out")
   
#while True:
#    try:
#        eve = pi.event_callback(gpio_pin)
Пример #40
0
import pigpio
from time import sleep
from tkinter import *
from tkinter.colorchooser import *

pi = pigpio.pi('192.168.1.12', 8888)  # Connect to the local Pi

pins_used = (17, 27, 22, 18, 23, 24)

for i in pins_used:  # Sets up pins as outputs
    pi.set_mode(i, pigpio.OUTPUT)

# Assign pins to strips and colors
strip1 = (17, 27, 22)
strip2 = (18, 23, 24)

# Set frequency
Hz = 800
freq = 1 / Hz  # in seconds

# Set min and max levels
min_level = 0
max_level = 255


def breathe(color, time=1):
    # Reset each color
    for i in pins_used:
        pi.set_PWM_dutycycle(i, 0)
    # Get initial level
    level = pi.get_PWM_dutycycle(color)
Пример #41
0
PWM_FREQ = 50
CLOSE = 170
OPEN = 135
FEEDING = False
PWM = None

config = configparser.ConfigParser()
config.read('config.ini')

format_config = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=format_config,
                    level=logging.INFO,
                    filename='run.log')
logger = logging.getLogger()
try:
    PWM = pigpio.pi()
except Exception as e:
    logger.error("Error starting PWM" + str(e))

updater = Updater(token=config['TELEGRAM']['ACCESS_TOKEN'], use_context=True)
dispatcher = updater.dispatcher


def angle_to_duty_cycle(angle=0):
    duty_cycle = int((500 * PWM_FREQ + (1900 * PWM_FREQ * angle / 180)))
    return duty_cycle


def unchanging(chat_id):
    global USERSTATUS, SCHEDULECHANGING
    if chat_id in USERSTATUS:
Пример #42
0
    #GPIO.output(spark_pin,GPIO.LOW)
    
    print("Ignition Stoped")

def open_valve():
    
    GPIO.output(valve_pin,GPIO.HIGH)
    print("Valve Open")
    
def close_valve():
    
    GPIO.output(valve_pin,GPIO.LOW)
    print("Valve Closed")


pi = pigpio.pi()#Neccessary Preamble for the thermocouple

if not pi.connected:
   exit(0)


######Infinite While Loop "Main Code"#######

while 1:
    valvefile=open("valvestat.txt", "r")#Checking the valve remote status
    valve=float(valvefile.read())

    if valve == 1:   #Global Variable Changed in the shell, initiates ignition sequence
        open_valve()        
        print ("Valve Open")
Пример #43
0
#!/usr/bin/env python
import pigpio
import sys
from time import sleep
try:
    thePinNum = int(sys.argv[1])
except IndexError:
    print("Missing Pin Num")
else:
    pi = pigpio.pi()  # Connect to local Pi.
    pi.set_mode(thePinNum, pigpio.OUTPUT)
    GPIOstatus = pi.read(thePinNum)
    if GPIOstatus == 1:
        print("Switching pin " + str(thePinNum) + " to 0")
        pi.write(thePinNum, 0)
        pi.stop()
    else:
        print("Switching pin " + str(thePinNum) + " to 1")
        pi.write(thePinNum, 1)
        pi.stop()
Пример #44
0
    def log_data(self):

        # pigpio
        self.ioif = pigpio.pi()

        # software i2c
        try:
            self.ioif.bb_i2c_open(P_SDA, P_SCK, P_BAUD)
        except:
            logging.error("bus already open")
            self.ioif.bb_i2c_close(P_SDA)
            self.ioif.bb_i2c_open(P_SDA, P_SCK, P_BAUD)

        logging.info("Data Logger started")

        log = 0
        data_fast = np.zeros(8)
        data_perm = np.zeros(8)
        n_fast = 1
        n_perm = 1
        while logging:
            logging.debug("Data Logger logging")
            columns = list(("time", ))

            for i in range(SENSOR_BASEID, SENSOR_BASEID + 8):
                (count, data) = self.ioif.bb_i2c_zip(P_SDA, [
                    I2C_SET_ADDR, i, I2C_START, I2C_READ, SENSOR_DATALEN,
                    I2C_STOP, I2C_END
                ])
                columns.append(str(i))
                if count > 1:
                    read = ((data[0] << 8) & 0xFF00) + (data[1])
                    read = read / 256.0
                    if read > 127:
                        read -= 256
                    data_fast[i - SENSOR_BASEID] += read
                    data_perm[i - SENSOR_BASEID] += read
                else:
                    data_fast[i - SENSOR_BASEID] = np.nan
                    data_perm[i - SENSOR_BASEID] = np.nan
                time.sleep(0.05)

            infoline = np.empty((1, 9), dtype=object)

            if n_fast % 10 == 0:
                infoline[0, 1:9] = data_fast[0:8] / n_fast
                n_fast = 0
                infoline[0, 0] = dt.datetime.now()
                pdataline = pa.DataFrame.from_records(infoline,
                                                      columns=columns)
                self.savetofile(False, pdataline)
                data_fast = np.zeros(8)

            if n_perm % 100 == 0:
                infoline[0, 1:9] = data_perm[0:8] / n_perm
                n_perm = 0
                infoline[0, 0] = dt.datetime.now()
                pdataline = pa.DataFrame.from_records(infoline,
                                                      columns=columns)
                self.savetofile(True, pdataline)
                data_perm = np.zeros(8)

            n_fast += 1
            n_perm += 1
Пример #45
0
"""
Ollie Langhorst
Robotics Research for Dr. Krauss
1/5/2016
Before this script is run, it is necessary to start the pigpio daemon.
Do this by: sudo pigpiod
"""

from matplotlib.pyplot import *
from scipy import *

import time
import pigpio
import serial_utils

pi1 = pigpio.pi()

channel = 0
bps = 1000000
mode = 3
h = pi1.spi_open(channel, bps, mode)

#~ n = 100
n = 10

t1 = time.time()
responses = []
ilist = range(1, n)
testbyte = 0
sendindex_list = []
allbytes = []
Пример #46
0
def exe_sunset():
    #Hier werden die GPIO Pins als Variable deklariert.
    #Das ist einfacher und übersichtlicher.

    RED = 17
    GREEN = 22
    BLUE = 24
    WHITE = 23

    pi = pigpio.pi()

    #Hier werden die Farbwerte festgelegt.

    r = 155.4
    g = 147.12
    b = 256.05
    w = 255

    durchlauf = 0

    while durchlauf == 0:

        ticks1 = 0
        ticks2 = 0
        ticks3 = 0
        ticks4 = 0

        while ticks1 <= 101:

            #erste Schleife

            r = r - 0
            g = g - 0
            b = b - 1
            w = w - 2.5

            pi.set_PWM_dutycycle(RED, r)
            pi.set_PWM_dutycycle(GREEN, g)
            pi.set_PWM_dutycycle(BLUE, b)
            pi.set_PWM_dutycycle(WHITE, w)
            time.sleep(8)

            ticks1 = ticks1 + 1

        print("erste Schleife")

        print(r)
        print(g)
        print(b)
        print(w)

        while ticks2 <= 37:

            #zweite Schleife

            r = r - 0.05
            g = g - 1.5
            b = b - 1.6
            w = w - 0

            pi.set_PWM_dutycycle(RED, r)
            pi.set_PWM_dutycycle(GREEN, g)
            pi.set_PWM_dutycycle(BLUE, b)
            pi.set_PWM_dutycycle(WHITE, w)
            time.sleep(8)

            ticks2 = ticks2 + 1

        print("zweite Schleife")

        print(r)
        print(g)
        print(b)
        print(w)

        while ticks3 <= 40:

            #dritte Schleife

            r = r - 1
            g = g - 1.32
            b = b - 2
            w = w - 0

            pi.set_PWM_dutycycle(RED, r)
            pi.set_PWM_dutycycle(GREEN, g)
            pi.set_PWM_dutycycle(BLUE, b)
            pi.set_PWM_dutycycle(WHITE, w)
            time.sleep(8)

            ticks3 = ticks3 + 1

        print("dritte Schleife")

        print(r)
        print(g)
        print(b)
        print(w)

        while ticks4 <= 44:

            #vierte Schleife

            r = r - 2.5
            g = g - 0.76
            b = b - 0.2
            w = w - 0

            pi.set_PWM_dutycycle(RED, r)
            pi.set_PWM_dutycycle(GREEN, g)
            pi.set_PWM_dutycycle(BLUE, b)
            pi.set_PWM_dutycycle(WHITE, w)
            time.sleep(8)

            ticks4 = ticks4 + 1

        print("vierte Schleife")

        print(r)
        print(g)
        print(b)
        print(w)

        durchlauf = +1
        print("Jetzt ist Nacht")
Пример #47
0
import pigpio
import time

pi = pigpio.pi('doggo-control')

pi.set_servo_pulsewidth(22, 1500)

time.sleep(1)

pi.set_servo_pulsewidth(22, 1200)

time.sleep(1)

pi.set_servo_pulsewidth(22, 1500)

time.sleep(1)

pi.set_servo_pulsewidth(22, 0)
Пример #48
0
	#calculation of the temperature based on 
	#the first word and the first byte
	
	# !!! not tested for negative temperatures !!!!
	#last 4 bits of the word0
	l4b = (word0 & 0b1111000000000000)>>12
	temperature = ((byte0<<4) | l4b) * 0.0625
	return temperature
	
	

#i2c bus of the Raspberry Pi 3
i2c_bus = 1
#TMP 102 address on the i2c bus
addr = 0x48


dev_pi = pigpio.pi()
dev_tmp = dev_pi.i2c_open(i2c_bus, addr, 0)
register_n = 0
try:
	while True:
		t_byte = dev_pi.i2c_read_byte_data(dev_tmp, 0)
		t_word = dev_pi.i2c_read_word_data(dev_tmp, 0)
		t = tmp102_reading(t_byte, t_word)
		print(' Temperature: {} C'.format(t))
		time.sleep(1)
except KeyboardInterrupt:
	pass
print('Exiting the loop');
r = dev_pi.i2c_close(dev_tmp)
Пример #49
0
def setup():
    # set up board
    pi = pigpio.pi()
    # set pins
    pi.set_mode(led_pin, pigpio.OUTPUT)
    return pi
Пример #50
0
GPIOA = 18  # Port A bits register.

portABits = 0
changedABits = 0


def IntA(gpio, level, tick):
    global portABits, changedABits
    # Read port A, clear interrupt.
    now = pi.i2c_read_byte_data(chip, GPIOA)
    changedABits = now ^ portABits
    portABits = now
    print("port A is {:08b} changed {:08b}".format(portABits, changedABits))


pi = pigpio.pi("tom")  # Connect to tom.

pi.set_mode(gpioA7, pigpio.OUTPUT)

chip = pi.i2c_open(0, 0x20)  # tom is a Rev.1 board.

pi.i2c_write_byte_data(chip, DEFVALA, 0)
pi.i2c_write_byte_data(chip, INTCONA, 0)
pi.i2c_write_byte_data(chip, INTENA, 0xFF)  # Interrupt on any PORTA change.

# Call IntA on Port A interrupt.
cb = pi.callback(gpioPortAInt, pigpio.FALLING_EDGE, IntA)

# Make sure gpio changes state when first interrupt arrives.
# Otherwise the callback won't be called and the interrupt
# won't be cleared.
Пример #51
0
 def _init_gpio_spi(self):
     pi = pigpio.pi()
     pi.set_mode(self.intPin, pigpio.INPUT)
     pi.set_mode(self.rstPin, pigpio.OUTPUT)
     self.spi= pi.spi_open(0, 4000000, 0) #TODO: need to include for options?
     self.pi = pi
Пример #52
0
# -*- coding: utf-8 -*-
import time
import pigpio

BUZZER = 18
gpio = pigpio.pi()
gpio.set_mode(BUZZER, pigpio.OUTPUT)

##1オクターブの周波数
scale = [523.251, 587.33, 659.255, 698.456, 783.991, 880, 987.767, 1046.502]
##ド=0、レ=1、ミ=2、ファ=3、ソ=4、ラ=5、シ=6、ド=7、4分音符(+0)、2分音符(+10)
##曲(ちょうちょ)
music = [
    4, 2, 12, 3, 1, 11, 0, 1, 2, 3, 4, 4, 14, 4, 2, 2, 2, 3, 1, 1, 1, 0, 2, 4,
    4, 2, 2, 12
]

try:
    for note in music:
        if note >= 10:
            note = note - 10
            gpio.hardware_PWM(BUZZER, scale[note], 500000)
            time.sleep(1)
        else:
            gpio.hardware_PWM(BUZZER, scale[note], 500000)
            time.sleep(0.5)
        gpio.hardware_PWM(BUZZER, 0, 0)
        time.sleep(0.1)
except KeyboardInterrupt:
    gpio.hardware_PWM(BUZZER, 0, 0)
    gpio.stop()
Пример #53
0
sw_blue = 21
motor_out_1 = 19
motor_out_2 = 26

# PWMの周波数
freq = 1000
# duty比の分解能
pwm_range = 100
# 初期duty比
duty = 50

# 7segledの点灯パターン
num_char = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7c, 0x07, 0x7f, 0x67, 0x00]

# GPIOの初期設定
pi_g = pi.pi()

# 入力設定
pi_g.set_mode(sw_black, pi.INPUT)
pi_g.set_mode(sw_white, pi.INPUT)
pi_g.set_mode(sw_red, pi.INPUT)
pi_g.set_mode(sw_orange, pi.INPUT)
pi_g.set_mode(sw_yellow, pi.INPUT)
pi_g.set_mode(sw_green, pi.INPUT)
pi_g.set_mode(sw_blue, pi.INPUT)

# プルアップ設定
pi_g.set_pull_up_down(sw_black, pi.PUD_UP)
pi_g.set_pull_up_down(sw_white, pi.PUD_UP)
pi_g.set_pull_up_down(sw_red, pi.PUD_UP)
pi_g.set_pull_up_down(sw_orange, pi.PUD_UP)
Пример #54
0
    cycle = 1 # number of cycles

if args['experiment'] == 2:
    prepulse = 4 * 60 # 4 minutes
    lpulse = 3 * 60 # 3 minutes
    interpulse = 2 * 60 
    cycle = 2

if args['experiment'] == 3:
    prepulse = 0
    lpulse = 2 * 60
    interpulse = 0
    cycle = 1

#initialize handles for TTL and UDP
pi = pigpio.pi() #TTL

try:
    pi.write(18, 0)
    pi.write(12, 0)
    pi.write(4 , 0)
    print('Turned off lights')
except:
    print('Lights are turned off')

#TTL write
def pulse(GPIO, dur):
    pi.write(GPIO, 1) # high
    time.sleep(dur) # in sec
    pi.write(GPIO, 0) # low
Пример #55
0
# - - - - - - - - - - - - - - - -
GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.IN)  # Save button
GPIO.setup(16,GPIO.IN)   # Reset button 
GPIO.setup(6, GPIO.IN)   # Not Used
GPIO.setup(13, GPIO.IN)  # Endless Repeat switch
GPIO.setup(19, GPIO.IN)  # Set Origin switch
GPIO.setup(26, GPIO.IN)  # Follow switch
GPIO.setup(12, GPIO.IN)  # Repeat switch
GPIO.setup(21, GPIO.OUT) # Blink LED
servoGripperPin = 24     # Servo Gripper

# - - - - - - - - - - - - - - - - 
# - - -  Global Objects - - - - -
# - - - - - - - - - - - - - - - -
pi = pigpio.pi('localhost', 8888)

blinkLED = BlinkLED(21)
stepperArm = StepperRobotArm(blinkLED, pi, servoGripperPin)
replicaArm = ReplicaRobotArm()

replayButton = Button(20, stepperArm.shortPressAction, lambda: True)
deleteButton = Button(16, stepperArm.deleteReplayList, lambda: True)

motorHoldSwitch = Switch(6, lambda: stepperArm.setMotorHold('hold'), lambda: stepperArm.setMotorHold('release'))
endlessRepeatSwitch = Switch(13, lambda: stepperArm.setEndlessReplay(True), lambda: stepperArm.setEndlessReplay(False))
setOriginSwitch = Switch(19, replicaArm.getCorrValues, lambda: True)
followSwitch = Switch(26, lambda: stepperArm.setMode('follow'), lambda: stepperArm.setMode('idle'))
repeatSwitch = Switch(12, lambda: stepperArm.setMode('replay'), lambda: stepperArm.setMode('idle'))

# - - - - - - - - - - - - - - - - 
# Initialize pigpio daemon
from subprocess import call
call(["sudo", "pigpiod"])

#Importing libraries
import psutil, os
import pigpio
import chewnumber
from threading import Event
global exit

#Setting variables
exit = Event()
p = psutil.Process(os.getpid())
p.nice(-19)
pi = pigpio.pi('Dragon47')
n = 3

#pi.hardware_clock(4,4689)
pi.set_PWM_frequency(4, constants.CLOCKSPEED)
pi.set_PWM_dutycycle(4, constants.DUTYCYCLE)

pi.write(10, 1)

global send_value_bin
send_value = [0] * n
send_value_bin = [0] * n
zerostring = [0] * n
diff = [0] * n
zerolist = [0] * n
Пример #57
0
# exp setting
schedule = args.schedule
ratio = args.ratio
sessionLength = args.sessionLength
timeout = args.timeout
rat1ID = args.rat1ID
rat2ID = args.rat2ID
rat0ID = "ratUnknown"

# motor code from https://www.raspberrypi.org/forums/viewtopic.php?t=220247#p1352169
# pip3 install pigpio
# git clone https://github.com/stripcode/pigpio-stepper-motor

## initiate pump motor
pi = pigpio.pi()
motor = StepperMotor(pi, 17, 23, 22, 24)
pwma = pigpio.pi()
pwma.write(18, 1)
pwmb = pigpio.pi()
pwmb.write(12, 1)
stby = pigpio.pi()
stby.write(27, 0)

# Create I2C bus.
i2c = busio.I2C(board.SCL, board.SDA)
# Create MPR121 object.
mpr121 = adafruit_mpr121.MPR121(i2c)

# Initialize GPIO
gpio.setwarnings(False)
Пример #58
0
from imutils.video.pivideostream import PiVideoStream

print "Initializing point tracking"

parser = argparse.ArgumentParser(
    description='Cast some spells!  Recognize wand motions')
parser.add_argument(
    '--train',
    help='Causes wand movement images to be stored for training selection.',
    action="store_true")

parser.add_argument('--circles',
                    help='Use circles to select wand location',
                    action="store_true")

pi = pigpio.pi()
#pin for Powerswitch (Lumos,Nox)
switch_pin = 23
pi.set_mode(switch_pin, pigpio.OUTPUT)

#pin for Particle (Nox)
nox_pin = 24
pi.set_mode(nox_pin, pigpio.OUTPUT)

#pin for Particle (Incendio)
incendio_pin = 22
pi.set_mode(incendio_pin, pigpio.OUTPUT)

#pin for Trinket (Colovario)
trinket_pin = 12
pi.set_mode(trinket_pin, pigpio.OUTPUT)
Пример #59
0
 def __init__(self, motorName, gpio):
     self.name = motorName
     self.gpioPin = gpio
     self.pi = pigpio.pi()
     self.idle()
Пример #60
0
 def __init__(self, mode):
     """Constructor for the main program. Accepts the mode: RLS or ADP"""
     self._pi = pigpio.pi()
     self.mode = mode