Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SPI.h>
- #include <Ethernet.h>
- // Give pin 13 a name
- int led = 13;
- // Local Network Settings
- byte mac[] = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network
- // ThingSpeak Settings
- char thingSpeakAddress[] = "api.thingspeak.com";
- String thingSpeakChannel = "2738"; // Channel number looking for twitter update
- String thingSpeakField = "1"; // Field number of the CheerLights commands
- const int thingSpeakInterval = 16 * 1000; // Time interval in milliseconds to get data from ThingSpeak (number of seconds * 1000 = interval)
- // Variable Setup
- long lastConnectionTime = 0;
- String lastCommand = "";
- boolean lastConnected = false;
- int failedCounter = 0;
- // Initialize Arduino Ethernet Client
- EthernetClient client;
- void setup()
- {
- // initialize the digital pin as an output.
- pinMode(led, OUTPUT);
- // Setup Serial
- Serial.begin(9600);
- delay(100);
- Serial.flush();
- delay(100);
- // Start Ethernet on Arduino
- startEthernet();
- }
- void loop()
- {
- if (client.available() > 0)
- {
- delay(100);
- String response;
- char charIn;
- do
- {
- charIn = client.read();
- response += charIn;
- }
- while(client.available() > 0);
- if (response.indexOf("gumball") > 0)
- {
- lastCommand = "gumball";
- }
- // Echo command
- delay(200);
- Serial.println("CheerLight Command Received: "+lastCommand);
- Serial.println();
- delay(200);
- }
- if (!client.connected() && lastConnected)
- {
- Serial.println();
- Serial.println("disconnecting.");
- client.stop();
- }
- // Subscribe to ThingSpeak Channel and Field
- if(!client.connected() && (millis() - lastConnectionTime > thingSpeakInterval))
- {
- subscribeToThingSpeak(thingSpeakChannel, thingSpeakField);
- }
- // Check if Arduino Ethernet needs to be restarted
- if (failedCounter > 3 )
- {
- startEthernet();
- }
- lastConnected = client.connected();
- }
- void subscribeToThingSpeak(String tsChannel, String tsField)
- {
- if (client.connect(thingSpeakAddress, 80))
- {
- Serial.println("Connecting to ThingSpeak...");
- Serial.println();
- failedCounter = 0;
- client.println("GET /channels/"+tsChannel+"/field/"+tsField+"/last.txt HTTP/1.0");
- client.println();
- lastConnectionTime = millis();
- }
- else
- {
- failedCounter++;
- Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
- Serial.println();
- lastConnectionTime = millis();
- }
- }
- void startEthernet()
- {
- client.stop();
- Serial.println("Connecting Arduino to network...");
- Serial.println();
- delay(1000);
- // Connect to network amd obtain an IP address using DHCP
- if (Ethernet.begin(mac) == 0)
- {
- Serial.println("DHCP Failed, reset Arduino to try again");
- Serial.println();
- }
- else
- {
- Serial.println("Arduino connected to network using DHCP");
- Serial.println();
- }
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement