Exemple #1
0
def test_invalid_duty_cycle():

    PWM_chip = 0
    PWM_pin = 0
    frequency_Hz = 500
    Duty_Cycle_Percent_high = 150
    Duty_Cycle_Percent_low = -50

    with pytest.raises(Exception) as ex:
        p = GPIO.PWM(PWM_chip, PWM_pin, frequency_Hz, Duty_Cycle_Percent_high)
        p.duty_cycle(150)
        assert str(
            ex.value
        ) == "Duty cycle must br between 0 and 100. Current value: {0} is out of bounds".format(
            Duty_Cycle_Percent_high)
        p.pwm_close()

    with pytest.raises(Exception) as ex:
        p = GPIO.PWM(PWM_chip, PWM_pin, frequency_Hz, Duty_Cycle_Percent_low)
        p.duty_cycle(-50)
        assert str(
            ex.value
        ) == "Duty cycle must br between 0 and 100. Current value: {0} is out of bounds".format(
            Duty_Cycle_Percent_low)
        p.pwm_close()
Exemple #2
0
 def configureGPIO(self):
     try:
         for control in self.temperature_control:
             if control['isEnabled']:
                 GPIO.setup(self.toInt(control['gpioPin']), GPIO.OUT, initial=GPIO.HIGH if control['activeLow'] else GPIO.LOW)
         for rpi_output in self.rpi_outputs:
             pin = self.toInt(rpi_output['gpioPin'])
             if rpi_output['outputType'] == 'regular':
                 if self.toInt(rpi_output['gpioPin']) not in self.previous_rpi_outputs :
                     initialValue = GPIO.HIGH if rpi_output['activeLow'] else GPIO.LOW
                     GPIO.setup(pin, GPIO.OUT,initial=initialValue)
             if rpi_output['outputType'] == 'pwm':
                     for pwm in (pwm for pwm in self.PWM_INSTANCES if pin in pwm):
                         self.PWM_INSTANCES.remove(pwm)
                     self.clearChannel(pin)
                     GPIO.setup(pin, GPIO.OUT)
                     p = GPIO.PWM(pin, self.toInt(rpi_output['frequency']))
                     self.PWM_INSTANCES.append({pin:p})
             if rpi_output['outputType'] == 'neopixel':
                     self.clearChannel(pin)
         for rpi_input in self.rpi_inputs:
             pullResistor = pull_up_down=GPIO.PUD_UP if rpi_input['inputPull'] == 'inputPullUp' else GPIO.PUD_DOWN
             GPIO.setup(self.toInt(rpi_input['gpioPin']), GPIO.IN, pullResistor)
             if rpi_input['eventType'] == 'gpio' and self.toInt(rpi_input['gpioPin']) != 0:
                 edge =  GPIO.RISING if rpi_input['edge'] == 'rise' else  GPIO.FALLING
                 GPIO.add_event_detect(self.toInt(rpi_input['gpioPin']), edge, callback= self.handleGPIOControl, bouncetime=200)
             if rpi_input['eventType'] == 'printer' and rpi_input['printerAction'] != 'filament' and self.toInt(rpi_input['gpioPin']) != 0:
                 edge =  GPIO.RISING if rpi_input['edge'] == 'rise' else  GPIO.FALLING
                 GPIO.add_event_detect(self.toInt(rpi_input['gpioPin']), edge, callback= self.handlePrinterAction, bouncetime=200)
     except Exception as ex:
         template = "An exception of type {0} occurred on configureGPIO. Arguments:\n{1!r}"
         message = template.format(type(ex).__name__, ex.args)
         self._logger.warn(message)
         pass
Exemple #3
0
    def on(self, power=None):
        if power is not None:
            self.power = int(power)

        if self.frequency is None:
            self.frequency = 0.5  # 2 sec

        self.p = GPIO.PWM(int(self.gpio), float(self.frequency))
        self.p.start(int(self.power))
Exemple #4
0
def test_pwm_wrong_chip_pin():

    # Test for a chip-pin combo that does not exist
    PWM_chip = 99
    PWM_pin = 99
    frequency_Hz = 500
    Duty_Cycle_Percent = 50

    with pytest.raises(Exception) as ex:

        GPIO.PWM(PWM_chip, PWM_pin, frequency_Hz, Duty_Cycle_Percent)
        if ex.errno == 2:
            assert str(
                ex.value
            ) == "FileNotFoundError: [Errno 2] No such file or directory: '/sys/class/pwm/pwmchip{0}/export'".format(
                PWM_chip)
        elif ex.errno == 19:
            assert str(ex.value) == "OSError: [Errno 19] No such device"
