Code
/* CONSTANTS & VARIABLES
------------------------------------------------------*/
const String myID = Particle.deviceID();
int ledPin = D0; //Setup LED
int testledPin = D1; //test values
int photoCellPin = A0; //Setup Photocell
int photoCellReading = 0; //Store the sensor reading
int ledState = 0;
int remoteState = 0;
/* SETUP
------------------------------------------------------*/
void setup(){
//Function that will allow direct communication between usb port, analogue reading
Serial.begin(9600);
//Connect the photo cell reading to the cloud to read the value on "cloud variables"
Particle.variable("light", &photoCellReading, INT);
Particle.variable("brightness", &ledState, INT );
pinMode (ledPin, OUTPUT);
pinMode(testledPin, OUTPUT);
pinMode (photoCellPin, INPUT);
Particle.subscribe("SweetTalkProject", eventHandler);
Particle.function("setState", setStateFromCloud); //Just to chech LED locally
}
/* LOOP
------------------------------------------------------*/
void loop(){
monitorPhotocell();
}
/* FUNCTIONS
------------------------------------------------------*/
void eventHandler (const char *event, const char *data){
Serial.println( "event detected" );
Serial.println( data );
Serial.println( event );
String dataStr = data;
if (!data) return;
//String myID = System.deviceID(); (redudnant to line 3)
if( dataStr.indexOf( myID ) > -1 ) return;
//Serial.println( "Not from another ... "); // i dont know what not from another refers to
int index = dataStr.indexOf(",");
String value = dataStr.substring( 0, index );
int state = value.toInt();
setState( state );
}
int monitorPhotocell(){
photoCellReading = analogRead(photoCellPin); //Read from photoCellPin
int convertedToState = map ( photoCellReading, 800, 4000, 0, 255 ); // Set range for states
analogWrite( testledPin, photoCellReading );
//Serial.println( photoCellReading ); //Display it on serial
if (remoteState != convertedToState){
announceState (convertedToState);
remoteState = convertedToState;
delay (1000);
}
}
int setStateFromCloud (String command){
int newState = command.toInt();
setState ( newState );
return 1;
}
void setState(int state){
if ( state == ledState ) return;
if ( state != ledState ){
ledState = state;
analogWrite(ledPin, state);
}
}
void announceState (int state){
//String myID = System.deviceID(); (Redundant with like 3)
String data = String(state) + "," + myID;
Particle.publish("SweetTalkProject", data);
delay (2500);
}
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .