// Arduino digital pin serial control
// Ben Fasoli
//
// Takes input strings over a standard serial connection and sets
// digital pins high/low.
//
// Input:
// Set pin# to 0,1 (LOW, HIGH)
// [pin#].[0,1]\n
// 2.1\n
// 3.0\n
//
// Warning: if changing multiple pins at the same time, add some slight delay
// between sending the serial commands to avoid overloading the serial buffer.
#include <math.h>
// declare variables
boolean debug = false;
boolean readComplete = false;
String inputString = "";
// runs on initiation
void setup() {
// initialize serial interface
Serial.begin(9600);
// reserve 200 bytes for the serial buffer
inputString.reserve(200);
// initialize pins 2 to 13 high
for (int i = 2; i <= 13; i++) {
pinMode(i, OUTPUT);
digitalWrite(i, HIGH);
}
}
// continually loops
void loop() {
readSerialBuffer();
// print the string when readSerialBuffer() sets readComplete to true
if (readComplete) {
// split incoming number 2.1 into setting 1 on pin 2
float inNum = inputString.toFloat();
int pin = floor(inNum);
int setto = round(10 * (inNum - pin));
// print setting to serial window - floating point number received,
// extracted pin number, extracted pin setting
if (debug) {
Serial.print(inNum);
Serial.print('\t');
Serial.print(pin);
Serial.print('\t');
Serial.println(setto);
}
// set desired pin to desired state
digitalWrite(pin, setto);
// clear the string buffer
inputString = "";
readComplete = false;
}
delay(50);
}
// dumps available serial data when new bytes are found
void readSerialBuffer() {
while (readComplete == false & Serial.available()) {
// get a single new byte and add to inputString
char inChar = (char)Serial.read();
inputString += inChar;
// tell loop that the read is complete
if (inChar == '\n') {
readComplete = true;
}
}
}