Arduino tutorial #02 | Serial communication
Contents
- Basic
- functions
- Hello, Arduino
- Blink
- Use
- Long message
- +Processing
Basic
Functions
- Serial.begin(<band>)
- Serial.available()
- Serial.read()
- Serial.print(<message>)
- Serial.println(<message>)
Hello, Arduino
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | void setup(){ Serial.begin(9600); } void loop(){ } void serialEvent() { if (Serial.available()>0){ if (Serial.read()== 'h' ){ Serial.println( "Hello, I am Arduino" ); } } } |
Blink
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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) } |