这个例子展示了读取模拟脚输入,映射结果到0-255的范围,把读取结果以PWM输出来点亮LED。
/* 读取模拟输入,映射结果到0-255,用映射值通过PWM点亮LED,显示结果到串口监视器上。 */ const int analogInPin = A0; // 设置引脚: const int analogOutPin = 9; int sensorValue = 0; // 电位器值 int outputValue = 0; // PWM模拟输出值 void setup() { Serial.begin(9600); // 初始化串口通讯为9600波特率 } void loop() { sensorValue = analogRead(analogInPin); // 读取模拟输入 outputValue = map(sensorValue, 0, 1023, 0, 255); // 映射 analogWrite(analogOutPin, outputValue); // 输出: Serial.print("sensor = " ); // 显示到串口 Serial.print(sensorValue); Serial.print("\t output = "); Serial.println(outputValue); delay(2); // 等待两毫秒秒让模数转换器稳定 }