Created
June 18, 2026 18:21
-
-
Save arpruss/09b2c50ab1f0b6750e80695c651c8b90 to your computer and use it in GitHub Desktop.
blue pill sound
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int pos = 0; // 8; uncompressed | |
| unsigned shift = 0; | |
| int channel; | |
| int channel2; | |
| timer_dev* dev; | |
| HardwareTimer interruptTimer(2); | |
| void handler() { | |
| timer_set_compare(dev, channel, sound[pos]); | |
| pos+=1; | |
| if (pos >= sizeof(sound)) | |
| pos = 8; | |
| } | |
| const int32_t deltaTable[] = {-20, -5, 5, 20}; | |
| int32_t predicted = 0x80; | |
| const uint32_t mask=3; | |
| const uint32_t bits=2; | |
| void handlerCompressed() { | |
| // Extract 2 bits (Right-justified / Little Endian) | |
| int32_t code = (compressed[pos] >> shift) & mask; | |
| predicted += deltaTable[code]; | |
| if (predicted < 0) | |
| predicted = 0; | |
| else if (predicted > 255) | |
| predicted = 255; | |
| shift += bits; | |
| if (shift >= 8) { | |
| shift = 0; | |
| pos++; | |
| if (pos >= sizeof(compressed)) { | |
| pos = 0; | |
| predicted = 0x80; | |
| } | |
| } | |
| timer_set_compare(dev, channel, predicted); | |
| timer_set_compare(dev, channel2, predicted); | |
| } | |
| static void pwm_mode(timer_dev *dev, uint8 channel, bool reversed) { | |
| timer_disable_irq(dev, channel); | |
| timer_set_mode(dev,channel, TIMER_PWM ); | |
| timer_oc_set_mode(dev, channel, reversed?TIMER_OC_MODE_PWM_2:TIMER_OC_MODE_PWM_1, TIMER_OC_PE); | |
| timer_cc_enable(dev, channel); | |
| } | |
| uint32_t pin = PA8; | |
| uint32_t pin2 = PA9; | |
| void setup() { | |
| dev = PIN_MAP[pin].timer_device; | |
| channel = PIN_MAP[pin].timer_channel; | |
| channel2 = PIN_MAP[pin2].timer_channel; | |
| gpio_set_mode(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit, GPIO_AF_OUTPUT_PP); | |
| gpio_set_mode(PIN_MAP[pin2].gpio_device, PIN_MAP[pin2].gpio_bit, GPIO_AF_OUTPUT_PP); | |
| pwm_mode(dev, PIN_MAP[pin].timer_channel, false); | |
| pwm_mode(dev, channel2, true); | |
| // timer_cc_set_pol(dev, PIN_MAP[pin].timer_channel, 0); | |
| // timer_cc_set_pol(dev, PIN_MAP[pin2].timer_channel, 1); | |
| timer_set_prescaler(dev, 0); | |
| timer_set_reload(dev, 256); | |
| interruptTimer.pause(); | |
| interruptTimer.setPeriod(1000000/(15360)); | |
| interruptTimer.attachInterrupt(TIMER_CH1, handlerCompressed); | |
| interruptTimer.refresh(); | |
| interruptTimer.resume(); | |
| } | |
| void loop() { | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment