hello, im new of arduino yun, i try to make a web to control the led, ive already finished, but everytime the browser need to refresh, so i want to make a button and use AJAX, i heard use ajax could not need refresh the browser. but the button didnt work i dont know why.
here is my code:
#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>
int LEDPIN = 3; // your LED PIN
BridgeServer server;
String http_req = "";
void setup() {
// Start our connection
Serial.begin(9600);
pinMode(LEDPIN,OUTPUT);
digitalWrite(LEDPIN,HIGH); // turn on Led while connecting
Bridge.begin();
// Show a fancy flash pattern once connected
digitalWrite(LEDPIN,LOW);
delay(150);
digitalWrite(LEDPIN,HIGH);
delay(150);
digitalWrite(LEDPIN,LOW);
delay(150);
digitalWrite(LEDPIN,HIGH);
delay(150);
digitalWrite(LEDPIN,LOW);
delay(150);
// Disable for some connections:
// Start listening for connections
//server.listenOnLocalhost();
server.begin();
}
void loop() {
// Listen for clients
BridgeClient client = server.accept();
// Client exists?
if (client) {
// Lets process the request!
process(client);
client.print("***");
client.print(http_req);
client.print("***");
client.stop();
http_req = "";
}
delay(50);
}
void process(BridgeClient client) {
// Collect user commands
while (client.connected()) {
if (client.available()) {
// read request form browser
char c = client.read();
http_req += c;
http_req.trim();
if (c == '\n') {
// Serial.println(readString);
//检查收到的信息中是否有”on”,有则开灯
if(http_req.indexOf("?on") >0) {
digitalWrite(LEDPIN, HIGH);
Serial.println("Led On");
break;
}
//检查收到的信息中是否有”off”,有则关灯
if(http_req.indexOf("?off") >0) {
digitalWrite(LEDPIN, LOW);
Serial.println("Led Off");
break;
}
//发送HTML文本
client.println("Status: 200");
client.println("Content-type: text/html");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html><head><script type=\"text/javascript\">");
client.println("function send2arduino(){var xmlhttp;xmlhttp=new XMLHttpRequest();element=document.getElementById(\"light\");if (element.innerHTML.match(\"Turn on\")){element.innerHTML=\"Turn off\"; xmlhttp.open(\"GET\",\"?on\",true);}else{ element.innerHTML=\"Turn on\";xmlhttp.open(\"GET\",\"?off\",true); }xmlhttp.send();}");
client.println("</script></head>");
// Show UI
client.println("<B><Center>");
client.println("<h1>Arduino AJAX Button</h1>");
client.println("<button id=\"light\" type=\"button\" onclick=\"send2arduino()\">Turn on</button>
");
client.println("</B></Center></html>");
break;
}
}
}
}
there are 2 problems:
-
i dont know what is the address, i know it should be like arduinolocal/arduino/?, but whatever i put in the browser, it is ok,(for example: arduinolocal/arduino/on or arduinolocal/arduino/test)
-
the string i get from client.read() is always the same as the address(for example, if address is arduinolocal/arduino/test, the string is 'test'),
i dont if my way is right, hope someone could help me