Serial

Example 1: On-board LEDs Control with Serial

#include "mbed.h"              
 
Serial     pc(USBTX, USBRX);
DigitalOut ledA(LED1);
DigitalOut ledB(LED2);
DigitalOut ledC(LED3);
DigitalOut ledD(LED4);
char       cmd;

int main() {
    pc.printf("Lighting Management System\n");
    while(1) {
        if (pc.readable()) {
        	cmd = pc.getc();
        	switch (cmd) {
        		case 'A': ledA = 1; break;
        		case 'B': ledB = 1; break;
        		case 'C': ledC = 1; break;
        		case 'D': ledD = 1; break;
        		case 'a': ledA = 0; break;
        		case 'b': ledB = 0; break;
        		case 'c': ledC = 0; break;
        		case 'd': ledD = 0; break;
        	}
        }
    }
}

Example 2: On-board LEDs Control with Serial

#include "mbed.h"

DigitalOut  Led1(LED1);
DigitalOut  Led2(LED2);
DigitalOut  Led3(LED3);
DigitalOut  Led4(LED4);

Serial pc(USBTX, USBRX); // tx, rx
char   ch;

int main() {
    pc.printf("Lighting Control Program!\r\n");
    pc.printf("Press <n> to toggle LED <n>\r\n");
    while (1) {
        ch = pc.getc();
        if (ch == '1') Led1 = !Led1;
        else if (ch == '2') Led2 = !Led2;
        else if (ch == '3') Led3 = !Led3;
        else if (ch == '4') Led4 = !Led4;
    }
}

Example 3: On-board LEDs Control with Serial and Automatic Switch Off

#include "mbed.h"

DigitalOut  Led1(LED1);
DigitalOut  Led2(LED2);
DigitalOut  Led3(LED3);
DigitalOut  Led4(LED4);
Timeout     TimerInterrupt;

void SwitchOff() { Led1 = Led2 = Led3 = Led4 = 0;}

Serial pc(USBTX, USBRX); // tx, rx
char   ch;

int main() {
    pc.printf("Lighting Control Program!\r\n");
    pc.printf("Press <n> to toggle LED <n>\r\n");
    while (1) {
        ch = pc.getc();
        if      (ch == '1') Led1 = !Led1;
        else if (ch == '2') Led2 = !Led2;
        else if (ch == '3') Led3 = !Led3;
        else if (ch == '4') Led4 = !Led4;
        else if (ch == 'a' || ch == 'A') {Led1 = Led2 = Led3 = Led4 = 1;}
        else if (ch == 'z' || ch == 'Z') {Led1 = Led2 = Led3 = Led4 = 0;}

        if (Led1 || Led2 || Led3 || Led4)
            TimerInterrupt.attach(&SwitchOff, 5.0);
    }
}


1 comment on Serial:

03 Dec 2017

Hi,

Great series of programs. They work with my BBC micro:bit. LED1 to pin 0, LED2 to pin 1, LED 3 to pin 2 and LED4 to pin 16.

Many thanks,

Gary

Please log in to post comments.