Electronic + Coding 2
Serial Communication: Arduino-Processing
Arduino-Code
#include "serialComLib.h"
// ----------------------------------------------------------------------------
// cmdId constants
#define CMD_WRITE_DOUT2 1
#define CMD_READ_DIN3 2
#define CMD_READ_AD0 3
#define CMD_RET_READ_DIN3 4
#define CMD_RET_READ_AD0 5
// ----------------------------------------------------------------------------
// global var
SerialComLib comLib;
unsigned char din;
unsigned char digitalOutPin = 2;
unsigned char digitalInPin = 3;
unsigned char analogPin = 0;
void setup()
{
pinMode(digitalOutPin, OUTPUT);
pinMode(digitalInPin, INPUT);
digitalWrite(digitalOutPin, LOW);
comLib.open(Serial,9600);
}
unsigned char data[] = {11,22};
void loop()
{
if(comLib.readPacket() == SerialComLib::Ok)
{ // there is some data on the serial port
// interprete the command
switch(comLib.getCmd())
{
case CMD_WRITE_DOUT2:
// set the digital out 2
digitalWrite(digitalOutPin, comLib.getByte() > 0 ? HIGH : LOW);
break;
case CMD_READ_DIN3:
// read in the digtial input 3
comLib.beginSend(CMD_RET_READ_DIN3);
comLib.sendByte(digitalRead(digitalInPin));
comLib.endSend();
break;
case CMD_READ_AD0:
// read in the anolog input 0
comLib.beginSend(CMD_RET_READ_AD0);
comLib.sendInt(analogRead(analogPin));
comLib.endSend();
break;
default:
// unknown cmd
break;
}
}
else
{ // do something else ???
}
}
Download Arduino Code
Processing Code
import processing.serial.*;
final static byte CMD_WRITE_DOUT2 = 1;
final static byte CMD_READ_DIN3 = 2;
final static byte CMD_READ_AD0 = 3;
final static byte CMD_RET_READ_DIN3= 4;
final static byte CMD_RET_READ_AD0 = 5;
SerialComLib serialComLib;
void setup()
{
size(500,400);
println("Serial Ports:");
println(Serial.list());
String portName = Serial.list()[0];
serialComLib = new SerialComLib(this, portName, 9600);
}
void draw()
{
background(255);
serialComLib.update();
}
void keyPressed()
{
switch(key)
{
case '1':
println("Send read DIN3");
serialComLib.beginSend(CMD_READ_DIN3);
serialComLib.endSend();
break;
case '2':
println("Send read AD0");
serialComLib.beginSend(CMD_READ_AD0);
serialComLib.endSend();
break;
case '3':
println("Send write DOUT2 low");
serialComLib.beginSend(CMD_WRITE_DOUT2);
serialComLib.sendByte(0);
serialComLib.endSend();
break;
case '4':
println("Send write DOUT2 high");
serialComLib.beginSend(CMD_WRITE_DOUT2);
serialComLib.sendByte(1);
serialComLib.endSend();
break;
}
}
void onReceiveSerialCom(int cmdId,SerialComLib serialCom)
{
switch(cmdId)
{
case CMD_RET_READ_DIN3:
println("DIN3: " + serialCom.getByte());
// get din3
break;
case CMD_RET_READ_AD0:
// get ad0
println("AD0: " + serialCom.getUShort());
break;
default:
println("Unknown command: " + cmdId);
break;
}
}
Download Processing Code