Led heart beat by changing brightness

Hi all, here a rookie question.

I want to create a hear beat by changing the brightness of a led.
But something goes wrong in my code.

It looks like it's still sends out high or low instead of a pwm value between 0 and 255.

It's a loop of 8 stages:

50% brightness 750 ms
75 % birghtness 25 ms
100 % brightness 25 ms
75 % birghtness 25 ms
50% brightness 67 ms
75 % birghtness 25 ms
100 % brightness 25 ms
75 % birghtness 25 ms

What do I miss and what's the right code?

Thanx.

Cristian

Down below the code:

const int redled = A1;

void setup(){
    pinMode(redled, OUTPUT);
}

void loop(){
    analogWrite(redled, 127); // brightness 50%
    delay(750);
    
    analogWrite(redled, 191); // brightness 75%
    delay(25);
    
    analogWrite(redled, 255); // brightness 100%
    delay(25);
    
    analogWrite(redled, 191); // brightness 75%
    delay(25);
    
    analogWrite(redled, 127); // brightness 50%
    delay(67);
    
    analogWrite(redled, 191); // brightness 75%
    delay(25);
    
    analogWrite(redled, 255); // brightness 100%
    delay(25);
    
    analogWrite(redled, 191); // brightness 75%
    delay(25);
    
}

You can only use analogWrite on certain pins.
A1 is not one of the ones used, unless you have an Arduino Zero - (you didn't tell us what Arduino you are using).

For details of which pins you can use see:
https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

Hi John,

I'm using an Arduino Uno.
Changed the pin and now it works's thanx.

Cristian

Hi Cristian,
Good to hear that you got it working.

Now improve it by making it data driven rather than using fixed program steps

const int redled = 3;

struct dataFormat
{
    byte brightness;
    int period;
};

dataFormat ledData[] = {
    { 127, 750 },   //brightness and delay period for each step
    { 191, 25 },
    { 255, 25 },
    { 191, 25 },
    { 127, 67 },
    { 191, 25 },
    { 255, 25 },
    { 191, 25 }
};

const byte STEPCOUNT = sizeof(ledData) / sizeof(ledData[0]);  //calculate number of steps

void setup()
{
    pinMode(redled, OUTPUT);
}

void loop()
{
    for (int step = 0; step < STEPCOUNT; step++)
    {
        analogWrite(redled, ledData[step].brightness);
        delay(ledData[step].period);
    }
}

cool, thanx (-:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.