Example #1
0
 def __init__(self):
     """ Set up hardware """
     super().__init__()
     wiringpi.wiringPiSetup()
     # Set up each pin for digital output
     for i in self.lightPinMap:
         wiringpi.pinMode(i, 1)
Example #2
0
 def __init__(self):
     self.output_pins1 = [65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80]
     self.output_pins2 = [81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96]
     self.output_pins3 = [97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112]
     self.output_pins4 = [113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128]
     
     self.input_pins1 = [129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144]
     self.input_pins2 = [145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160]  
     
     self.led_pins1 = [161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176]  
     self.led_pins2 = [177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192] 
     
     self.ulazi = []
     for i in range(32):
         self.ulazi.append(0);
     
     self.indikatori = []
     for i in range(32):
         self.indikatori.append(0);
             
     self.svi = []
     self.svi =self.svi+ self.output_pins1 
     self.svi =self.svi+ self.output_pins2 
     self.svi =self.svi+ self.output_pins3 
     self.svi =self.svi+ self.output_pins4 
     self.svi =self.svi+ self.led_pins1        
     self.svi =self.svi+ self.led_pins2 
     
     self.svi_motori = []
     self.svi_motori = self.svi_motori + self.output_pins1 
     self.svi_motori = self.svi_motori + self.output_pins2 
     self.svi_motori = self.svi_motori + self.output_pins3 
     self.svi_motori = self.svi_motori + self.output_pins4 
     
     self.svi_ulazi = []
     self.svi_ulazi=self.svi_ulazi + self.input_pins1 
     self.svi_ulazi =self.svi_ulazi + self.input_pins2
     
     self.svi_indikatori = []
     self.svi_indikatori = self.svi_indikatori + self.led_pins1
     self.svi_indikatori = self.svi_indikatori + self.led_pins2
     
     wiringpi.wiringPiSetup()
     wiringpi.mcp23s17Setup(65,0,0) # first pin,spi port,i2c address
     wiringpi.mcp23s17Setup(81,0,1)
     wiringpi.mcp23s17Setup(97,0,2)
     wiringpi.mcp23s17Setup(113,0,3)
     #ulazi
     wiringpi.mcp23s17Setup(129,1,0)
     wiringpi.mcp23s17Setup(145,1,1)
     #indikatori
     wiringpi.mcp23s17Setup(161,1,2) # za led na drugoj liniji
     wiringpi.mcp23s17Setup(177,1,3) # za led na drugoj liniji
     
     for i in self.svi_motori:
         wiringpi.pinMode(int(i),1)     # sets pin of mcp23s17-0 to output
     for i in self.svi_ulazi:
         wiringpi.pinMode(int(i),0)    
     for i in self.svi_indikatori:
         wiringpi.pinMode(int(i),0) 
Example #3
0
    def leds_on(self, name, priority):
        """ turns on the LEDs for a service based on priority"""

        # set wiring pi to use pins
        wiringpi.wiringPiSetup()

        # temporary list of pins from service
        servicePins = []
        for group in self.pinGroups:
            if group[0] == str(name):
                servicePins = group[1:4]
        
        # enable the pins for writing
        wiringpi.pinMode(servicePins[0], 1)
        wiringpi.digitalWrite(servicePins[0], 0)
        wiringpi.pinMode(servicePins[1], 1)
        wiringpi.digitalWrite(servicePins[1], 0)
        wiringpi.pinMode(servicePins[2], 1)
        wiringpi.digitalWrite(servicePins[2], 0)

        # enable LEDs based on priority
        if (int(priority) == 1) or (int(priority) == 2):
            wiringpi.digitalWrite(servicePins[0], 1)

        # index 1, yellow is enabled for priority levels 2, 3, and 4
        if (int(priority) == 2) or (int(priority) == 3) or (int(priority) == 4):
            wiringpi.digitalWrite(servicePins[1], 1)

        # index 2, red is enabled for priority levels 4 and 5
        if (int(priority) == 4) or (int(priority) == 5):
            wiringpi.digitalWrite(servicePins[2], 1)
def initialize():
    """Set pins as outputs and start all lights in the off state."""
    wiringpi.wiringPiSetup()
    enable_device()
    set_pins_as_outputs()

    turn_off_lights()
Example #5
0
 def init(self, pins):
   wiringpi2.wiringPiSetup()
   self._pins = set(pins)
   Log('Setting pins %s to output mode...' % list(self._pins))
   for i in self._pins:
     wiringpi2.pinMode(i, PINMODE_OUTPUT)
   Log("Done.")
Example #6
0
def fancontrol(input):
    import wiringpi2 as wiringpi
    OUTPUT = 1
    INPUT = 0
    wiringpi.wiringPiSetup()
    wiringpi.pinMode(8,OUTPUT)
    wiringpi.digitalWrite(8,input)
Example #7
0
def test():
    pin = 0
    gpio.wiringPiSetup()  #初始化
    gpio.wiringPiSetupSys()  #初始化
    gpio.pinMode(pin, GPIO.OUTPUT) # 把pin25设置为输出模式
    gpio.digitalWrite(pin, GPIO.HIGH) #pin25输出为高电平
    print(gpio.digitalRead(pin)) #打印pin25的状态
Example #8
0
def Init():
	wiringpi2.pinMode(data_pin, 0)
	wiringpi2.pinMode(clock_pin, 0)
	wiringpi2.wiringPiSetup()
	
	SendData(cmdlist["led_cmd"])
	wiringpi2.delay(50)
Example #9
0
def init_PWM(_redPin = 23, _greenPin = 24, _bluePin = 25, _flashPin= 22, initDutyCycle = [100]*3, flashRate = 0): 
   global colorPins, colors, flashActive, flashPin 
 
   colorPins = [_redPin, _greenPin, _bluePin] #list for pins used in raspberry pi

   wiringpi2.wiringPiSetup() # Initialize using wiringPi pin numbering scheme   

   for dc in initDutyCycle: #Check for valid initial duty cycle
      if dc < 0 or dc > 255: return -1

   #Create intial PWM signals for input to LED strip
   for i in range(3):
      wiringpi2.softPwmCreate(colorPins[i], int(initDutyCycle[i]*100.0/255.0), 100)

   #Current RGB values of LED strip
   colors = list(initDutyCycle)

   #Create square wave for flashing beat
   flashPin = _flashPin
   wiringpi2.softToneCreate(flashPin)
   if flashRate != 0:
      wiringpi2.softToneWrite(flashPin, flashRate)
      flashActive = True
   else:
      wiringpi2.softToneStop(flashPin)
      flashActive = False

   #Use Colors.txt file to create list of preset color options
   readColorsFile()

   return 0
 def init(self, PWMmode):
     self.PWMmode = PWMmode
     wiringpi2.wiringPiSetup()
     if self.PWMmode == True:
       wiringpi2.pinMode(1, 2)
     else:
       wiringpi2.pinMode(1,1)
Example #11
0
def init_control_plane():
    logger.info("Initializing control plane")
    chip1_i2c_addr = 0x20  # Controlled by A0, A1, A2 pins GND or +5V
#    chip2_i2c_addr = 0x22  # Controlled by A0, A1, A2 pins GND or +5V
#    chip3_i2c_addr = 0x23  # Controlled by A0, A1, A2 pins GND or +5V
#    chip4_i2c_addr = 0x24  # Controlled by A0, A1, A2 pins GND or +5V

    wiringpi.wiringPiSetup()  # initialise wiringpi

    wiringpi.mcp23017Setup(pin_base, chip1_i2c_addr)  # pins 65-80
#    wiringpi.mcp23017Setup(pin_base + 16, chip2_i2c_addr)  # pins 81-96
#    wiringpi.mcp23017Setup(pin_base + 32, chip3_i2c_addr)  # pins 97-112
#    wiringpi.mcp23017Setup(pin_base + 48, chip4_i2c_addr)  # pins 113-128

    for pin in range(pin_base, pin_max):
        set_pin(pin, OFF)
        wiringpi.pinMode(pin, PIN_MODE_ACTIVE)  # set to output mode

    sleep(1)

    for pin in range(pin_base, pin_max):
        mode = wiringpi.getAlt(pin)
        if mode != PIN_MODE_ACTIVE:
            logger.error("Initialized pin {0} to mode {1} but found it in mode {2}".format(pin, PIN_MODE_ACTIVE, mode))

    # and then apply our CHANGES
    apply_model(False)
    logger.info("Control plane initialized successfully")
Example #12
0
	def initialize_hardware(self):
		wiringpi.wiringPiSetup()
		wiringpi.pinMode(GPIOPin.PIN_STATUS_LED.value, PinMode.OUTPUT.value)
		wiringpi.pinMode(GPIOPin.PIN_SOUND.value, PinMode.OUTPUT.value)
		wiringpi.pinMode(GPIOPin.PIN_RGB_RED.value, PinMode.OUTPUT.value)
		wiringpi.pinMode(GPIOPin.PIN_RGB_GREEN.value, PinMode.OUTPUT.value)
		wiringpi.pinMode(GPIOPin.PIN_RGB_BLUE.value, PinMode.OUTPUT.value)
Example #13
0
    def __init__ (self):

        # tuple of lists containing groups of pins and their associated service
        self.pinGroups = ["unused", 8, 9, 7],\
                         ["unused", 0, 2, 3],\
                         ["unused", 12, 13, 14],\
                         ["unused", 15, 16, 1],\
                         ["unused", 6, 10, 11]

        # initialize all pins to 0V
        wiringpi.wiringPiSetup()
        wiringpi.digitalWrite(8, 0)
        wiringpi.digitalWrite(9, 0)
        wiringpi.digitalWrite(7, 0)
        wiringpi.digitalWrite(0, 0)
        wiringpi.digitalWrite(2, 0)
        wiringpi.digitalWrite(3, 0)
        wiringpi.digitalWrite(12, 0)
        wiringpi.digitalWrite(13, 0)
        wiringpi.digitalWrite(14, 0)
        wiringpi.digitalWrite(15, 0)
        wiringpi.digitalWrite(16, 0)
        wiringpi.digitalWrite(1, 0)
        wiringpi.digitalWrite(6, 0)
        wiringpi.digitalWrite(10, 0)
        wiringpi.digitalWrite(11, 0)
Example #14
0
    def __init__(self):
        wp.wiringPiSetup()

        #left 23017, for audio
        wp.mcp23017Setup( PB1,0x20)
        for pin in OUTPUT_PINS_1:
            wp.pinMode(pin,OUTPUT)
        for pin in INPUT_PINS_1:
            wp.pinMode(pin, INPUT)

        #right 23017 for 230v switching
        wp.mcp23017Setup( PB2,0x21)
        for pin in OUTPUT_PINS_2:
            wp.pinMode(pin,OUTPUT)
        for pin in INPUT_PINS_2:
            wp.pullUpDnControl(pin,PUD_UP)
            wp.pinMode(pin, INPUT)


        #display
        wp.digitalWrite(70,0)  # write mode
        self.display1 = wp.lcdInit(2,16,8, 71,69,72,73,74,75,76,77,78,79) #connected to first expander
        wp.lcdClear(self.display1)


        #pwm driver
        self.pwm = PWM()
        self.pwm.setPWMFreq(200)
Example #15
0
def setupBoard():
  """
  This sets up the library to use the "Wiring" pin numbering
  and sets the a flag that setup has happened
  """
  if not setupOK():
    wpi.wiringPiSetup()
    setSetup(True)
Example #16
0
 def initQTI(self,wiring=True):
     #pin = pinNum
     if wiring == True:
         wp.wiringPiSetup()
         wp.wiringPiSetupGpio()
         wp.wiringPiSetupPhys()
     else:
         GPIO.setmode(GPIO.BOARD)
Example #17
0
def init_pump_control():
    #os.system("gpio mode 7 out")
    wpi.wiringPiSetup()
    wpi.pinMode(_PIN, _OUTPUT)
    rospy.set_param("pump_state", False)
    rospy.init_node("pump_control")
    s = rospy.Service("pump_control", PumpControl, pump_control_callback)
    rospy.spin()
 def __init__(self, ce_channel, speed):
     self.ce_channel = ce_channel
     os.system('gpio load spi')
     wiringpi.wiringPiSetup()
     error = wiringpi.wiringPiSPISetup(ce_channel,speed)
     if (error == -1):
         raise SetupException('Error while SPI setup')
     print('InterfaceSPI initalized (CE_%d, speed:%.1fMHz)' % (ce_channel, speed * 0.000001))
Example #19
0
 def __init__(self,):
     threading.Thread.__init__(self)
     #self.adc = adc
     self.waterflow = 0.0
     self.quit = False
     wp.wiringPiSetup()
     for i in range(0, 7):
         wp.pinMode(i, 0)
Example #20
0
 def __init__(self):
         self.amyPin = 4  
         self.benPin = 5
         
         wiringpi2.wiringPiSetup()
         
         wiringpi2.pinMode(self.amyPin,1)
         wiringpi2.pinMode(self.benPin,1)
