带 LED 通道的 Arduino
arduino with led channel
我这里有一个代码可以来回转动伺服电机,我想在伺服电机转动时添加闪烁的 LED。我该如何申请?
here's the code
#include <Servo.h>
int pos = 0;
Servo servo_9;
void setup()
{
servo_9.attach(9, 500, 2500);
pinMode(13, OUTPUT);
}
void loop()
{
blink();
for (pos = 0; pos <= 180; pos++) {
servo_9.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos--) {
servo_9.write(pos);
delay(15);
}
}
void blink() {
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
假设您想将闪烁速度保持在 100 毫秒,您可以这样做:
#include <Servo.h>
int pos = 0;
Servo servo_9;
const unsigned long BLINK_DELAY = 100 ;
unsigned long blink_time = 0 ;
bool led_on = false ;
void setup()
{
servo_9.attach(9, 500, 2500);
pinMode(13, OUTPUT);
}
void loop()
{
start_blink();
for (pos = 0; pos <= 180; pos++) {
servo_9.write(pos);
delay(15);
blink();
}
stop_blink();
delay(2000);
start_blink();
for (pos = 180; pos >= 0; pos--) {
servo_9.write(pos);
delay(15);
blink();
}
stop_blink();
}
void start_blink() {
digitalWrite(13, HIGH);
led_on = true ;
blink_time = millis() + BLINK_DELAY ;
}
void stop_blink() {
digitalWrite(13,LOW);
led_on = false ;
}
void blink() {
if ( millis() > blink_time ) {
led_on = !led_on ;
digitalWrite(13, led_on ? HIGH : LOW);
blink_time = millis() + BLINK_DELAY ;
}
}
这使用标志 led_on
在 LED 开和关之间切换,并使用时间变量 blink_time
来决定 LED 何时需要切换。 BLINK_DELAY
控制闪烁的速度。
我这里有一个代码可以来回转动伺服电机,我想在伺服电机转动时添加闪烁的 LED。我该如何申请?
here's the code
#include <Servo.h>
int pos = 0;
Servo servo_9;
void setup()
{
servo_9.attach(9, 500, 2500);
pinMode(13, OUTPUT);
}
void loop()
{
blink();
for (pos = 0; pos <= 180; pos++) {
servo_9.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos--) {
servo_9.write(pos);
delay(15);
}
}
void blink() {
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
假设您想将闪烁速度保持在 100 毫秒,您可以这样做:
#include <Servo.h>
int pos = 0;
Servo servo_9;
const unsigned long BLINK_DELAY = 100 ;
unsigned long blink_time = 0 ;
bool led_on = false ;
void setup()
{
servo_9.attach(9, 500, 2500);
pinMode(13, OUTPUT);
}
void loop()
{
start_blink();
for (pos = 0; pos <= 180; pos++) {
servo_9.write(pos);
delay(15);
blink();
}
stop_blink();
delay(2000);
start_blink();
for (pos = 180; pos >= 0; pos--) {
servo_9.write(pos);
delay(15);
blink();
}
stop_blink();
}
void start_blink() {
digitalWrite(13, HIGH);
led_on = true ;
blink_time = millis() + BLINK_DELAY ;
}
void stop_blink() {
digitalWrite(13,LOW);
led_on = false ;
}
void blink() {
if ( millis() > blink_time ) {
led_on = !led_on ;
digitalWrite(13, led_on ? HIGH : LOW);
blink_time = millis() + BLINK_DELAY ;
}
}
这使用标志 led_on
在 LED 开和关之间切换,并使用时间变量 blink_time
来决定 LED 何时需要切换。 BLINK_DELAY
控制闪烁的速度。