Created
April 6, 2016 13:35
-
-
Save inigoalonso/f4c1535a44a9e41683f427fa3952ee0c to your computer and use it in GitHub Desktop.
Serial Control of an Arduino from http://www.smolloy.com/2015/12/serial-control-of-an-arduino/
This file contains hidden or 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
const int ledPin = 11; | |
const int photoPin = A0; | |
int ledState = LOW; | |
int oldState = LOW; | |
String input = ""; // This will capture the serial input commands | |
void setup() { | |
pinMode(ledPin, OUTPUT); | |
pinMode(photoPin, INPUT); | |
Serial.begin(115200); // Make sure the Serial commands match this baud rate | |
} | |
void loop () { | |
if (oldState != ledState) { // Only write to the LED when necessary | |
analogWrite(ledPin, ledState); | |
oldState = ledState; | |
} | |
while (Serial.available()>0){ | |
char lastRecvd = Serial.read(); | |
if (lastRecvd == '\n') { // The end of the command has arrived | |
switch (input[0]) { | |
case 'W': // A write command has come in | |
input = input.substring(1,input.length()); | |
ledState = constrain(input.toInt(), 0, 255); | |
input = ""; | |
break; | |
case 'R': // A read command has come in | |
Serial.print("R "); | |
Serial.print(analogRead(photoPin)+'0'); | |
Serial.print("\n"); | |
input = ""; | |
break; | |
default: | |
break; | |
} | |
} | |
else { // Input is still coming in | |
input += lastRecvd; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment