![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
IoT demo
Fork of my_example_esp8266 by
Diff: main.cpp
- Revision:
- 8:d5e340a59c71
- Parent:
- 7:49a823b5a935
diff -r 49a823b5a935 -r d5e340a59c71 main.cpp --- a/main.cpp Wed Dec 13 10:09:44 2017 +0000 +++ b/main.cpp Mon Mar 19 03:32:21 2018 +0000 @@ -11,49 +11,36 @@ #include "esp8266.h" Serial ser2usb(PA_2, PA_3, 115200); -DigitalOut LED(PD_2); -DigitalIn humansensor(PA_0); - -int test_main(void){ - Serial esp8266(PA_9, PA_10, 9600); - while(1){ - if(ser2usb.readable()) - esp8266.putc(ser2usb.getc()); - if(esp8266.readable()) - ser2usb.putc(esp8266.getc()); - } -} +DigitalIn ref(PA_12); +DigitalOut LED(PC_13); int main(void) { + ser2usb.printf("starting\r\n"); // 选定与 esp8266 相连接的串口,WiFi 名称和密码 - // 参数分别为 TX pin / RX pin / SSID / Password - Esp8266 client(PA_9, PA_10, "TSINGHUA.iCenter", "TS.icenter"); + Esp8266 client(PA_9, PA_10, "iot_b827eb91bf24", "b827ebc4ea71");// 参数分别为 TX pin / RX pin / SSID / Password //声明所有的传感器,每行一个,每个由名字、单位两部分组成,最后一行必须为空指针作为结尾 - //服务器收到声明后,将在网页上显示这些传感器 const char* sensors[][2] = { - //"pressure", "Pa", -// "temperature", "C", -// "humidity", "%", - "huamn","person", + "light", "lx", + "reflection"," ", NULL, NULL //最后一行以空指针作为结束标记 }; //声明所有的执行器,每行一个,每个由名字、参数类型两部分组成,最后一行必须为空指针作为结尾 - //服务器收到声明后,将在网页上显示这些执行器 const char* actuators[][2] = { - "servo1", "int", - "switch2", "int", + "led", "int", NULL, NULL //最后一行以空指针作为结束标记 }; + ser2usb.printf("connecting...\r\n"); //连接到服务器 - client.connect_mqtt_broker("tdxls-iot.xicp.net", sensors, actuators); + client.connect_mqtt_broker("192.168.12.1", "alpha", sensors, actuators); ser2usb.printf("Initialization done.\r\n"); char actuator_name[32], control_value[32]; + bool ref_last; float last_report=0; Timer t;// 定时器用于计量发送传感器数据的时间 t.start(); @@ -61,23 +48,29 @@ while(1) { //检查有没有收到新的执行器控制指令 if(client.get_control_cmd(actuator_name, control_value)){ - ser2usb.printf("Received CMD %s, %s\r\n", actuator_name, control_value); + ser2usb.printf("Received CMD %s %s\r\n", actuator_name, control_value); //判断哪个执行器收到命令 - if(strcmp(actuator_name, "switch1")){ - //do something for switch1 + if(strcmp(actuator_name, "led")==0){ LED = atoi(control_value); - }else if(strcmp(actuator_name, "switch2")){ - //do something for switch2 } } + + bool reflection = ref; + if(reflection != ref_last){ //仅在传感器发生变化时汇报数据 + + ref_last = reflection; + + char val[4]; + sprintf(val, "%d", (int)reflection); + + //汇报传感器数据,两个参数分别是传感器名字和值 + client.publish_value("reflection", val); + } if(t.read() - last_report > 1){ // 每1s发送汇报一次传感器数据 //汇报传感器数据,两个参数分别是传感器名字和值 - //client.publish_value("pressure", "100000 Pa"); -// client.publish_value("temperature", "20 C"); -// client.publish_value("humidity", "30 %"); - client.publish_value("huamn", "30 %"); + //client.publish_value("light", "30 lx"); last_report = t.read(); }