def loop(start_pwm, stop_pwm, step, printchar): for x in range(start_pwm, stop_pwm, step): wiringpi.pwmWrite(18, x) # if x is an exact multiple of 19, i.e. x/19 has remainder 0 if x % (19) == 0: display(printchar) # print the + or - character sleep(rest)
def on_message(aioClient, feed_id, msg): payload = msg.partition(MESSAGE_DELIM) if type(payload[2]) is '': print '%s, missing timestamp in payload: %s' % (feed_id, msg) return None try: global last_ts value = float(payload[0]) ts = float(payload[2]) if ((feed_id == aio_switch_feedid) and (ts > last_ts) and (feed_id == aio_switch_feedid) ): if(value == 1): print "%s: switch is on, turn it off" % feed_id rotate_arm(175) time.sleep(TICK_S) rotate_arm(ROTATE_NEUTRAL) time.sleep(TICK_S) wiringpi.pwmWrite(PWM_PIN, 0) last_ts = time.time() else: print "%s switch is off" % feed_id last_ts = time.time() elif ( (feed_id == aio_rotate_feedid) and (ts > last_ts)): rotate_arm(value) time.sleep(TICK_S) wiringpi.pwmWrite(PWM_PIN, 0) last_ts = time.time() except ValueError: print "%s: bad switch message: %s" % (feed_id, msg)
def Update(self): if (time.time() - self.brightStart > 5): backLight = 500 if (time.localtime().tm_hour > 22 or time.localtime().tm_hour < 5): backLight = 1 wiringpi.pwmWrite(18, backLight) pygame.mouse.set_visible(False)
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
def __init__(self, dev=(0,0),speed=4000000, brightness=256, contrast=CONTRAST): self.spi = spidev.SpiDev() self.speed = speed self.dev = dev self.spi.open(self.dev[0],self.dev[1]) self.spi.max_speed_hz=self.speed # Set pin directions. self.dc = DC self.rst = RST wiringpi.wiringPiSetup() for pin in [self.dc, self.rst]: wiringpi.pinMode(pin, 1) self.contrast=contrast self.brightness=brightness # Toggle RST low to reset. wiringpi.digitalWrite(self.rst, OFF) time.sleep(0.100) wiringpi.digitalWrite(self.rst, ON) # Extended mode, bias, vop, basic mode, non-inverted display. wiringpi.digitalWrite(self.dc, OFF) self.spi.writebytes([0x21, 0x14, self.contrast, 0x20, 0x0c]) # cls() self.ledpin = LED if self.ledpin == 1: wiringpi.pinMode(self.ledpin, 2) wiringpi.pwmWrite(self.ledpin, self.brightness) else: wiringpi.pinMode(self.ledpin, 1) wiringpi.digitalWrite(self.ledpin, ON)
def updateLights(): global tlConfig STEP_INTERVAL = 1 / PWM_FREQ # how often STEP_BRIGHTNESS = 1 / (tlConfig.lightsFadeTime * PWM_FREQ) # how much currentBrightness = 1.00 while not shutdownFlag: changed = False if abs(currentBrightness - targetBrightness) > STEP_BRIGHTNESS / 2: if currentBrightness < targetBrightness: currentBrightness += STEP_BRIGHTNESS changed = True elif currentBrightness > targetBrightness: currentBrightness -= STEP_BRIGHTNESS changed = True if changed: if config.get('lights', 'pwm_mode') == 'HW': wiringpi.pwmWrite(TL_PWM, math.trunc(1024 * (1.00 - currentBrightness))) elif config.get('lights', 'pwm_mode') == 'SW': wiringpi.softPwmWrite(TL_PWM, math.trunc(100 * (1.00 - currentBrightness))) rootLogger.debug("{0:.2f} <- {1} <- {2:.2f}".format(currentBrightness, lastEvent, targetBrightness)) time.sleep(STEP_INTERVAL)
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)
def led(self, led_value): if self.ledpin == 1: wiringpi.pwmWrite(self.ledpin,led_value) else: if led_value == 0: wiringpi.digitalWrite(self.ledpin, OFF) else: wiringpi.digitalWrite(self.ledpin, ON)
def shutoffRobot(): wp.pwmWrite(PWM_L, OFF) wp.pwmWrite(PWM_R, OFF) wp.digitalWrite(INPUT_2_LEFT, OFF) wp.digitalWrite(INPUT_1_LEFT, OFF) wp.digitalWrite(INPUT_1_RIGHT, OFF) wp.digitalWrite(INPUT_2_RIGHT, OFF) print 'turn off'
def shutoffRobot(): wp.pwmWrite(PWM_L, 0) wp.pwmWrite(PWM_R, 0) wp.digitalWrite(INPUT_2_LEFT_MOTOR, 0) wp.digitalWrite(INPUT_1_LEFT_MOTOR, 0) wp.digitalWrite(INPUT_1_RIGHT_MOTOR, 0) wp.digitalWrite(INPUT_2_RIGHT_MOTOR, 0) print 'turn off'
def __del__(self): wp.pwmWrite(self.pwm, PWM_MIN) wp.digitalWrite(self.outA, LOW) wp.digitalWrite(self.outB, LOW) wp.pinMode(self.pwm, INPUT_MODE) wp.pinMode(self.outA, INPUT_MODE) wp.pinMode(self.outB, INPUT_MODE)
def function PwmControl(self,turnForward): if turnForward: for i in range(255): wiringpi.pwmWrite(MotorEnable,i) sleep(.001) else: for i in range(255,0,-1): wiringpi.pwmWrite(MotorEnable,i) sleep(.001)
def on_connect(aioClient): global last_ts rotate_arm(ROTATE_NEUTRAL) time.sleep(TICK_S) wiringpi.pwmWrite(PWM_PIN, 0) # Once connected, hook into i/o events aioClient.subscribe(aio_switch_feedid) aioClient.subscribe(aio_rotate_feedid) print 'subscribing to feeds: %s, %s' % (aio_switch_feedid, aio_rotate_feedid) last_ts = time.time()
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 setSpeed(self, speed): # Constrain if speed > PWM_MAX: speed = PWM_MAX elif speed < PWM_MIN: speed = PWM_MIN wp.pwmWrite(self.pwm, speed) self.speed = speed
def setup(): # Set pin directions. wiringpi.wiringPiSetup() for pin in [DC, RST]: wiringpi.pinMode(pin, ON) wiringpi.pinMode(LED,2) wiringpi.pwmWrite(LED,128) spi.open(0,0) spi.max_speed_hz=5000000
def sendToRPi(self): for pn in range(0, 6): pin = self.motorPins[pn] val = self.pinValues[pn] if not Globals.globSimulate: wiringpi.digitalWrite(pin, 1 if val else 0) if not Globals.globSimulate: wiringpi.pwmWrite(18, self.pwmValue) if self.debug: print "Sent to RPi: pinValues(%s) pwmValue(%s)" % (self.pinValues, self.pwmValue)
def rotate_arm(angle=ROTATE_NEUTRAL): global rotation angle = float(angle) if (angle > 180): angle = 180 elif (angle < 0): angle = 0 target = angle_to_duty_cycle(angle) rotation = target wiringpi.pwmWrite(PWM_PIN, rotation) print "rotate to target angle: %s, duty-cycle: %s/1024" % (angle, rotation)
def setSpeed(self, speed): if speed < 0: speed = -speed dir_value = 1 else: dir_value = 0 if speed > MAX_SPEED: speed = MAX_SPEED io_init() wiringpi.digitalWrite(self.dir_pin, dir_value) wiringpi.pwmWrite(self.pwm_pin, speed)
def __init__(self, pins): threading.Thread.__init__(self) Observable.__init__(self) if len(pins) != 6: raise "MotorDriver needs 6 pins" self.motorPins = pins if not Globals.globSimulate: for pn in range(0, 6): pin = self.motorPins[pn] wiringpi.pinMode(pin, GPIO_OUTPUT) wiringpi.pinMode(18, GPIO_PWM) wiringpi.pwmWrite(18, self.pwmValue)
def set_brightness(self, led_value): #''' #Set the backlight LED brightness. Valid values are 0 <-> 1023 #When not connected to the PWM port, any value > 0 will turn the LED on full #''' assert(0 <= led_value <= 1023) if self.ledpin == 1: wiringpi.pwmWrite(self.ledpin, led_value) else: if led_value == 0: wiringpi.digitalWrite(self.ledpin, OFF) else: wiringpi.digitalWrite(self.ledpin, ON) self.brightness = led_value
def update_physical_state(self): """Send the right values to the GPIO pins.""" # Do some note taking self.update_state_histories() if self._not_initialized: logger.info('initializing state, should only happen once or so') self.initialize_state() if not self.same_physical_state(): logger.info('State: L {} R {} DIR {}'.format(self.left_motor, self.right_motor, self.steering_servo)) # If we are on the rPi, make the physical state changes if self.use_motors: self.setSpeed(self.m1conf.get('pwm_pin'), self.m1conf.get('dir_pin'), self.left_motor) self.setSpeed(self.m2conf.get('pwm_pin'), self.m2conf.get('dir_pin'), self.right_motor) if self.use_servo: logger.info('Turning Servo DIR {} PIN {}'.format(self.steering_servo, self.servo_gpio_pin)) wiringpi.pwmWrite(self.servo_gpio_pin, self.steering_servo) self.previous_physical_state = self.health_check().get('health_check', {})
def setup_gpio(): wiringpi.wiringPiSetup() # Set pin directions. # outputs : for pin in [DIN, SCLK, DC, RST, SCE]: wiringpi.pinMode(pin, OUT) # inputs : for pin in [UP, RIGHT, DOWN, LEFT, SELECT]: wiringpi.pinMode(pin, IN) # enable pull downs for the switches wiringpi.pullUpDnControl(UP, wiringpi.PUD_DOWN) wiringpi.pullUpDnControl(RIGHT, wiringpi.PUD_DOWN) wiringpi.pullUpDnControl(DOWN, wiringpi.PUD_DOWN) wiringpi.pullUpDnControl(LEFT, wiringpi.PUD_DOWN) wiringpi.pullUpDnControl(SELECT, wiringpi.PUD_DOWN) wiringpi.pinMode(LED,2) # pwm mode wiringpi.pwmWrite(LED,128) # mid-level
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.')
def set_servo_position(pos): """ Turn servo on specified angle in degrees Params: pos: angle to turn servo, in degrees """ move = int(40 + math.floor(pos * (200 - 40) / 180)) print("pos: {}".format(pos)) print("move: {}".format(move)) if move: print("move: ", move) try: wiringpi.pwmWrite(SERVO_PIN, move) # time.sleep(0.5) # print("wiringpi.pwmWrite(18,{})".format(move)) except: # clean up wiringpi.pwmWrite(18, 0) print("Exception")
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.')
def safe_exit(): """Ensures exit is handled cleanly. Shuts down hardware, quits pygame, and raises SystemExit. Args: None. Returns: None. Raises: SystemExit. """ if __debug__: print("Quiting WiringPi.") wiringpi.pwmWrite(18, 0) # set pwm to zero wiringpi.digitalWrite(18, 0) # port 18 off wiringpi.digitalWrite(17, 0) # port 17 off wiringpi.pinMode(17, 0) # port 17 back to input mode wiringpi.pinMode(18, 0) # port 18 back to input mode if __debug__: print("Quiting Pygame.") pygame.quit() if __debug__: print("Raising SystemExit.") raise SystemExit
def set_left_speed(self, dc): wp.pwmWrite(18, dc)
def set_right_speed(self, dc): wp.pwmWrite(19, dc)
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)
def initOS(scrntyp, configdir): global bootime, osversion, hwinfo, screentype, hostname, screenwidth, screenheight, portrait, dispratioW, dispratioH, DimType, dimpin screentype = scrntyp os.nice(-10) # hostname = socket.gethostname() # get platform info with open('/proc/stat', 'r') as f: for line in f: if line.startswith('btime'): bootime = int(line.split()[1]) osversion = platform.platform() with open('/proc/device-tree/model') as f: hwinfo = f.read() screendefs = {} with open('screendefinitions') as f: defs = f.read().splitlines() for l in defs: screenitem = l.split('|') screendefs[screenitem[0]] = screenitem[1:] try: # allow overwrite of system values with open(configdir + '/screendefinitions') as f: defs = f.read().splitlines() for l in defs: screenitem = l.split('|') screendefs[screenitem[0]] = screenitem[1:] except: pass if screentype not in screendefs: print('Screen type undefined') raise ValueError if screendefs[screentype][1] != 'XWin': if 'DISPLAY' in os.environ: del os.environ['DISPLAY'] os.environ['SDL_FBDEV'] = screendefs[screentype][0] os.environ['SDL_VIDEODRIVER'] = screendefs[screentype][1] DimType = screendefs[screentype][2] if DimType in ('PWM18', 'PWM19'): if DimType == 'PWM18': dimpin = 18 elif DimType == 'PWM19': dimpin = 19 try: # if this system has the newer screen control then turn off the SMTPE control so PWM works with open('/sys/class/backlight/soc:backlight/brightness', 'w') as f: f.write('0') except: pass wiringpi.wiringPiSetupGpio() wiringpi.pinMode(dimpin, 2) wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS) # default balanced mode makes screen dark at about 853/1024 wiringpi.pwmWrite(dimpin, 1024) # print('Screen: {} Device: {} Driver: {} Dim: {}'.format(screentype, os.environ['SDL_FBDEV'], # os.environ['SDL_VIDEODRIVER'], DimType)) pygame.display.init() screenwidth, screenheight = (pygame.display.Info().current_w, pygame.display.Info().current_h) if screenwidth > screenheight: portrait = False dispratioW = float(screenwidth) / float(basewidth) dispratioH = float(screenheight) / float(baseheight) GoBright(100)
def servo_control(self): # Checking if text file used for memory by the program exists if os.path.isfile('mem2.txt'): print "Inside if (mem2.txt) already exists" 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()] # Calculating the angle of deviation of the brightest object from the center of the frame # in terms of the y-axis # Vertical field of view for pi camera: 41.41 degrees +/- 0.11 degrees # Converting pixel value which is the distance from the center pixel (150) # Total number of pixels = 400 x 300 # Center = 150 angle = int((self.y_raw - 150) * 41.41 / 300) # Defining the new angle/position for the servo motor required_angle = angle + current_val[0] # Preventing the servo from turning more than 90 degrees from its rest position of 0 degrees # since the servo motor in use only has 180 degrees of freedom if required_angle > 90: required_angle = 90 elif required_angle < -90: required_angle = -90 # 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(Servo.delay_period) # Helpful debug statements # print "Angle:",angle # print "Requried angle:",required_angle # 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(Servo.default) try: # Opening storage file for reading fp = open("mem2.txt", 'r') except IOError: print 'Cannot open storage file for reading' else: # Calculating the angle of deviation of the brightest object from the center of the frame # in terms of the y-axis # Vertical field of view for pi camera: 41.4 degrees # Converting pixel value which is the distance from the center pixel (150) # Total number of pixels = 400 x 300 # Center = 300 angle = int((self.y_raw - 150) * 41.41 / 300) # Preventing the servo from turning more than 90 degrees from its rest position of 0 degrees # since the servo motor in use only has 180 degrees of freedom if angle > 90: angle = 90 elif angle < -90: angle = -90 # Calculating the required pulse width corresponding to the desired # servo motor angle/position pulse_width = 133 + int(0.888 * angle) time.sleep(0.1) # Driving the servo motor wiringpi.pwmWrite(18, pulse_width) time.sleep(Servo.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(angle)
# -*- coding: utf-8 -*- import wiringpi import time import sys servo_pin = 12 # get degree param = sys.argv set_degree = int(param[1]) print(set_degree) wiringpi.wiringPiSetupGpio() # input / output wiringpi.pinMode( servo_pin, 2 ) wiringpi.pwmSetMode(0) wiringpi.pwmSetRange(1024) wiringpi.pwmSetClock(375) wiringpi.pwmWrite( servo_pin, set_degree ) if ( set_degree >= -90 ): move_deg = int( 81 + 41 / 90 * set_degree ) wiringpi.pwmWrite( servo_pin, move_deg )
# -*- coding: utf-8 -*- from time import sleep import wiringpi pinSrv = 12 wiringpi.wiringPiSetupGpio() wiringpi.pinMode(pinSrv, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) wiringpi.pwmSetClock(375) wiringpi.pwmWrite(pinSrv, 50) #S35 STD rightcyc = 70 leftcyc = 80 stop = 75 list = [rightcyc, stop, leftcyc, stop] try: while True: for duty in list: wiringpi.pwmWrite(pinSrv, duty) if duty == stop: sleep(1) else: sleep(3) except KeyboardInterrupt: pass
import wiringpi import time SERVO_PIN = 18 wiringpi.wiringPiSetupGpio() wiringpi.pinMode(SERVO_PIN, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) wiringpi.pwmSetClock(192) wiringpi.pwmSetRange(1000) angle = 50 wiringpi.pwmWrite(SERVO_PIN, angle) time.sleep(1) angle = 140 wiringpi.pwmWrite(SERVO_PIN, angle)
def unlock(): wiringpi.pwmWrite(lockpin, 135)
print('Setting up motor pin') wi.pinMode(args.motor_pin, wi.GPIO.PWM_OUTPUT) # set the PWM mode to milliseconds stype wi.pwmSetMode(wi.GPIO.PWM_MODE_MS) print('setting clock, range to 192, 2000') wi.pwmSetClock(192) wi.pwmSetRange(2000) scale = scale_to_motor(servo_min, servo_max, args.motor_min, args.motor_max) for i in range(0, args.cycles): # Indicate the motor should flow forward wi.digitalWrite(dir_pin, 1) for x in range(servo_min, servo_max, servo_step): print('To X: ', x) wi.pwmWrite(args.servo_pin, x) wi.pwmWrite(args.motor_pin, scale(x)) time.sleep(.1) # Indicate the motor should flow backward wi.digitalWrite(dir_pin, 0) for x in range(servo_max, servo_min, servo_step): print('To X: ', x) wi.pwmWrite(args.servo_pin, x) wi.pwmWrite(args.motor_pin, scale(x)) time.sleep(.1)
def quit(self): wiringpi.pwmWrite(self.pin, 0) # no pluse
def controlBrightness(): wiringpi.pwmWrite(led, comboStates['brightness']) time.sleep(.2)
def change(self, speed): pulse = self.calcPulse(speed) wiringpi.pwmWrite(self.pin, pulse)
wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pinMode(13, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # divide down clock for servos wiringpi.pwmSetClock(192) wiringpi.pwmSetRange(2000) #handle servos and settings changes startMillis = lastUpdate = int(round(time.time() * 1000)) while True: time.sleep(MAIN_LOOP_DELAY) if varDict['mode'] == 0: millis = int(round(time.time() * 1000)) if millis - lastUpdate > 500: lastUpdate = millis wiringpi.pwmWrite(18, varDict['x']) wiringpi.pwmWrite(13, varDict['y']) elif varDict['mode'] == 1: millis = int(round(time.time() * 1000)) x = pnoise1((startMillis - millis) / PERLIN_SPEED + 1234.56789, octaves=4) y = pnoise1((startMillis - millis) / PERLIN_SPEED, octaves=4) wiringpi.pwmWrite(18, int((x + 1) / 2 * 200 + 50)) wiringpi.pwmWrite(13, int((y + 1) / 2 * 200 + 50)) elif varDict['mode'] == 2: millis = int(round(time.time() * 1000)) if millis - lastUpdate > 500: lastUpdate = millis x = random.randrange(50, 250) y = random.randrange(50, 250) wiringpi.pwmWrite(18, int(x))
def moveServo(self, lower, upper, step): for pulse in range(lower, upper, step): wiringpi.pwmWrite(18, pulse) time.sleep(self.delay_period)
SPIMISO = 9 SPICS = 8 # SPI通信用の入出力を定義 GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICS, GPIO.OUT) wiringpi.wiringPiSetupGpio() # GPIO名で番号を指定する wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT) # PWM出力を指定 wiringpi.pinMode(19, wiringpi.GPIO.PWM_OUTPUT) # PWM出力を指定 wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # 周波数を固定するための設定 wiringpi.pwmSetClock(375) # 50 Hz。ここには 18750/(周波数) の計算値に近い整数を入れる # PWMのピン番号18とデフォルトのパルス幅をデューティ100%を1024として指定。 # ここでは6.75%に対応する69を指定 wiringpi.pwmWrite(18, 69) wiringpi.pwmWrite(19, 69) adc_pin0 = 0 adc_pin1 = 1 try: while True: inputVal0 = readadc(adc_pin0, SPICLK, SPIMOSI, SPIMISO, SPICS) duty0 = servo_duty_hwpwm(inputVal0) wiringpi.pwmWrite(18, duty0) inputVal1 = readadc(adc_pin1, SPICLK, SPIMOSI, SPIMISO, SPICS) duty1 = servo_duty_hwpwm(inputVal1) wiringpi.pwmWrite(19, duty1) sleep(0.2)
def down_slow(self): '''Moves the hook down slowly.''' wp.digitalWrite(DIR_PIN, 0) wp.pwmWrite(PWM_PIN, 1023)
Motor2PWM = 23 # gpio pin 33 = wiringpi no. 23 (BCM 13) Motor2BIN1 = 21 # gpio pin 29 = wiringpi no. 21 (BCM 5) Motor2BIN2 = 22 # gpio pin 31 = wiringpi no. 22 (BCM 6) # Initialize PWM output wiringpi.wiringPiSetup() wiringpi.pinMode(Motor1PWM, 2) # PWM mode wiringpi.pinMode(Motor1AIN1, 1) #Digital out mode wiringpi.pinMode(Motor1AIN2, 1) #Digital out mode wiringpi.pinMode(MotorStandby, 1) #Ditial out mode wiringpi.pinMode(Motor2PWM, 2) # PWM mode wiringpi.pinMode(Motor2BIN1, 1) #Digital out mode wiringpi.pinMode(Motor2BIN2, 1) #Digital out mode wiringpi.pwmWrite(Motor1PWM, 0) # OFF wiringpi.pwmWrite(Motor2PWM, 0) # OFF wiringpi.digitalWrite(Motor1AIN1, 1) #forward mode wiringpi.digitalWrite(Motor1AIN2, 0) #forward mode wiringpi.digitalWrite(Motor2BIN1, 1) wiringpi.digitalWrite(Motor2BIN2, 0) wiringpi.digitalWrite(MotorStandby, 1) #enabled # Initialise SPI stuff spi = spidev.SpiDev() spi.open(0, 0) #SPI bus 0, device 0 spi.max_speed_hz = 1000000 #max speed of 1MHz # Set Motor Speed def motorspeed(speed1, speed2):
def stop(self): '''Stops the hook dead.''' wp.digitalWrite(DIR_PIN, 0) wp.pwmWrite(PWM_PIN, 0)
import wiringpi as wpi pin = 18 wpi.wiringPiSetupGpio() wpi.pinMode(pin, wpi.OUTPUT) wpi.pwmSetClock(1920) wpi.pwmSetRange(1000) while True: for i in range(0, 1001): wpi.pwmWrite(pin, i) wpi.delay(1) for i in range(1000, -1, -1): wpi.pwmWrite(pin, i) wpi.delay(1)
PWMは、以下の式で成り立つ [PWM周波数] = 19.2MHz / [Clock] / [Range] [Duty比] = [Duty] / [Range] wiringpiでは、[Range] = 1024で固定し、[Clock]と[Duty] の2つのパラメータでPWMを制御する [Range] = 1024 [PWM周波数] = 18750 / [Clock] [Duty比] = [Duty] / 1024 """ range = 1024 duty_ratio = pulse / interval hz = 1 / (interval * 0.001) clock = int(18750 / hz) duty = int(duty_ratio * range) print("pin = ", pwm_pin, " interval[ms] = ", interval, " pulse[ms] = ", pulse) print("clock = ", clock, " duty=", duty, " duty_ratio=", duty_ratio) # 初期設定 wiringpi.wiringPiSetupGpio() wiringpi.pinMode(pwm_pin, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # ClockとDutyを設定してPWMを生成する wiringpi.pwmSetClock(clock) wiringpi.pwmWrite(pwm_pin, duty)
import wiringpi import time import sys 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) if (set_degree <= 90 and set_degree >= -90): move_deg = int(81 + 41 / 90 * set_degree) wiringpi.pwmWrite(servo_pin, move_deg)
def GoDimPWM(level): # This version of hw uses the real hw pwm for screen dimming - much better appearance wiringpi.pwmWrite(dimpin, int((level * 1024) // 100))
def up_slow(self): '''Moves the hook up slowly.''' wp.digitalWrite(DIR_PIN, 1) wp.pwmWrite(PWM_PIN, 1024)
#Adam Corbin 7/31/2017 #This module is used to communicate to any device over bluetooth. #For testing purposes using an Android app here: #Your android device needs to be paired with the RPi before you can send commands fadingLED = False blinking = False valueOn = 0 valueOff = 1024 wiringpi.wiringPiSetup() ledPin = 1 #This pin maps to RasPi3 GPIO 18 which is the PWM pin #We need to ensure that the pin mode has been set to PWM so we can fade the led wiringpi.pinMode(ledPin, wiringpi.PWM_OUTPUT) wiringpi.pwmWrite(ledPin, valueOn) server_sock = BluetoothSocket(RFCOMM) server_sock.bind(("", PORT_ANY)) server_sock.listen(1) port = server_sock.getsockname()[1] uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" #This is the UUID that needs to map the the Android SerialPortService ID #This sets up the bluetooh module what to look for advertise_service( server_sock, "PiServer", service_id=uuid, service_classes=[uuid, SERIAL_PORT_CLASS],
import time import wiringpi servoPin = 21 wiringpi.wiringPiSetupGpio() wiringpi.pinMode(servoPin, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) wiringpi.pwmSetClock(192) wiringpi.pwmSetRange(2000) delay_period = 0.01 while True: for pulse in range(50,250,1): wiringpi.pwmWrite(servoPin, pulse) time.sleep(delay_period) for pulse in range(250, 50, -1): wiringpi.pwmWrite(servoPin, pulse) time.sleep(delay_period)
def callback(data): wp.pwmWrite(ENA, 120 + data) wp.pwmWrite(ENB, 120 - data)
def calcNewDC(dc): # Calculate duty cycle on correct scale from percentage scale return int(50 + 0.35 * dc) try: # Setup functions gpioSetup() fileInitialization() # Client name clientName = "RPILamp" # Server IP serverAddress = "localhost" # Client instantiation mqttClient = mqtt.Client(clientName) mqttClient.on_connect = connectionStatus mqttClient.on_message = messageDecoder mqttClient.connect(serverAddress) # Monitoring for the Terminal mqttClient.loop_forever() except KeyboardInterrupt: mqttClient.disconnect() finally: wiringpi.pwmWrite(1, 0) f.close()
# Look for faces in the image using the loaded cascade file faces = faceCascade.detectMultiScale(gray, 1.2, 5) if len(faces) > 0: for (x, y, w, h) in faces: # Create rectangle around faces cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 0), 2) # Create the resizeable window cv2.namedWindow('Kitty', cv2.WINDOW_NORMAL) # Display the image cv2.imshow('Kitty', image) delay_period = 0.01 for pulse in range(50, 250, 1): wiringpi.pwmWrite(18, pulse) time.sleep(delay_period) for pulse in range(250, 50, -1): wiringpi.pwmWrite(18, pulse) time.sleep(delay_period) sleep(30) #close window and delete picture sleep(5) GPIO.cleanup()
elif monitorBtn.is_pressed: toggleState() elif wifiBtn.is_pressed: wifiToggle() elif bluetoothBtn.is_pressed: bluetoothToggle() elif cheatBtn.is_pressed: showCheat() # Initial File Setup try: comboStates = readData(statePath) wiringpi.wiringPiSetup() wiringpi.pinMode(led, 2) wiringpi.pwmWrite(led, comboStates['brightness']) os.system("amixer sset -q 'PCM' " + str(comboStates['volume']) + "%") if comboStates['wifi'] == 1: os.system("sudo rfkill unblock wifi") else: os.system("sudo rfkill block wifi") if comboStates['bluetooth'] == 1: os.system("sudo rfkill unblock bluetooth") else: os.system("sudo rfkill block bluetooth") except: writeData(statePath) wiringpi.wiringPiSetup() wiringpi.pinMode(led, 2) wiringpi.pwmWrite(led, comboStates['brightness']) os.system("amixer sset -q 'PCM' " + str(comboStates['volume']) + "%")
def messageDecoder(client, userdata, msg): message = msg.payload.decode(encoding='UTF-8') # Debugging prints included in the following #print(message) # Access global variables global dc global state global maxLight global nightMode global measurements # Change lamp state if "on" in message: print("Lamp state switched to: ON") printTime("ON") wiringpi.pwmWrite(1, calcNewDC(dc)) # Return to previous duty # cycle on correct scale state = True elif "off" in message: print("Lamp state switched to: OFF") printTime("OFF") wiringpi.pwmWrite(1, 0) # Turn duty cycle to 0% state = False elif "dc" in message: dc = int(message[3:len(message)]) #print("Lamp duty cycle switched to: " + str(dc) + "%") if (dc == 0): wiringpi.pwmWrite(1, 0) else: wiringpi.pwmWrite(1, calcNewDC(dc)) print(calcNewDC(dc)) if state: printTime("ON") else: printTime("OFF") elif "light" in message: if nightMode and state: # Move former five measurements saved in array for i in range(len(measurements) - 2, -1, -1): measurements[i + 1] = measurements[i] data = int(message[6:len(message)]) measurements[0] = data if data > maxLight: maxLight = data # Calculate new duty cycle from average of last five # measurements saved in array measAvg = sum(measurements) / float(len(measurements)) if (data <= int(measAvg) + 50 and data >= int(measAvg) - 50): offset = measAvg / maxLight newDC = int(50 + offset * 35) if (newDC > dc): dc += 1 wiringpi.pwmWrite(1, dc) elif (newDC < dc): dc -= 1 wiringpi.pwmWrite(1, dc) mqttClient.publish("rpi/back", str((dc - 50) / 0.35)) elif "night" in message: nightMode = True print("Night mode activated") printTime("NIGHT") elif "day" in message: nightMode = False print("Night mode deactivated") printTime("DAY") else: print("Unknown message!")
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)
def lock(): wiringpi.pwmWrite(lockpin, 55)