Bluetooth serial communication example

Dependencies:   mbed

main.cpp

Committer:
dralisz82
Date:
2017-09-18
Revision:
0:d511d7e52cd8

File content as of revision 0:d511d7e52cd8:

#include "mbed.h"

DigitalOut red(LED_RED);
DigitalOut green(LED_GREEN);
DigitalOut blue(LED_BLUE);

Serial pc(USBTX, USBRX);  // USB serial via debugger
Serial BT(PTC15, PTC14);  // Bluetooth module header

char color;

/**
 * UART Interrupt handler
 */
void gotChar() {
    char c = BT.getc(); // read incoming character
    pc.putc(c); // forward to debug serial
    
    // interpret received character as a command to switch color
    if(c == 'r' || c == 'g' || c == 'b')
        color = c;
}

/**
 * Main thread
 */
int main()
{
    red = 1; green = 1; blue = 1; // turn off all LEDs
    color = 'r'; // red is initial
    
    // initialization
    BT.baud(9600); // HC-05 module works at this rate by default
    pc.printf("Hello World!\n");
    BT.printf("Hello World!\n");
    BT.attach(&gotChar); // register interrupt handler
    
    // main program loop
    while (true) {
        wait(0.5f); // wait half second
        if(color == 'r') {
            red = !red; // toggle red
            green = 1; blue = 1; // turn off other 2 colors
        }
        if(color == 'g') {
            green = !green; // toggle green
            red = 1; blue = 1; // turn off other 2 colors
        }
        if(color == 'b') {
            blue = !blue; // toggle blue
            red = 1; green = 1; // turn off other 2 colors
        }
    }
}