int brightness = 0; //定义整数型变量brightness与其初始值,此变量用来表示LED的亮度
int fadeAmount = 5; //定义整数型变量fadeAmount,此变量用来做亮度变化的增减量
int val = 0;
void setup() {
Serial.begin(9600);// 设置串口波特率
pinMode(0, INPUT);// 设置3号模拟口为输入端口
pinMode(6, OUTPUT);// 设置6号数字口为输出端口
}
void loop() {
val = analogRead(0);
Serial.print(val);
Serial.println();
if (val > 20) {
analogWrite(6, brightness);//把brightness的值写入6号端口
brightness = brightness + fadeAmount;//改变brightness值,使亮度在下一次循环发生改变
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ; //在亮度最高与最低时进行翻转
}
delay(30); //延时30毫秒
}
else
{
digitalWrite(6, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100); // wait for a second
digitalWrite(6, LOW); // turn the LED off by making the voltage LOW
delay(100); // wait for a second
}
}