Digistump Forums
The DigiX => DigiX Support => Topic started by: Twistit on June 20, 2014, 01:36:04 pm
-
I was looking up on examples for controlling my terraria over wifi..
Really wanted to have te DigiX serve a website with buttons and forms and ofcourse data for example if i wanted to have one of the fans turn at 50% i'd fill 50 in the form for fan1 and well you get with i mean..
I found a perfect example for a regular arduino, but i have no clue on how to make this work for the DigiX with it's fancy wifi thingamajigs.
Anyone out there that could give me some pointers? Because this would be perfect for me to work off and understand how the DigiX handles this..
https://www.inkling.com/read/arduino-cookbook-michael-margolis-2nd/chapter-15/recipe-15-10
-
For anyone interested I'm solving it by tearing up dbell's script, attached my rough draft for controlling a pc fan.
Any pointers on cleaning this up always welcome, i am no pro at programming arduino's hehe
I'm not using POST but hell, this works..
-
This works but not cleaned up yet.
all you need to do is add pinMode() to setup
and in the html function
copy this and add new buttons
String body = "<lable>Digital Pin 4<button class='relay' pin='d4' val='0'>LOW</button><button class='relay' pin='d4' val='1'>HIGH</button></label";
change pin='d4' to d? . d= digital and ? = number of the pin you want to use.
#include <DigiFi.h>
DigiFi server;
void setup() {
Serial.begin(9600);
server.begin(9600);
pinMode(7,OUTPUT);
pinMode(6,OUTPUT);
pinMode(5,OUTPUT);
pinMode(4,OUTPUT);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
digitalWrite(5,LOW);
digitalWrite(4,LOW);
//DigiX trick - since we are on serial over USB wait for character to be entered in serial terminal
while(!Serial.available()){
Serial.println("Enter any key to begin");
delay(1000);
}
Serial.println("Starting");
Serial.println("wifi inited");
while (server.ready() != 1)
{
Serial.println("Error connecting to network");
delay(15000);
}
Serial.println("Connected to wifi!");
Serial.print("Server running at: ");
String address = server.server(8080);//sets up server and returns IP
Serial.println(address);
}
void loop() {
if ( server.serverRequest()){
if( findOutHowManyCharInAString( server.serverRequestPath() , '=') !=0){
getUrlVariablesFromWifiString( server.serverRequestPath() );
server.serverResponse(htmlReturn()); //need relay so brouser dont hang
}
else
server.serverResponse(htmlPage()); //defaults to 200
}
}
void runVariableCommand(String string){
if(string.charAt(0)=='d'){ // letter d = Digital
int endOfVariableName = string.indexOf('=');
int booleanValue = stringToInt(string.substring(endOfVariableName+1,string.length()));
String variableName = string.substring(0,endOfVariableName);
digitalWrite( stringToInt( variableName.substring(1,variableName.length()) ), booleanValue );
Serial.print("digital Pin ");
Serial.print(stringToInt( variableName.substring(1,variableName.length()) ));
Serial.print(" to ");
Serial.println(booleanValue);
}
}
boolean getUrlVariablesFromWifiString( String data ){
Serial.print("Request = ");
Serial.println(data);
if(data.length()>=0){
getEachVariable(data.substring(data.indexOf('?')+1, data.length()));
return true;
}else
return false;
}
// split get Into smaller Chunks ie. ?d12=1&d13=0 into d12=1 and d13=0
String splitVariablesUP( String *str , String strTemp, int strLength ){
String singleVariableAsString;
int startIndex=0;
//finds the first index of &
int endIndex=strTemp.indexOf('&');
// get the variable parts into a string
singleVariableAsString = strTemp.substring( startIndex , endIndex );
//now delete variable from reference string
*str = strTemp.substring( endIndex+1 , strLength );// endIndex +1 is so we loose the & char as we do not need it
return singleVariableAsString;
}
// break down GET sting into each variable + value
void getEachVariable(String strTemp){
// returns variable count
int variableCount = findOutHowManyCharInAString( strTemp , '=');
Serial.print("Variable Count = ");
Serial.println(variableCount);
// loops through each variable
for(int i=0;i<variableCount;i++){
// assigns each variable and value to a string array
runVariableCommand(splitVariablesUP( &strTemp , strTemp , strTemp.length() ));
}
}
//return int value from string
int stringToInt(String thisString) {
int i, value, length;
length = thisString.length();
char blah[(length+1)];
for(i=0; i<length; i++) {
blah[i] = thisString.charAt(i);
}
blah[i]=0;
value = atoi(blah);
return value;
}
//return how many variables are in the GET
int findOutHowManyCharInAString(String str, char findChar){
int positionChar = 0;
int count=0;
while(positionChar != -1){
positionChar = str.indexOf( findChar , positionChar+1 );
if(positionChar!=-1)
count++;
}
return count;
}
// html code
String htmlPage(){
String startHtml = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8' /><title>Arduino DigiX Wifi</title>";
String jquery = "\n<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>"
"\n<script>\n$(function(){\n$('.relay').click( function(){"
"\najaxCallScript( $(this).attr('pin') + '=' + $(this).attr('val'));\n"
"});\n});\n"
"alert('jquery Loaded');"
"</script>";
String ajax = "\n<script>\nfunction ajaxCallScript( get ){"
"\nfile = '?' + get;"
"\nif (window.XMLHttpRequest)"
"\n{// code for IE7+, Firefox, Chrome, Opera, Safari"
"\nxmlhttp=new XMLHttpRequest();"
"\n}"
"\nelse"
"\n{// code for IE6, IE5"
"\nxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');"
"\n}"
"\nxmlhttp.onreadystatechange=function(){"
"\nif (xmlhttp.readyState==4 && xmlhttp.status==200){"
"\ndocument.getElementById(elementName).innerHTML = 'done';}"
"\nelse"
"\ndocument.getElementById(elementName).innerHTML = 'Sent';"
"\n}"
"\nxmlhttp.open('GET',file,true);"
"\nxmlhttp.send();"
"\n}\n</script>";
String javascript = "";
String body = "<lable>Digital Pin 4<button class='relay' pin='d4' val='0'>LOW</button><button class='relay' pin='d4' val='1'>HIGH</button></label";
String endHtml = "\n</body>\n</html>";
return startHtml+jquery+ajax+javascript+body+endHtml;
}
String htmlReturn(){
return "hello";
}
-
this one has anologWrite which is more what you was asking for.
only changes to need to make are in setup pinMode etc and
function htmlPage
String body = ""; //add buttons selector
#include <DigiFi.h>
DigiFi server;
void setup() {
Serial.begin(9600);
server.begin(9600);
pinMode(7,OUTPUT);
pinMode(6,OUTPUT);
pinMode(5,OUTPUT);
pinMode(4,OUTPUT);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
digitalWrite(5,LOW);
digitalWrite(4,LOW);
//DigiX trick - since we are on serial over USB wait for character to be entered in serial terminal
while(!Serial.available()){
Serial.println("Enter any key to begin");
delay(1000);
}
Serial.println("Starting");
Serial.println("wifi inited");
while (server.ready() != 1)
{
Serial.println("Error connecting to network");
delay(15000);
}
Serial.println("Connected to wifi!");
Serial.print("Server running at: ");
String address = server.server(8080);//sets up server and returns IP
Serial.println(address);
}
void loop() {
if ( server.serverRequest()){
if( findOutHowManyCharInAString( server.serverRequestPath() , '=') !=0){
getUrlVariablesFromWifiString( server.serverRequestPath() );
server.serverResponse(htmlReturn()); //need relay so brouser dont hang
}
else
server.serverResponse(htmlPage()); //defaults to 200
}
}
void runVariableCommand(String string){
if(string.charAt(0)=='d'){ // letter d = Digital
int endOfVariableName = string.indexOf('=');
int booleanValue = stringToInt(string.substring(endOfVariableName+1,string.length()));
String variableName = string.substring(0,endOfVariableName);
digitalWrite( stringToInt( variableName.substring(1,variableName.length()) ), booleanValue );
Serial.print("digital Pin ");
Serial.print(stringToInt( variableName.substring(1,variableName.length()) ));
Serial.print(" to ");
Serial.println(booleanValue);
}
if(string.charAt(0)=='a'){ // letter a = Analog
int endOfVariableName = string.indexOf('=');
int booleanValue = stringToInt(string.substring(endOfVariableName+1,string.length()));
String variableName = string.substring(0,endOfVariableName);
analogWrite( stringToInt( variableName.substring(1,variableName.length()) ), booleanValue );
Serial.print("Analog Pin ");
Serial.print(stringToInt( variableName.substring(1,variableName.length()) ));
Serial.print(" to ");
Serial.println(booleanValue);
}
}
boolean getUrlVariablesFromWifiString( String data ){
Serial.print("Request = ");
Serial.println(data);
if(data.length()>=0){
getEachVariable(data.substring(data.indexOf('?')+1, data.length()));
return true;
}else
return false;
}
// split get Into smaller Chunks ie. ?d12=1&d13=0 into d12=1 and d13=0
String splitVariablesUP( String *str , String strTemp, int strLength ){
String singleVariableAsString;
int startIndex=0;
//finds the first index of &
int endIndex=strTemp.indexOf('&');
// get the variable parts into a string
singleVariableAsString = strTemp.substring( startIndex , endIndex );
//now delete variable from reference string
*str = strTemp.substring( endIndex+1 , strLength );// endIndex +1 is so we loose the & char as we do not need it
return singleVariableAsString;
}
// break down GET sting into each variable + value
void getEachVariable(String strTemp){
// returns variable count
int variableCount = findOutHowManyCharInAString( strTemp , '=');
Serial.print("Variable Count = ");
Serial.println(variableCount);
// loops through each variable
for(int i=0;i<variableCount;i++){
// assigns each variable and value to a string array
runVariableCommand(splitVariablesUP( &strTemp , strTemp , strTemp.length() ));
}
}
//return int value from string
int stringToInt(String thisString) {
int i, value, length;
length = thisString.length();
char blah[(length+1)];
for(i=0; i<length; i++) {
blah[i] = thisString.charAt(i);
}
blah[i]=0;
value = atoi(blah);
return value;
}
//return how many variables are in the GET
int findOutHowManyCharInAString(String str, char findChar){
int positionChar = 0;
int count=0;
while(positionChar != -1){
positionChar = str.indexOf( findChar , positionChar+1 );
if(positionChar!=-1)
count++;
}
return count;
}
// html code
String htmlPage(){
String startHtml = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8' /><title>Arduino DigiX Wifi</title>";
String jquery = "\n<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>"
"\n<script>\n"
"\n$(function(){"
"\nalert('jquery Loaded');"
"\n$('.relay').click( function(){"
"\najaxCallScript( $(this).attr('pin') + '=' + $(this).attr('val'));"
"\n});"
" \n$('.selector').change(function(){\najaxCallScript( \n$(this).attr('pin') + '=' + $(this).val());"
"\n});"
"\n});"
"\n</script>";
String ajax = "\n<script>\nfunction ajaxCallScript( get ){"
"\nfile = '?' + get;"
"\nif (window.XMLHttpRequest)"
"\n{// code for IE7+, Firefox, Chrome, Opera, Safari"
"\nxmlhttp=new XMLHttpRequest();"
"\n}"
"\nelse"
"\n{// code for IE6, IE5"
"\nxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');"
"\n}"
"\nxmlhttp.onreadystatechange=function(){"
"\nif (xmlhttp.readyState==4 && xmlhttp.status==200){"
"\ndocument.getElementById(elementName).innerHTML = 'done';}"
"\nelse"
"\ndocument.getElementById(elementName).innerHTML = 'Sent';"
"\n}"
"\nxmlhttp.open('GET',file,true);"
"\nxmlhttp.send();"
"\n}\n</script>";
String javascript = "";
String body = "<lable>Digital Pin 4<button class='relay' pin='d4' val='0'>LOW</button><button class='relay' pin='d4' val='1'>HIGH</button></label>"
"<br><lable>Analog Pin 1<select class='selector' pin='a1'><option>0</option><option>50</option><option>100</option><option>150</option><option>200</option><option>255</option></select>";
String endHtml = "\n</body>\n</html>";
return startHtml+jquery+ajax+javascript+body+endHtml;
}
String htmlReturn(){
return "hello";
}
-
Perfect! Thanks! Much better then what i had going ;D
-
how did youre code work out in the end
-
Awesome, got it doing what i wanted ;)
-
Originally when i called the page for the first time i had to refresh to actually get the page.
Now that it's incorporated in my "large" script the above still applies but when i call for the page for a third time the DigiX freezes?
If i wait 5 minutes it will continue doing it's thing (serial console pops back to life and it responds to my button).
Sometimes when i refresh again it will continue sooner and i will actually get the page but that's a hit and miss,
most often i have to wait 5 minutes for the DigiX to do anything again.
I'm stumped -.-
-
i gave up on digiX trying to a server & client, had problems with wifi crashing (can't do both at the same time). So i did this instead
digiX <---> raspberry Pi <---> me
raspberry is setup with apache server, which is also going to do my smart home server(ie lights, heating, power usage and some security )
digiX talks to raspberyy every 5min( with data which is sorted by PHP into mySql )
- raspberry replies with variables ?tempMax=28&tempMin=15&lightsOn=13&lightsOff=23 the return GET can be passed to getUrlVariablesFromWifiString( String string to be sort )
I(me) talks to the raspberry(webpage is serverd from here). digiX has been runing for months now with no problems.
if you have a raspberry or host a webpage with php & mysql and can help you with the code needed to the server side :)
-
using the tabs helps break down the code for easier reading
open the "WebNTPRelayTimersTempRev12.ino" not the others.
-
example code will finsih rest off tomo,
what is TL1,Tl1, SPOT and NIGHT for.
and do you have a nokia 5110 screen?
-
Goodmorning!
TL is what we call a fluorescent tube in the Netherlands, got 2 ;) So TL1 and TL2.
Spot is the spot light which the tortoise uses for basking and Night are the night leds.
I do have a nokia screen somewhere, but that was planned for later on. Still need to make a waterproof/tortoiseproof housing for it and fix wiring through the bottom.
I have a webhost with php and sql support.
I didn't even know i could use tabs... That's nifty!
The 2 Fluorescent tubes start and stop at the same time.
The Night leds start when the tubes stop.
The spot light starts with the tubes but stops earlier.
The temp sensors should turn on a pc fan and if that does not help turn off the spot and then one tube at a time when temps get to high. (depends on which sensor if spot or tubes go first)
The webpage was going to allow manual control over the lights and fan overruling the timer or temp and tell me what is on and what is off.
So you know what i was going for.
-
done
-
Sweet! Started tinkering with it right away, question tho.. The cases you used like case 840: // lightsOn how do you calculate those?
[Edit] Got it, it's adding up the DEC value's! Smart hehe
[Edit 2] Under wifi tab i see updateData.php and test.php but i dont see the php code for those.
Toki said thank you ;)
(https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-xpf1/v/t1.0-9/10696177_10152810834068584_6601415374104970059_n.jpg?oh=a649b78975baff4f988103444731e057&oe=54ABD76D&__gda__=1425008402_058d2c694816324117dc64703e74a029)
-
test.php is the same as getVariables.php just forgot to change it.
changes done and new index.php added and another sql db
-
Got it! Running perfectly, already edited my spot and led's in!
Forgot to call setPins(); in setup, but figured that out fast enough when the relay didnt respond :)
-
Sound :)
you got it running on you're own server??
if so i can stop access to the php test files
cheers
-
Yup, Got it running on my own server!
However, the timestamp only gets updated twice or three times.. Did i break something already?
Modified the page to show last updated.
[edit] Okay, replaced the 0.5a power adapter with a 1a. seems to be running better.
[edit2] Right.. so.. when i pull the usb cord with serial console the digix freezes.. lights stay on but stops updating web, wont turn of lights.
[edit3] Well, seems the digix start without being hooked up to my laptop? Hooked it up to my adapter and a usb power adapter.. doesn't seem to be updating the web interface.
Cant check the lights till tomorrow, Tortoise doesn't like the disco I'm causing with resetting the digix ;)
[edit4] Watching serial after editing updatephp from the page.. Page reads 1, phpmyadmin the table reads 1.. However serial keeps getting old data? phpupdate = 5 and also not writing to updateData? I'm at loss.. Am i testing on a wonky server? Am i asking to much of the DigiX? After it boots it gets the correct values.. but after that it just does not update it from the database? It did work a few times.. But it's on and off.
-
ok, ill try it on my digiX using your server data. since your not use at the moment.
can you adda new line to digiXvariable table and let me know what the arduino number is. should be 2.
cheers.
-
you had a problem with updating. got it working on my side. ive created the php file in a seperate folder in the rar as not sure if you added some html code tothe file?? and there is a new tab xChanges to explain some stuff. do you have more than 1 digiX?
-
I only have one digiX, i guess my temp host is horrible (my current host was working on the sql server so was unavailable) hope i can get access again soon!
On yours it seems to run fine (so far, will test more later).
I do get the following a lot, just after i said it's running fine.. Guess i jinxed it:
get Data = <HTML><HEAD>
<TITLE>Request Timeout</TITLE>
</HEAD><BODY>
<H1>Request Timeout</H1>
The server timed out while waiting for the browser's request.<P>
Reference #2.7902655f.1414347051.0
</BODY></HTML>
-
Pulled my serial cable and it hasn't updated for 10 minutes..
I'm powering my Arduino with a 12v 1000ma..
Connected to the 5v out on the Arduino is a 8port 220 relay, only 4 relays on the strip in use.
TCP timeout on the DigiX is set at 300 btw, is this right?
What kind of power supply do you run?
Back on serial, the script still runs.. Just getting the updatedata error's, returnvariabledata works fine even when spammed :P
-
5volt 1amp, or 1.5amp with 8 relays but only using 2. had no problems in months
-
boot without Serial connected. then pulg in Serial after its booted.???
-
Same thing, pulled serial went out the door for 2 hours..
Came back no updates on the page, inserted serial and voila it updates the page.
Just once tho, after that it went back to server timing out.
I'm guessing it doesnt like my 12v 1a power adapter.
Still got a 5v 1a around, wondering if that would help..
Else i've got to order a 5v 2a
[Edit] Fun fact: Everytime i restart wifi from the Digix Setting page it runs the updateData fine.. once.. then goes back to server timed out.
Factory resetting wifi makes it updateData 5 times.. then goes back to server timed out.
However, i found a 12v 2a adapter and it seems to run more stable apart from the time outs.
-
get a raspberry PI B+ and install lamp. it will give you apache, php, phpmyadmin and mysql. i dont get any timeouts.
http://www.youtube.com/watch?v=CEji-qN-TEE
next project is to build this program using raspberry and touch screen,