def __init__(self, conffile):
        Observable.__init__(self)
	cp = ConfigParser()
	cp.read(conffile)

	if not Globals.globSimulate:
	    wiringpi.wiringPiSetupGpio()

	self.md = MotorDriver([
		    cp.getint("MotorDriver", "LEFT_L"),
		    cp.getint("MotorDriver", "LEFT_R"),
		    cp.getint("MotorDriver", "RIGHT_L"),
		    cp.getint("MotorDriver", "RIGHT_R"),
		    cp.getint("MotorDriver", "VERTICAL_L"),
		    cp.getint("MotorDriver", "VERTICAL_R"),
		    ])
	self.md.start()

	self.ds = DistanceSensor(
		    cp.getint("DistanceSensor", "TRIGGER"),
		    cp.getint("DistanceSensor", "ECHO")
		    )
	self.ds.start()

	self.acl = AltitudeControlLoop(self.md, self.ds)

	self.update("MotorDriver", self.md)
	self.update("DistanceSensor", self.ds)
	self.update("AltitudeControlLoop", self.acl)

	self.md.subscribe(self.update)
	self.ds.subscribe(self.update)
	self.acl.subscribe(self.update)

	self.setCamera(False)
Beispiel #2
0
def main():
    #all needs to run automatically
    port0 = '/dev/ttyUSB0'
    port1 = '/dev/ttyUSB1'
    port2 = '/dev/ttyUSB2'
    ##
    th_cl1 = TestThread(port1, './original_data/data1208.csv')
    th_cl1 = TestThread(port1, './original_data/data1208.csv')

    #th_cl1.start()
    #th_cl2.start()

    f = open('./original_data/data1209.csv', 'w')
    ##
    servo_pin = 18

    param = sys.argv
    set_degree = int(param[1])
    print(set_degree)

    wiringpi.wiringPiSetupGpio()

    wiringpi.pinMode(servo_pin, 2)

    wiringpi.pwmSetMode(0)
    wiringpi.pwmSetRange(1024)
    wiringpi.pwmSetClock(375)


    while True:
        try:
            ser = serial.Serial(port0, 38400, timeout=10)  # 10s-timeout baudrate=38400
            ser.write(b'<RM,>??\r\n')  # send command (CR+LF)
            line = ser.readline()
            line = str(datetime.datetime.now()) + str(",") + line.decode('utf-8')
            line = line.split(',')

            velocity = float(line[2])
            temp = float(line[5])

            print('CPU_temperature' + '/' + line[0] + ',' + line[2] + ','
                    + line[3] + ',' + line[4] + ',' + line[5])
            f.write(line[0] + ',' + line[2] + ','
                    + line[3] + ',' + line[4] + ',' + line[5] + "\n")

            if temp >= 35.0:
#                print('too hot')
                wiringpi.pwmWrite(servo_pin, set_degree + 5)
#                LED(11, True)
            else:
#                print('oh.. cool')
#                move_deg = int (81+41/90*set_degree)

                wiringpi.pwmWrite(servo_pin, set_degree)
#                LED(11, False)

            time.sleep(5)

        except IndexError:
            pass
Beispiel #3
0
def configureHardware(postMotionEvent, postButtonClickEvent):
    wiringpi.wiringPiSetupGpio()

    # PIR motion detector
    def reportMotion():
        if wiringpi.digitalRead(BCM_PIR) == 1:
            postMotionEvent()

    wiringpi.pinMode(BCM_PIR, wiringpi.GPIO.INPUT)
    wiringpi.pullUpDnControl(BCM_PIR, wiringpi.GPIO.PUD_OFF)
    wiringpi.wiringPiISR(BCM_PIR, wiringpi.GPIO.INT_EDGE_BOTH, reportMotion)

    # Display buttons
    for btnNum, bcmPin in (
                (1, BCM_BTN_1),
                (2, BCM_BTN_2),
                (3, BCM_BTN_3),
            ):
        @debounce(0.02)
        def reportClick(_bcmPin=bcmPin, _btnNum=btnNum):
            if wiringpi.digitalRead(_bcmPin) == 0:
                postButtonClickEvent(_btnNum)

        wiringpi.pinMode(bcmPin, wiringpi.GPIO.INPUT)
        wiringpi.pullUpDnControl(bcmPin, wiringpi.GPIO.PUD_UP)
        wiringpi.wiringPiISR(bcmPin, wiringpi.GPIO.INT_EDGE_BOTH, reportClick)

    # Servos
    wiringpi.pinMode(BCM_SERVO_ACTIVATION, wiringpi.GPIO.OUTPUT)
    wiringpi.pinMode(BCM_SERVO_SPRING, wiringpi.GPIO.OUTPUT)
    wiringpi.pinMode(BCM_SERVO_HOLDER, wiringpi.GPIO.OUTPUT)
Beispiel #4
0
    def __init__(self):

        wiringpi.wiringPiSetupGpio()
        wiringpi.pinMode(self.PIN_PWM, wiringpi.GPIO.PWM_OUTPUT)
        wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
        wiringpi.pwmSetClock(375)

        wiringpi.pwmWrite(self.PIN_PWM, self.FRONT)
Beispiel #5
0
 def __init__(self, config):
     import wiringpi
     Unlocker.__init__(self, config)
     # PIN numbers follow P1 header BCM GPIO numbering, see https://projects.drogon.net/raspberry-pi/wiringpi/pins/
     # Local copy of the P1 in repo mapping see gpio_vs_wiringpi_numbering_scheme.png.
     wiringpi.wiringPiSetupGpio()
     self.lockPin = self.config.getint("UnlockerWiringPi", "lock_pin")
     wiringpi.pinMode(self.lockPin, wiringpi.OUTPUT) #output
	def wakeup(self):
		if self.isFirst:
			# setup, if first
			self.isFirst = False
			wiringpi.wiringPiSetupGpio()
			wiringpi.pinMode(self.pin, wiringpi.OUTPUT)
		self.quit()
		self.ledThread = LedThread(self.pin)		
		self.ledThread.startRun()
		self.ledThread.startBlink()
Beispiel #7
0
def initOS():
	os.environ['SDL_FBDEV'] = '/dev/fb1'
	os.environ['SDL_MOUSEDEV'] = '/dev/input/touchscreen'
	os.environ['SDL_MOUSEDRV'] = 'TSLIB'
	os.environ['SDL_VIDEODRIVER'] = 'fbcon'

	wiringpi.wiringPiSetupGpio()
	wiringpi.pinMode(18, 2)
	wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS)  # default balanced mode makes screen dark at about 853/1024
	wiringpi.pwmWrite(18, 1024)
	def wakeup(self):
		self.isRun = True
		if self.isFirst:
			# setup, if first
			self.isFirst = False
			wiringpi.wiringPiSetupGpio()
			wiringpi.pinMode(self.pinLed, wiringpi.OUTPUT)
			wiringpi.pinMode(self.pinButton, wiringpi.INPUT)
		self.quitLed()
		self.ledThread = LedThread(self.pinLed)
		self.ledThread.startRun()
