|
34 | 34 | import digitalio |
35 | 35 | import pulseio |
36 | 36 |
|
37 | | -def tone(pin, frequency, duration=1): |
| 37 | +def tone(pin, frequency, duration=1, length=100): |
38 | 38 | """ |
39 | | - Generates a square wave of the specified frequency (50% duty cycle) |
40 | | - on a pin |
| 39 | + Generates a square wave of the specified frequency on a pin |
41 | 40 |
|
42 | 41 | :param ~microcontroller.Pin Pin: Pin on which to output the tone |
43 | | - :param int frequency: Frequency of tone in Hz |
| 42 | + :param float frequency: Frequency of tone in Hz |
| 43 | + :param int length: Variable size buffer (optional) |
44 | 44 | :param int duration: Duration of tone in seconds (optional) |
45 | 45 | """ |
46 | 46 | try: |
47 | | - length = 4000 // frequency |
48 | | - square_wave = array.array("H", [0] * length) |
49 | | - for i in range(length): |
50 | | - if i < length / 2: |
51 | | - square_wave.append(0xFFFF) |
52 | | - else: |
53 | | - square_wave.append(0x00) |
54 | | - with audioio.AudioOut(pin, square_wave) as waveform: |
55 | | - waveform.play(loop=True) |
56 | | - time.sleep(duration) |
57 | | - waveform.stop() |
58 | | - except (NameError, ValueError): |
59 | | - with pulseio.PWMOut(pin, frequency=frequency, variable_frequency=False) as pwm: |
| 47 | + with pulseio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm: |
60 | 48 | pwm.duty_cycle = 0x8000 |
61 | 49 | time.sleep(duration) |
| 50 | + except ValueError: |
| 51 | + sample_length = length |
| 52 | + square_wave = array.array("H", [0] * sample_length) |
| 53 | + for i in range(sample_length / 2): |
| 54 | + square_wave[i] = 0xFFFF |
| 55 | + sample_tone = audioio.AudioOut(pin, square_wave) |
| 56 | + sample_tone.frequency = int(len(square_wave) * frequency) |
| 57 | + if not sample_tone.playing: |
| 58 | + sample_tone.play(loop=True) |
| 59 | + time.sleep(duration) |
| 60 | + sample_tone.stop() |
| 61 | + |
| 62 | + |
62 | 63 |
|
63 | 64 | def bitWrite(x, n, b): #pylint: disable-msg=invalid-name |
64 | 65 | """ |
|
0 commit comments