Friday, December 24, 2010

Arduino and The Serial port

Arduino Duemilanove has an on-board serial port(connected to pins 0(RX) and 1(TX)), which used for communication with a computer or other device. It also used for uploading of the program to the board. Actually the board and the computer connected with USB port, but on board side there is a USB to Serial converting chip, and on computer side the driver convert Serial to USB(this is why on the Arduino software the type of connection port is COM port).

The Arduino software(IDE) has a "Serial Monitor" tool, for receiving and sending data through serial port. So we can using it see how the next program will run. We will write a simple program sending "Hello World" text through serial port.
// program: send "Hello World" through serial port
void setup()
{
  Serial.begin(9600);              //switch on serial port and set the speed to 9600 bits per second
  Serial.println("Hello World"); // send a text ...
}
void loop()
{
  // nothing to do
}
Copy above code to a new project, verify and upload it, then open Serial monitor. Set the connection speed to 9600(the speed set in the program). After reseting the board you will see the "Hello World" on the screen.
Serial monitor
Now lets try to enhance our program to use two way communication.
// program: send "hello World" through serial port
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if (0 < Serial.available()) // See is there any coming data
{
    int data = Serial.read();     // read first byte
    Serial.println(data, HEX); // print data in HEX
  }
}
The program see is there any data to read, if there is, read it and return HEX value. So lets run it and see how it works.
As you can see it prints the ASCII HEX values of inputed characters :).

There are many Arduino boards, the one we using for our programs is Arduino Duemilanove, which has only one serial port. But there are Arduino Mega boards, which has 4 serial ports. Those serial ports can be accessed the same way, changing Serial with Serial1, Serial2 and Serial3.
Arduino Mega 2560
More information about Serial can be found at Arduino site(http://arduino.cc/en/Reference/Serial).

No comments:

Post a Comment