lightweight Web server dust sensor
Dependencies: EthernetInterface HTTPD mbed-rpc mbed-rtos mbed
main.cpp
- Committer:
- mbedschool
- Date:
- 2015-02-02
- Revision:
- 1:943c19be081b
- Parent:
- 0:b6cf0e62b3a2
File content as of revision 1:943c19be081b:
#include "mbed.h" #include "EthernetInterface.h" #include "HTTPD.h" EthernetInterface *eth; HTTPD *httpd; Serial pc(USBTX, USBRX); InterruptIn probe(p8); LocalFileSystem local("local"); DigitalOut led1(LED1), led2(LED2); Timer timer; Ticker ticker; uint32_t low_time = 0; void down(); void up(); void tick() { pc.printf("%d us, %f %%\r\n", low_time, low_time / (30.0 * 1000000)); low_time = 0; } void down() { probe.rise(&up); led1 = 0; timer.start(); } void up() { led1 = 1; timer.stop(); probe.fall(&down); low_time += timer.read_us(); timer.reset(); } void callback_api(int id) { int i, n; char low_time_buf[256]; char buf[256]; sprintf( low_time_buf, "%f", low_time / (30.0 * 1000000)); strcpy(buf, "{"); strcat(buf, "success: true ,"); strcat(buf, "data: {"); strcat(buf, "lowpulseoccupancytime: "); strcat(buf, low_time_buf); strcat(buf, "}"); strcat(buf, "}"); n = strlen(buf); i = httpd->receive(id, &buf[n], sizeof(buf) - n); if (i < 0) return; i += n; buf[i] = 0; printf("API %d %s\r\n", id, buf); httpd->send(id, buf, i, "Content-Type: text/plain\r\n"); } int main() { pc.baud(115200); pc.printf("Dust Sensor test\r\n"); probe.fall(&down); ticker.attach(tick, 30); printf("HTTP Server...\r\n"); eth = new EthernetInterface; eth->init("192.168.21.81", "255.255.255.0", "192.168.21.2" ); if (eth->connect()) return -1; printf("IP Address is %s\r\n", eth->getIPAddress()); httpd = new HTTPD; httpd->attach("/1/mbed/lpc1768/sensor/dust/sen12291p", &callback_api); httpd->attach("/", "/local/"); httpd->start(80); printf("httpd ready\r\n"); led2 = 1; }