Hardware Reference
In-Depth Information
Listing 6-1: Potentiometer Serial Print Test Program—pot.ino
//Simple Serial Printing Test with a Potentiometer
const int POT=0; //Pot on analog pin 0
void setup()
{
Serial.begin(9600); //Start serial port with baud = 9600
}
void loop()
{
int val = analogRead(POT); //Read potentiometer
int per = map(val, 0, 1023, 0, 100); //Convert to percentage
Serial.print("Analog Reading: ");
Serial.print(val); //Print raw analog value
Serial.print(" Percentage: ");
Serial.print(per); //Print percentage analog value
Serial.println("%"); //Print % sign and newline
delay(1000); //Wait 1 second, then repeat
}
Using a combination of Serial.print() and Serial.println() statements,
this code prints both the raw and percentage values once per second. Note that
by our using Serial.println() only on the last line, each previous transmis-
sion stays on the same line.
Open the serial monitor from the Arduino IDE and ensure that your baud
rate is set to 9600 to match the value set in the Arduino sketch. You should see
the values printing out once per second as you turn the potentiometer.
UsingSpecialCharacters
You can also transmit a variety of “special characters” over serial, which allow
you to change the formatting of the serial data you are printing. You indicate
these special characters with a slash escape character ( \ ) followed by a com-
mand character. There are a variety of these special characters, but the two of
greatest interest are the tab and newline characters. To insert a tab character,
add a \t to the string. To insert a newline character, add a \n to the string. This
proves particularly useful if you want a newline to be inserted at the beginning
of a string, instead of at the end as the Serial.println() function does. If, for
some reason, you actually want to print \n or \t in the string, you can do so by
printing \\n or \\t , respectively. Listing 6-2 is a modification of the previous
code to use these special characters to show data in a tabular format.
Search WWH ::




Custom Search