Home > Net >  arduino with led channel
arduino with led channel

Time:05-01

I have a code here that turn servo motor back and forth and i want to add blinking led while servo motor is turning. How do i apply it?

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);
}

CodePudding user response:

Presuming you want to keep the blink speed at 100ms you could do something like this:

#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 ;
  }
}

This uses a flag led_on to toggle between the LED being on and off and a time variable blink_time to decide when the LED needs to toggle. BLINK_DELAY controls the speed of the blinking.

  •  Tags:  
  • perl
  • Related