我已经使用Ajax成功测试了一个Web服务器。下面的代码显示了网页中条形图中的Arduino模拟读数。接下来我想在网页中打开/关闭开关1 /开关2(连接到引脚7和8)等开关状态。
Arduino代码
#include <SPI.h>
#include <Ethernet.h>
//Make sure to modify the 5100.h file to suit the Ethernet chip on your shield (eg. W5500) as per the gitHub instructions: https://github.com/Wiznet/WIZ_Ethernet_Library
byte mac[] = {
0x00, 0x08, 0xDC, 0x1C, 0xB8, 0x4C
};
//Enter the MAC address that is on your Ethernet shield (sticker) - eg. 00-08-DC-1C-B8-4C (but use hexadecimal format eg. 0x00)
IPAddress ip(192, 168, 1, 4);
//The IP address that you will give the Server - will depend on your local network range
EthernetServer server(8081);
//The port to listen for Web Browsers - the default is 80, but some routers will block this port.. so change to 8081.
//*************************************************************************************************
// setup function
//=================================================================================================
void setup() {
Serial.begin(9600);
//Begin Serial communication (baud rate = 9600).
Ethernet.begin(mac, ip);
//Initialise the ethernet library and network settings: https://www.arduino.cc/en/Reference/EthernetBegin
server.begin();
//Tell the server to begin listening for incoming connections (on port 8081 in this example)
Serial.print("Server IP address : ");
Serial.println(Ethernet.localIP());
//If you see the IP address within the Serial monitor - you know that the server started successfully
}
//*************************************************************************************************
// loop function
//=================================================================================================
void loop() {
EthernetClient client = server.available();
// assign any newly connected Web Browsers to the "client" variable.
if(client.connected()) {
Serial.println("Client Connected");
while(client.available()) {
//Serial.write(client.read());
// Uncomment if you want to write the request from the Browser (CLIENT) to the SERIAL MONITOR (and comment out the next line)
client.read();
// This line will clear the communication buffer between the client and the server.
}
//Send the Server response header back to the browser.
client.println("HTTP/1.1 200 OK");
// This tells the browser that the request to provide data was accepted
client.println("Access-Control-Allow-Origin: *");
//Tells the browser it has accepted its request for data from a different domain (origin).
client.println("Content-Type: application/json;charset=utf-8");
//Lets the browser know that the data will be in a JSON format
client.println("Server: Arduino");
// The data is coming from an Arduino Web Server (this line can be omitted)
client.println("Connection: close");
// Will close the connection at the end of data transmission.
client.println();
// You need to include this blank line - it tells the browser that it has reached the end of the Server reponse header.
//Transmit the Analog Readings to the Web Browser in JSON format
//Example Transmission: [{"key":0, "value":300},{"key":1, "value":320},{"key":2, "value":143},{"key":3, "value":24},{"key":4, "value":760},{"key":5, "value":470}]
client.print("[");
// This is tha starting bracket of the JSON data
for(int i=0; i<6; i++) {
// Transmit analog readings from Analog Pin 0 to Analog Pin 5
client.print("{\"key\": ");
client.print(i);
// The key for Analog pin 0 (A0) is equal to 0 eg. "key":0
client.print(", \"value\": ");
client.print(analogRead(i));
// The value is equal to the Analog reading from that pin. eg. "value":300
if(i==5){
client.print("}");
// The last value will end with a bracket (without a comma)
} else {
client.print("},");
// All other values will have a comma after the bracket.
}
}
client.println("]");
// This is the final bracket of the JSON data
client.stop();
// This method terminates the connection to the client
Serial.println("Client has closed");
// Print the message to the Serial monitor to indicate that the client connection has closed.
}
}
网页代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ArduinoBasics WebServer Data Viewer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<style>
.table{
width: 100%;
background: #eeeeee;
line-height: 32px;
border: 1px solid black;
}
.bars {
float: left;
height: 30px;
line-height: 30px;
border: 1px solid black;
padding-left: 10px;
padding-right: 10px;
background: #FFFF33;
color: #000000;
}
.row{
width: 100%;
clear: both;
}
</style>
<div align="center" style="background: #eeeeee; border: 1px solid black;">
<h1>ArduinoBasics Data Viewer</h1>
</div>
<br>
<div id="IP Address" style="width: 220px; float:left" align="center">IP Address</div><div id="Port Num" style="width: 200px; float:left;" align="center">Port</div><br>
<select id="Addr0"></select> .
<select id="Addr1"></select> .
<select id="Addr2"></select> .
<select id="Addr3"></select> :
<input id="port" value='8081' /><br>
<button type="button" id="startData" style="height: 50px; width: 228px">Click here to start getting data</button>
<button type="button" id="stopData" style="height: 50px; width: 172px">Click here to stop </button><br>
<br>
<div class="table">
<div class="row"><div class="bars">A0: </div><div class="bars" id="Analog0"></div><div class="bars" id="A0">0</div></div><br>
<div class="row"><div class="bars">A1: </div><div class="bars" id="Analog1"></div><div class="bars" id="A1">0</div></div><br>
<div class="row"><div class="bars">A2: </div><div class="bars" id="Analog2"></div><div class="bars" id="A2">0</div></div><br>
<div class="row"><div class="bars">A3: </div><div class="bars" id="Analog3"></div><div class="bars" id="A3">0</div></div><br>
<div class="row"><div class="bars">A4: </div><div class="bars" id="Analog4"></div><div class="bars" id="A4">0</div></div><br>
<div class="row"><div class="bars">A5: </div><div class="bars" id="Analog5"></div><div class="bars" id="A5">0</div></div><br>
</div>
<br>
<div id="FailureStatus"><H2>Status:</H2></div>
<br>
<div id="statusDiv"><i>This viewer is <b>not compatible</b> with Internet Explorer, and requires JavaScript.</i></div>
<script>
<!--This is the jQuery script which will connect to the Arduino -->
var timeOut; //This variable is responsible for the frequency of data acquisition
$(document).ready(function() {
//Populate the options for the IP address drop-down boxes.
for(j=0; j<256; j++) {
for(i=0; i<4; i++) {
$('#Addr'+i)
.append($("<option></option>")
.attr("value",j)
.text(j));
}
}
//Set the default IP address in the drop down boxes.
$('#Addr0').val('10');
$('#Addr1').val('1');
$('#Addr2').val('1');
$('#Addr3').val('99');
});
//When the start button is clicked - get the data from the Arduino
$("#startData").click(function() {
$(document).ready(function() {
getMyData(); //get data once the document is ready
});
});
//Stop collecting data when the stop button is clicked.
$("#stopData").click(function() {
clearTimeout(timeOut);
//This clears any future requests for data (until the Start button is pressed again)
});
function getMyData() {
//get the IP address from the drop-down boxes
var x0 = $('#Addr0 option:selected').text();
var x1 = $('#Addr1 option:selected').text();
var x2 = $('#Addr2 option:selected').text();
var x3 = $('#Addr3 option:selected').text();
//get the port number from the text box
var x4 = $('#port').val();
//Construct the URL of the Arduino Server we plan to connect to
var myUrl = 'http://' + x0 + "." + x1 + "." + x2 + "." + x3 + ":" + x4 + "/";
var myData = $.ajax({
url: myUrl, // eg. http://10.1.1.99:8081/
data: { tag: 'GetDataFromArduino'},
dataType : "json", //We will be requesting data in JSON format
timeout : 10000, //this will cancel the request if it has not received a reply within 10 seconds.
success: function(data) {
console.log('Success - you are a legend');
$("#FailureStatus").html("<H2>Status: OK</H2>"); //clear any failure messages.
$.each(data, function(index, element) {
if(element.value<100) {
console.log('Low');
$('#Analog' + element.key).css({'background-color':'#FF1128'});
} else {
$('#Analog' + element.key).css({'background-color':'#22FF22'});
}
$('#A'+element.key).html("<span>" + element.value + "</span>");
$('#Analog' + element.key).animate({width: ((element.value/1023)*80)+"%"});
});
}
});
myData.error(function(xhr, status, errorThrown) {
$("#FailureStatus").html("<span><H2>Status:FAILED to get DATA !! </H2></SPAN>");
console.log('Failure');
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
});
timeOut = setTimeout('getMyData()', 1000); //this will request data again in 1 second.
}
</script>
</body>
</html>