Exemple #5
0
    def _setup_pin(self, pin):
        self._logger.debug(u"_setup_pin(%s)" % (pin, ))
        if pin:
            p = None
            startup = 100.0 if self._settings.get_boolean(['on_startup'
                                                           ]) else 0.0

            if self._pigpiod is None:
                self._pigpiod = pigpio.pi()

            if self._settings.get_boolean(['pigpiod']):
                if not self._pigpiod.connected:
                    self._logger.error(u"Unable to communicate with PiGPIOd")
                else:
                    p = PiGPIOpin(self._pigpiod, pin, self._logger)
            else:
                GPIO.setwarnings(False)
                GPIO.setmode(GPIO.BOARD)
                GPIO.setup(pin, GPIO.OUT)
                GPIO.output(pin, GPIO.HIGH)
                p = GPIO.PWM(pin, 100)
            p.start(startup)
            return p
Exemple #6
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import OPi.GPIO as GPIO
from time import sleep

GPIO.setboard(GPIO.ZERO)
GPIO.setmode(GPIO.BOARD)  # set up BOARD BCM numbering
GPIO.setup(26, GPIO.OUT)  # set pin 26 as an output (LED)

p = GPIO.PWM(26, 10)  # new PWM on channel=26 frequency=10Hz
p.start(0)
try:
    while 1:
        for dc in range(0, 101, 5):
            p.ChangeDutyCycle(dc)
            sleep(0.1)
        for dc in range(100, -1, -5):
            p.ChangeDutyCycle(dc)
            sleep(0.1)
except KeyboardInterrupt:
    pass
p.stop()
GPIO.output(26, 0)
GPIO.cleanup()
Exemple #7
0
from time import sleep          # this lets us have a time delay

GPIO.setboard(GPIO.PCPCPLUS)    # Orange Pi PC board
GPIO.setmode(GPIO.BOARD)

# The output pins will be declared, which are connected with the LEDs. 
LED_Red = 7
LED_Green = 29
# Set pins to output mode
GPIO.setup(LED_Red, GPIO.OUT) 
GPIO.setup(LED_Green, GPIO.OUT)
  
Freq = 100 #Hz
  
# The specific colors will be initialized.
RED = GPIO.PWM(LED_Red, Freq) 
GREEN = GPIO.PWM(LED_Green, Freq)
RED.start(0)  
GREEN.start(0)
  
# This function generate the actually color
# You can change the color with the specific color variable.
# After the configuration of the color is finished, you will time.sleep to
# configure how long the specific will be displayed.
 
def LED_color(Red, Green, pause):
    RED.ChangeDutyCycle(Red)
    GREEN.ChangeDutyCycle(Green)
    sleep(pause)
 
    RED.ChangeDutyCycle(0)
Exemple #8
0
import OPi.GPIO as GPIO

if __name__ == "__main__":

    PWM_chip = 0
    PWM_pin = 0
    frequency_Hz = 3800
    Duty_Cycle_Percent = 100

    p = GPIO.PWM(
        PWM_chip, PWM_pin, frequency_Hz,
        Duty_Cycle_Percent)  # new PWM on channel=LED_gpio frequency=38KHz

    print("turn on pwm by pressing button")
    input()
    p.start_pwm()

    print("dimm pwm by pressing button")
    input()
    p.duty_cycle(50)

    print("change pwm frequency by pressing button")
    input()
    p.change_frequency(500)

    print("stop pwm by reducing duty cycle to 0 by pressing button")
    input()
    p.stop_pwm()

    print("change polarity by pressing button")
    input()
Exemple #9
0
import OPi.GPIO as GPIO
import time

GPIO.setboard(GPIO.ZEROPLUS)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
p = GPIO.PWM(7, 50)
p.start(7.5)
p.ChangeDutyCycle(12.5)
time.sleep(1)
p.stop()
GPIO.cleanup()
#Needed modules will be imported and configured.
import OPi.GPIO as GPIO
GPIO.setboard(GPIO.PCPCPLUS)  # Orange Pi PC board
GPIO.setmode(GPIO.BOARD)

