The goal is to start from a very basic form of Arduino Serial communication, and progressively add or improve components so that we can ultimately transmit data from one computer to another using an XBee.
Briefly talking about the Serial library:the serial library allows us to interface the Arduino with other hardware, like a computer.
Serial.begin()
To use the functions of the Serial library, we have to initiate serial communication – to do this we use the Serial.begin() function. Serial.begin() needs to go in the setup()
void setup() {
//Initiate Serial communication.
Serial.begin(9600);
}
The value 9600 specifies the baud rate. The baud rate is the rate at which information will pass from the Arduino to the computer, or in the other direction.
Serial.print()
Say we have a sketch. This sketch has a variable called
tempValue.
I want to be able to monitor the value of the
tempValue variable – that is, I want it displayed on my computer screen.
//A variable to hold the level of temperature
int tempValue = 3;
void setup() {
Serial.begin(9600);
}
void loop() {
//Send the value of tempValue to the the Serial port.
//So we can see it in the serial monitor window
Serial.print(tempValue);
}
Now in the loop(), if I want to display
tempValue’s value with print(), I simply type Serial.print() and in the parenthesis I type the variable name.
If we upload this sketch to the Arduino, the value of
tempValue will be sent to the serial port every time through the loop(). In the Arduino IDE, if you open up the serial monitor window, you will see the values streaming down.
Another example.
int x = 0;
void setup() {
Serial.begin(9600);
Serial.println("Ciao, come va?");
delay(2000);// Give reader a chance to see the output.
}
void loop() {
Serial.println(x);
delay(500);
x = x + 1; // (Yes, I know there's a more clever way....
//this page is about the serial monitor, remember?)
if (x > 5) {
x = 0;
}
}
Post A Comment:
0 comments:
Post a Comment