[Analog I/O]
描述
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()
或 digitalWrite()
on the same pin). On the 86Duino, the frequency of the PWM signal is 1000 Hz.
On the 86Duino Zero, this function works on pins 3, 5, 6, 9, 10, 11, and 13. On the 86Duino EduCake, it works on pins 3, 5, 6, 9, 10, 11, 13, 31, and 32. On the 86Duino One, it works on pins 3, 5, 6, 9, 10, 11, 13, 29, 30, 31, and 32. On the 86Duino PLC, it works on pins 1, 3, 4, 7.
You do not need to call pinMode()
to set the pin as an output before calling analogWrite()
.
The analogWrite function has nothing to do with the analog input pins or the analogRead function.
語法
analogWrite(pin, value)
參數
pin
: the pin to write to.value
: the duty cycle – between 0 (always off) and 255 (always on) by default.
You can call analogWriteResolution()
to set a higher PWM resolution.
回傳
nothing
範例程式碼
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 }
參考
- [程式語法] analogRead()
- [程式語法] analogWriteResolution()
- [Example] Tutorial: PWM
語法參考主頁面
86Duino 參考的文本是根據 Creative Commons Attribution-ShareAlike 3.0 License,部分文本是從 the Arduino reference 修改的。 參考中的代碼示例已發佈到公共領域。