Blinking a physical LED with a virtual button

Hello there,
I wonder why I am not able to blink an LED connected to digital pin 9 by a virtual button (10)?

Code:

BLYNK_WRITE(10)
{
  digitalWrite(9, HIGH);
}

I know I can do it directly by placing the button on digital pin 9 though I want to know why I can’t do it this way.
And please, how do I control a virtual LED by a virtual button? Can you provide me with the code?
Thank you :slight_smile:

@zaid_riadh

Have you specified pinMode for pin 9? In case you do direct mapping pin->widget it is done automatically, but in your case you need to that manually for pin 9.

No :
I will try it now :smile:

@Dmitriy
Thank you :smile: it worked, but when I pressed the vitual button the physical LED turned on and kept on even after turning off the button :\ why is that?

why is that?

Cause you do only

digitalWrite(9, HIGH);

See this sketch

Or briefly :

BLYNK_WRITE(10)
{
if (param.asInt()) {
digitalWrite(9, HIGH);
} else {
digitalWrite(9, LOW);
}
}

3 Likes

@Dmitriy
used this trick though I think yours is better;
int x = 0;

x = 1-x;
Blynk.virtualWrite(9, x);

I will try what you recommeded
Thank you :slight_smile:

1 Like

@Dmitriy
Last thing sir, what if I wanted to fade it using a slider?
Can you provide code?
Thanks

BLYNK_WRITE(10)
{
   analogWrite(9, param.asInt());
}

The slider value should go from 0 to 255

Editet the 256, 255 is the correct value and digitalWrite

2 Likes

@twobe, shouldn’t the be analogWrite(9, param.asInt());?

2 Likes

No, the LED is connected to the digital, not the analog port.

@zaid_riadh, I must be missing something then. How is the slider supposed to dim the LED if the pin is not using PWM?

@peekay123
Pin 9 IS using the PWM.

@peekay123 you’re right. It must be analogWrite

@zaid_riadh you can use analogwrite on some digital Pins to use pulse width modulation. You can find more about that if you google pwm.

@twobe
Can you give more explanation?
Do you mean that I can use both digitalWrite and analogWrite to fade a LED connected to digital pin 9?

If you are using digitalWrite you can only turn the led on and off. With analogWrite you can fade the led.

@twobe
even if the LED is connected to the digital port?
And can I turn it on and off with analogWrite?
I am really confused now :confused:
Thank you

@zaid_riadh what board are running Blynk on?

@peekay123
Arduino Uno

On the Uno pin 9 can be both a pure digital input or output pin OR a PWM output pin. The function depends on how you set pinMode () and what function you use - digitalRead ()/Write () or analogWrite (). Since you want PWM output to control the brightness of your LED, analogWrite () is what you want to use.

1 Like

@peekay123
Thank you :smile: I really got it now.

1 Like