Beispiel #9
0
def run_wiringpi(args):
    import wiringpi
    global debug, last_time
    wiringpi.wiringPiSetupGpio()
    wiringpi.pinMode(args.pinout, 1)
    while True:
        last_time = "%.9f" % shared.time()
        wiringpi.digitalWrite(args.pinout, 1)
        time.sleep(0.00001)
        wiringpi.digitalWrite(args.pinout, 0)
        if debug: print(last_time)
        time.sleep(args.interval)
    def __init__(self, keymap):
        self.DSPin = 24
        self.LatchPin = 23
        self.ClockPin = 25
        self.keymap = keymap        
        self.outputArray = [0] * 48
        self.resetOutputArray()
	self.timeout =0.0005
        wiringpi.wiringPiSetupGpio()
        wiringpi.pinMode(self.DSPin,1)
        wiringpi.pinMode(self.LatchPin,1)
        wiringpi.pinMode(self.ClockPin,1)
def setup_gpio():
    wiringpi.wiringPiSetupGpio()

    wiringpi.pinMode(LEFT_FORWARD, 1)
    wiringpi.pinMode(LEFT_BACKWARD, 1)
    wiringpi.pinMode(RIGHT_FORWARD, 1)
    wiringpi.pinMode(RIGHT_BACKWARD, 1)

    wiringpi.softPwmCreate(LEFT_FORWARD, 0, 100)
    wiringpi.softPwmCreate(LEFT_BACKWARD, 0, 100)
    wiringpi.softPwmCreate(RIGHT_FORWARD, 0, 100)
    wiringpi.softPwmCreate(RIGHT_BACKWARD, 0, 100)
Beispiel #12
0
def init(SCLK = 24, DIN = 23, DC = 22, RST = 18, LED = 17, RS = 4, contrast = default_contrast):
    """ init screen, trun off backlight, clearscreen """
    wiringpi.wiringPiSetupGpio()
    pins = [SCLK, DIN,DC, RST, LED, RS]
    pin_SCLK, pin_DIN, pin_DC, pin_RST, pin_LED, pin_RS = pins
    map(lambda p: wiringpi.pinMode(p, ON), pins)
    wiringpi.digitalWrite(pin_RST, OFF)
    time.sleep(0.1)
    wiringpi.digitalWrite(pin_RST, ON)
    map(writec, [0x21, 0x14, contrast, 0x20, 0x0c])
    cls()
    backlight(OFF)
    position(0, 0)
	def __init__(self):
		# GPIO番号でピンを指定
		wiringpi.wiringPiSetupGpio()

		self.servos = []
		for index in RPiDirectServoController.PIN_MAP.iterkeys():
			pin = RPiDirectServoController.PIN_MAP[index]
			# サーボを作る
			self.servos.append(SG90Direct(pin, self.getPartName(index), RPiDirectServoController.PWM_COUNTUP_FREQUENCY, RPiDirectServoController.PWM_CYCLE_RANGE))

		wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS)
		wiringpi.pwmSetClock(RPiDirectServoController.PWM_COUNTUP_FREQUENCY)
		wiringpi.pwmSetRange(RPiDirectServoController.PWM_CYCLE_RANGE)
def calibrateServo(conn):
    print 'calibrateServo'
    # Set up the servo
    wiringpi.wiringPiSetupGpio()
    wiringpi.pinMode(19,1)
    wiringpi.digitalWrite(19,0)

    cal = [0,0]
    min1 = []
    min2 = []

    period_time = 0.02
    # This pulse time puts the servo at 0 degrees
    pulse_time = 0.00037
    for i in range(1,100):
        wiringpi.digitalWrite(19,1)
        sleep(pulse_time)
        wiringpi.digitalWrite(19,0)
        sleep(period_time-pulse_time)
    min1.append(readServo(conn))
    # This pulse time puts teh servo at 180 degrees
    pulse_time = 0.0023
    for i in range(101,200):
        wiringpi.digitalWrite(19,1)
        sleep(pulse_time)
        wiringpi.digitalWrite(19,0)
        sleep(period_time-pulse_time)
    min2.append(readServo(conn))
        # This pulse time puts the servo at 0 degrees
    pulse_time = 0.00037
    for i in range(1,100):
        wiringpi.digitalWrite(19,1)
        sleep(pulse_time)
        wiringpi.digitalWrite(19,0)
        sleep(period_time-pulse_time)
    min1.append(readServo(conn))
    # This pulse time puts teh servo at 180 degrees
    pulse_time = 0.0023
    for i in range(101,200):
        wiringpi.digitalWrite(19,1)
        sleep(pulse_time)
        wiringpi.digitalWrite(19,0)
        sleep(period_time-pulse_time)
    min2.append(readServo(conn))


    cal[0] = numpy.mean(min1)
    cal[1] = numpy.mean(min2)

    print cal
    return cal
	def wakeup(self):
		if self.isFirst:
			# setup, if first
			self.isFirst = False
			wiringpi.wiringPiSetupGpio()
			wiringpi.pinMode(self.pinLed, wiringpi.OUTPUT)
			wiringpi.pinMode(self.pinButton, wiringpi.INPUT)
		self.quitLed()
		self.ledThread = LedThread(self.pinLed)
		self.ledThread.startRun()
		self.ledThread.startBlink()
		self.servo.setPinMode()
		self.servo.setPwm()
		self.servo.stop()
def app_main():
    """
    application main loop
    """
    pic = picamera.PiCamera()
    sw01 = tact.GPIOTactSwitch(SWITCH_PIN_01)
    sw02 = tact.GPIOTactSwitch(SWITCH_PIN_02)
    wp.wiringPiSetupGpio()
    sw01.setup()
    sw02.setup()
    pic.resolution = (960, 540)
    pic.framerate = 24
    pic.exposure_mode = 'auto'

    dt_start = dt.datetime.now()

    while True:
        sw01.check_pin()
        sw02.check_pin()
        if sw01.is_changed(True):
            if sw01.switch_state is True:
                print('Start preview')
                pic.start_preview()
            else:
                print('Stop preview')
                pic.stop_preview()
        if sw02.is_changed(True):
            if sw02.switch_state is True:
                print('Start recording')
                dt_start = dt.datetime.now()
                pic.start_recording(
                    '%s.h264' % dt.datetime.now().strftime('%Y%m%d_%H%M%S'))
            else:
                print('Stop recording')
                pic.stop_recording()
        elif sw02.switch_state is True:
            dt_now = dt.datetime.now()
            dt_diff = dt_now - dt_start
            if dt_diff.seconds > MAX_RECORD_SECONDS:
                print('Start New File')
                pic.stop_recording()
                dt_start = dt_now
                pic.start_recording(
                    '%s.h264' % dt.datetime.now().strftime('%Y%m%d_%H%M%S'))

        time.sleep(CHECK_INTERVAL)
