Friday, December 2, 2011

Another web server

Still not much of a server - it is simply sending back the same page whatever the client requests.  But I have set it up so that the values of the three potentiometers change the colour of the background of the page, and it displays the values of the temperature sensor and light sensor. Apologies for the blurriness of some of this - the Flip camera doesn't do close-ups very well (or maybe I haven't worked out how to make it do close-ups).

#include <SPI.h>
#include <Ethernet.h>

Server server(80);
const int chipSelect = 4;
const int LED_R = 6;
const int LED_B = 5;
const int LED_G = 3;
const int POT_R = 0;
const int POT_B = 1;
const int POT_G = 2;
const int LIGHT = 3;
const int TEMP  = 4;

void setup()
{
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x7F, 0xB6 };
    byte ip[] = { 143,210,109,74 };
    Serial.begin(9600);

    Ethernet.begin(mac, ip);
    server.begin();
    
    pinMode(LED_R, OUTPUT);
    pinMode(LED_B, OUTPUT);
    pinMode(LED_G, OUTPUT);
    // HIGH for the multicolour LED unit is off.
    digitalWrite(LED_R, HIGH);
    digitalWrite(LED_B, HIGH);
    digitalWrite(LED_G, HIGH);
}

void loop()
{
    String s;
    
    int red   = analogRead(POT_R) / 4;
    int blue  = analogRead(POT_B) / 4;
    int green = analogRead(POT_G) / 4;
    int light = analogRead(LIGHT);    
    int temp  = analogRead(TEMP);
    
    analogWrite(LED_R, red);
    analogWrite(LED_B, blue);
    analogWrite(LED_G, green);
    
    Client client = server.available();
    if (client)
    {
        while (client.connected())
        {
            if (client.available())
            {
                while (s = get_line(client), s.length() != 0)
                {
                    Serial.println(s);
                }
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println();
                client.print("<html><head><title>Test</title>");
                client.print("<style>body { background: rgb(");
                client.print(255 - red);
                client.print(",");
                client.print(255 - green);
                client.print(",");
                client.print(255 - blue);
                client.print("); } h1 { background: white; text-align: center; border: solid black 5px; padding: 10px; }</style></head><body><h1>Light level is ");
                client.print(light);
                client.print(", temperature ");
                client.print(temp);
                client.println("</h1></body></html>");
                break;
            }
        } 
        client.stop();
    }
}

String get_line(Client client)
{
    String s = "";
    char   c;
    while (c = client.read(), c != '\n')
    {
        if (c != '\r')
        {
            s = s + c;
        }
    }
    return s;
}

No comments:

Post a Comment