analogWrite()
Description 介紹
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal is approximately 490 Hz.
將模擬值(PWM波)輸出到管腳。可用於在不同的光線亮度調節發光二極管亮度或以不同的速度驅動馬達。調用analogWrite()后,該引腳將產生一個指定占空比的穩定方波,直到下一次調用analogWrite()(或在同一引腳調用digitalRead()或digitalWrite())。 PWM的信號頻率約為490赫茲。
On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 through 13. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11. You do not need to call pinMode() to set the pin as an output before calling analogWrite().
在大多數Arduino板(帶有ATmega168或ATmega328),這個函數工作在引腳3,5,6,9,10和11。在ArduinoMega,它適用於2-13號引腳。老的帶有ATmega8的Arduino板只支持9,10,11引腳上使用。你並不需要在調用analogWrite()之前為設置輸入引腳而調用pinMode()。
The analogWrite function has nothing whatsoever to do with the analog pins or the analogRead function.
這個analogWrite方法與模擬引腳或者analogRead方法毫不相干
Syntax 語法
analogWrite(pin, value)
Parameters 參數
pin: the pin to write to.
pin:輸出的引腳號
value: the duty cycle: between 0 (always off) and 255 (always on).
value:占用空:從0(常關)到255(常開)
Returns 返回值
nothing
Notes and Known Issues 備注和已知問題
The PWM outputs generated on pins 5 and 6 will have higher-than-expected duty cycles. This is because of interactions with the millis() and delay() functions, which share the same internal timer used to generate those PWM outputs. This will be noticed mostly on low duty-cycle settings (e.g 0 - 10) and may result in a value of 0 not fully turning off the output on pins 5 and 6.
引腳5和6的PWM輸出將產生高於預期的占空比。這是因為millis()和delay()函數,它們共享同一個內部定時器用於產生PWM輸出所產生的相互作用。這提醒我們引腳5和6在多數低占空比的設置(如0- 10)的情況下0數值的結果並沒有完全關閉。
Example 例子
Sets the output to the LED proportional to the value read from the potentiometer.
int ledPin = 9; // LED connected to digital pin 9 int analogPin = 3; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value void setup() { pinMode(ledPin, OUTPUT); // sets the pin as output } void loop() { val = analogRead(analogPin); // read the input pin analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255 }