This program demonstrates serial communications and digital output. I have a similar program for the Arduino Uno. The purpose of this program is to compare mbed and Arduino code.

Fork of Serial_ex_2 by mbed_example

This is the corresponding Arduino/Wiring .ino program:

/* Serial2RGB_A

Toggles RGB LED junctions based on characters received via serial connection. Echos characters sent.

Hardware Required:

Arduino (or similar board as written)

Created by Dr. C. S. Tritt

Revision History

16-07-07 v. 1.0 Initial development (on TI MSP432). 17-03-13 v. 1.1 Ported to Arduino boards. 17-03-14 v. 1.2 Added echo of read characters.

  • /

Use defines for pin IDs and other constants

  1. define RED_PIN 9 RED_LED
  2. define GRN_PIN 10 GREEN_LED
  3. define BLU_PIN 11 BLUE_LED
  4. define BAUD 9600 Other settings default to 8-N-1.

char inChar; boolean redState = LOW; boolean grnState = LOW; boolean bluState = LOW;

void setup() { Initialize the pins as an output. Assumes adjacent pins. for (int led = RED_PIN; led <= BLU_PIN; led++) { pinMode(led, OUTPUT); } Initialize serial communication. Serial.begin(BAUD); Set baud rate. }

void loop() { Read serial if available. if (Serial.available() > 0) { get incoming byte: inChar = (char) Serial.read(); Read and convert a value. Serial.print(inChar); Echo what was read. Use it to toggle outputs (LED states) if (inChar == 'r') { redState = !redState; digitalWrite(RED_PIN, redState); } else if (inChar == 'g') { grnState = !grnState; digitalWrite(GRN_PIN, grnState); } else if (inChar == 'b') { bluState = !bluState; digitalWrite(BLU_PIN, bluState); } } }

Committer:
mab5449
Date:
Thu Jan 19 14:23:37 2017 -0600
Revision:
0:8d318218bac1
Child:
1:fdb8ecdf954f
Initial commit. Ported code snippets to mbed OS 5 projects

Who changed what in which revision?

UserRevisionLine numberNew contents of line
mab5449 0:8d318218bac1 1 #include "mbed.h"
mab5449 0:8d318218bac1 2 //K64F
mab5449 0:8d318218bac1 3 Serial pc(USBTX, USBRX); // tx, rx
mab5449 0:8d318218bac1 4 Serial device(MBED_CONF_APP_UART1_TX, MBED_CONF_APP_UART1_RX); // tx, rx
mab5449 0:8d318218bac1 5
mab5449 0:8d318218bac1 6 int main() {
mab5449 0:8d318218bac1 7 while(1) {
mab5449 0:8d318218bac1 8 if(pc.readable()) {
mab5449 0:8d318218bac1 9 device.putc(pc.getc());
mab5449 0:8d318218bac1 10 }
mab5449 0:8d318218bac1 11 if(device.readable()) {
mab5449 0:8d318218bac1 12 pc.putc(device.getc());
mab5449 0:8d318218bac1 13 }
mab5449 0:8d318218bac1 14 }
mab5449 0:8d318218bac1 15 }