#The output pin, which is connected with the buzzer, will be declared here.
GPIO_PIN = 7
GPIO.setup(GPIO_PIN, GPIO.OUT)
#The software-PWM module will be initialized - a frequency of 500Hz will be taken as default.
Frequenz = 500  #In Hertz
pwm = GPIO.PWM(GPIO_PIN, Frequenz)
pwm.start(50)
# The program will wait for the input of a new PWM-frequency from the user.
# Until then, the buzzer will be used with the before inputted frequency (default 500Hz).
try:
    while (True):
        print "----------------------------------------"
        print "Current frequency: %d" % Frequenz
        Frequenz = input("Please input a new frequency (50-5000):")
        pwm.ChangeFrequency(Frequenz)

except KeyboardInterrupt:
    # here you put any code you want to run before the program
    # exits when you press CTRL+C
    print "An error or exception occurred!"

except:
    # this catches ALL other exceptions including errors.
    # You won't get any error messages for debugging
    # so only use it once your code is working
    print "Other error or exception occurred!"
Exemple #11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import OPi.GPIO as GPIO
from time import sleep

GPIO.setboard(GPIO.ZERO)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(26, GPIO.OUT)

p = GPIO.PWM(26, 0.5)               # channel=26 frequency=0.5Hz
p.start(1)
raw_input('Press return to stop:')  # use input for Python 3
p.stop()
GPIO.cleanup()
GPIO.setboard(GPIO.PCPCPLUS)  # Orange Pi PC board
GPIO.setmode(GPIO.BOARD)

# The output pins will be declared, which are connected with the LEDs.
LED_Red = 29
LED_Green = 31
LED_Blue = 7

# Set pins to output mode
GPIO.setup(LED_Red, GPIO.OUT)
GPIO.setup(LED_Green, GPIO.OUT)
GPIO.setup(LED_Blue, GPIO.OUT)

Freq = 100  #Hz
# The different colors will be initialized.
RED = GPIO.PWM(LED_Red, Freq)
GREEN = GPIO.PWM(LED_Green, Freq)
BLUE = GPIO.PWM(LED_Blue, Freq)
RED.start(0)
GREEN.start(0)
BLUE.start(0)

# This function generate the actually color<br /># You can change the color with the specific color variable.<br /># After the configuration of the color is finished, you will use time.sleep to<br /># configure how long the specific color will be displayed.


