6 ways to blink the built-in Led

From Pinguino-Wiki
Jump to: navigation, search

Here are 6 ways to blink the built-in Led (USERLED) on a Pinguino board.

The User Led is connected to pin :

  • Microchip Pin Designation : pin #2 or RA0 (bit 0 of PORT A)
  • Pinguino Pin Designation : pin #13 (aka D13)

(it could be another pin on some Pinguino boards)

Contents

Example 1 : with PIC registers

void setup()
{
    // declare pin RA0 as an Output
    TRISAbits.TRISA0 = OUTPUT; 
}
 
void loop()
{
    LATAbits.LATA0 = LOW;
    delay(50);   // wait for 50 ms
    LATAbits.LATA0 = HIGH;
    delay(50);   // wait for 50 ms
}

Or (only for PIC32MX)

void setup()
{
    // declare pin RA0 as an Output
    TRISACLR = 1; // (bit 0 set to 1)
}
 
void loop()
{
    LATACLR = 1; // (bit 0 set to 1)
    delay(50);   // wait for 50 ms
    LATASET = 1; // (bit 0 set to 1)
    delay(50);   // wait for 50 ms
}

Example 2 : the Arduino way

void setup()
{
    pinMode(USERLED, OUTPUT);
}
 
void loop()
{
    digitalWrite(USERLED, LOW);
    delay(50);
    digitalWrite(USERLED, HIGH);
    delay(50);
}

Example 3 : even simpler ?

void setup()
{
    pinMode(USERLED, OUTPUT);
}
 
void loop()
{
    toggle(USERLED);
    delay(50);
}

Example 4 : using an interrupt

void blink()
{
    toggle(USERLED);
}
 
void setup()
{
    pinMode(USERLED,OUTPUT);
 
    // Use Timer1 to toggle USERLED every 1000 ms
    OnTimer1(blink, INT_MILLISEC, 1000);
}
 
void loop()
{
    // your code here
}

Example 5 : using the watchdog timer

The Watchdog, when enabled, operates from the 32kHz internal Low-Power Oscillator (LPRC) clock source and can be used to detect system software malfunctions by resetting the device if the Watchdog is not cleared periodically in software. The Watchdog can also be used to wake the device from Sleep or Idle mode. The Watchdog time-out period is set to 1ms.

void setup()
{
    pinMode(USERLED, OUTPUT);
    // The Watchdog timer is disabled by default
    // after any device Reset, so we have to start it
    Watchdog.enable();
}
 
void loop()
{
    u32 counter;
 
    // Service the Watchdog
    Watchdog.clear();
    // Put device into sleep mode
    System.sleep();
 
    // code execution will resume here after wake
    counter++;
    if (counter > 1000)
        toggle(USERLED);
}

Example 6 : using the built-in user button

void setup()
{
    pinMode(USERLED, OUTPUT);      
    pinMode(USERBUTTON, INPUT);     
}
 
void loop()
{
    u8 state = digitalRead(USERBUTTON);
 
    if (state == LOW)
    {     
        digitalWrite(USERLED, HIGH);  
    } 
    else
    {
        digitalWrite(USERLED, LOW); 
    }
}
Personal tools