Friday, May 22, 2015

Using the serial for an output

Logging

One useful tool for the arduino is the Serial input output.  This tutorial will only cover outputs for the serial.  If you place the serial outputs in the correct positions you can tell what the arduino is thinking.



Setup the serial connection

Whenever a serial connection is used the first thing you need to do is tell the arduino to start the serial output.


void setup(){
  Serial.begin(9600);
}

The number inside the parenthesis is referring to the baud rate, the symbols per second that are transmitted through this connection.  You can pick any number that is available on the terminal monitor.  If you pick a number that isn't on the serial monitor or you pick the wrong baud rate then you will just have garbage appearing on your screen when the arduino tries to use the serial output.







Sending the message

We are going to modify the light switch code so that the arduino sends a message when the LED turns on and off.  Inside the if/else block add the following line of code:
  Serial.println("The light is on");

Don't forget that the if/else statement needs curly brackets now that we are over one line long.  There are two options for printing to the serial output:

  Serial.println("Foo");
  Serial.print("Foo"); 

ln means include a new line so print("Foo"); will print Foo and the next thing printed will also be on this line whereas println("Foo") will allow Foo to be the last string on this line.

Sending variables

A useful feature of the serial output is to display current variable settings.  To do this we are going to use a mix of print and println and use the project for the nightlight.  Inside the loop we are going to add 2 lines:

  Serial.print("The value of the LDR is: ");
  Serial.println(val);

There are 3 important things to note:
  1. We have included a space in between the colon and close quotation marks.  This is to display ...is: 500 rather than ...is:500
  2. The first line only has print but the next line has println.  This is to keep the value on the same line but have each iteration on a new line
  3. val is not quoted.  This is because we want to display the value not the phrase "val"
When you upload only this modification you might notice that the text scrolls by very quickly.  To solve this issue you can add a small delay into the loop method.

No comments:

Post a Comment