Tone generation using PWM



  • My routine is:

    def Tone(Speaker, Frequency, Duration):
        pwm = PWM(0, frequency = Frequency)
        pwm = pwm.channel(0, pin=Speaker, duty_cycle = 0.5)
        sleep_ms(Duration)
    

    Calling it with:

    Tone(Speaker, 800, 1000)
    

    How do I stop the Tone after the delay?

    This routine on the Esp8266 worked:

    def Tone(Speaker, Frequency, Duration):
        pwm = PWM(Pin(Speaker))
        pwm.freq(Frequency)
        pwm.duty(500)
        sleep_ms(Duration)
        pwm.deinit()
    


  • Actually this is a better fix, the previous fix left the Speaker pin High and using power, this leaves it Low.

    def Tone(Speaker, Frequency, Duration):
        pwm = PWM(0, frequency = Frequency)
        pwm = pwm.channel(0, pin=Speaker, duty_cycle = 0.5)
        sleep_ms(Duration)
        i = Pin(Speaker, mode=Pin.IN)
    

    I seem to be talking to myself a lot !!?? Anyone else around?



  • I'm answering my own query again but a workaround that I found is this:

    def Tone(Speaker, Frequency, Duration):
        pwm = PWM(0, frequency = Frequency)
        pwm = pwm.channel(0, pin=Speaker, duty_cycle = 0.5)
        sleep_ms(Duration)
        pwm = PWM(0, frequency = 4000)
    

    Setting the PWM frequency to >3999Hz kills the output. Must be a more elegant way though.


Log in to reply
 

Pycom on Twitter