Arduino tutorial #02 | Serial communication

Contents

  1. Basic
    1. functions
    2. Hello, Arduino
    3. Blink
  2. Use
    1. Long message
    2. +Processing

Basic

Functions

  • Serial.begin(<band>)
  • Serial.available()
  • Serial.read()
  • Serial.print(<message>)
  • Serial.println(<message>)

Hello, Arduino

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

void loop(){
}

void serialEvent() {
 if(Serial.available()>0){
  if(Serial.read()=='h'){
   Serial.println("Hello, I am Arduino");
  }
 }
}

Blink

int led = 13;

void setup(){
 Serial.begin(9600);
 pinMode(led, OUTPUT);
}

void loop(){
}

void serialEvent() {
 if(Serial.available()>0){
  char c = Serial.read();
  if(c=='h'){
   digitalWrite(led,HIGH);
   Serial.println("I turned led on!");
  }
  if(c=='l'){
   digitalWrite(led,LOW);
   Serial.println("I turned led off!");
  }
 }
}

Use

Long message

String inputString = "";
boolean stringComplete = false;

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

void loop() {
 if (stringComplete) {
 if(inputString == "hello"){
 Serial.println("Hello, I'm Arduino.");
 }else if(inputString == "bye"){
 Serial.println("See you.");
 }else{
 Serial.println("?");
 }
 inputString = "";
 stringComplete = false;
 }
}

void serialEvent() {
 while (Serial.available()) {
 char inChar = (char)Serial.read();
 if (inChar == '\n') {
 stringComplete = true;
 }else{
 inputString += inChar;
 }
 }
}

+Processing

Arduino code

int led = 9;

void setup() {
 Serial.begin(9600);
 pinMode(led,OUTPUT);
}

void loop() {
}

void serialEvent() {
 if(Serial.available()>0){
 analogWrite(led, int(Serial.read()));
 }
}

processing code

import processing.serial.*;

Serial myPort;

void setup() {
 size(255, 255);
 println(Serial.list());
 strokeWeight(5);
 String portName = Serial.list()[2];
 myPort = new Serial(this, portName, 9600);
}

void draw() {
 background(255);
 myPort.write(int(mouseX));
 point(mouseX,mouseY)
}