编写至少四个LED不同亮度同时出现 编写利用定时器产生不同占空比的PWM控制单个LED的呼吸灯效果(亮度从最亮到灭,再从灭到最亮) 分别用两个按键控制1只高亮的LED亮度从亮到灭和从灭到亮
时间: 2024-02-16 07:02:59 浏览: 104
1. 编写至少四个LED不同亮度同时出现:
```c
#include <stdio.h>
#include <wiringPi.h>
#define LED_PIN_1 0
#define LED_PIN_2 1
#define LED_PIN_3 2
#define LED_PIN_4 3
int main(void)
{
if (wiringPiSetup() == -1)
{
return 1;
}
pinMode(LED_PIN_1, OUTPUT);
pinMode(LED_PIN_2, OUTPUT);
pinMode(LED_PIN_3, OUTPUT);
pinMode(LED_PIN_4, OUTPUT);
digitalWrite(LED_PIN_1, HIGH);
delay(100);
digitalWrite(LED_PIN_2, HIGH);
delay(100);
digitalWrite(LED_PIN_3, HIGH);
delay(100);
digitalWrite(LED_PIN_4, HIGH);
delay(100);
digitalWrite(LED_PIN_1, LOW);
delay(100);
digitalWrite(LED_PIN_2, LOW);
delay(100);
digitalWrite(LED_PIN_3, LOW);
delay(100);
digitalWrite(LED_PIN_4, LOW);
delay(100);
return 0;
}
```
2. 编写利用定时器产生不同占空比的PWM控制单个LED的呼吸灯效果:
```c
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
#define LED_PIN 0
#define PWM_RANGE 100
int main(void)
{
if (wiringPiSetup() == -1)
{
return 1;
}
pinMode(LED_PIN, OUTPUT);
softPwmCreate(LED_PIN, 0, PWM_RANGE);
int i;
while (1)
{
for (i = 0; i <= PWM_RANGE; i++)
{
softPwmWrite(LED_PIN, i);
delay(5);
}
for (i = PWM_RANGE; i >= 0; i--)
{
softPwmWrite(LED_PIN, i);
delay(5);
}
}
return 0;
}
```
3. 用两个按键控制1只高亮的LED亮度从亮到灭和从灭到亮:
```c
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
#define LED_PIN 0
#define PWM_RANGE 100
#define BUTTON_UP 1
#define BUTTON_DOWN 2
int main(void)
{
if (wiringPiSetup() == -1)
{
return 1;
}
pinMode(LED_PIN, OUTPUT);
softPwmCreate(LED_PIN, 0, PWM_RANGE);
pinMode(BUTTON_UP, INPUT);
pinMode(BUTTON_DOWN, INPUT);
int brightness = 0;
int direction = 1;
while (1)
{
if (digitalRead(BUTTON_UP) == LOW)
{
brightness++;
if (brightness > PWM_RANGE)
{
brightness = PWM_RANGE;
}
softPwmWrite(LED_PIN, brightness);
delay(10);
}
else if (digitalRead(BUTTON_DOWN) == LOW)
{
brightness--;
if (brightness < 0)
{
brightness = 0;
}
softPwmWrite(LED_PIN, brightness);
delay(10);
}
else
{
if (direction == 1)
{
brightness++;
if (brightness >= PWM_RANGE)
{
direction = -1;
}
}
else
{
brightness--;
if (brightness <= 0)
{
direction = 1;
}
}
softPwmWrite(LED_PIN, brightness);
delay(10);
}
}
return 0;
}
```
在这个例子中,我们使用了两个按键来控制 LED 的亮度变化。一个按键用来增加亮度,另一个用来减小亮度。同时,LED 也会呼吸灯效果地变化。我们使用了一个 `direction` 变量来控制 LED 的亮度变化方向。
阅读全文