Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- -----------------------------------
- Webpage = MonitorSwitch.html
- Monitors the state of switch1. If switch1 is pressed then the value of variable sw1 changes.
- The webpage monitors the state of sw1 by sending a $.get request.
- If sw1 is 1 then the webpage sends $.post to the core to switch led1 ON.
- If sw1 is 0 then the webpage sends $.post to the core to switch led1 OFF.
- Builds on the code for controlling LEDs on the Sparkcore from the Webpage
- -----------------------------------
- */
- // name the pins
- int led1 = D0;
- int led2 = D1;
- int switch1 = D2;
- int sw1 = 0;
- // This routine runs only once upon reset
- void setup()
- {
- //Register our Spark function here
- Spark.function("led", ledControl);
- Spark.function("state", swState);
- Spark.variable("sw1", &sw1, INT);
- // Configure the pins to be outputs
- pinMode(led1, OUTPUT);
- pinMode(led2, OUTPUT);
- pinMode(switch1, INPUT);
- // Initialize both the LEDs to be OFF
- digitalWrite(led1, LOW);
- digitalWrite(led2, LOW);
- }
- // This routine loops forever
- void loop()
- {
- if(digitalRead(switch1) == LOW)
- {
- if(sw1 == 1)
- {
- sw1 = 0;
- digitalWrite(led2,LOW);
- }
- else
- {
- sw1 = 1;
- digitalWrite(led2,HIGH);
- }
- while(digitalRead(switch1) == LOW)
- delay(10);
- }
- //else
- //digitalWrite(led2,HIGH);
- }
- // This function gets called whenever there is a matching API request
- // the command string format is l<led number>,<state>
- // for example: l1,HIGH or l1,LOW
- // l2,HIGH or l2,LOW
- int ledControl(String command)
- {
- int state = 0;
- //find out the pin number and convert the ascii to integer
- int pinNumber = command.charAt(1) - '0';
- //Sanity check to see if the pin numbers are within limits
- if (pinNumber < 0 || pinNumber > 1) return -1;
- // find out the state of the led
- if(command.substring(3,7) == "HIGH") state = 1;
- else if(command.substring(3,6) == "LOW") state = 0;
- else return -1;
- // write to the appropriate pin
- digitalWrite(pinNumber, state);
- return 1;
- }
- // This function gets called whenever there is a matching API request
- // the command string format is sw<switch number>,<state>
- // for example: sw1,HIGH or sw1,LOW
- // sw2,HIGH or sw2,LOW
- int swState(String command)
- {
- int state = 0;
- //find out the pin number and convert the ascii to integer
- int pinNumber = command.charAt(2) - '0';
- //Sanity check to see if the pin numbers are within limits
- if (pinNumber < 0 || pinNumber > 1) return -1;
- // find out the state of the led
- if(command.substring(4,8) == "HIGH") sw1 = 1;
- else if(command.substring(4,7) == "LOW") sw1 = 0;
- else return -1;
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement