def __init__(self, address=0x40, debug=False): """ Setup a Pulse-Width Modulation object, for controlling an I2C device. Parameters address: The address of the I2C device in hex. Find using `i2cdetect -y [0|1]` debug: Boolean value specifying whether or not to print debug messages. """ wp.wiringPiSetupSys() self.i2c = wp.I2C() self.fd = self.i2c.setupInterface('/dev/i2c-' + str(PWM.getPiI2CBusNumber()), address) self.address = address self.debug = debug if (self.debug): print("Got an fd: %d" % self.fd) print("Reseting PCA9685") self.setAllPWM(0, 0) #self.i2c.writeReg8(self.fd, self.__MODE1, 0x00) self.i2c.writeReg8(self.fd, self.__MODE2, self.__OUTDRV) #set as totempole ###############test###self.i2c.writeReg8(self.fd, self.__MODE2, self.__INVRT) #set non-inverted #self.i2c.writeReg8(self.fd, self.__MODE1, self.__ALLCALL) time.sleep(0.005) # wait for oscillator mode1 = self.i2c.readReg8(self.fd, self.__MODE1) mode1 = mode1 & ~self.__SLEEP # wake up (reset sleep) self.i2c.writeReg8(self.fd, self.__MODE1, mode1) time.sleep(0.005)
def __init__(self, therm_pin, sensor_pin, target_temp=55): self.target_temp = target_temp self.THERM = therm_pin self.sensor = Sensor(sensor_pin) self.running = True self.heat_on = False self.current_temp = None self.OUT = 1 self.IN = 0 self.PWM = 0 self.bounds = [55, 66, 80] self.learner = learner.Events(self, 'therm', 55, 5, 5 * 60) self.set_lock = RLock() wiringpi.wiringPiSetupSys() setupInCmd1 = 'echo "{}" > /sys/class/gpio/export'.format(sensor_pin) setupOutCmd1 = 'echo "{}" > /sys/class/gpio/export'.format(self.THERM) setupInCmd2 = 'echo "in" > /sys/class/gpio/gpio{}/direction'.format(sensor_pin) setupOutCmd2 = 'echo "out" > /sys/class/gpio/gpio{}/direction'.format(self.THERM) Popen( setupInCmd1, shell=True) Popen( setupInCmd2, shell=True) Popen(setupOutCmd1, shell=True) Popen(setupOutCmd2, shell=True) wiringpi.pinMode(self.THERM, self.OUT) wiringpi.pinMode(sensor_pin, self.IN) wiringpi.digitalWrite(self.THERM, 0) # give some time to read an initial temperature self.timer = Timer(15, self.tick) self.timer.start() self.temp_log_timer = Timer(5 * 60, self.logTemp) self.temp_log_timer.start() self.temp_logger = jsonlog.jsonLog('data/real-therm-data')
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的状态
def gpio_setup(pc): _gpio_cleanup(pc) _gpio_export(settings.PCS[pc]['gpio']['power'], 'out') _gpio_export(settings.PCS[pc]['gpio']['mains_power'], 'out') _gpio_export(settings.PCS[pc]['gpio']['power_led'], 'in') wiringpi.wiringPiSetupSys() wiringpi.pinMode(settings.PCS[pc]['gpio']['power'], 1) wiringpi.pinMode(settings.PCS[pc]['gpio']['mains_power'], 1) wiringpi.pinMode(settings.PCS[pc]['gpio']['power_led'], 0)
def __init__(self, pinNumber): threading.Thread.__init__(self) self.daemon = True self.pinNumber = pinNumber wiringpi2.wiringPiSetupSys() self.__initialState = wiringpi2.digitalRead(self.pinNumber) self.__previousState = self.__initialState
def __init__(self): self.log = logging.getLogger(__name__) # Setup GPIO pins # This routine uses /sys/class/gpio for non-root access. # Attention: export all pins beforehand (done by launcher.sh at the moment) wiringpi2.wiringPiSetupSys() # Inputs for key, value in self.PINS.items(): self.log.debug('Setting up pin %d for "%s"', value, key) # Set input mode wiringpi2.pinMode(value, self.GPIO_INPUT) # Pull pin down to ground wiringpi2.pullUpDnControl(value, self.GPIO_PUD_DOWN)
def __init__(self): wiringpi.wiringPiSetupSys() self._power_on_pin = 5 self._btn_1_pin = 7 self._btn_2_pin = 8 self._btn_3_pin = 25 self._last_value_1 = 0 self._last_value_2 = 0 self._last_value_3 = 0 self._worker = threading.Thread(target=self._work) self._worker.daemon = True self._worker.start()
def __init__(self, name, brew_time, pin): super(RaspCoffeePot, self).__init__(name) self.gpio_pin = pin try: subprocess.check_call('gpio export {} out'.format(self.gpio_pin).split()) except OSError: logger.warn('Not running in a Raspberry Pi environment or wiringpi is not installed. Continuing in simulation mode.') self.simulate = True else: self.simulate = False wiringpi2.wiringPiSetupSys() self.busy = False self.brew_time = brew_time
def __init__(self, name, brew_time, pin): super(RaspCoffeePot, self).__init__(name) self.gpio_pin = pin try: subprocess.check_call('gpio export {} out'.format( self.gpio_pin).split()) except OSError: logger.warn( 'Not running in a Raspberry Pi environment or wiringpi is not installed. Continuing in simulation mode.' ) self.simulate = True else: self.simulate = False wiringpi2.wiringPiSetupSys() self.busy = False self.brew_time = brew_time
def initialize(): """Set pins as outputs and start all lights in the off state.""" if _EXPORT_PINS: logging.info("Running as non root user, disabling pwm mode on " "all pins") for pin in xrange(GPIOLEN): PIN_MODES[pin] = "onoff" is_pin_pwm[pin] = False wiringpi.wiringPiSetupSys() else: # TODO(mdietz): Configrable pin mode or GPIO mode #wiringpi.wiringPiSetup() wiringpi.wiringPiSetupGpio() enable_device() set_all_pins_as_outputs() turn_off_all_lights()
def __init__(self, address=0x40, debug=False): """ Setup a Pulse-Width Modulation object, for controlling an I2C device. Parameters address: The address of the I2C device in hex. Find using `i2cdetect -y [0|1]` debug: Boolean value specifying whether or not to print debug messages. """ wiringpi.wiringPiSetupSys() self.i2c = wiringpi.I2C() self.fd = self.i2c.setupInterface('/dev/i2c-' + str(PWM.getPiI2CBusNumber()), address) self.address = address self.debug = debug if (self.debug): print("Got an fd: %d" % self.fd) print("Reseting PCA9685") self.i2c.writeReg8(address, self.__MODE1, 0x00)
def setup(): # use Gpio pin numbering # w.wiringPiSetupGpio() w.wiringPiSetupSys() # use the non-root mode. Needs to export pins via gpio first! # polarity pins are outputs: for pin in pins_pol: w.pinMode(pin, 1) # defined as output w.digitalWrite(pin,0) # all output off # PWM pins: for pin in pins_pwm: w.softPwmCreate(pin,0,100) #define pin as pwm output # all magnets turned off magnet(0,0,0) magnet(1,0,0) magnet(2,0,0) magnet(3,0,0)
def run(continuous=False, verbose=False, save=False, laser_position=None, as_pfc=False, rpc=None, ro=None): global camera assert laser_position in LASER_POSITIONS def log(*args): if verbose: return ' '.join(map(str, args)) log('Initializing GPIO...') wiringpi2.wiringPiSetupSys() # Set laser control pin to output. #wiringpi2.pinMode(LASER_EN_PIN, 1)#TODO:has no effect?! pinMode(LASER_EN_PIN, 1) log('GPIO initialized.') # def process(): # while 1: # t00 = time.clock() # # log('Recording reference image with laser off...') # #time.sleep(capture_delay) # stream = io.BytesIO() # yield stream # # camera.capture( # # #os.path.expanduser('~/laser-off.jpg'), # # stream, # # format='jpeg', # # quality=JPEG_QUALITY, # # use_video_port=True, # # ) # stream.seek(0) # laser_off_image = Image.open(stream) # if save: # laser_off_image.save(os.path.expanduser('~/laser-off.jpg')) # # log('Turning laser on...') # wiringpi2.digitalWrite(LASER_EN_PIN, 1) # # log('Recording reference image with laser on...') # #time.sleep(capture_delay) # stream = io.BytesIO() # yield stream # # camera.capture( # # #os.path.expanduser('~/laser-on.jpg'), # # stream, # # format='jpeg', # # quality=JPEG_QUALITY, # # use_video_port=True, # # ) # stream.seek(0) # laser_on_image = Image.open(stream) # if save: # laser_on_image.save(os.path.expanduser('~/laser-on.jpg')) # # log('Turning laser off...') # wiringpi2.digitalWrite(LASER_EN_PIN, 0) # # log('Calculating distance...') # t0 = time.clock() # distance = calculate_distance( # # os.path.expanduser('~/laser-off.jpg'), # # os.path.expanduser('~/laser-on.jpg'), # laser_off_image, # laser_on_image, # save=save, # ) # td = time.clock() - t0 # distance = map(int, compress_list(distance, bins=10)) # print 'distance calculation took %s seconds' % td # print 'distance:', distance # # tdd = time.clock() - t00 # print 'fps:', 1./tdd # print 'exposure_speed:', camera.exposure_speed # print 'shutter_speed:', camera.shutter_speed # print 'camera.framerate:', camera.framerate # # if not continuous: # break distance = None with picamera.PiCamera() as camera: log('Initializing camera...') #camera.resolution = (1024, 768) camera.resolution = (320, 240) if laser_position == BOTTOM: camera.rotation = 180 camera.meter_mode = 'backlit' #camera.start_preview() #camera.led = False #camera.shutter_speed = 30000 # microseconds (default) camera.shutter_speed = 10000 # microseconds #camera.shutter_speed = 5000 # microseconds #camera.shutter_speed = 1000 # microseconds camera.framerate = 80 log('Camera initialized.') #TODO:fix? ignores KeyboardInterrupt? # camera.capture_sequence(process(), format='jpeg', use_video_port=True) if rpc is not None: rpc = float(rpc) if ro is not None: ro = float(ro) while 1: t00 = time.clock() log('Recording reference image with laser off...') #time.sleep(capture_delay) # Take at least two images to ensure proper exposure. for _i in xrange(2): stream = io.BytesIO() camera.capture( #os.path.expanduser('~/laser-off.jpg'), stream, format='jpeg', quality=JPEG_QUALITY, use_video_port=True, ) stream.seek(0) laser_off_image = Image.open(stream) if save: laser_off_image.save(os.path.expanduser('~/laser-off%i.jpg' % _i)) log('Turning laser on...') wiringpi2.digitalWrite(LASER_EN_PIN, 1) log('Recording reference image with laser on...') #time.sleep(capture_delay) stream = io.BytesIO() camera.capture( #os.path.expanduser('~/laser-on.jpg'), stream, format='jpeg', quality=JPEG_QUALITY, use_video_port=True, ) stream.seek(0) laser_on_image = Image.open(stream) if save: laser_on_image.save(os.path.expanduser('~/laser-on.jpg')) log('Turning laser off...') wiringpi2.digitalWrite(LASER_EN_PIN, 0) try: log('Calculating distance...') t0 = time.clock() lrf = LaserRangeFinder( laser_position=laser_position, rpc=rpc or 0.00103721750257, ro=ro or 0.418921972295, ) distances = lrf.get_distance( off_img=laser_off_image,#os.path.join(CURRENT_DIR, '../../docs/images/sample1/sample-a-0.jpg'), on_img=laser_on_image,#os.path.join(CURRENT_DIR, '../../docs/images/sample1/sample-b-0.jpg'), save_images_dir='~', as_pfc=as_pfc, ) # distance = calculate_distance( # # os.path.expanduser('~/laser-off.jpg'), # # os.path.expanduser('~/laser-on.jpg'), # laser_off_image, # laser_on_image, # save=save, # ) td = time.clock() - t0 #distance = map(int, compress_list(distance, bins=10)) print 'distance calculation took %s seconds' % td print 'distances:', distances distances_10 = utils.compress_list(distances, bins=10, as_int=True) print 'distances_10:', distances_10 tdd = time.clock() - t00 print 'fps:', 1./tdd print 'exposure_speed:', camera.exposure_speed print 'shutter_speed:', camera.shutter_speed print 'camera.framerate:', camera.framerate except IOError as e: # On rare occassions we see: # IOError: broken data stream when reading image file print>>sys.stderr, e if not continuous: break return distance
#!/usr/bin/env python ''' Program: Bit_rPiw.py Version: 0.1.2w Date: 23-Nov-2013 Purpose: To define useful functions for controlling bits (GPIOs). Converted to use WiringPi2 Dependencies: WiringPi2 Copyright (2013) by Dale Weber, [email protected], @hybotics (Twitter and App.Net) ALL Rights Reserved. ''' # This is specific to the Raspberry Pi import wiringpi2 wiringpi2.wiringPiSetupSys() # For /sys/class/gpio with GPIO pin numbering wiringpi2.wiringPiSetupGpio() # For GPIO pin numbering #import RPi.GPIO as GPIO ''' wiringpi2.pinMode(1,1) # Set pin 1 to output wiringpi2.digitalWrite(1,1) # Write 1 HIGH to pin 1 wiringpi2.digitalRead(1) # Read pin 1 ''' from hybotics import zilch from time import sleep ''' Functions ''' '''
def _init_picamera_led(self): self.led = 5 os.system("gpio export " + str(self.led) + " out") if gpio.wiringPiSetupSys() != 0: rospy.logfatal("Unable to setup gpio") gpio.digitalWrite(self.led,False)
def __init__(self, dev='/dev/spidev0.0', spd=1000000): spi.openSPI(device=dev,speed=spd) wiringpi2.wiringPiSetupSys() wiringpi2.pinMode(self.NRSTPD, 1) wiringpi2.digitalWrite(self.NRSTPD, 1) self.MFRC522_Init()
def gpio_ns_init(): call( [ "gpio", "drive", str(PADS_0_TO_27), str(GPIO_DRIVE_STRENGTH_PADS_0_TO_27) ] ) #configure the output drive strength of the gpio - this is needed for the level translator call(["gpio", "export", str(VOLTAGE_TEST_PIN), "out"]) #configure bcm pin 4 as an output - Voltage Test call(["gpio", "export", str(MFG_TRIG_PIN), "out"]) #configure bcm pin 17 as an output - MFG Test call(["gpio", "export", str(MFG_TOGGLE_PIN), "in"]) #configure bcm pin 22 as an input - Toggle/Continue call(["gpio", "export", str(POWER_PIN), "out"]) #configure bcm pin 24 as an output. call(["gpio", "export", str(FIXTURE_CLOSED_PIN), "in"]) #configure bcm pin 2 as an input - Fixture Closed call(["gpio", "export", str(FLASHER_OK_PIN), "in"]) #configure bcm pin 7 as an input - Flasher Programmer OK call(["gpio", "export", str(FLASHER_BUSY_PIN), "in"]) #configure bcm pin 8 as an input - Flasher Programmer Busy call(["gpio", "export", str(FLASHER_START_PIN), "out" ]) #configure bcm pin 25 as an output - Flasher Programmer Start call(["gpio", "export", str(IN_JTAG_VCC_CTL), "out" ]) #configure bcm pin 11 as an output - Flasher Programmer Start call(["gpio", "export", str(IN_MFG_INFO_CTL), "out"]) #configure bcm pin 10 as an output - UART RX call(["gpio", "export", str(POGOPIN_TEST_PIN), "out"]) #configure bcm pin 5 as an output - Pogo Pin Test Pin call(["gpio", "export", str(POGOPIN_RELAY_PIN), "out"]) #configure bcm pin 6 as an output - Pogo Pin Test Pin time.sleep(GP_DELAY_TIME) call(["gpio", "-g", "mode", str(MFG_TOGGLE_PIN), "up"]) #configure bcm pin 22 to have a pull up resistor call(["gpio", "-g", "mode", str(FLASHER_OK_PIN), "up"]) #configure bcm pin 7 to have a pull up resistor call(["gpio", "-g", "mode", str(FLASHER_BUSY_PIN), "up"]) #configure bcm pin 8 to have a pull up resistor call(["gpio", "-g", "mode", str(MFG_INFO_PIN), "alt0"]) #configure bcm pin 15 to be a UART Rx call(["gpio", "export", str(ENCODER_A0), "in"]) #configure bcm pin 16 as an input - Encoder A0 call(["gpio", "export", str(ENCODER_A1), "in"]) #configure bcm pin 20 as an input - Encoder A1 call(["gpio", "export", str(ENCODER_A2), "in"]) #configure bcm pin 21 as an input - Encoder A2 call(["gpio", "export", str(PUSH1_ACTUATOR), "out" ]) #configure bcm pin 13 as an output - Actuate piston for PUSH1 call(["gpio", "export", str(PUSH2_ACTUATOR), "out" ]) #configure bcm pin 19 as an output - Actuate piston for PUSH2 call(["gpio", "export", str(PUSH3_ACTUATOR), "out" ]) #configure bcm pin 26 as an output - Actuate piston for PUSH3 call(["gpio", "export", str(CRYSTAL_CAL_PIN), "out" ]) #configure bcm pin 26 as an output - Actuate piston for PUSH3 # set the actuator pins to low. gpio_ns_write(PUSH1_ACTUATOR, 0) gpio_ns_write(PUSH2_ACTUATOR, 0) gpio_ns_write(PUSH3_ACTUATOR, 0) gpio_ns_write(POWER_PIN, 1) #initialize pin to 1 since the power is active low. time.sleep(GP_DELAY_TIME) wiringpi2.wiringPiSetupSys( ) #setup gpio to work with no sudo. must be called after 'gpio export' and 'gpio mode' calls time.sleep(GP_DELAY_TIME) time.sleep(GP_DELAY_TIME) time.sleep(GP_DELAY_TIME)
def _init_led(self): self.led = 5 os.system("gpio export " + str(self.led) + " out") if gpio.wiringPiSetupSys() != 0: rospy.logfatal("Unable to setup gpio") gpio.digitalWrite(self.led, False)
#!/usr/bin/python import time import wiringpi2 wiringpi2.wiringPiSetup() wiringpi2.wiringPiSetupSys() wiringpi2.wiringPiSetupGpio() #setup wiringpi2.pinMode(11,1) # turn 11 into an output #loop while 1 : wiringpi2.digitalWrite(11,1) time.sleep(2) wiringpi2.digitalWrite(11,0) time.sleep(2)
import curses import wiringpi2 import time import serial #importing necessary libraries wiringpi2.wiringPiSetupSys( ) # For /sys/class/gpio with GPIO pin numbering - THE USED ONE # OR #wiringpi2.wiringPiSetup() # For sequential pin numbering, one of these MUST be called before using IO functions # OR #wiringpi2.wiringPiSetupGpio() # For GPIO pin numbering # important MX-28 constants AX_WRITE_DATA = 3 AX_READ_DATA = 4 s = serial.Serial() # create a serial port object s.baudrate = 1000000 # baud rate, in bits/second s.port = "/dev/ttySAC0" # this is whatever port your are using s.open() #function which takes input from keyboard without the need to press ENTER def input_char(message): try: win = curses.initscr() win.addstr(0, 0, message) while (True): ch = win.getch() if ch in range(32, 127): break
def init_output(self): """Set the pin as output mode""" wiringpi.wiringPiSetupSys() wiringpi.pinMode(self.write_bcm_pin, 1) # output mode
def init_input(self): """Set the pin as input mode""" wiringpi.wiringPiSetupSys() wiringpi.pinMode(self.read_bcm_pin, 0) # input mode
def process_write_gpio(bcm_pin, value): if value == "1": pi.digitalWrite(bcm_pin, 1) else: pi.digitalWrite(bcm_pin, 0) #this function is used to setup the thread for gpio writes #use this one from python code def write_gpio(bcm_pin, value): p = Process(target=process_write_gpio, args=(bcm_pin, value)) p.start() p.join() call(["gpio", "export", "18", "out"]) #configure bcm pin 18 as an output call(["gpio", "export", "17", "in"]) #configure bcm pin 17 as an input call(["gpio", "-g", "mode", "17", "up"]) #configure bcm pin 17 to have a pull up resistor pi.wiringPiSetupSys() #setup gpio to work with no sudo. must be called after 'gpio export' and 'gpio mode' calls choice = raw_input("Enter '0' for low and '1' for high >") write_gpio(18,choice) # example write of pin 18 of the user choice. choice must be 0 or 1 print(pi.digitalRead(18)) print(pi.digitalRead(17)) call(["gpio", "unexportall"]) #return gpio to raspi print('just printing something to see if gets to end')