9番ピンと10番ピンで交互にPWM
const int MOTOR1_PIN = 9;
const int MOTOR2_PIN = 10;
unsigned int PWM_FREQ = 100;
unsigned long CLOCK_FREQ = 16000000; //16MHz
unsigned int RATIO = 256; //分周比256
float duty = 0.8;
unsigned int top_val = CLOCK_FREQ / (2*RATIO*PWM_FREQ);
void setup() {
pinMode(MOTOR1_PIN, OUTPUT);
pinMode(MOTOR2_PIN, OUTPUT);
TCCR1A = 0;
TCCR1B = 0;
}
void loop() {
// 9PinのPWM
// モード(位相・周波数基準PWM + TOP.ICR1: WGM13 WGM12 WGM11 WGM10 = 1 0 0 0)
TCCR1A = 0b10000000;//10:9ピンON 00:10ピンOFF 00:N/A 00:WGM11 WGM10
TCCR1B = 0b00010100; //000:N/A 10:WGM13 WGM12 100:分周比256
// Top値
ICR1 = top_val;
//duty比
OCR1A = (unsigned int)(top_val * duty); //9ピンはOCR1A
delay(5000);
// 10PinのPWM
// モード(位相・周波数基準PWM + TOP.ICR1: WGM13 WGM12 WGM11 WGM10 = 1 0 0 0)
TCCR1A = 0b00100000;//10:9ピンOFF 00:10ピンON 00:N/A 00:WGM11 WGM10
TCCR1B = 0b00010100; //000:N/A 10:WGM13 WGM12 100:分周比256
// Top値
ICR1 = top_val;
//duty比
OCR1B = (unsigned int)(top_val * duty);//10ピンはOCR1B
delay(5000);
}
参考
https://garretlab.web.fc2.com/arduino/inside/hardware/arduino/avr/cores/arduino/wiring_analog.c/analogWrite.html
https://geek.tacoskingdom.com/blog/52#part-h3-1-h2-0
https://usicolog.nomaki.jp/engineering/avr/avrPWM.html
https://ht-deko.com/arduino/portregisters.html