User Tools

Site Tools


arduino:arduino_crash_course:serial_communication

Serial Communication

Serial communication is a two-way stream of text characters that is communicated over a serial port. It is one way to let the Arduino board (called the target) communicate with the computer you are using to develop Arduino programs (called the development host or just host).

Serial communication is often used to make the Arduino report back to the host the value of the program's variables or other information as the program is running. This can be of great value when you are trying to debug programs.

Switch controlled LED with serial reporting

The following is our switch-controlled LED example modifed to report the state of the pushbutton back to the host computer.

Once you have uploaded the program to the Arduino and it is running, open the serial monitor using the IDE's Tools > Serial Monitor menu item. Notice the values that are reported in the Serial Monitor window when you press and unpress the switch.

LightSwitchMonitored.ino
/*
 LightSwitchMonitored
 Turn an LED on and off and send switch state to serial monitor
 */
 
int pushButtonPin = 2;  // connect the push button to digital pin 2
int ledPin = 13;        // connect the LED to pin 13
 
void setup() {
  Serial.begin(9600);  // initialize serial communication at 9600 bits/second
 
  pinMode(pushButtonPin, INPUT);      // make the pushbutton's pin an input
  digitalWrite(pushButtonPin, HIGH);  // turn on pullup resistors
 
  pinMode(ledPin, OUTPUT);            // make LED's pin an output
}
 
void loop() {
  int buttonState = digitalRead(pushButtonPin);  // read the input pin
 
  // set LED state accordingly
  if (buttonState == LOW)         // if the button is pushed
    digitalWrite(ledPin, HIGH);   // turn the LED on
  else                            // otherwise
    digitalWrite(ledPin, LOW);    // turn the LED off
 
  Serial.println(buttonState);    // print out state of button
  delay(500);                     // delay between reads
}

The official Arduino Serial reference material.

arduino/arduino_crash_course/serial_communication.txt · Last modified: 2012/11/12 18:23 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki