Skip to content

Instantly share code, notes, and snippets.

@Measter
Created June 5, 2020 16:41
Show Gist options
  • Save Measter/f34bcf3e95616b45a351f3d74b8280ad to your computer and use it in GitHub Desktop.
Save Measter/f34bcf3e95616b45a351f3d74b8280ad to your computer and use it in GitHub Desktop.
Tone Prototype
template <class TonePin>
void make_tone(int frequency) {
IO::DigitalOut<TonePin> tonePin;
typename TonePin::TimerChannel channel;
typename TonePin::TimerChannel::Timer timer;
using PrescaleModes = typename TonePin::TimerChannel::Timer::PrescaleModes;
using WaveformModes = typename TonePin::TimerChannel::Timer::WaveformModes;
PrescaleModes mode = PrescaleModes::Stopped;
int ocr = 0;
frequency *= 2;
for (uint8_t i = 0; i < timer.prescale_count; i++) {
ocr = F_CPU / frequency / timer.prescale_values[i] - 1;
if (ocr <= 255) {
// Not exactly safe, but works for the 328p.
mode = static_cast<PrescaleModes>(i+1);
break;
}
}
timer.reset_timer_control();
timer.set_waveform(WaveformModes::CTC_OCRA);
channel.set_output_compare(ocr);
// Connect pin TonePin to timer to toggle on each compare match.
channel.set_mode(Timers::CompareOutputMode::Mode1);
timer.set_prescale(mode);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment