Last active
April 11, 2016 16:37
-
-
Save benfasoli/961c3a683c6de894b724 to your computer and use it in GitHub Desktop.
Use arduino digital pins to interface with the outside world.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment