使用arduino作为web客户端,以get方式发送带参数的http请求到服务器实现物联网

应朋友需求,在工作学习之余学习了半个月的Arduino,分享一下自己的学习成果。

软件:本地服务器中的项目是使用JAVA,框架Springboot+Mybatis,数据库Mysql,在项目中开放一个可以直接向数据库存储数据的接口来接收arduino发出的请求。

硬件:Arduino UNO开发板,DHT11传感器+Ethernet W5100拓展板,将arduino中读出的数据以带参数的http请求的方式发送给本地服务器,其他传感器实现方式几乎相同,在此以DHT11温湿度传感器为例来进行阐述。

TP-LINK路由器+网线若干,尽量不要使用交换机,交换机无法自动分配IP并且兼容性一般比较差,造成无法设置静态IP,要使用带有DHCP功能的路由器,一些兼容性差的路由器会出现无法识别Arduino W5100的情况,造成无法自动分配IP地址,尽量选用兼容性较好的TP系列路由器(非广告,厚脸皮在省科技市场尝试了无数交换机和路由器血的教训)

 Springboot的application.yml配置文件:

server:
  port: 8085
  context-path: /arduino
  jsp-servlet:
    init-parameters:
      development: true
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/arduino
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: cja
mybatis:
  type-aliases-package: com.arduino.entity
  mapper-locations: classpath:edu/zzu/mapper/*Mapper.xml

JAVA项目中开放的接口地址为:http://localhost:8085/arduino/data/set?tem=XXX

本地服务器IP地址为:192.168.1.129

Arduino的IP地址由路由器自动分配,使用路由器无需设置,但写上也无妨。

Arduino程序如下:

 /*
  Web client

 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

#include 
#include 
#include
dht11 DHT11;
#define DHT11PIN 2

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "192.168.1.129";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 102);
IPAddress myDns(192, 168, 1, 1);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
// Variables to measure the speed
unsigned long beginMicros, endMicros;
unsigned long byteCount = 0;
bool printWebData = true;  // set to false for better speed measurement

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
  //Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet
  
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  int chk =DHT11.read(DHT11PIN); 
  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.print("connecting to ");
  Serial.print(server);
  Serial.println("...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 8085)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:
    //char* pre = 'GET /arduino/data/set?tem=';
    //char* data = DHT11.temperature;
    //char* posta = " HTTP/1.1";
    //char *result = (char*)malloc(strlen(pre)+strlen(data)+strlen(posta)+1);
    //strcpy(result,pre);
    //strcpy(result,data);
    //strcpy(result,posta);
    //client.println(result);
     //Serial.println(*result);
    client.println("GET /arduino/data/set?tem="+String(DHT11.temperature)+" HTTP/1.1");
    client.println("Host: 192.168.1.129");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  beginMicros = micros();
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  int len = client.available();
  if (len > 0) {
    byte buffer[80];
    if (len > 80) len = 80;
    client.read(buffer, len);
    if (printWebData) {
      Serial.write(buffer, len); // show in the serial monitor (slows some boards)
    }
    byteCount = byteCount + len;
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    endMicros = micros();
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    Serial.print("Received ");
    Serial.print(byteCount);
    Serial.print(" bytes in ");
    float seconds = (float)(endMicros - beginMicros) / 1000000.0;
    Serial.print(seconds, 4);
    float rate = (float)byteCount / seconds / 1000.0;
    Serial.print(", rate = ");
    Serial.print(rate);
    Serial.print(" kbytes/second");
    Serial.println();

    // do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
}

使用此段代码可以将DHT11传感器读取到的数据通过http请求的方式发送至后端服务器,由服务器将将数据进行持久化后,通过前端的Ajax异步请求并集成ECharts数据可视化工具来完成数据的折线图等统计图展示和实时更新。

java项目源码已经推在Github中,有需要的朋友欢迎clone/star

https://github.com/BuffettCui/arduino

你可能感兴趣的:(物联网)