Пример #1
0
 def initPWM(pin):
     """ Sets a pin to PWM """
     pwm = PWM(pin, 0)
     pwm.frequency = 1e3
     pwm.duty_cycle = 0
     pwm.enable()
     return pwm
Пример #2
0
 def prepare(self) -> None:
     logger = get_logger(0)
     for (pin, initial) in self.__channels.items():
         try:
             logger.info("Probing pwm chip %d channel %d ...", self.__chip,
                         pin)
             pwm = PWM(self.__chip, pin)
             self.__pwms[pin] = pwm
             pwm.period_ns = self.__period
             pwm.duty_cycle_ns = self.__get_duty_cycle(bool(initial))
             pwm.enable()
         except Exception as err:
             logger.error("Can't get PWM chip %d channel %d: %s",
                          self.__chip, pin, tools.efmt(err))
Пример #3
0
 def initPWM(pin):
     pwm = PWM(pin, 0)
     pwm.frequency = 1e3
     pwm.duty_cycle = 0
     pwm.enable()
     return pwm
Пример #4
0
print(mode)

# Open PWM channel 0, pin 32
pins = range(0, 41)
"""
for pin in pins:
	try:
		pwm = PWM(0, pin)
		print("** Channel 0 pin {} works!".format(pin))
	except:
		print("Pin {} does not work".format(pin))
"""
pwm = PWM(0, 2)
pwm = PWM(0, 0)

#Channel 0 pin 2

# Set frequency to 1 kHz
pwm.frequency = 2e3
# Set duty cycle to 75%
pwm.duty_cycle = 0.25

pwm.enable()

# Change duty cycle to 50%
pwm.duty_cycle = 0.25

time.sleep(5 * 60)

pwm.close()
Пример #5
0
class HPWMPeriphery(HPWM):
    """Wrapper around python periphery pwm implementation extends :class:`HPWM`.
    
    This class need the periphery module to be installed. Also some configuration
    files need to be added to the system. More info in the repo's README.

    Args:
        pin (int): The pin number in bcm mode.

    Raises:
        ImportError: Error if the periphery library is not installed.
    """

    _chip = 0  # PWM chip

    def __init__(self, pin):
        # Check if the pin is valid
        super(HPWMPeriphery, self).__init__(pin)

        if PWM is None:
            raise ImportError("Failed to import PWM from periphery.")

        self._pwm = PWM(self._chip, self._SELECTED_COMB.index(pin))

    def read(self):
        """Read from hardware pwm pin.
        
        Returns:
            float: The duty cycle of the pwm pin.
        """

        return self.duty_cycle

    def write(self, value):
        """Write to the pwm pin.
        
        Args:
            value (float): The new duty cycle value.
        """

        self.duty_cycle = value

    def close(self):
        self.enable = 0

    def _get_frequency(self):
        return self._pwm.frequency

    def _set_frequency(self, frequency):
        "Ugly solution to sysf permission error"
        try:
            self._pwm.frequency = frequency
        except PermissionError:
            sleep(0.1)
            self._pwm.frequency = frequency

    def _get_duty_cycle(self):
        return self._pwm.duty_cycle

    def _set_duty_cycle(self, duty_cycle):
        self._pwm.duty_cycle = duty_cycle

    def _get_enable(self):
        return self._enable

    def _set_enable(self, enable):
        #self._pwm.enable = enable
        self._enable = enable
        if self._enable:
            self._pwm.enable()
        else:
            self._pwm.disable()

    def _get_polarity(self):
        pass

    def _set_polarity(self, polarity):
        pass
Пример #6
0
class PERIPHERY_PWM(PERIPHERY):
    """
    PWM出力ピンを表すクラス。
    指定ピンがハードウェアPWMに対応しない場合は、疑似PWMとして操作する。
    """
    def __init__(self, pin, freq=None, range=None, threshold=0.01, debug=False):
        """
        親クラスのコンストラクタ処理後、指定のピンに対しPWM出力ピンとして設定を行う。
        初期値としてPWMサイクル値をゼロに指定する。
        引数:
            pin     int     PWM番号、必須(1~3)
            freq    int     PWM Frequency値(Hz)
            range   int     PWMサイクル値の範囲(25から40,000までの整数)
            threshold   float   入力値を0として認識するしきい値(-threshold < value< threshold => 0)
        """
        super().__init__(pin, mode=OUT, debug=debug)
        self.freq = freq or DEFAULT_FREQ
        self.threshold = threshold
        if self.pin == 1:
            self.chip_number = 0
            self.channel_number = 0
        elif self.pin == 2:
            self.chip_number = 1
            self.channel_number = 0
        elif self.pin == 3:
            self.chip_number = 2
            self.channel_number = 0
        else:
            raise ValueError('[PERIPHERY_PWM] pwm:{} is out of range(1.. 3)'.format(str(self.pin)))
        try:
            from periphery import PWM
        except ImportError:
            exit('[PERIPHERY_PWM] This code requires periphery package')
        self.gpio = PWM(self.chip_number, self.channel_number)
        self.gpio.frequency = self.freq
        self.gpio.duty_cycle = 0
        self.gpio.enable()
        self.run(0)
        if self.debug:
            print('[PERIPHERY_PWM] pwm:{} set freq:{}/dutycycle:{}, enabled and set value 0'.format(
                str(self.pin), str(self.freq), str(self.gpio.duty_cycle)))

    def run(self, input_value):
        """
        引数で渡されたpulse値をPWMサイクル値に変換し、指定ピンへ出力する。
        引数:
            input_value float       コントローラ/AIからの入力値
        戻り値:
            なし
        """
        cycle = self.to_duty_cycle(input_value)
        self.gpio.duty_cycle(cycle)
        if self.debug:
            print('[PERIPHERY_PWM] pwm:{} set cycle {}(input_value:{})'.format(
                str(self.pin), str(cycle), str(input_value)))


    def to_duty_cycle(self, input_value):
        """
        コントローラ/AIからの入力値をPWMサイクル値に変換する。
        しきい値範囲内の場合やNoneの場合は、0として扱う。
        引数:
            input_value     float   コントローラ/AIからの入力値(None含む)
        戻り値:
            cycle           float     PWM duty_cycle値
        """
        if input_value is None or (abs(float(input_value)) < self.threshold):
            if self.debug:
                print('[PERIPHERY_PWM] gpio:{} input_value None to zero'.format(str(self.pin)))
            return float(0)
        input_value = abs(input_value)
        if input_value >= 1.0:
            return float(1.0)
        return float(input_value)
    
    def shutdown(self):
        self.run(0)
        self.gpio.disable()
        if self.debug:
            print('[PERIPHERY_PWM] set duty_cycle to 0 and disabled')
        super().shutdown()