def io_init():
  global io_initialized
  if io_initialized:
    return

  wiringpi.wiringPiSetupGpio()
  wiringpi.pinMode(12, wiringpi.GPIO.PWM_OUTPUT)
  wiringpi.pinMode(13, wiringpi.GPIO.PWM_OUTPUT)

  wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
  wiringpi.pwmSetRange(MAX_SPEED)
  wiringpi.pwmSetClock(2)

  wiringpi.pinMode(5, wiringpi.GPIO.OUTPUT)
  wiringpi.pinMode(6, wiringpi.GPIO.OUTPUT)

  io_initialized = True
Beispiel #18
0
    def initDevice(self):
        '''
        Does a reset to put all registers in initial state
        '''

        # Set pin numbering mode
        #  wiringPiSetupSys() did not work because pins were low after booting and running the write commands
        # This requires root!
        wiringpi.wiringPiSetupGpio()

        # Define the reset pin as output
        wiringpi.pinMode(self.RstPin, wiringpi.GPIO.OUTPUT)
        # Create a reset impulse
        wiringpi.digitalWrite(self.RstPin, wiringpi.GPIO.LOW)
        # wait for 50 ms
        time.sleep(.050)
        wiringpi.digitalWrite(self.RstPin, wiringpi.GPIO.HIGH)
Beispiel #19
0
 def __init__(self, callback):
     log.debug('GpioButtons.__init__')
     wiringpi.wiringPiSetupGpio()
     self.debounce = dict()
     self.debounce_time = fire_pong.util.config['InputManager']['gpio']['debounce_time']
     self.callback = callback
     for action in ['quit', 'start', 'swipe1', 'swipe2']:
         try:
             pin = fire_pong.util.config['InputManager']['gpio'][action]
             wiringpi.pinMode(pin, wiringpi.GPIO.INPUT)
             wiringpi.pullUpDnControl(pin, wiringpi.GPIO.PUD_UP)
             wiringpi.wiringPiISR(pin, wiringpi.GPIO.INT_EDGE_FALLING, getattr(self, action))
             self.debounce[action] = 0
             log.debug('GpioButtons.__init__() %s => pin %s' % (action, pin))
             
         except KeyError as e:
             log.warning('GpioButtons.__init__(): %s' % e)
             pass
Beispiel #20
0
    def setup(self):
        self.max = 1024
        self.high = 500
        self.normal = 300
        self.low = 100

        wp.wiringPiSetupGpio()

        wp.pinMode(18, 2)
        wp.pinMode(19, 2)
        wp.pinMode(23, 1)
        wp.pinMode(24, 1)

        self.set_left_dir(0)  # Set rotation direction to forward for both wheels
        self.set_right_dir(0)

        self.freq = 400  # PWM frequency
        self.dc = 0  # Duty cycle
        print("Completed setting up motors!")
Beispiel #21
0
    def __init__(self, sensor_pin=27, detector_delay=1, settletime=0.01):
        """ Initialize the tripwire.  See module documentation for the details
            of the parameter settings used here.
        """
        self.sensor_pin = sensor_pin
        self.detector_delay = detector_delay
        self.logger = logging.getLogger('main.tripwire')

        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.sensor_pin, GPIO.IN)
        
        wiringpi.wiringPiSetupGpio()
        wiringpi.pinMode(PWM_PIN, 2)
        # Choose mark-space mode for better frequency control
        wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
        wiringpi.pwmSetRange(2)
        wiringpi.pwmSetClock(253)
        
        wiringpi.pwmWrite(PWM_PIN, 1) # set duty cycle to 1 over range=2, or 50%
        
        time.sleep(settletime) # I'm not sure how long is necessary,
                                  # the demodulator datasheet
                                  # suggests at least 0.0004 s
        self.logger.info('IRon curtain initialized.')
Beispiel #22
0
    def initialize_state(self):
        self._not_initialized = False
        self._MAX_SPEED = self.config.get('max_motor_speed', 10)
        self._MIN_SPEED = self._MAX_SPEED * -1
        self.MIN_SERVO = self.config.get('min_servo', 100)
        self.MAX_SERVO = self.config.get('max_servo', 100)
        self.ZERO_SERVO = self.config.get('zero-servo', 150)
        self._INITIAL_SERVO = 100
        gears = 5
        for index in range(1, gears + 1):
            self.gear_lookup[index] = int((self._MAX_SPEED / gears) * index)
        logger.info('Setting gears: ' + str(self.gear_lookup))

        if self.use_motors or self.use_servo:
            res = wiringpi.wiringPiSetupGpio()
            if res != 0:
                logger.error('Could not set up software PWM')
        if self.use_motors:
            logger.info('Setting up Motor Software-Based PWM')
            # a cluster of horrible looking code, should be refactored but is it single use???
            wiringpi.pinMode(self.m1conf.get('en_pin'), wiringpi.GPIO.OUTPUT)
            wiringpi.pinMode(self.m1conf.get('dir_pin'), wiringpi.GPIO.OUTPUT)
            wiringpi.pinMode(self.m2conf.get('en_pin'), wiringpi.GPIO.OUTPUT)
            wiringpi.pinMode(self.m2conf.get('dir_pin'), wiringpi.GPIO.OUTPUT)
            logger.info('Pull both motors out of low-power mode')
            wiringpi.digitalWrite(self.m1conf.get('en_pin'), 1)
            wiringpi.digitalWrite(self.m2conf.get('en_pin'), 1)
            logger.info('Set up motor software pwm')
            wiringpi.softPwmCreate(self.m1conf.get('pwm_pin'), 0, self._MAX_SPEED)
            wiringpi.softPwmCreate(self.m2conf.get('pwm_pin'), 0, self._MAX_SPEED)
            wiringpi.softPwmWrite(self.m1conf.get('pwm_pin'), 0)
            wiringpi.softPwmWrite(self.m2conf.get('pwm_pin'), 0)
            logger.info('Setting motor speeds to zero.')
        if self.use_servo:
            logger.info('Setting up Servo Hardware-Based PWM')
            wiringpi.pinMode(self.servo_gpio_pin, wiringpi.GPIO.PWM_OUTPUT)
            wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
            wiringpi.pwmSetClock(192)
            wiringpi.pwmSetRange(2000)
            logger.info('Servo config done')
            wiringpi.pwmWrite(self.servo_gpio_pin, self.ZERO_SERVO)
            logger.info('Setting servo speed to zero.')
Beispiel #23
0
 def __init__(self, motors):
     self.motors = motors
     self.value = 0
     wp.wiringPiSetupGpio()
Beispiel #24
0
    def __init__(self, wrapper):
        GpioInterface.__init__(self, wrapper)

        wpi.wiringPiSetupGpio()  # requires sudo
