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): 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 __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 __init__(self, outputPinA, outputPinB, pwmPin): self.outA = outputPinA self.outB = outputPinB wp.pinMode(self.outA, OUTPUT_MODE) wp.pinMode(self.outB, OUTPUT_MODE) self.forward() wp.pwmSetMode(0) wp.pwmSetClock(400) wp.pwmSetRange(PWM_MAX) self.pwm = pwmPin wp.pinMode(self.pwm, PWM_MODE) self.speed = PWM_MIN self.setSpeed(self.speed)
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
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 __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.')
# # 02_led_wiringpi_hardware_pwm.py # import wiringpi LED_PORT = 18 # GPIO 18 PWM_RANGE = 1024 PWM_FREQUENCY = 500 # Hz CLOCK_BASE = int(18750 / PWM_FREQUENCY) # Hardware PWM wiringpi.wiringPiSetupGpio() wiringpi.pinMode(LED_PORT, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) wiringpi.pwmSetRange(PWM_RANGE) wiringpi.pwmSetClock(CLOCK_BASE) # LEDを2秒間点灯する for duty_cycle in (5, 20, 50, 80, 100): print(duty_cycle) wiringpi.pwmWrite(LED_PORT, int(PWM_RANGE * duty_cycle / 100)) wiringpi.delay(2000) wiringpi.pwmWrite(LED_PORT, 0) print('done')
# Servo Control import time import wiringpi # use 'GPIO naming' wiringpi.wiringPiSetupGpio() # set #18 to be a PWM output wiringpi.pinMode(16, 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(16, pulse) time.sleep(delay_period) for pulse in range(250, 50, -1): wiringpi.pwmWrite(16, pulse) time.sleep(delay_period)
def init(): wiringpi.wiringPiSetupGpio() wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) wiringpi.pwmSetClock(192) wiringpi.pwmSetRange(2000)
import wiringpi as wPi from time import sleep pin = 18 wPi.wiringPiSetupGpio() wPi.pinMode(pin, 2) wPi.pwmSetMode(wPi.PWM_MODE_MS) wPi.pwmSetClock(1920) wPi.pwmSetRange(200) def killing(): print("killing") wPi.pwmWrite(pin, 0) wPi.pinMode(pin, 0) try: for i in range(10): print(i) wPi.pwmWrite(pin, 15) sleep(0.5) wPi.pwmWrite(pin, 20) sleep(0.5) wPi.pwmWrite(pin, 10) sleep(0.5) killing() except KeyboardInterrupt: killing()
GPIO.setup(SERVO_RELAY_PIN, GPIO.OUT) LIGHT_RELAY_PIN = 19 GPIO.setup(LIGHT_RELAY_PIN, GPIO.OUT) FAN_RELAY_PIN = 26 GPIO.setup(FAN_RELAY_PIN, GPIO.OUT) # Setup for LCD LCD1602.init(0x27, 1) # init(slave address, background light) # Setup for Servo controller SERVO_CONTROL_PIN = 18 wiringpi.wiringPiSetupGpio() # use 'GPIO naming' wiringpi.pinMode(SERVO_CONTROL_PIN, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode( wiringpi.GPIO.PWM_MODE_MS) # set the PWM mode to milliseconds stype wiringpi.pwmSetClock(192) # divide down clock wiringpi.pwmSetRange(2000) # Setup for Camera PICTURE_FILENAME = 'pibatercam' # Setup for basic logging logging.basicConfig(filename='/var/log/pibater.log', format='%(asctime)s %(message)s', level=logging.DEBUG) # Setup for logging # Need to persist this value across executions of logging script last_email_sent = 0 # Setup for main()
dir_pin = args.dir_pin print('setup') # use 'GPIO naming' wi.wiringPiSetupGpio() print('Setting up servo pin') wi.pinMode(args.servo_pin, wi.GPIO.PWM_OUTPUT) 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
import wiringpi as pi, time, math from lis3dh import lis3dh sleep_time = 0.01 servo_pin = 18 pi.wiringPiSetupGpio() pi.pinMode( servo_pin, 2 ) pi.pwmSetMode(0) pi.pwmSetRange(1024) pi.pwmSetClock(375) SPI_CS = 0 lis3dh = lis3dh( pi, SPI_CS ) angle_deg = 0.0 while True: x= lis3dh.read( pi, "x" ) y= lis3dh.read( pi, "y" ) z= lis3dh.read( pi, "z" ) angle_reg = math.atan2( y, z ) angle_deg_new = math.degrees( angle_reg ) angle_deg = angle_deg * 0.9 + angle_deg_new * 0.1 print ("x:", x, " y:", y, " z:", z, " angle:", angle_deg)
import tty import sys import termios # imports for pwm use import wiringpi import time # setting up the GPIO pin for pwm and seting the frequency wiringpi.wiringPiSetupGpio() wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # pwm frequency in Hz: 19,200,000 / pwmSetClock / pwmSetRange # 19,200,000 / 10 / 1000 = 1920 wiringpi.pwmSetClock(10) wiringpi.pwmSetRange(1000) # loop-de-loop input into stdin 'r' to run the motor 's' to stop it while 1: x = sys.stdin.read(1) if x == 'r': #motor on wiringpi.pwmWrite(18, 600) if x == 's': #motor off wiringpi.pwmWrite(18, 0) if x == '1': wiringpi.pwmWrite(18, 100)
MOTORL_INB = 24 # GPIO 24 = Pin 18 MOTORL_PWM = 18 # GPIO 18 = Pin 12 #MOTORR_INA = 5 # GPIO 5 = Pin 29 #MOTORR_INB = 6 # GPIO 6 = Pin 31 #MOTORR_PWM = 27 # GPIO 27 = Pin 13 w.wiringPiSetupGpio() w.pinMode(MOTORL_INA, w.GPIO.OUTPUT) w.pinMode(MOTORL_INB, w.GPIO.OUTPUT) w.pinMode(MOTORL_PWM, w.GPIO.PWM_OUTPUT) # Set PWM Mode # balanced: PWM_MODE_BAL # mark-space: PWM_MODE_MS w.pwmSetMode(w.PWM_MODE_MS) # Set PWM range and divisor(clock) # 1.92MHz/divisor = range*freq # range:1024, divisor:15 => freq:125Hz w.pwmSetRange(1024) w.pwmSetClock(15) w.digitalWrite(MOTORL_INA, 1) w.digitalWrite(MOTORL_INB, 0) duty = 50 while True: w.pwmWrite(MOTORL_PWM, int(duty * 10)) print(duty)
print(" a TreatTrainer product ") print("------------------------------------------------------------") print("(C) Andrew DeJong, distributed under the LGPL ") print("") print("") print("Initializing...") wiringpi.wiringPiSetupGpio() wiringpi.pinMode(redPin, 1) wiringpi.pinMode(greenPin, 1) wiringpi.pinMode(bluePin, 1) led('red') print("Configuring PWM servo pin...") wiringpi.pinMode(servoPin, 2) wiringpi.pwmSetMode(0) wiringpi.pwmSetClock(384) wiringpi.pwmSetRange(1000) wiringpi.pwmWrite(servoPin, servoRest) # Rest position print("Opening SQLite database...") sqconn = sqlite3.connect('/var/www/databases/barkActivity.db') sqcurs = sqconn.cursor() print("Last entry: ") for row in sqcurs.execute( "SELECT * FROM sessions ORDER BY datetime DESC LIMIT 1"): print(row) sqconn.close() print("Saving barkBit file name...") # Save bitFilename is db, if not already there intDate = int(date.today().strftime("%Y%m%d"))
wiringpi.pinMode(18,2) # x = 2 declares alt function, pwm only works on GPIO port 18 wiringpi.pullUpDnControl(24, wiringpi.PUD_DOWN) # PUD_OFF allows to float # PUD_DOWN enables internal pull down resistor, pulling to GND # PUD_UP enables internal pull up resistor, pulling to 3.3V wiringpi.pinMode(24,0) # x = 0 sets pin to input # according to GPIO PADS CONTROL2 PDF... # maximum low level voltage = 0.8V # minimum high level voltage = 1.3V # set PWM Mode # balanced (default, varies frequency with duty cycle for even pulses) # mark-space mode (traditional) 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 # GPIO pins support 0v-3.3v 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) prompt = raw_input("please proceed, press ENTER ") # attempt to insert pause so pin voltage is read correctly # forum suggests GPIO library can only read at 1MHz max # tested at above and below 1MHz, misreading still occurs about # 1 out of 10 trials # the sampling period is variable and will not be accurate for such # an attempt without implementing an interrupt
# run with sudo!! import wiringpi as wpi pin = 18 wpi.wiringPiSetupGpio() wpi.pinMode(pin, wpi.PWM_OUTPUT) wpi.pwmSetMode(wpi.PWM_MODE_MS) wpi.pwmSetClock(384) #19.2MHz / 384 = 50000Hz = 50KHz(0.02ms) wpi.pwmSetRange(1000) # 0.02ms * 1000 = 20ms, 50KHz / 1000 = 50Hz while True: answer = raw_input("1:-90, 2:0, 3: +90 > ") if answer == '1': wpi.pwmWrite(pin, 25) # 25 * 0.02ms = 0.5ms elif answer == '2': wpi.pwmWrite(pin, 75) # 75 * 0.02ms = 1.5ms else: wpi.pwmWrite(pin, 125) # 125 * 0.02ms = 2.5ms
class ServoManual: # Defining class constructor def __init__(self): pass # Using GPIO naming wiringpi.wiringPiSetupGpio() # Defining pin 18 of the Raspberry Pi to be a PWM output wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT) # Setting the PWM mode to milliseconds wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # Dividing down clock # Pin 18 on the Raspberry Pi declared for the purpose of being a PWM output requires a # frequency of 50 Hz for the servo to operate properly. # If pwmClock is 192 and pwmRange is 2000 the PWM frequency would be 50 Hz # PWM frequency = 19,200,000 Hz / pwmClock / pwmRange = 50 Hz 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 # Defining default servo angle default = 0 # Defining angle limit for the servo 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 occurred print 'Cannot open storage file for writing' else: # Closing the opened file f.close() # 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 = 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 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 = 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)
class Servo: # Defining class constructor def __init__(self, y_raw): self.y_raw = y_raw # Using GPIO naming wiringpi.wiringPiSetupGpio() # Defining pin 18 of the Raspberry Pi to be a PWM output wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT) # Setting the PWM mode to milliseconds wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # Dividing down clock # Pin 18 on the Raspberry Pi declared for the purpose of being a PWM output requires a # frequency of 50 Hz for the servo to operate properly. # If pwmClock is 192 and pwmRange is 2000 the PWM frequency would be 50 Hz # PWM frequency = 19,200,000 Hz / pwmClock / pwmRange = 50 Hz wiringpi.pwmSetClock(192) wiringpi.pwmSetRange(2000) # Defining delay period (given in milliseconds) delay_period = 0.01 # Defining default servo angle default = 0 # 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 occurred print 'Cannot open storage file for writing' else: # Closing the opened file f.close() # Defining a method that will be utilized to control the position of the servo motor 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)
def setPwm(self): wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS) wiringpi.pwmSetClock(self.CLOCK) wiringpi.pwmSetRange(self.RANGE)
#enable pins motor1 -- Lmotor wp.pinMode(INPUT_1_LEFT_MOTOR, OUTPUT_MODE) wp.pinMode(INPUT_2_LEFT_MOTOR, OUTPUT_MODE) #enable pins motor2 -- Rmotor wp.pinMode(INPUT_1_RIGHT_MOTOR, OUTPUT_MODE) wp.pinMode(INPUT_2_RIGHT_MOTOR, OUTPUT_MODE) wp.pinMode(GIFT_PIN, INPUT_MODE) wp.pinMode(TREE_PIN, INPUT_MODE) wp.pinMode(12, PWM_MODE) wp.pinMode(13, PWM_MODE) wp.pwmSetMode(0) wp.pwmSetClock(400) wp.pwmSetRange(1024) wp.pwmWrite(12,0) wp.pwmWrite(13,0) class easy_encoders(): #encoder pin numbers on pi (broadcom numbering scheme) RW_A = 20 #pin = 38 RW_B = 26 #pin = 37 LW_A = 19 #pin = 35 LW_B = 16 #pin =36 #encoder counts rw_count = 0 lw_count = 0
# GPIOを制御するライブラリ import wiringpi # タイマーのライブラリ import time # 引数取得 import sys # サーボモータに接続したGPIO端子番号を指定 servo_pin = 18 # サーボモータを動かす角度を指定する # set_degree = 90 デフォルト # 引数から値を受け取る param = sys.argv set_degree = int(param[1]) print(set_degree) wiringpi.wiringPiSetupGpio() # ハードウェアPWMで出力する wiringpi.pinMode(servo_pin, 2) # サーボモータに合わせたPWM波形の設定 wiringpi.pwmSetMode(0) wiringpi.pwmSetRange(1024) wiringpi.pwmSetClock(375) # 角度から送り出すPWMのパルス幅を算出する move_deg = int(81 + 41 / 90 * set_degree) # サーボモータにPWMを送り、サーボモータを動かす wiringpi.pwmWrite(servo_pin, move_deg) time.sleep(1)
#!/usr/bin/python from evdev import InputDevice, categorize, ecodes from select import select import wiringpi as wp dev = InputDevice('/dev/input/touchscreen') wp.wiringPiSetupGpio() wp.pinMode(18,wp.PWM_OUTPUT) wp.pwmSetClock(20000) wp.pwmSetRange(100) wp.pwmWrite(18,50) while True: # Lighweight wait for IO activity on device select([dev], [], []) for event in dev.read(): if event.type == ecodes.EV_ABS # PiTFT 2.8 capacitive reports ABS_MT_POSITION_Y events if event.code == ecodes.ABS_MT_POSITION_Y: # PiTFT 2.8 capacitive events range from exactly 0 to 320 dc = 100*(320-event.value)/320 # PiTFT 2.8 resistive reports ABS_Y events #if event.code == ecodes.ABS_Y: # PiTFT 2.8 resistive Y events range from approx. 700 to 3900 #dc = 100*(event.value-700)/3200 # Debug events, you should also try evtest /dev/input/[device] for proper eventnames #print(dc)
import wiringpi as pi, time servo_pin = 13 set_degree = -90 pi.wiringPiSetupGpio() pi.pinMode(servo_pin, 2) pi.pwmSetMode(0) pi.pwmSetRange(1024) pi.pwmSetClock(375) if (set_degree <= 90 and set_degree >= -90): move_deg = int(74 + 48 / 90 * set_degree) pi.pwmWrite(servo_pin, move_deg)
import wiringpi def getServoDutyForWebIOPi(val): val_min = 0.0 val_max = 1.0 servo_min = 36 # 50Hz(周期20ms)、デューティ比3.5%: 3.5*1024/100=約36 servo_max = 102 # 50Hz(周期20ms)、デューティ比10%: 10*1024/100=約102 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.pinMode(19, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # 周波数固定 wiringpi.pwmSetClock(375) # 50 Hz wiringpi.pwmWrite(18, getServoDutyForWebIOPi(0.5)) # wiringpi.pwmWrite(19, getServoDutyForWebIOPi(0.5)) # デバッグ出力を有効に webiopi.setDebug() # WebIOPiの起動時に呼ばれる関数 def setup(): webiopi.debug("Script with macros - Setup") # WebIOPiにより繰り返される関数 def loop(): webiopi.sleep(5) # WebIOPi終了時に呼ばれる関数
PWM_PIN=18 ROTATE_NEUTRAL = 90 PWM_RANGE = 1024 PWM_CLOCK = 375 TICK_S = 0.5 MESSAGE_DELIM = ';' last_ts = 0 # can call wiringPiSetupSys() if we've previously exported GPIO pins wiringpi.wiringPiSetupGpio() # use PWM on port 18 wiringpi.pinMode(PWM_PIN, 2) wiringpi.pwmSetMode(PWM_MODE_MS) wiringpi.pwmSetClock(PWM_CLOCK) wiringpi.pwmSetRange(PWM_RANGE) rotation = ROTATE_NEUTRAL def angle_to_duty_cycle(angle=0): # 2.5ms of 20ms pulse is full 180deg swing ubound = 0.1 offset = 0.5/20 * PWM_RANGE # set duty cycle as 0-180deg expressed as 0-1024 return int(offset + float(angle) / 180 * ubound * PWM_RANGE) def on_connect(aioClient): global last_ts rotate_arm(ROTATE_NEUTRAL) time.sleep(TICK_S)
##wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) ## ### Configure Frequency ##wiringpi.pwmSetClock(numClock) ##wiringpi.pwmSetRange(numRange) ## ### Set Duty Cycle ##wiringpi.pwmWrite(18, 140) # Initialize WiringPi, then Pin, then PWM Mode wiringpi.wiringPiSetupGpio() wiringpi.pinMode(19, 2) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # Configure Frequency wiringpi.pwmSetClock(numClock) wiringpi.pwmSetRange(numRange) # Set Duty Cycle print("Stop for 1 s") wiringpi.pwmWrite(19, 150) sleep(1) wiringpi.pwmWrite(19, 174) sleep(1.5) wiringpi.pwmWrite(19, 130) sleep(0.6) print("Stop") wiringpi.pwmWrite(19, 150)
import wiringpi import time import math #use BCM pin numbers wiringpi.wiringPiSetupGpio() # setup WiringPi PWM SERVO_PIN = 18 PWM_DIVISOR = 384 # clock at 50kHz (20us tick) PWM_RANGE = 1000 # range at 1000 ticks (20ms) # setup pin as an output wiringpi.pinMode(SERVO_PIN, 2) wiringpi.pwmSetMode(0) wiringpi.pwmSetClock(PWM_DIVISOR) wiringpi.pwmSetRange(PWM_RANGE) wiringpi.pwmWrite(SERVO_PIN, 0) #theretically 50 (1ms) to 100 (2ms) on my servo 40-200 works ok 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))
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]], [[0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0]]] w.wiringPiSetupGpio() base = 0 for ano in range(7): w.pinMode(P_ANO[ano], 1) w.digitalWrite(P_ANO[ano], 0) w.pinMode(P_MOT, 2) w.pwmSetMode(0) w.pwmSetRange(1024) w.pwmSetClock(375) m_deg = int(74 + 48 / 90 * base) w.pwmWrite(P_MOT, m_deg) while 1: time.sleep(0.1) for base in range(110): m_deg = int(74 + 48 / 90 * (base - 90)) w.pwmWrite(P_MOT, m_deg) for ano in range(7): w.digitalWrite(P_ANO[ano], DT[0][ano][base // 10]) time.sleep(0.002) time.sleep(0.1) for base in reversed(range(0, 110)): m_deg = int(74 + 48 / 90 * (base - 90)) w.pwmWrite(P_MOT, m_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
dly = .5 # 500ms Delay # Here we are going to setup our interpolation ranges. # To determine the pw_range, follow the directions in the README.md # deg_range, is the range of your servo. Leave as is if it is a 180 degree servo pw_range = [50, 260] deg_range = [0, 180] interp_degrees = interp1d(deg_range, pw_range) # Setting up wiringpi. We are setting the pinmode to PWM Output, # PWM Mode to MS (milliseconds), Clock and range set as they are # tell wiringpi to run at 50hz. wiringpi.wiringPiSetupGpio() wiringpi.pinMode(pin, wiringpi.GPIO.PWM_OUTPUT) wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) wiringpi.pwmSetClock(192) wiringpi.pwmSetRange(2000) # This method takes input of degrees, converts it to pulse width, # waits half a second, then sets the pulse width to 0. In wiringpi # setting the pulsewidth to zero essentially turns off the servo. # otherwise it will be jittery. def setAngle(deg): wiringpi.pwmWrite(pin, int(interp_degrees(deg))) sleep(dly) wiringpi.pwmWrite(pin, 0) # run the example. 0 -> 90 -> 180 -> 90 -> 0 ... def main(args=None): try: while True:
import wiringpi as wpi pin = 18 wpi.wiringPiSetupGpio() wpi.pinMode(pin, wpi.PWM_OUTPUT) wpi.pwmSetMode(wpi.PWM_MODE_MS) wpi.pwmSetClock(1920) wpi.pwmSetRange(100) while True: answer = raw_input("1:-90, 2:0, 3: +90 > ") if answer == '1': wpi.pwmWrite(pin, 5) elif answer == '2': wpi.pwmWrite(pin, 15) else: wpi.pwmWrite(pin, 25)
DUTY_MIN = 26 DUTY_HOME = 74 duty = 0 fan = 24 fan2 = 26 respTime = 0.01 AcSpeed = 3 standard = 7.5 s_hold = 50 FPS = 30 wp.wiringPiSetupGpio() wp.pinMode(gp_outX, wp.GPIO.PWM_OUTPUT) wp.pwmSetMode(wp.GPIO.PWM_MODE_MS) wp.pwmSetClock(375) wp.pwmWrite(gp_outX, DUTY_HOME) wp.delay(100) def move(degree): duty = int((DUTY_MAX - DUTY_MIN) / 180.0 * degree + DUTY_HOME) wp.pwmWrite(gp_outX, duty) #GPIO.setup(fan,GPIO.OUT) #GPIO.output(fan,1) for degree in [0, 45, 90, 0, -45, -90, 0, 30, -30, 0]: move(degree)
import wiringpi as pi import time SERVO_PIN = 18 set_degree = 90 CYCLE = 20 MIN_PULSE = 0.5 MAX_PULSE = 2.4 MIN_DEG = 0 MAX_DEG = 180 RANGE = 2000 clock = int(19.2 / float(RANGE) * CYCLE * 1000) min_val = RANGE * MIN_PULSE / CYCLE max_val = RANGE * MAX_PULSE / CYCLE pi.wiringPiSetupGpio() pi.pinMode(SERVO_PIN, pi.GPIO.PWM_OUTPUT) pi.pwmSetMode(pi.GPIO.PWM_MODE_MS) pi.pwmSetRange(RANGE) pi.pwmSetClock(clock) if (set_degree <= MAX_DEG and set_degree >= MIN_DEG): move_deg = int((max_val - min_val) / MAX_DEG * set_degree) pi.pwmWrite(SERVO_PIN, move_deg)
# elif lastEvent == eventPrefix + "<b>CE_Automate<li>resumed</b>" or elif lastEvent == eventPrefix + "<b>playeractions<li>playback_resumed</b>": playerState.resume() else: rootLogger.warn("Event not recognized: " + lastEvent) PWM_FREQ = config.getfloat('lights', 'pwm_freq') TL_PWM = 1 # gpio pin 12 = wiringpi no. 1 (BCM 18) # Initialize PWM output for theater lights wiringpi.wiringPiSetup() if config.get('lights', 'pwm_mode') == 'HW': wiringpi.pwmSetMode(0) # PWM_MODE_MS wiringpi.pwmSetClock(math.trunc(18750 / PWM_FREQ)) wiringpi.pinMode(TL_PWM, 2) # PWM mode wiringpi.pwmWrite(TL_PWM, 0) # OFF elif config.get('lights', 'pwm_mode') == 'SW': wiringpi.pinMode(TL_PWM, 1) # Software PWM mode wiringpi.softPwmCreate(TL_PWM, 0, 100) # Setup PWM using Pin, Initial Value and Range parameters else: rootLogger.error("Invalid pwm_mode: {0}. Exiting...".format(config.get('lights', 'pwm_mode'))) def updateLights(): global tlConfig STEP_INTERVAL = 1 / PWM_FREQ # how often STEP_BRIGHTNESS = 1 / (tlConfig.lightsFadeTime * PWM_FREQ) # how much currentBrightness = 1.00