各位大佬,我想用arduino uno做一个led闪亮程序,现在闪亮频率定义为200Hz,亮的时间定义为占空比,通过占空比计算。
同时该程序通过串口接收一个占空比参数,但是为什么我发送1次占空比参数,arduino会自动补发一次占空比为0的参数呢?
向各位大佬求助。
int ledPin = 13;
int dutyCycle = 50; // 默认占空比为50%
int restTime = 1000 / 200 * dutyCycle / 100; // 计算休息时间
int highTime = 5;
void setup()
{
pinMode(ledPin, OUTPUT);
// 开启串口通信
Serial.begin(9600);
Serial.println(F("++++++++++++++++++++++++++++++++++++"));
Serial.println(F("++++++++ Wind motor program ++++++++"));Serial.println(F("++++++++++++++++++++++++++++++++++++"));
Serial.println(F(""));
Serial.println(F("Please input duty cycle (1-100):"));
}
void loop()
{
while (Serial.available())
{
dutyCycle = Serial.parseInt(); // 读取占空比参数
if (dutyCycle >= 0 && dutyCycle <= 100)
{
restTime = 5 * dutyCycle * 10; // 重新计算休息时间
highTime = 5000 - restTime;
Serial.println(F("++++++++++++++++++++++++++++++++++++"));
Serial.print(F("Recived dutyCycle : "));
Serial.print(dutyCycle);
Serial.print(F(" restTime : "));
Serial.print(restTime);
Serial.print(F(" highTime : "));
Serial.println(highTime);
Serial.println(F("++++++++++++++++++++++++++++++++++++"));
}
else
{
Serial.println("Invalid duty cycle. Using default value. 0-100");
}
}
digitalWrite(ledPin, HIGH);
delayMicroseconds(restTime);
digitalWrite(ledPin, LOW);
delayMicroseconds(highTime);
}
当我输入一次50时的反应是这样的:
更多回帖