Beispiel #25
0
# Servo Control
#https://learn.adafruit.com/adafruits-raspberry-pi-lesson-8-using-a-servo-motor/software

import time
import wiringpi

PIN_SERVO = 18
# use 'GPIO naming'
wiringpi.wiringPiSetupGpio()

# set #18 to be a PWM output
wiringpi.pinMode(PIN_SERVO, wiringpi.GPIO.PWM_OUTPUT)

# set the PWM mode to milliseconds stype
wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)

# divide down clock
wiringpi.pwmSetClock(192)
wiringpi.pwmSetRange(2000)

delay_period = 0.01

while True:
        for pulse in range(50, 250, 1):
                wiringpi.pwmWrite(PIN_SERVO, pulse)
                time.sleep(delay_period)
        for pulse in range(250, 50, -1):
                wiringpi.pwmWrite(PIN_SERVO, pulse)
                time.sleep(delay_period)
Beispiel #26
0
    def __init__(self):
        GPIO.setmode(GPIO.BCM)

        # output pin definitions
        self.arm_up = 26
        self.arm_down = 13
        self.claw_open = 23
        self.claw_close = 24
        self.forward = 5
        self.backward = 6
        self.right = 4
        self.left = 17
        self.led = 18
        out_pins = [self.arm_up,self.arm_down,self.claw_open,self.claw_close,self.forward,self.backward,self.right,self.left,self.led]

        for pin in out_pins:
            GPIO.setup(pin,GPIO.OUT)

        self.forward_pwm  = GPIO.PWM(self.forward,15)
        self.backward_pwm = GPIO.PWM(self.backward,15)


        for pwm in [self.forward_pwm,self.backward_pwm]:
            pwm.start(0)
            pwm.ChangeFrequency(15)

        # hardware pwm
        '''
        self.hardware_pwm_pin = 18
        wiringpi.wiringPiSetupGpio()
        wiringpi.pinMode(self.hardware_pwm_pin, wiringpi.GPIO.PWM_OUTPUT)
        wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
        wiringpi.pwmSetClock(192)
        self.hardware_pwm_range = 2000
        wiringpi.pwmSetRange(self.hardware_pwm_range)
        self.hardware_pwm = int(self.hardware_pwm_range*0.055)
        wiringpi.pwmWrite(self.hardware_pwm_pin,self.hardware_pwm) # 5.5% duty cycle
        self.hardware_pwm_timeflag = time.time()
        '''

        # itermitent move
        self.itm_k = 100
        self.itm_checkpoint = time.time()
        self.itm_press = 0

        # connection cont
        self.led_cont = 100

        self.restarting = False

        return

        self.direction = 'steady'
        out_pins = [12,13,4,27]
        self.speed = 0
        self.in_routine = False
        for pin in out_pins:
            GPIO.setup(pin,GPIO.OUT)
        self.pwms = [GPIO.PWM(pin,15) for pin in out_pins]
        for pwm in self.pwms:
            pwm.start(self.speed)
            pwm.ChangeFrequency(15)
        # distances
        self.distances = [0 for i in range(3)]
        # servos
        self.servo = 18
        wiringpi.wiringPiSetupGpio()
        wiringpi.pinMode(self.servo, wiringpi.GPIO.PWM_OUTPUT)
        wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
        wiringpi.pwmSetClock(192)
        self.pwm_range = 2000
        wiringpi.pwmSetRange(self.pwm_range)
        self.servo_pwm = int(self.pwm_range*0.055)
        wiringpi.pwmWrite(self.servo,self.servo_pwm) # 5.5% duty cycle

        self.in_routine = False
        self.routine = None
        self.sensor_data = {
            "left" :  0,
            "right" : 0,
            "speed" : self.speed,
            "inRoutine" : (self.in_routine == None),
        }

        self.last_right = 0
        self.last_left = 0
        self.servo_time_set = time.time()

        self.LED = 20
        GPIO.setup(  self.LED, GPIO.OUT )
        GPIO.output( self.LED, 1 )
    if data["yellow"] == "1":
        GPIO.setup(yellow, GPIO.OUT)
        GPIO.output(yellow, GPIO.HIGH)
    else:
        GPIO.setup(yellow, GPIO.OUT)
        GPIO.output(yellow, GPIO.LOW)

    if data["blue"] == "1":
        GPIO.setup(blue, GPIO.OUT)
        GPIO.output(blue, GPIO.HIGH)
    else:
        GPIO.setup(blue, GPIO.OUT)
        GPIO.output(blue, GPIO.LOW)

#-------------------------------------------
'''
# input pin
button = 4

wirePi.wiringPiSetupGpio()

wirePi.pinMode(button, 0)

wirePi.pullUpDnControl(button, wirePi.PUD_DOWN)


while True:

    if wirePi.digitalRead(button):
        print ("Button ON")
    else:
Beispiel #28
0
def setup():
    piwiring.wiringPiSetupGpio()
    piwiring.pinMode(GPIO_pos, piwiring.OUTPUT)
    piwiring.digitalWrite(GPIO_pos, piwiring.LOW)
Beispiel #29
0
import time
import wiringpi


def getServoDutyForWebIOPi(val):
    val_min = 0.0
    val_max = 1.0
    servo_min = 48
    servo_max = 90

    duty = int((servo_max - servo_min) * (val - val_min) /
               (val_max - val_min) + servo_min)
    return duty


wiringpi.wiringPiSetupGpio()  # GPIO名で番号指定
wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT)
wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)  # 周波数固定
wiringpi.pwmSetClock(375)  # 50 Hz
wiringpi.pwmWrite(18, getServoDutyForWebIOPi(0.5))

# デバッグ出力を有効に
webiopi.setDebug()

# GPIOライブラリの取得
GPIO = webiopi.GPIO

PWM1 = 25
PWM2 = 24
PWM3 = 23
PWM4 = 22
Beispiel #30
0
#!/usr/bin/env python2.7
# Python 2.7 version by Alex Eames of http://RasPi.TV
# functionally equivalent to the Gertboard buttons test
# by Gert Jan van Loo & Myra VanInwegen
# Use at your own risk - I'm pretty sure the code is harmless,
# but check it yourself.

import wiringpi
import sys
board_type = sys.argv[-1]

wiringpi.wiringPiSetupGpio()  # initialise wiringpi
for port_num in range(23, 26):
    wiringpi.pinMode(port_num, 0)  # set up ports for input
    wiringpi.pullUpDnControl(port_num, wiringpi.PUD_UP)  #set pullups


def reset_ports():  # resets the ports for a safe exit
    for i in range(23, 26):
        wiringpi.pinMode(i, 0)  # set ports to input mode
        wiringpi.pullUpDnControl(i, wiringpi.PUD_OFF)  #unset pullups


# Print  Instructions appropriate for the selected board
if board_type == "m":
    print "These are the connections for the Multiface buttons test:"
    print "GPIO 25 --- 1 in BUFFERS"
    print "GPIO 24 --- 2 in BUFFERS"
    print "GPIO 23 --- 3 in BUFFERS"
    print "Optionally, if you want the LEDs to reflect button state do the following:"
    print "jumper on BUFFER DIRECTION SETTINGS, OUT 1"
Beispiel #31
0
##wiringpi.wiringPiSetupGpio()
##wiringpi.wiringPiSetup()
##wiringpi.wiringPiSetupPhys()

# Port Setup
# wiringpi.pinMode(port_or_pin_number, X)
    # port_or_pin_number depends on Reference Setup
    # X defines Port Function
        # 0 = input, 1 = output, 2 = alternative function
        # in this case, alt function for GPIO pin 18 is hardware PWM

# Hardware PWM setups
print "0"
# Elevate Privileges
# If using BCM GPIO NUMBERS
wiringpi.wiringPiSetupGpio() # must run with root privileges!
print "0.5"
wiringpi.pinMode(18,2) # X = 2 declares alt function, pwm only works on GPIO port 18
# set PWM Mode
    # balanced (default, varies frequency with duty cycle for even pulses)
    # mark-space mode (traditional)
print "1"
wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS)
wiringpi.pwmSetRange(Range) # sets the range register for the PWM. Default is 1024.
wiringpi.pwmSetClock(Divisor) # sets divisor for the PWM clock
wiringpi.pwmWrite(18,DutyCalc) # duty cycle between 0 and 1024. 0 = off, 1024 = fully on
print "2"
Volts = 3.3*DutyCalc/Range
Sensor = 0.9*DutyCalc/Range
print("Pin 18 is set to %g Volts" %Volts)
print("Past the Op Amp, sensor voltage calculates to %g Volts" %Sensor)
Beispiel #32
0
def setup():
    piwiring.wiringPiSetupGpio()
    piwiring.pinMode(GPIO_pos, piwiring.PWM_OUTPUT)
    # piwiring.pwmSetRange(1024)
    # piwiring.pwmSetClock(1000)
    piwiring.pwmWrite(GPIO_pos, 0)
Beispiel #33
0
import wiringpi as piwiring
import time
""" Definitions """

freq = 100
pin2 = 18
min = 0
max = 1024
""" GPIO SETTINGS """
piwiring.wiringPiSetupGpio()
piwiring.pinMode(pin2, 2)
""" STARTING ROUTINE """
piwiring.pwmWrite(pin2, 0)

check = 0
while (check == 0):
    value = input("Enter value for dimmer\n range 0 - 1024: (-1 to end)\n")
    if (value == -1):
        piwiring.pwmWrite(pin2, 0)
        check = -1
    elif (value < min) or (value > max):
        print("Out of range! Acceptable values only in 1-99\n")
    else:
        print(value)
        piwiring.pwmWrite(pin2, value)
        time.sleep(1)
""" EXITING """
print("Thankyou for using!\n")
Beispiel #34
0
class ServoManual:

    # Defining class constructor
    def __init__(self):
        pass

# Use 'GPIO naming'

    wiringpi.wiringPiSetupGpio()

    # Set #18 to be a PWM output
    wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT)

    # Set the PWM mode to milliseconds stype
    wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)

    # Divide down clock
    wiringpi.pwmSetClock(192)
    wiringpi.pwmSetRange(2000)

    # Defining delay period (given in milliseconds)
    delay_period = 0.01

    # Defining angle by which the servo motor will move up or down
    # when the corresponding arrow key is pressed by the user
    angle = 10

    # Defininf defualt servo angle
    default = 0

    # Defining angle limit for the servo (determined by the case printed for the camera)
    angle_limit = 90

    # Side-note 210 is 2.1 ms
    # pulse = 213 (90 degrees to the right from the reference)
    # pulse = 53 (90 degrees to the left from the reference)
    # pulse = 133 (reference)

    # one degree of movement corresponds to 0.888 ms

    # Defining a function that writes a list to a text file.
    # This function is used as a means of providing memory to keep track of the position
    # associated with the servo motor.
    def write_to_temp_file_servo(self, value):
        # Opening/creating temporary text file if it does not exist
        try:
            with open("mem2.txt", 'w') as f:
                f.write('%d' % int(value))
        except IOError:

            # Letting the user know that an IO error has occured
            print 'Cannot open storage file for writing'
        else:

            # Closing the opened file
            f.close()

    # Defining a function used to move the servo motor up
    def servo_control_up(self):

        # Checking if text file used for memory by the program exists
        if os.path.isfile('mem2.txt'):

            try:
                # Opening storage file for reading
                fp = open("mem2.txt", 'r')

            except IOError:

                print 'Cannot open storage file for reading'

            else:

                # Obtaining current position of the servo motor
                current_val = [int(n) for n in fp.read().split()]

                # Defining the new required angle to which the servo motor
                # has to move after a key press
                required_angle = ServoManual.angle + current_val[0]

                # Preventing the servo motor from moving more than 90 degree from rest
                # since the motor can only span 180 degrees of motion
                if required_angle > ServoManual.angle_limit:
                    required_angle = ServoManual.angle_limit

    # Calculating the required pulse width corresponding to the desired
    # servo motor angle/position
                pulse_width = 133 + int(0.888 * required_angle)
                time.sleep(0.1)

                # Driving the servo motor
                wiringpi.pwmWrite(18, pulse_width)
                time.sleep(ServoManual.delay_period)

                # Closing file that was opened for reading
                fp.close()

                # Writing new servo position to temporary storage file
                self.write_to_temp_file_servo(required_angle)
        else:

            # Creating a text file with the initial/default position of the servo motor
            self.write_to_temp_file_servo(ServoManual.default)
            try:
                # Opening storage file for reading
                fp = open("mem2.txt", 'r')
            except IOError:

                print 'Cannot open storage file for reading'

            else:
                # Calculating the required pulse width corresponding to the desired
                # servo motor angle/position
                pulse_width = 133 + int(0.888 * ServoManual.angle)

                time.sleep(0.1)

                # Driving the servo motor
                wiringpi.pwmWrite(18, pulse_width)
                time.sleep(ServoManual.delay_period)

                # Closing file that was opened for reading
                fp.close()
                self.write_to_temp_file_servo(ServoManual.angle)

    # Defining a function used to move the servo motor down

    def servo_control_down(self):

        # Checking if text file used for memory by the program exists
        if os.path.isfile('mem2.txt'):

            try:
                # Opening storage file for reading
                fp = open("mem2.txt", 'r')

            except IOError:

                print 'Cannot open storage file for reading'

            else:

                # Obtaining current position of the servo motor
                current_val = [int(n) for n in fp.read().split()]

                # Defining the new required angle to which the servo motor
                # has to move after a key press
                required_angle = current_val[0] - ServoManual.angle

                # Preventing the servo motor from moving more than 90 degree from rest
                # since the motor can only span 180 degrees of motion
                if required_angle < -ServoManual.angle_limit:
                    required_angle = -ServoManual.angle_limit

    # Calculating the required pulse width corresponding to the desired
    # servo motor angle/position
                pulse_width = 133 + int(0.888 * required_angle)

                time.sleep(0.1)

                # Driving the servo motor
                wiringpi.pwmWrite(18, pulse_width)
                time.sleep(ServoManual.delay_period)

                # Closing file that was opened for reading
                fp.close()

                # Writing new servo position to temporary storage file
                self.write_to_temp_file_servo(required_angle)
        else:

            # Creating a text file with the initial/default position of the servo motor
            self.write_to_temp_file_servo(ServoManual.default)
            try:
                # Opening storage file for reading
                fp = open("mem2.txt", 'r')
            except IOError:

                print 'Cannot open storage file for reading'

            else:

                # Calculating the required pulse width corresponding to the desired
                # servo motor angle/position
                pulse_width = 133 + int(0.888 * -ServoManual.angle)

                time.sleep(0.1)

                # Driving the servo motor
                wiringpi.pwmWrite(18, pulse_width)
                time.sleep(ServoManual.delay_period)

                # Closing file that was opened for reading
                fp.close()

                # Writing new servo position to the temporary storage file
                self.write_to_temp_file_servo(-ServoManual.angle)
Beispiel #35
0
 def __init__(self):
     wiringpi.wiringPiSetupGpio()
     wiringpi.pullUpDnControl(PIN_FAN, OFF)
     wiringpi.pullUpDnControl(PIN_WIRE, OFF)
Beispiel #36
0
import wiringpi as wPi
from time import sleep

pin = 18
wPi.wiringPiSetupGpio()

wPi.pinMode(pin, 2)

try:
    for i in range(50):
        
        print(i)
        
        for j in range(0, 1024):
            wPi.pwmWrite(pin, j)
            sleep(0.0005)
            
        for j in range(0, 1024):
            wPi.pwmWrite(pin, 1024-j)
            sleep(0.0005)

except KeyboardInterrupt:
    print("killing")
    wPi.pwmWrite(pin, 0)
    wPi.pinMode(pin, 0)
Beispiel #37
0
import wiringpi as pi, time

inv_time = 1

led1_pin = 23
led2_pin = 24
sw_pin = 17

pi.wiringPiSetupGpio()
pi.pinMode( led1_pin, 1 )
pi.pinMode( led2_pin, 1 )
pi.pinMode( sw_pin, 0 )

light = 0

while ( True ):
	pi.digitalWrite( led1_pin, 0 )
	pi.digitalWrite( led2_pin, 0 )

	while ( pi.digitalRead(sw_pin) == 1 ):
		if ( light == 0 ):
			pi.digitalWrite( led1_pin, 1 )
			pi.digitalWrite( led2_pin, 0 )
			light = 1
		else:
			pi.digitalWrite( led1_pin, 0 )
			pi.digitalWrite( led2_pin, 1 )
			light = 0
		time.sleep( inv_time )

#
#==============================================================#
import wiringpi
import sys
from time import sleep
#board_type = sys.argv[-1]

button = 25
red_led = 24
yellow_led = 23
green_led = 22
led_ON  = 1
led_OFF = 0

# initialise all ports first
wiringpi.wiringPiSetupGpio()        # initialise wiringpi to use BCM_GPIO port numbers
wiringpi.pinMode(button, 0)         # set up button port for input
wiringpi.pullUpDnControl(button, wiringpi.PUD_UP)   # set button port as pullup
wiringpi.pinMode(red_led, 1)        # set up red LED port for output
wiringpi.pinMode(yellow_led, 1)     # set up yellow LED port for output    
wiringpi.pinMode(green_led, 1)      # set up green LED port for output
wiringpi.digitalWrite(red_led, led_OFF)     # make sure red led is off to start
wiringpi.digitalWrite(yellow_led, led_OFF)  # make sure yellow led is off to start
wiringpi.digitalWrite(green_led, led_OFF)   # make sure green led is off to start

def reset_ports():                          # resets the ports for a safe exit
    wiringpi.pullUpDnControl(22, wiringpi.PUD_OFF) #unset pullup on button port
    wiringpi.pinMode(button,0)              # set button port to input mode
    wiringpi.pinMode(red_led,0)             # set red led port to input mode
    wiringpi.pinMode(yellow_led,0)          # set yellow led port to input mode
    wiringpi.pinMode(green_led,0)           # set red led port to input mode
Beispiel #39
0
	def __init__(self):
		wiringpi.wiringPiSetupGpio()
		wiringpi.pullUpDnControl(PIN_FAN, OFF)
		wiringpi.pullUpDnControl(PIN_WIRE, OFF)
Beispiel #40
0
 def __init__(self):
     self.wp = wp
     wp.wiringPiSetupGpio()
Beispiel #41
0
 def setupGpio(self):
     wiringpi.wiringPiSetupGpio()
Beispiel #42
0
from math import fmod as mod
import wiringpi
from time import sleep

wiringpi.wiringPiSetupGpio(
)  # sets up to use BCM GPIO raspberry pi gpio pin numbers
pwm = 18  # one webpage says only gpio 18 will work one uses it on multiple pins (neither are 18)
i = 0

for i in range(40):
    if i == 1 or i == 2 or i == 4 or i == 6 or i == 9 or i == 14 or i == 17:
        i = i + 1
        continue
    elif i == 20 or i == 25 or i == 27 or i == 28 or i == 30 or i == 34 or i == 39:
        i = i + 1
        continue
    else:
        wiringpi.pinMode(i, 1)
        wiringpi.digitalWrite(i, 0)

wiringpi.pinMode(pwm, 2)  # set to pwm mode
i = 0

while i <= 1:
    print("Iteration: ", i, end='\r')
    i = i + 0.01
    wiringpi.pwmWrite(pwm, int(i * 1024))
    sleep(0.07)  # limit to 50Hz
    if i >= 1:
        wiringpi.pinMode(pwm, 1)
        wiringpi.digitalWrite(pwm, 0)
Beispiel #43
0
def move(a_deg=0, b_deg=0, waiting=0):
    a_deg_offset = 77
    b_deg_offset = 83

    move_A_deg = int(a_deg_offset + a_deg)
    move_B_deg = int(b_deg_offset - b_deg)
    pi.pwmWrite(servoA_pin, move_A_deg)
    pi.pwmWrite(servoB_pin, move_B_deg)
    time.sleep(waiting)
    return


#-------------------------------------------------------
# Setup
#-------------------------------------------------------
pi.wiringPiSetupGpio()

laser_pin = 23
led_pin = 10
servoA_pin = 18  # Altura
servoB_pin = 13  # Azimuth

# set pinMode
pi.pinMode(laser_pin, 1)
pi.pinMode(led_pin, 1)
pi.pinMode(servoA_pin, 2)
pi.pinMode(servoB_pin, 2)
# set pwm
pi.pwmSetMode(0)
pi.pwmSetRange(1024)
pi.pwmSetClock(375)
Beispiel #44
0
 def __init__(self, id, angle):
    time.sleep(0.01)
    self.__pin = id
    full_angle = angle
    wiringpi.wiringPiSetupGpio()
    wiringpi.pinMode(self.__pin, wiringpi.INPUT)
Beispiel #45
0
def init():
    """Setup the SPI interface for communication with the microcontroller."""
    wiringpi.wiringPiSetupGpio()  # For GPIO pin numbering
    wiringpi.wiringPiSPISetup(0, 500000)
Beispiel #46
0
 def __init__(self, id):
    time.sleep(0.01)
    wiringpi.wiringPiSetupGpio()
    self.__pin = id
    wiringpi.pinMode(self.__pin, wiringpi.OUTPUT)
Beispiel #47
0
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from time import sleep

from wiringpi import wiringPiSetupGpio, pinMode, digitalRead, digitalWrite, GPIO

wiringPiSetupGpio()

TM1637_CMD1 = 0x40  # 0x40 data command
TM1637_CMD2 = 0xc0  # 0xC0 address command
TM1637_CMD3 = 0x80  # 0x80 display control command
TM1637_DSP_ON = 0x08  # 0x08 display on
TM1637_DELAY = 0.00000001  # 10us delay between clk/dio pulses
TM1637_MSB = 0x80  # msb is the decimal point or the colon depending on your display

# 0-9, a-z, blank, dash, star
_SEGMENTS = bytearray(
    b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67'
    b'\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')


class TM1637(object):
	def setupGpio(self):
		wiringpi.wiringPiSetupGpio()
Beispiel #49
0
    config_values = {
        # Et dictionary vi kan bruke til å sette og justere forskjellige variabler, primært for Sensobs.
        #
        # key:    Navnet på variabelen
        # value:  Verdien til variabelen
        "left_line_tresh": .7,
        "right_line_tresh": .7,
        "stop_line_tresh": .7,
        "blue_tresh": .5,
        "distance_tresh": 15
    }

    autorun = True  # True: kjører roboten uten å vente på knappetrykk

    if autorun:
        wp.wiringPiSetupGpio()
    else:
        ZumoButton().wait_for_press()

    motors = Motors()
    motob = Motob(motors, commands)

    prios = {"carry_on": .1, "avoid_lines": 1, "obstacle": 3, "picture": 1}

    bbcon = BBCON(config_values, motob)

    behaviors = {
        "carry_on": CarryOn(bbcon, True, prios["carry_on"],
                            [sensobs["distnc"]]),
        "avoid_lines": AvoidLines(bbcon, True, prios["avoid_lines"],
                                  line_sensobs),
Beispiel #50
0
# Use at your own risk - I'm pretty sure the code is harmless, but you are
# responsible for checking  it yourself.
# This will not work unless you have installed py-spidev and wiringpi for Python
# as described in the README.txt file. SPI must also be enabled on your system

# This is a simplified combination of the atod.py and motor-wp.py programs.
# The potentiometer position (read by the ADC) determines
# motor direction and speed (PWM value)
# Middle value = no movement. 1023 = Max one way, 0 = Max the other way.

from __future__ import print_function
import spidev
from time import sleep
import wiringpi

wiringpi.wiringPiSetupGpio()  # Initialise wiringpi GPIO
wiringpi.pinMode(18, 2)  # Set up GPIO 18 to PWM mode
wiringpi.pinMode(17, 1)  # GPIO 17 to output
wiringpi.digitalWrite(17, 0)  # port 17 off for rotation one way
wiringpi.pwmWrite(18, 0)  # set pwm to zero initially


def get_adc(channel):  # read SPI data from MCP3002 chip
    if ((channel > 1)
            or (channel < 0)):  # Only channels 0 and 1 else return -1
        return -1
    r = spi.xfer2([1, (2 + channel) << 6,
                   0])  # these two lines explained at end
    ret = ((r[1] & 31) << 6) + (r[2] >> 2)
    return ret
Beispiel #51
0
def setup():
    # Initializing buttons
    w.wiringPiSetupGpio()
    w.pinMode(btnLeft,0)
    w.pinMode(btnRight,0)
Beispiel #52
0
 def __init__(self):
     wp.wiringPiSetupGpio()
     wp.pinMode(22, 0)
     wp.pullUpDnControl(22, 2)
from __future__ import print_function       
from time import sleep

# reload spi drivers to prevent spi failures
import subprocess
unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE)
start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE)
sleep(3)

import spidev                         
import wiringpi
import sys
board_type = sys.argv[-1]

wiringpi.wiringPiSetupGpio()                # Initialise wiringpi GPIO
wiringpi.pinMode(18,2)                      # Set up GPIO 18 to PWM mode
wiringpi.pinMode(17,1)                      # GPIO 17 to output
wiringpi.digitalWrite(17, 0)                # port 17 off for rotation one way
wiringpi.pwmWrite(18,0)                     # set pwm to zero initially

def get_adc(channel):                     # read SPI data from MCP3002 chip
    if ((channel > 1) or (channel < 0)):  # Only channels 0 and 1 else return -1
        return -1
    r = spi.xfer2([1,(2+channel)<<6,0])   # these two lines explained at end
    ret = ((r[1]&31) << 6) + (r[2] >> 2)
    return ret 

def reset_ports():                          # resets the ports for a safe exit
    wiringpi.pwmWrite(18,0)                 # set pwm to zero
    wiringpi.digitalWrite(18, 0)            # ports 17 & 18 off
Beispiel #54
0
class CloneThread(QThread):
    signal = pyqtSignal('PyQt_PyObject')
    wiringpi.wiringPiSetupGpio()
    def __init__(self, interval):
        QThread.__init__(self)
        self.interval = interval
         
    # run method gets called when we start the thread
    def run(self):
        
        while True:
            data = 0
            
            # reset the counter
            wiringpi.digitalWrite(reset, 0)
            wiringpi.delayMicroseconds(1)
            # wiringpi.delayMicroseconds(1)
            wiringpi.digitalWrite(reset, 1)
            # print(self.interval)
            
            #wiringpi.delay(self.interval-2) # Delay for interval ms
            time.sleep(((self.interval)/1000))
            #time.sleep(0.99838)
            
            ## store the count value into internal storage register
            #wiringpi.digitalWrite(rclk, 1)
            ##wiringpi.delayMicroseconds(1)
            #wiringpi.digitalWrite(rclk, 0)

    
            wiringpi.digitalWrite(byteSelect[0], 0) # select the first byte
            #data1 = wiringpi.digitalReadByte() # read the first 8 bits
            #data5 = wiringpi.digitalRead(8) # read the first 8 bits
            data1 = self.read(0) # read first counter
            data5 = self.read(1) # read second counter
            wiringpi.digitalWrite(byteSelect[0], 1)
            
            wiringpi.digitalWrite(byteSelect[1], 0) # select the second byte
            #data2 = wiringpi.digitalReadByte()# read data
            #data6 = wiringpi.digitalReadByte2() #
            data2 = self.read(0) # read first counter
            data6 = self.read(1) # read second counter
            wiringpi.digitalWrite(byteSelect[1], 1)
            
            wiringpi.digitalWrite(byteSelect[2], 0) # select the third byte
            #data3 = wiringpi.digitalReadByte() # read data
            #data7 = wiringpi.digitalReadByte2() # 
            data3 = self.read(0) # read first counter
            data7 = self.read(1) # read second counter
            wiringpi.digitalWrite(byteSelect[2], 1)
            
            wiringpi.digitalWrite(byteSelect[3], 0) # select the forth byte
            #data4 = wiringpi.digitalReadByte() # read data
            #data8 = wiringpi.digitalReadByte2() # 
            data4 = self.read(0) # read first counter
            data8 = self.read(1) # read second counter
            wiringpi.digitalWrite(byteSelect[3], 1)
            
            
            data_cnt1 = (data4<<24) | (data3<<16) | (data2<<8) | (data1)
            data_cnt2 = (data8<<24) | (data7<<16) | (data6<<8) | (data5)
            countms_cnt1 = str(data_cnt1*(1000/self.interval))
            countms_cnt2 = str(data_cnt2*(1000/self.interval))
            
            #print("data = ", countms_cnt1, data_cnt1, data4, data3, data2, data1, countms_cnt2, data_cnt2, data8, data7, data6, data5)
            
            #count = str(bin(data))
            self.signal.emit([data_cnt1, countms_cnt1, data_cnt2, countms_cnt2, QDateTime.currentMSecsSinceEpoch()])
            #gui.liste_sayim.append(str(data*(1000/self.scan_interval)))
        
    def read(self, byte):
        self.veri = 0
        for i in reversed(range(byte*8, (byte*8)+8)):
            self.x = wiringpi.digitalRead(wiringpi.wpiPinToGpio(i))
            self.veri = (self.veri << 1) | self.x

        return self.veri
Beispiel #55
0
# GPIOを制御するライブラリ
import wiringpi
# タイマーのライブラリ
import time
# 引数取得
import sys

# 74HC5411(7セグメントドライバー)に接続しているGPIO端子番号を指定
d0_pin = 18
d1_pin = 23
d2_pin = 24
d3_pin = 25

# 各端子を出力モードにする
wiringpi.wiringPiSetupGpio()
wiringpi.pinMode( d0_pin, 1 )
wiringpi.pinMode( d1_pin, 1 )
wiringpi.pinMode( d2_pin, 1 )
wiringpi.pinMode( d3_pin, 1 )

# 初期化 すべて0にする
wiringpi.digitalWrite( d0_pin, 0 )
wiringpi.digitalWrite( d1_pin, 0 )
wiringpi.digitalWrite( d2_pin, 0 )
wiringpi.digitalWrite( d3_pin, 0 )

# 引数取得
param = sys.argv
set_number = int(param[1])

if( set_number >= 0 and set_number < 10):
Beispiel #56
0
def init():
    logging.debug("GPIOManager.__init__")
    wiringpi.wiringPiSetupGpio()
Beispiel #57
0
def temp_init():  # 初期設定
    GPIO.setmode(GPIO.BCM)
    pi.wiringPiSetupGpio()  # GPIO名で番号を指定する
    pi.pinMode(temp_sensor, pi.INPUT)  # 温湿度センサのデータを入力として扱う
Beispiel #58
0
import wiringpi #ctrl GPIO
import time
import sys

motor_pin_1 = 23
motor_pin_2 = 24

wiringpi.wiringPiSetupGpio() #initilize GPIO control

print("stop 5sec")
wiringpi.pinMode( motor_pin_1, 0 )
wiringpi.pinMode( motor_pin_2, 0 )
print("right 5sec")
wiringpi.digitalWrite( motor_pin_1, 1 )
wiringpi.digitalWrite( motor_pin_2, 0 )
time.sleep(5)
print("stop 5sec")
wiringpi.digitalWrite( motor_pin_1, 1 )
wiringpi.digitalWrite( motor_pin_2, 1 )
time.sleep(5)
print("left 5sec")
wiringpi.digitalWrite( motor_pin_1, 0 )
wiringpi.digitalWrite( motor_pin_2, 1 )
time.sleep(5)
print("stop 5sec")
wiringpi.digitalWrite( motor_pin_1, 0 )
wiringpi.digitalWrite( motor_pin_2, 0 )
print("Done")
Beispiel #59
0
#!/usr/bin/env python2.7
# Python 2.7 version by Alex Eames of http://RasPi.TV 
# functionally equivalent to the Gertboard butled test 
# by Gert Jan van Loo & Myra VanInwegen
# Use at your own risk - I'm pretty sure the code is harmless, 
# but check it yourself.
import wiringpi

wiringpi.wiringPiSetupGpio()                # initialise wiringpi
wiringpi.pinMode(22, 0)                     # set up ports for input
wiringpi.pinMode(24, 0)
wiringpi.pullUpDnControl(23, wiringpi.PUD_UP)   # set port 23 pull-up 

def reset_ports():                      # resets the ports for a safe exit
    wiringpi.pinMode(22,0)              # set ports to input mode
    wiringpi.pinMode(24,0)

print "These are the connections you must make on the Gertboard for this test:"
print "GP23 in J2 --- B3 in J3"
print "GP22 in J2 --- B6 in J3"
print "U3-out-B3 pin 1 --- BUF6 in top header"
print "jumper on U4-in-B6"
raw_input("When ready hit enter.\n")

button_press = 0                          # set intial values for variables
previous_status = ''

try:
    while button_press < 20:  # read inputs constantly until 19 changes are made
        status_list = [wiringpi.digitalRead(23), wiringpi.digitalRead(22)]
        for i in range(0,2):
Beispiel #60
0
#!/usr/bin/env python3

import time
import wiringpi as GPIO
 
trig = 22
echo = 27
sound_speed = 34000
 
GPIO.wiringPiSetupGpio()
 
GPIO.pinMode(trig, GPIO.OUTPUT)
GPIO.pinMode(echo, GPIO.INPUT)
GPIO.digitalWrite(trig, GPIO.LOW)
time.sleep(1)
 
def measure_distance():
	GPIO.digitalWrite(trig, GPIO.HIGH)
	time.sleep(0.000011) #11usec
	GPIO.digitalWrite(trig, GPIO.LOW)
	while (GPIO.digitalRead(echo) == GPIO.LOW):
		time_start = time.time()
	while ( GPIO.digitalRead( echo ) == 1 ):
		time_end = time.time()
	return ((time_end - time_start) * sound_speed) / 2
 
while True:
	distance = measure_distance()
	print (round(distance, 1), "cm")
	time.sleep(0.2)