Part 11 – Using the Serial Port

For me this was the missing piece to the platform, being able to do some kind of real-time debugging of values during execution. The Serial. library that comes with the Arduino allows you to interact with it while it’s running, which is great. Besides some of the Serial.print(ln) functions that I showed in quite a bit of the Lab 10 code, this lab work was really focused on getting input through the Serial interface. The code for this exercise is below….

#define MYLED 11 // Setup my LED pin

int inChar = 0;  // Global for the character in
char outChar = ” “; // Global for the character out

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600); // Setup Serial i/o
  pinMode(MYLED,OUTPUT); / Setup the LED for output.
}

void loop() {
  // put your main code here, to run repeatedly:
  // Do a loop as long as serial is working to read input
  while (Serial.available()) {
    inChar = Serial.read(); // Read a char, default int.
    outChar = char(inChar); // Change the int to a char

    // Print the debugging/serial output of what we read.
    Serial.print(“Value “); 
    Serial.print(inChar);
    Serial.print(” is character “);
    Serial.println(outChar);

    // If it’s a “1” turn it on, a “0” turn if off
    if (inChar == 49) {
      digitalWrite(MYLED,HIGH);
      Serial.println(“LED ON!”);
    }
    if (inChar == 48) {
      digitalWrite(MYLED,LOW);
      Serial.println(“LED OFF!”);
    }
  }
}

In addition to the code, here is a picture of the screen during execution of the example.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.