def LED_color(Red, Green, Blue, pause):
    RED.ChangeDutyCycle(Red)
    GREEN.ChangeDutyCycle(Green)
    BLUE.ChangeDutyCycle(Blue)
    sleep(pause)
    def pinUpdate(self, pin, value,type = 'plain',stepDelay = 0.003):
        #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin]
        #print "pin",pin
        #print "pvalue",self.pinValue
        self.pinValue[pin] = value
        self.mFreq = max(5,abs(value/2))
        if (self.ledDim < 100) and (type == 'plain'):
            type = "pwm"
            value = value * self.ledDim
        try:
            #print pin,value,type,self.pinUse[pin]
            if type[0:3] == "pwm": # 
                #print "processing pwm"
                #return
                if (self.pinInvert[pin] == True): # Invert data value (needed for active low devices)
                    value = 100 - abs(value)
                    
                #print "motor freq calc", self.mFreq
                try: 
                    #print "try jsut updating pwm"
                    self.pinRef[pin].ChangeDutyCycle(max(0,min(100,abs(value)))) # just update PWM value
                    if type == "pwmmotor":
                        #print "motor freq used a", self.mFreq
                        self.pinRef[pin].ChangeFrequency(self.mFreq) # change freq to motor freq
                    elif type != "pwmbeep":
                        #print "motor freq used a", self.mFreq
                        self.pinRef[pin].ChangeFrequency(self.pFreq) # change freq to motor freq                        
             
                    #print "updating pwm suceceed"
                except:
                    #print "pwm not set so now setting up"
                    try:
                        GPIO.remove_event_detect(pin)
                        self.callbackInUse[pin] = False
                    except:
                        pass
                       
                    GPIO.setup(pin,GPIO.OUT) # Setup
                    if type == "pwmmotor":
                        #print "motor freq used b", self.mFreq
                        self.pinRef[pin] = GPIO.PWM(pin,self.mFreq) # create new PWM instance
                    elif type != "pwmbeep":
                        #print "motor freq used a", self.mFreq
                        self.pinRef[pin] = GPIO.PWM(pin,self.pFreq) # create new PWM instance
                    self.pinRef[pin].start(max(0,min(100,abs(value)))) # update PWM value
                    #print "pwm setup on pin",pin, "now has ref",self.pinRef[pin]
                    self.pinUse[pin] = self.PPWM # set pin use as PWM
         
            elif type == "plain":
                #print "Plain processing- Pin " , pin , " commanded to be " , value
                #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin]
                if (self.pinInvert[pin] == True): # Invert data value (useful for 7 segment common anode displays)
                    value = 1 - abs(value)
                if (self.pinUse[pin] == self.POUTPUT): # if already an output
                    GPIO.output(pin, int(value)) # set output to 1 ot 0
                    #print 'pin' , pin , ' was already an output.  Now set to' , value
                    
                elif (self.pinUse[pin] in [self.PINPUT,self.PINPUTNONE,self.PINPUTDOWN]): # if pin is an input
                    try:
                        GPIO.remove_event_detect(pin)
                        self.callbackInUse[pin] = False
                    except:
                        pass  
                    self.pinUse[pin] = self.POUTPUT # switch it to output
                    GPIO.setup(pin,GPIO.OUT)
                    GPIO.output(pin, int(value)) # set output to 1 to 0
                    #print 'pin' , pin , ' was an input - change to output value' , value                    
               
                  
                elif (self.pinUse[pin] == self.PUNUSED): # if pin is not allocated
                    self.pinUse[pin] = self.POUTPUT # switch it to output
                    GPIO.setup(pin,GPIO.OUT)
                    GPIO.output(pin,int(value)) # set output to 1 or 0
                    #print 'pin' , pin , ' was ununsed - now out value ' , value            

                elif (self.pinUse[pin] == self.PPWM): # pin was set as pwm
                    #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin]
                    try:
                        #print "pinUpdate p,v,t,pwmref: ",pin,value,type,self.pinRef[pin]
                        #print ("Stopping previous instance on pin",pin)
                        #print "pinref on pin" ,pin , "is" ,self.pinRef[pin]
                        self.pinRef[pin].stop()
                        #print ("previous instance on pin",pin ,"stopped")
                        self.pinRef[pin] = None
                    except:
                        pass
                    self.pinUse[pin] = self.POUTPUT # switch it to output

                    GPIO.setup(pin,GPIO.OUT)
                    #print "switched to output"
                    GPIO.output(pin, int(value)) # set output to 1 to 0
                    
                    #print 'pin' , pin , ' was PWM now set to ' , value                       
        except ValueError:
            print "mistake made in trying to update an invalid pin"
            print pin,value,type
            pass
Exemple #14
0
    with open(file) as cpud:
        return int(cpud.readline()) / 1000.0


def cpu():
    return _temp(cpupath)


def gpu():
    return _temp(gpupath)


#### FAN related
PWM_FREQ = 1000
GPIO.setup(PIN_FANCONTROL, GPIO.OUT)
pwm = GPIO.PWM(PIN_FANCONTROL, PWM_FREQ)
pwm.ChangeDutyCycle(0)
pwm.start(1)


def set_fanspeed(speed):
    if speed > 100:
        speed = 100

    if speed < 0:
        speed = 0

    pwm.ChangeDutyCycle(speed)
    fanspeed = speed

Exemple #15
0
#!/bin/env python3
import OPi.GPIO as GPIO
from time import sleep
from flask import Flask, render_template
import atexit

# setup the gpio
GPIO.setboard(GPIO.PCPCPLUS)
GPIO.setmode(GPIO.BCM)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(19, GPIO.OUT)

GPIO.output(19, 0)

p = GPIO.PWM(13, 1000)
p.start(0)

app = Flask(__name__)


@app.route('/')
def hello():
    return '<a href="/home">here</a>'


@app.route('/home/')
@app.route('/home/<auto_update>')
def home(auto_update=None):
    return render_template('index.html', no_update=auto_update)