0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【個人的備忘録】Arduino Unoのレジスタに直接アクセスしてPWMしてみた

Posted at

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?