Example #21
0
def initialize_hardware():
	SPI_CHANNEL = 1
	SPI_SPEED = 100000
	
	wiringpi.wiringPiSetup()  # can be used like this: wiringpi.wiringPiSetup(SPI_CHANNEL, SPI_SPEED)
	wiringpi.pinMode(pin_a0, pin_mode_output)
	wiringpi.pinMode(pin_a1, pin_mode_output)
	wiringpi.pinMode(pin_en, pin_mode_output)
 def run(self):
     self.is_running == True
     wiringpi.wiringPiSetup()
     wiringpi.mcp3442Setup(0)
     while self.is_running == True:
         'Read from pin 10 (MOSI SPI pin)'
         current_voltage = wiringpi.analogRead(10)
         print 'Voltage read: ' + current_temp
         time.sleep(1)
Example #23
0
	def __init__(self):
		wpi.wiringPiSetup()
		pins = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,21,22,23,26,27,30,31]
		#GPIO pin setup
		for x in pins:
			wpi.pinMode(x,1)
			wpi.digitalWrite(x,0)
		#initialize threads
		TurnCounter = Thread(target=PhotoIntA.startCount())
Example #24
0
	def __init__(self, servo_pin):
		super(Servo, self).__init__()
		wpi.wiringPiSetup()

		self.pin = servo_pin
		wpi.pinMode(self.pin, 1)
		wpi.digitalWrite(self.pin, 0)

		self.stopped = 1
		self.frequency = int(1/60*1000000)	# 60 Hz
		self.pulse = 1000
Example #25
0
def setup():
	wiringpi.wiringPiSetup()
	wiringpi.pinMode(DATA_PIN,1)	# Output fuer DATA
	wiringpi.pinMode(CLK_PIN,1)	# Output fuer CLK
	wiringpi.pinMode(ENB_RX_PIN,1)	# Output fuer ENB_RX
	wiringpi.pinMode(ENB_TX_PIN,1)	# Output fuer ENB_TX
	wiringpi.pinMode(PWR_PIN,1)	# Output fuer PWR_PIN
	wiringpi.digitalWrite(ENB_RX_PIN,0)
	wiringpi.digitalWrite(ENB_TX_PIN,0)
	wiringpi.digitalWrite(CLK_PIN,0)
	wiringpi.digitalWrite(DATA_PIN,0)
Example #26
0
    def __init__(self, pin, name='relay', pulse_duration=1, log_level=logging.INFO):
        threading.Thread.__init__(self)
        self.name = name
        self.pin = pin
        self.pulse_duration = pulse_duration
        self.finish = False
        self.daemon = True
        self.logger = util.set_logger(level=log_level)
        self.last_reading = None

        # initialize relay
        wiringpi.wiringPiSetup()
def initLCD_DVK512():
    global lcdFD

    RS = 3
    EN = 14
    D0 = 4
    D1 = 12
    D2 = 13
    D3 = 6

    wiringpi.wiringPiSetup()
    lcdFD = wiringpi.lcdInit(2, 16, 4, RS, EN, D0, D1, D2, D3, 0, 0, 0, 0)
Example #28
0
def softPwm():
	print "SoftPwm Mode"

	wiringpi2.wiringPiSetup()
	wiringpi2.pinMode(PIN_TO_PWM,SET_PWM)
	wiringpi2.pwmSetMode(PWM_MODE_MS)	
	#wiringpi2.softPwmCreate(PIN_TO_PWM,0,100) # Setup PWM using Pin, Initial Value and Range parameters
	#wiringpi2.softServoSettup()
	#softServoWrite()
	wiringpi2.pwmWrite(PIN_TO_PWM, 900) 	
	wiringpi2.delay(150)
	print "PWM is in NEUTRAL"
Example #29
0
 def __init__(self, plugin, button_pins, switch_pins, led_pins):
     super(RaspberryThread, self).__init__(plugin)
     self.button_pins = button_pins
     self.switch_pins = switch_pins
     self.led_pins = led_pins
     self.plugin = plugin
     self.pin_state_cache = {}
     # wiringpi2 = wiringpi2.GPIO(wiringpi2.GPIO.WPI_MODE_PINS)
     wiringpi2.wiringPiSetup()
     # wiringpi2.wiringPiSetupSys()
     # wiringpi2.wiringPiSetupGpio()
     self.led_blink_list = []
Example #30
0
def init():
  wiringpi.wiringPiSetup()

  for pin in RED_LEDS:
    wiringpi.pinMode( pin, OUTPUT )

  for pin in GREEN_LEDS:
    wiringpi.pinMode( pin, OUTPUT )

  for pin in BUTTONS:
    wiringpi.pinMode( pin, INPUT )

  allOff()
Example #31
0
 def __init__(self):
     threading.Thread.__init__(self)
     global Station
     global eor_log
     try:
         ##Setup wiringpi to output on 3/4/5 = pins 7/0/2
         wiringpi.wiringPiSetup()
         wiringpi.pinMode(LED3, 1)  #Recieving data
         wiringpi.pinMode(
             LED4, 1
         )  #has network/ flash if IP address is ok, but not connected to external sites
         wiringpi.pinMode(LED5, 1)
         wiringpi.digitalWrite(LED3, 0)
         wiringpi.digitalWrite(LED4, 0)
         wiringpi.digitalWrite(LED5, 0)
         self.current_value = None
         self.running = True  #setting the thread running to true
         eor_log.info("Starting EOR Server")
         Station.FlashLED3 = True  # flash when reading sentence 3 (Temp) every 10 sec
     except:
         self.running = False
Example #32
0
def telmin():
    REF=3.3  # 5.p or 3.3
    mode=1
    w.wiringPiSetup()
    w.wiringPiSPISetup(0,1000000)
    w.pinMode(0,1)
    w.pinMode(2,1)
    w.pinMode(1,2)
    #w.softPwmCreate(1,0,100)
    w.softPwmCreate(2,0,100)

    w.digitalWrite(0,1)
    
    while 1:
        data1 = MCP3008(1)
        data7 = MCP3008(7)
        time.sleep(0.01)
        data11 = int(data1)-860;
        w.softPwmWrite(2,data11)
        data71 = int(((data7/20)*5.8)-225)
        w.pwmWrite(1,data71*10)
        print('%4.2f'%data11,'%4.2f'%data71,'%.2f'%(data1/1024*REF),"volt",'%.2f'%(data7/1024*REF),"volt")
Example #33
0
def init(dev=(0, 0), speed=4000000, brightness=256, contrast=CONTRAST):
    spi.open(dev[0], dev[1])
    spi.max_speed_hz = speed

    # Set pin directions.
    wiringpi.wiringPiSetup()
    for pin in [DC, RST]:
        wiringpi.pinMode(pin, 1)

    # Toggle RST low to reset.
    wiringpi.digitalWrite(RST, OFF)
    time.sleep(0.100)
    wiringpi.digitalWrite(RST, ON)
    # Extended mode, bias, vop, basic mode, non-inverted display.
    set_contrast(contrast)

    # if LED == 1 set pin mode to PWM else set it to OUT
    if LED == 1:
        wiringpi.pinMode(LED, 2)
        wiringpi.pwmWrite(LED, 0)
    else:
        wiringpi.pinMode(LED, 1)
        wiringpi.digitalWrite(LED, OFF)
Example #34
0
    def controlPin(self, onTime, offTime):
        wp.wiringPiSetup()
        wp.pinMode(self.clk, 1)
        wp.pinMode(self.cs, 1)
        wp.pinMode(self.do, 0)
        wp.digitalWrite(self.clk, 1)
        wp.digitalWrite(self.cs, 1)
        d = 0
        bitIndex = 0

        while not self.stop:
            wp.digitalWrite(self.clk, 0)
            if bitIndex == 0:
                d = 0
                wp.digitalWrite(self.cs, 0)
            d <<= 1
            d |= wp.digitalRead(self.do)
            time.sleep(offTime.value)
            wp.digitalWrite(self.clk, 1)
            time.sleep(onTime.value)
            if bitIndex == 31:
                if (d & 0x7):
                    # "Serious Problem"
                    print('Problem with MAX31855 board.')
                    d = 0
                elif (d & 0x80000000):
                    # Negative!
                    d = 0xFFFFC000 | ((d >> 18) & 0x00003FFFF)
                else:
                    d >>= 18
                d *= 0.25
                self.temp = d
                wp.digitalWrite(self.cs, 1)
                bitIndex = 0
            else:
                bitIndex += 1
Example #35
0
def lcd_setup():
	wiringpi2.wiringPiSetup()

	global lcdHandle

	lcdHandle = wiringpi2.lcdInit(LCD_ROW, LCD_COL, LCD_BUS,
		PORT_LCD_RS, PORT_LCD_E,
		PORT_LCD_D4, PORT_LCD_D5,
		PORT_LCD_D6, PORT_LCD_D7, 0, 0, 0, 0);

	# set to read mode
	for number in led_pins:
 		wiringpi2.pinMode(number,1)

	# set to write mode
	wiringpi2.pinMode(5,0)
	wiringpi2.pinMode(6,0)

	# clear the state
	lcd_clear()
	for i in range(0,7):
		lcd_led_set(i,0)

	return lcdHandle
Example #36
0
    def __init__(self, ssr):

        self.verbose = False

        self.ssr = ssr

        threading.Thread.__init__(self)

        # set up the pin in out mode
        if wiringpi2_available:
            #call(["/usr/local/bin/gpio", "mode", str(ssr.pin), "out"])
            #wiringpi2.wiringPiSetupSys()

            #rasp numbering
            wiringpi2.wiringPiSetup()

            #gpio numbering
            #wiringpi2.wiringPiSetupGpio()

            #set the pinmode
            wiringpi2.pinMode(int(ssr.pin), 1)
        elif bbb_available:
            GPIO.setup(ssr.pin, GPIO.OUT)
            #GPIO.cleanup()

        self.daemon = True
        self.duty_cycle = 0
        self.cycle_time = 0
        self.power = 60
        self.enabled = False
        self._On = False

        self.pid_controller = pid_controller.pidpy(ssr.pid)

        #create an event so we can stop
        self._stop = threading.Event()
Example #37
0
def init():
    """   
       BSP initialize function. Must be called before any other BSP related
       functions.
    
    """
    global gI2cFd

    if wiringpi2.wiringPiSetup() < 0:
        print "bsp_init: failed to initialize wiringPi"
        return -1

    gI2cFd = wiringpi2.wiringPiI2CSetup(LM75A_I2C_ADDR)

    if gI2cFd < 0:
        print "bsp_init: failed to initialize I2C"
        return -1

    if wiringpi2.wiringPiSPISetup(0, 1000000) < 0:
        print "bsp_init: failed to initialize SPI"
        return -1

    return 0
Example #38
0
 def __init__(self):
     wiringpi2.wiringPiSetup()
     wiringpi2.pinMode(self._relayAIO, 1)
     wiringpi2.pinMode(self._relayBIO, 1)
     print("Relay Initialized")
def init(channel):
    gpio.wiringPiSetup()
    gpio.pinMode(channel, gpio.OUTPUT)  #设置针脚为输出状态
    gpio.piHiPri(99)
def init_module(config):
    KlikAanKlikUitReceiver.__pin__ = int(config.get_setting(['kaku', 'pin']))
    KlikAanKlikUitReceiver.__repeats__ = int(
        config.get_setting(['kaku', 'repeats']))
    if wiringpi2.wiringPiSetup() == -1:
        raise WiringError("Unable to init wiringpi")
Example #41
0
        alist = bytearray(msg)
        alist.insert(0, chr(strlen))  # load length of string
        alist.insert(1, chr(myaddr))
        load_tx(spi, alist, strlen)
        transmit(rfspi)
        time.sleep(5)


# dump a few ti registers
def dump_regs(spi):
    dump_ti_reg(rfspi, rf_config_reg)
    dump_ti_reg(rfspi, rf_cc1100_misc)
    dump_ti_reg(rfspi, rf_cc1100_status_reg)


wiringpi.wiringPiSetup()
wiringpi.pinMode(GDO2_PIN, 0)  # chip ready 1=not ready, 0=ready
rfspi = setup_spi()
reset_cc1100(rfspi)
a = get_chip_info(rfspi)
print "chip info: ", a
setup_config_register(rfspi, rf_msk_433_250k)
#setup_config_register(rfspi,rf_fsk2_433_2_4k)
device_address_and_channel(rfspi, MYADDRESS, DEVICECHAN)
#set_syncword(rfspi,SYNCWORD)	# setting this breaks transmission/reception
set_packet_length(rfspi, MAXIMUM_PACKET_SIZE)
set_packet_ctrl1(rfspi, 0x07)  # append 2 status bytes (RSSI+LQI), addr+broad
set_packet_ctrl0(rfspi, 0x45)  # variable packet length
#disable_pre_sync(rfspi)
#read_loop(rfspi)
transmit_loop(rfspi, MYADDRESS)
Example #42
0
    def _start(self):
        # 1) setup logger
        if self._debugmode:
            # add stream handler
            loghandler = logging.StreamHandler()
            loghandler.setLevel(logging.DEBUG)
            loghandler.setFormatter(
                logging.Formatter("(%(name)s) %(message)s"))
        else:
            # add a rotating file handler, 10 kB
            # overwrite old log
            loghandler = logging.handlers.RotatingFileHandler(self._logpath,
                                                              maxBytes=10 *
                                                              1024,
                                                              backupCount=5)
            loghandler.setLevel(logging.WARNING)
            loghandler.setFormatter(
                logging.Formatter(
                    "%(levelname)s %(asctime)s (%(name)s) %(message)s",
                    "%d.%m.%y %H:%M:%S"))

        self.get_logger().addHandler(loghandler)
        self.get_logger().setLevel(
            logging.DEBUG if self._debugmode else logging.WARNING)

        # start message
        self.logd("***{}({})***".format(self.NAME, self.CODENAME))
        self.logd("Version: {}.{}".format(self.VERSION_MAJOR,
                                          self.VERSION_MINOR))
        self.logd("Path: {}".format(self._path))
        self.logd("***{}***".format("*" * len(self.NAME)))

        # 2) open config
        try:
            with open(self._configpath, 'r') as stream:
                try:
                    config = json.load(stream)
                except json.JSONDecodeError as e:
                    self.loge("Config parse error: {}".format(e))
                    return False
        except EnvironmentError:
            self.loge("Can not find config file")
            return False

        # 3) setup supplyreader
        if not self._supply.setup():
            self.loge("Supply Reader Error")
            return False

        # 4) setup timeouts
        timeout = config.get("timeout")
        if timeout is not None:
            self._timeout = int(timeout)

        # 5) init wiringpi
        wiringpi2.wiringPiSetup()

        # 6) sort by tasks by elevated property
        # > non elevated get executed first
        self._taskschedule.sort(key=lambda task: (task.get_elevated()))

        # 7) startup tasks
        if not self._startup_tasks(config):
            return False

        # create unique startup time latch
        # so web app can detect a version change
        self._instance_id = self._timefactory.now().jstimestamp()
        return True
Example #43
0
import wiringpi2 as wiringpi, time, random
wiringpi.wiringPiSetup()  # initialise wiringpi
wiringpi.mcp23017Setup(101, 0x20)  # set up the pins and i2c address
wiringpi.mcp23017Setup(117, 0x21)
wiringpi.mcp23017Setup(133, 0x22)
print('I2C Testing Section')
print('.')
for x in range(101, 149):
    wiringpi.pinMode(x, 1)  # sets GPA0 to output

#Start 1 on at a time
print('Start 1 on/off at a time')
L = 1  # number of loops
S = (.2)  # delay between loops

for run_a in range(0, L):
    for x in range(101, 149):
        print x
        wiringpi.digitalWrite(x, 0)
        time.sleep(S * 2)

#Start 1 on at a time
print('Start 1 on/off at a time')
L = 1  # number of loops
S = (.2)  # delay between loops
for run_a in range(0, L):
    for x in range(101, 149):
        print x
        wiringpi.digitalWrite(x, 1)
        time.sleep(S)
Example #44
0
import threading, logging, os, serial, time
from modules import EventManager
import wiringpi2 as wpi

wpi.wiringPiSetup()

log_dir = '/var/log/piserver'
if not os.path.isdir(log_dir): os.mkdir(log_dir)
logging.basicConfig(filename=log_dir+'/piserver.log', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

def log(value):
	print(value)
	logging.debug(value)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"" COMMANDS LIST """"""""""""""""""""""""""""""""""""""""""""""""
0 = ERROR
1 = DEFINE HOMEEASY SENDER CODE
2 = SEND/RECEIVE HOMEEASY ORDERS
3 = REQUEST/RECEIVE SENSORS VALUES
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

class ATMega328():
	"""Class 'ATMega328': Serial communication with ATMega328"""

	def __init__(self):
		#log("ATMega328::init")
		self.name = "ATMega328"
		self.cmds = []
		self.set_running(True)
		self.reading_response = False
Example #45
0
dname = os.path.dirname(abspath)
os.chdir(dname)

# Some of these constants are from
# https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPi.h
INPUT = 0
OUTPUT = 1
PWM_OUTPUT = 2
LOW = 0
HIGH = 1
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2

# Use wiringPi numbering scheme - pin1 is PWM (PCM_CLK)
wiringpi2.wiringPiSetup()

# Switch on wiring pi pin 4 (GPIO 23)
DOOR_PIN = 4
# Switch on wiring pi pin 0 (GPIO 17)
SPACE_PIN = 0

# How many times per second should we read the GPIO?
FREQUENCY = 2

# Global variables
detected = 0
notified = 0
spaceIsOpen = False
firstLoop = True
still = ""
Example #46
0
##############################################################################################
LCD_ROW = 2  # 16 Char
LCD_COL = 16  # 2 Line
LCD_BUS = 4  # Interface 4 Bit mode

PORT_LCD_RS = 7  # GPIOY.BIT3(#83)
PORT_LCD_E = 0  # GPIOY.BIT8(#88)
PORT_LCD_D4 = 2  # GPIOX.BIT19(#116)
PORT_LCD_D5 = 3  # GPIOX.BIT18(#115)
PORT_LCD_D6 = 1  # GPIOY.BIT7(#87)
PORT_LCD_D7 = 4  # GPIOX.BIT4(#104)

PORT_BUTTON1 = 5
PORT_BUTTON2 = 6

wiringpi2.wiringPiSetup()  # Initialize values for pin numbering

lcdHandle = wiringpi2.lcdInit(
    LCD_ROW,
    LCD_COL,
    LCD_BUS,  # Main initialization function
    PORT_LCD_RS,
    PORT_LCD_E,
    PORT_LCD_D4,
    PORT_LCD_D5,
    PORT_LCD_D6,
    PORT_LCD_D7,
    0,
    0,
    0,
    0)
Example #47
0
#Practica 2 - Control de Servos (Version en Python con control por teclas)
#Grupo 5
import wiringpi2
from tkinter import *

wiringpi2.wiringPiSetup()  #hacemos setup con los valores de
#Elegimos el modo OUTPUT (1) para ambos pines 0 y 1
wiringpi2.pinMode(0, 1)
wiringpi2.pinMode(1, 1)
#creamos el PWM en pin 1 y 0 con rango 100 y valor inicial 0
wiringpi2.softPwmCreate(0, 0, 100)
wiringpi2.softPwmCreate(1, 0, 100)


#Definimos funciones para 4 direcciones de movimiento
# El valor de bloqueo de posicion es 15 y menor de esto gira en sentido opuesto a horario
# y mayor que 15 gira en sentido horario.
def adelante():
    wiringpi2.softPwmWrite(1, 14)
    wiringpi2.softPwmWrite(0, 16)


def parar():
    wiringpi2.softPwmWrite(1, 0)
    wiringpi2.softPwmWrite(0, 0)


def derecha():
    wiringpi2.softPwmWrite(1, 16)
    wiringpi2.softPwmWrite(0, 16)
Example #48
0
import wiringpi2 as GPIO  #Import GPIO library
import Ultrasonic_distance as ult
import time  #Import time library

GPIO.wiringPiSetup()


def buzzer():
    Buzz = x  # x will be buzzer's Pin number
    GPIO.pinMode(Buzz, 1)

    while True:
        dist = ult.distance_5()
        if dist <= 30:
            GPIO.digitalWrite(BUzz, 0)
            time.sleep(dist / 30)
            GPIO.digitalWrite(BUZZ, 1)
Example #49
0
def initGPIO(pin):
    GPIO.wiringPiSetup()
Example #50
0
def initGPIO():
    GPIO.wiringPiSetup()
    GPIO.pullUpDnControl(DQ, PULL_UP)
Example #51
0
def main():
    noleds = False
    noservos = False
    noimage = False
    nothreshold = False

    next_servo_update = 0

    try:
        opts, args = getopt.getopt(
            sys.argv[1:], None,
            ["help", "noservos", "noleds", "noimage", "nothreshold"])
    except getopt.GetoptError as err:
        usage()
        sys.exit(2)

    for option, value in opts:
        if option == "--noleds":
            noleds = True
        elif option == "--noservos":
            noservos = True
        elif option == "--noimage":
            noimage = True
        elif option == "--nothreshold":
            nothreshold = True
        elif option == "--help":
            usage()
            sys.exit(0)

    #setup camera capture
    print('Setting up webcam'),
    capture = cv2.VideoCapture(-1)
    #capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 320);
    #capture.set(cv2.CAP_PROP_FRAME_WIDTH, 240);

    if (capture is not None):
        print('... OK')
    else:
        return

    # setup wiring pi and leds
    if noleds == False:
        print('Setting up wiring pi'),
        wiringpi.wiringPiSetup()
        wiringpi.pinMode(GREEN_PIN, 1)
        wiringpi.pinMode(RED_PIN, 1)
        print('... OK')
    else:
        print "Wiringpi setup skipped"

    # setup serial
    if noservos == False:
        print("Setting up serial connection to Arduino"),
        port = serial.Serial("/dev/ttyUSB0", baudrate=115200, timeout=3.0)
        if (port is not None):
            print('... OK')
        else:
            return
    else:
        print "Serial setup skipped"

    wiringpi.delay(16000)
    print "Starting object tracking"

    frames = 0
    start_time = time.time()
    while True:
        diagonal, center_x, center_y = find_ball(capture, noimage, nothreshold)

        if noservos == False:
            update_servos(diagonal, center_x, center_y)
            if (read_servo_update(port)):
                next_servo_update = wiringpi.millis() + 100

            if wiringpi.millis() > next_servo_update:
                send_servo_update(port)

        if noleds == False:
            update_leds(diagonal)

        frames += 1
        currtime = time.time()
        numsecs = currtime - start_time
        fps = frames / numsecs

        sys.stdout.write("Found ball at: (%d, %d)       " %
                         (center_x, center_y) + " Deviation %d     " %
                         (90 - panServoAngle) +
                         "Current FPS: %d     \t\t\r\n" % fps)
        sys.stdout.flush()

    return
Example #52
0
#!/usr/bin/python3.5
import numpy as np
import cv2
import wiringpi2 as wpi
import time


face = cv2.CascadeClassifier('/home/odroid/Desktop/bullseye_Stage0-15.xml')
cap = cv2.VideoCapture(0)
cx = 0

wpi.wiringPiSetup()  #set up 
wpi.pinMode(0,1)
wpi.digitalWrite(0,0)

##cap.set(cv2.CAP_PROP_FRAME_WIDTH, 325)  #resolution changes 
##cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 325)

serial = wpi.serialOpen('/dev/ttySAC0', 9600)  #open serial port for UART 

def moveCenter(x):
    if x<250:
         print("Left")
         wpi.serialPuts(serial, "2")  #Sends TX commands
         time.sleep(0.1)
         return 0
    elif x>375:
         print("Right")
         wpi.serialPuts(serial, "1")
         time.sleep(0.1)
         return 0
Example #53
0
    def initialise(self):
        u'''Initialises the gpio pins, the SPI interface and configures
        the rfm22 module
        '''
        wiringpi.wiringPiSetup()
        wiringpi.wiringPiSPISetup(RFM22_SPI_CHANNEL, 10000000)
        RPIO.setup(RFM22_NIRQ_GPIO_BCM_PIN, RPIO.IN)
        RPIO.cleanup_interrupts()
        RPIO.add_interrupt_callback(RFM22_NIRQ_GPIO_BCM_PIN,
                                    nirq_callback,
                                    edge='falling')

        wiringpi.pinMode(RFM22_SDN_GPIO_PIN, OUTPUT)
        wiringpi.pinMode(RFM22_TXEN_GPIO_PIN, OUTPUT)
        wiringpi.pinMode(RFM22_RXEN_GPIO_PIN, OUTPUT)

        self.__rx_ant_off()
        self.__tx_ant_off()
        self.__sdn_off()
        time.sleep(0.1)  #reset module
        self.__sdn_on()
        #Wait 100ms to give rfm22 time to wake up
        time.sleep(0.1)

        #Read out chip version via SPI
        version = self.__read(self.__DEVICE_VERSION)
        debug_log("RFM22 chip version:", version)
        if (version[1] != 0):
            debug_log("SPI Communication working!")

        #Reset all registers, software reset
        self.__write(self.__OPERATING_FUNCTION_CONTROL_1, 0x80)

        #Wait 20ms to let the module boot up
        time.sleep(0.02)
        u'''Enable FIFO under/overflow, external, packet send,
        received and crc error interrupt.'''
        self.__write(self.__INTERRUPT_ENABLE_1, 0x87)
        u'''Enable rssi interrupt'''
        #self.__write(self.__INTERRUPT_ENABLE_2, 0x10) #Raspberry PI does not react fast enough to read correct value
        u'''Switch to ready mode.  200us to tx or rx'''
        self.__write(self.__OPERATING_FUNCTION_CONTROL_1, 0x01)

        self.__write(self.__CRYSTAL_OSCILLATOR_LOAD, 0x7f)
        u'''Enable AFC'''
        self.__write(self.__AFC_LOOP_GEARSHIFT_OVERRIDE, 0x40)
        u'''Set AFC timing'''
        self.__write(self.__AFC_TIMING_CONTROL, 0x0A)
        self.__write(self.__CLOCK_RECOVERY_GEARSHIFT_OVERRIDE, 0x05)
        u'''Set IF filter bandwidth'''
        self.__write(self.__IF_FILTER_BANDWIDTH, 0x9A)
        u'''Set clock recovery oversampling rate'''
        self.__write(self.__CLOCK_RECOVERY_OVERSAMPLING_RATIO, 0x3C)
        self.__write(self.__CLOCK_RECOVERY_OFFSET_2, 0x02)
        self.__write(self.__CLOCK_RECOVERY_OFFSET_1, 0x22)
        self.__write(self.__CLOCK_RECOVERY_OFFSET_0, 0x22)

        self.__write(self.__CLOCK_RECOVERY_TIMING_LOOP_GAIN_1, 0x07)
        self.__write(self.__CLOCK_RECOVERY_TIMING_LOOP_GAIN_0, 0xFF)
        u'''Set AFC Limiter'''
        self.__write(self.__AFC_LIMITER, 0x48)
        u'''Set RSSI threshold for clear channel assessment'''
        self.__write(self.__RSSI_THRESSHOLF_FOR_CLEAR_CHANNEL_INDICATOR,
                     self.__RSSI_CLEAR_CHANNEL_THRESHOLD)
        u'''RX, TX packet handling, enable CCIT CRC'''
        self.__write(self.__DATA_ACCESS_CONTROL, 0xAC)
        u'''Header check, valid for broadcast or check byte'''
        self.__write(self.__HEADER_CONTROL_1, 0xFF)
        u'''4 byte header (Header 3,2,1,0) and 2 byte sync (Synchronization Word 3,2) '''
        self.__write(self.__HEADER_CONTROL_2, 0x42)
        u'''Synchronization words'''
        self.__write(self.__SYNC_WORD_3, self.__PACKET_SYNC_BYTE_3)
        self.__write(self.__SYNC_WORD_2, self.__PACKET_SYNC_BYTE_2)
        self.__write(self.__SYNC_WORD_1, self.__PACKET_SYNC_BYTE_1)
        self.__write(self.__SYNC_WORD_0, self.__PACKET_SYNC_BYTE_0)
        u'''Transmit header'''
        self.__write(self.__TRANSMIT_HEADER_3, self.__TRANSMIT_HEADER_BYTE_3)
        self.__write(self.__TRANSMIT_HEADER_2, self.__TRANSMIT_HEADER_BYTE_2)
        self.__write(self.__TRANSMIT_HEADER_1, self.__TRANSMIT_HEADER_BYTE_1)
        self.__write(self.__TRANSMIT_HEADER_0, self.__TRANSMIT_HEADER_BYTE_0)

        self.__write(self.__CHECK_HEADER_3, self.__TRANSMIT_HEADER_BYTE_3)
        self.__write(self.__CHECK_HEADER_2, self.__TRANSMIT_HEADER_BYTE_2)
        self.__write(self.__CHECK_HEADER_1, self.__TRANSMIT_HEADER_BYTE_1)
        self.__write(self.__CHECK_HEADER_0, self.__TRANSMIT_HEADER_BYTE_0)
        u'''Check header enable mask, 0xFF means all bits of the corresponding
         * header will be checked. '''
        self.__write(self.__HEADER_ENABLE_3, 0xFF)
        self.__write(self.__HEADER_ENABLE_2, 0xFF)
        self.__write(self.__HEADER_ENABLE_1, 0xFF)
        self.__write(self.__HEADER_ENABLE_0, 0xFF)
        u'''Switch on automatic RX gain control'''
        self.__write(self.__AGC_OVERRIDE_1, 0x60)
        u'''TODO: example check agc override Register 0x6a does not exist. Data sheet wrong?'''
        u'''Set TX power and  LNA controller on if RFM22 != TX
         * TXPower         equals
         * -1dbm        0x00
         *  2dbm        0x01   set to 2dbm
         *  5dbm        0x02
         *  8dbm        0x03
         *  11dbm       0x04
         *  14dbm       0x05
         *  17dbm       0x06
         *  20dbm       0x07
         * '''
        self.__write(self.__TX_POWER, (0x01 | 0x80))
        u'''Set TX data rate to 0x199a =  100 kbps.
         * Datarate calculation:
         * TX_DR = 10^6 * 0x199a / 2^16 '''
        self.__write(self.__TX_DATA_RATE_1, 0x19)
        #Bits 15:8
        self.__write(self.__TX_DATA_RATE_0, 0x9a)
        #Bits 7:0
        u'''Modulation control, manchester data inversion.'''
        self.__write(self.__MODULATION_MODE_CONTROL_1, 0x0C)
        u'''Modulation control, FIFO Mode, GFSK '''
        self.__write(self.__MODULATION_MODE_CONTROL_2, 0x23)
        u'''Frequency deviation 50kHz
         * deviation = 625 * 0x50'''
        self.__write(self.__FREQUENCY_DEVIATION, 0x50)
        u'''Select frequency band, high band = >480 < 960 MHz,
         * 860- 879.9MHz
         * Regulations: 869,4 869,65 at 500mW ERP < 10%
         * '''
        self.__write(self.__FREQUENCY_BAND_SELECT, 0x73)

        self.__write(self.__NOMINAL_CARRIER_FREQUENCY_1, 0x76)

        self.__write(self.__NOMINAL_CARRIER_FREQUENCY_0, 0xC0)
        u'''Set carrier '''
        debug_log(u"RFM22 initialised")
Example #54
0
# Import feedparser so we can easily get data from the gmail feed
import feedparser

# Import wiringpi2 which will be known as 'ledborg'!
import wiringpi2 as ledborg

# Import time so we can 'sleep' when flashing the LED
import time

# Enter your gmail username and password below
# ****** WARNING!!! Remember that anyone who can view this file can see your gmail username/password
username = "******"
password = "******"

# Initialise wiringPi
ledborg.wiringPiSetup()
red_led = 0
green_led = 2
blue_led = 3
# delay when 'flashing' a sequence of colours
flash_delay = 0.25
# how many repetitions of the sequence
sequence_length = 5

# Set pinModes
ledborg.pinMode(red_led, ledborg.GPIO.OUTPUT)
ledborg.pinMode(green_led, ledborg.GPIO.OUTPUT)
ledborg.pinMode(blue_led, ledborg.GPIO.OUTPUT)
  
# This function sets the rgb values of the ledborg
# Values can be 0 or 1 (if you want to set brightness levels see https://www.piborg.org/ledborg/lesson/5)
Example #55
0
import wiringpi2 as GPIO                     #Import wiringpi2 library
import time                                  #Import time library
GPIO.wiringPiSetup()                         #Set wiringpi2 pin numbering

def Blink(A):
    LED = 2                                  #Associate pin ? to LED

    GPIO.pinMode(LED,1)                      #Set pin as GPIO out

    while True:
        GPIO.digitalWrite(LED, 1)             #Set LED as HIGH
        time.sleep(1)                          #Wait for 1 second
        GPIO.digitalWrite(LED, 0)              #Set LED as LOW
        time.sleep(1)                          #Wait for 1 second
import wiringpi2 as odroid
import time
import os
import glob
import sys

odroid.wiringPiSetup()

Button = 3

odroid.pinMode(Button, 0)
odroid.pullUpDnControl(Button, 1)

#loop
print("Program Running")
while True:  #loops forever till keyboard interupt (ctr + C)
    if odroid.digitalRead(Button) == False:  #when button not pressed:
        sys.stderr.write(".")
        time.sleep(1)
    else:
        print("Button Pressed")
        #    ------|    photo & Bell    |------ #
        #Get FileName
        now = time.strftime("Date%m-%d-%yTime%H-%M-%S")
        #Make command to run odroidC2.sh
        command = "bash odroidC2.sh " + str(now)

        # -- odroidC2.sh is an Shell script that
        # -- is responsible for taking the photo and
        # -- making the Doorbell Noise
Example #57
0
import wiringpi2
import time

wiringpi2.wiringPiSetup() # IO 핀을 사용하기 위해서는 이 3개중 하나는 무조건 선언이 되어야한다.
speedSound = 33100 + (0.6*20)
# 사실 정확한 거리를 위해서는 저 온도값을 정확히 넣어줘야하겠지만
# 그정도의 정확한 거리가 필요한것은 아니므로 20이라고 맞추고 하자

# TRIG = 2 / 13
# ECHO = 3 / 15

def distance2():                     # 전방센서
    while True:                      
        wiringpi2.pinMode(2, 1)      # wpi상에서 2번핀이고 보드상에서는 13번이다. OUTPUT은 1이다.
        wiringpi2.pinMode(3, 0)      # wpi상에서 3번핀이고 보드상에서는 15번이다. INPUT은 0이다.
        wiringpi2.digitalWrite(2, 0) # trigpin -- 13 , LOW -- 0 & HIGH -- 1
        time.sleep(0.5)
        wiringpi2.digitalWrite(2, 1)
        time.sleep(0.00001)
        wiringpi2.digitalWrite(2, 0)
        start = time.time()

        while wiringpi2.digitalRead(3) == 0:
            start = time.time()
        while wiringpi2.digitalRead(3) == 1:
            stop = time.time()

        elapsed = stop - start

        distance = elapsed * speedSound
        distance = distance/2
Example #58
0
def serial_read():
    wiringpi.wiringPiSetup()
    serial = wiringpi.serialOpen('/dev/ttyAMA0', 9600)
    #	wiringpi.serialPuts(serial,'hello world!')
    while (1):
        print(hex(wiringpi.serialGetchar(serial)))
Example #59
0
                    self.activate(i)
                else:
                    self.deactivate(i)
            cycle = cycle + 1
            cycle = cycle % totalcycles
            run_time = time.time() - start_time
            sleep_time = 1.0 * settings.cycle_time / settings.number_of_cycles
            try:
                time.sleep(sleep_time - run_time)
            except IOError:
                self.quit = True
                LOGGER.fatal('Program runs too slow to perform this operation!')
        for i in range(0, 7): # Ready to quit
            self.deactivate(i)



if __name__ == '__main__':
    wp.wiringPiSetup()

    time.sleep(1)
    BAKER = Bakeout()
    BAKER.start()

    TUI = CursesTui(BAKER)
    TUI.start()

    while not BAKER.quit:
        time.sleep(1)

Example #60
0
# -*- coding: utf-8 -*-
import wiringpi2 as gpio
owpin=29     #第8脚为1-wire脚
tl=[]       #存放每个数据位的时间
gpio.wiringPiSetup()        #初始化wiringpi库
gpio.pinMode(owpin,1)       #设置针脚为输出状态
gpio.digitalWrite(owpin,1)  #输出高电平
gpio.delay(1)
###发开始指令,要求DHT11传输数据
gpio.digitalWrite(owpin,0)  #拉低25ms开始指令
gpio.delay(25)
gpio.digitalWrite(owpin,1)  #输出高电平,开始指令结束
gpio.pinMode(owpin,0)       #设针脚为输入状态
###开始指令发送完毕,把管脚设置为高电平,并等待DHT11拉低管脚。传输数据
while(gpio.digitalRead(owpin)==1): pass #如果管脚一直是1,则一直等待。
###若被拉低,说明传输开始,应答信号+40位数据+结束标志共42位
###下边共循环45次,故意多循环几次看结果。
for i in range(45):   #测试每个数据周期的时间(包括40bit数据加一个发送开始标志
    tc=gpio.micros()  #记下当前us数(从初始化开始算起,必要时重新初始化)
    '''
    一个数据周期,包括一个低电平,一个高电平,从DHT11第一次拉低信号线开始
    到DHT11发送最后一个50us的低电平结束(然后被拉高,一直维持高电平,所以
    最后的完成标志是一直为高,超过500ms)
    '''
    while(gpio.digitalRead(owpin)==0):pass  #一位数据由一个低电平
    while(gpio.digitalRead(owpin)==1):      #加一个高电平组成
        if gpio.micros()-tc>500:    #如果超过500us就结束了本次循环,传输结束后
            break                   #会被上拉电阻拉成高电平,防止进入死循环
    tl.append(gpio.micros()-tc) #记录每个周期时间的us数,存到tl这个列表

print(tl)