Using Ethernet Interface to send temperature/humidity info to client

Dependencies:   EthernetInterface SDFileSystem SHTx mbed-rtos mbed

main.cpp

Committer:
airaylee
Date:
2013-10-18
Revision:
1:788d545c9cd1
Parent:
0:e26dfd507000

File content as of revision 1:788d545c9cd1:


#include "mbed.h"
#include "SHTx/sht15.hpp"
#include "SDFileSystem.h"
#include "EthernetInterface.h"

//SPI-mosi,miso,sclk,DigitalOut-cs, name used to access the filesystem 
//For further update
SDFileSystem sd(p5, p6, p7, p8, "sd1"); 

//Terminal Port to display the file back
Serial pc(USBTX, USBRX);
DigitalOut busy(LED1);

// Use p28-sda--data,p27-scl--sck
SHTx::SHT15 sensor(p28, p27);

EthernetInterface eth;
#define ECHO_SERVER_PORT   7

int main() {
    
    // Speed things up a bit.
    sensor.setOTPReload(false);
    sensor.setResolution(true);
    
    eth.init(); //Use DHCP
    eth.connect(7000);//Longer timeout here
    //print out the MAC address first
    printf("MAC Address is %s\r\n", eth.getMACAddress());
    printf("IP Address is %s\r\n", eth.getIPAddress());
    //IP address is 130.207.234.205
    // Declare the TCP server 
    TCPSocketServer server;
    server.bind(ECHO_SERVER_PORT);
    server.listen();
    
    while(1) {
        printf("\nWait for new connection...\r\n");
        TCPSocketConnection client; //wait for a TCP connection
        server.accept(client);
        client.set_blocking(false); // Non-blocking
        
        printf("Connection from: %s\r\n", client.get_address());
        //Update the sensor
        busy = true;
        sensor.update();
        busy = false;
        //Initialize the buffer to send
        char buffer[256]={0};
        
        // Temperature in celcius and Humidity in percent
        sensor.setScale(false);
        sprintf(buffer,"Temperature [ %3.2f C ]\r\nHumdity     [ %3.2f %% ]\r\n\n", sensor.getTemperature(), sensor.getHumidity());
        //Send the data
        int n = sizeof(buffer);
        client.send_all(buffer, n);
        //close the connection and wait for new connection
        client.close();
        printf(" Connection over\r\n");
        
    }
}