Skip to content

Instantly share code, notes, and snippets.

@Tamakichi
Last active January 14, 2017 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tamakichi/f96697697d443e8884fe13ed294b1b07 to your computer and use it in GitHub Desktop.
Save Tamakichi/f96697697d443e8884fe13ed294b1b07 to your computer and use it in GitHub Desktop.
Arduini STM32でPWMを使った音出し(tone()、notone())
/*
* Arduino STN32
* Stm32ボード(STM32F103C8T6)で PWMで任意の周波数を生成する
* 作成日 2017/01/17 by たま吉さん
*
* 説明
* ・PB9端子の圧電スピーカーを接続することで任意の周波数を音を出す
* ・Timer4 チャンネル 4 を利用しているため、PWM出力ピンはPB9固定
*
* 参考にした情報
* ・Topic: DUE PWM Frequency (Read 51962 times)
* https://forum.arduino.cc/index.php?topic=131323.15
*
* サンプル作成に参考にしたサイト
* ・Arduinoで童謡「鯉のぼり」を流してみよう
* http://mag.switch-science.com/2015/04/29/gwprojact_koinobori/
*/
//
// 音出し
// 引数
// pin : PWM出力ピン (現状はPB9固定)
// freq : 出力周波数 (Hz) 15~ 50000
// duration: 出力時間(msec)
//
const int pwmOutPin = PB9; // PWM出力ピン
void _tone(uint8_t pin, uint16_t freq, uint16_t duration = 0) {
if (freq < 15 || freq > 50000 ) {
_notone(pin);
} else {
uint32_t f =1000000/(uint16_t)freq;
Timer4.setPrescaleFactor(72); // システムクロックを1/72に分周
Timer4.setOverflow(f);
Timer4.refresh();
Timer4.resume();
pwmWrite(pin, f/2);
if (duration) {
delay(duration);
Timer4.pause();
}
}
}
//
// 音の停止
// 引数
// pin : PWM出力ピン (現状はPB9固定)
//
void _notone(uint8_t pin) {
Timer4.pause();
}
//HardwareTimer pwmtimer(2);
#define PIN pwmOutPin
void setup() {
pinMode(pwmOutPin, PWM);
_tone(pwmOutPin,440, 100);
_tone(pwmOutPin,880,100);
delay(500);
_tone(PIN, 330, 150);
delay(150);
_tone(PIN, 294, 150);
delay(150);
_tone(PIN, 262, 300);
delay(300);
_tone(PIN, 294, 300);
delay(300);
_tone(PIN, 330, 300);
delay(300);
_tone(PIN, 440, 300);
delay(300);
_tone(PIN, 392, 150);
delay(300);
_tone(PIN, 330, 150);
delay(150);
_tone(PIN, 330, 150);
delay(150);
_tone(PIN, 330, 300);
delay(300);
_tone(PIN, 294, 150);
delay(150);
_tone(PIN, 262, 150);
delay(150);
_tone(PIN, 294, 300);
}
void loop() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment