Initial import of support files for all Digistump boards - Digispark, Pro, DigiX - including libraries, examples, tools, and other support files for the Arduino IDE

This commit is contained in:
Erik Tylek Kettenburg
2014-12-19 08:45:50 -08:00
parent 97abdbf157
commit 7e7473a2d6
3567 changed files with 722870 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,162 @@
// DigiX WiFi module example - released by Digistump LLC/Erik Kettenburg under CC-BY-SA 3.0
#ifndef DigiFi_h
#define DigiFi_h
#include "Arduino.h"
#include "Print.h"
#include <string.h>
#include "Client.h"
#include "IPAddress.h"
#define DIGIFI_RTS 105
#define DIGIFI_CTS 104
#define TCP 1
#define UDP 0
class DigiFi : public Client
{
public:
static const int requestTimeout = 15;
String serverRequestPathString;
DigiFi();
void begin(int aBaud = 9600, bool en = false);
bool ready();
void setDebug(bool debugStateVar);
void setTCPTimeout(uint16_t timeout);
bool serverRequest();
void serverResponse(String response, int code = 200);
String server(uint16_t port);
String serverRequestPath();
virtual int connect(IPAddress ip, uint16_t port);
virtual int connect(const char *host, uint16_t port);
virtual int disconnect();
int get(char *aHost, char *aPath);
int post(char *aHost, char *aPath, String postData);
void startATMode();
void endATMode();
void close();
void closeChunk();
void printChunk(const char *str);
void printChunk(int str);
void printChunk(long str);
void printChunk(String str);
void setMode(uint8_t protocol = TCP);
String header();
String body();
int lastError();
void debug(String output);
void debugWrite(char output);
String URLEncode(String smsg);
void setFlowControl(boolean);
//Ethernet implimentation
IPAddress localIP();
IPAddress subnetMask();
IPAddress gatewayIP();
IPAddress dnsServerIP();
uint8_t maintain();
/* Client Implementation */
virtual uint8_t connected();
//uint8_t status();
virtual operator bool();
virtual int available( void ) ;
virtual int peek( void ) ;
virtual int read( void ) ;
virtual int read(uint8_t *buf, size_t size);
virtual void flush( void ) ;
virtual void stop( void ) ;
virtual size_t write( const uint8_t c ) ;
virtual size_t write(const uint8_t *buf, size_t size);
using Print::write ; // pull in write(str) and write(buf, size) from Print
/* AT Wrappers */
String AT(char *cmd, char *params);
void toggleEcho(); //E
String getWifiMode(); //WMODE AP STA APSTA
void setWifiMode(char *mode);
void setTransparent(); //ENTM
String getTMode(); //TMODE throughput cmd
void setTMode(char *mode);
String getModId(); //MID
String version(); //VER
void factoryRestore(); //RELD rebooting...
void reset(); //Z (No return)
String help();//H
int readConfig(byte* buffer);//CFGRD
void writeConfig(byte* config, int len);//CFGWR
int readFactoryDef(byte* buffer);//CFGFR
void makeFactory(); //CFGTF
String getUart();//UART baudrate,data_bits,stop_bit,parity
void setUart(int baudrate,int data_bits,int stop_bit,char *parity);
/* These are commented out as I'm unsure how they should be named
String getAutoFrame(); //UARTF
void setAutoFrame(char *para);
int getAutoFrmTrigTime(); //UARTFT
void setAutoFrmTrigTime(int ms);
int getAutoFrmTrigLength(); //UARTFL
void setAutoFrmTrigLength(int v);
*/
void sendData(int len, char *data);//SEND
String recvData(int len);//RECV len,data (+ok=0 if timeout (3sec))
String ping(char *ip);//PING Success Timeout Unknown host
String getNetParams();//NETP (TCP|UDP),(SERVER|CLIENT),port,IP
void setNetParams(char *proto, char *cs, int port, const char *ip);
String getTCPLnk();//TCPLK on|off
String getTCPTimeout();//TCPTO 0 <= int <= 600 (Def 300)
String getTCPConn();//TCPDIS On|off
void setTCPConn(char *sta);
String getWSSSID();//WSSSID
void setWSSSID(char *ssid);
String getSTAKey();//WSKEY (OPEN|SHARED|WPAPSK|WPA2PSK),(NONE|WEP|TKIP|AES),key
void setSTAKey(char* auth,char *encry,char *key);
String getSTANetwork();//WANN (static|DHCP),ip,subnet,gateway
void setSTANetwork(char *mode, char *ip, char *subnet, char *gateway);
String getSTAMac();//WSMAC returns MAC
void setSTAMac(int code, char *mac);//Code default is 8888, no idea what its for
String STALinkStatus();//WSLK (Disconnected|AP SSID (AP MAC)|RF Off)
String STASignalStrength();//WSLQ (Disconnected|Value)
String scan();//WSCAN returns list
String getSTADNS();//WSDNS address
void setSTADNS(char *dns);
String getAPNetwork();//LANN ip,subnet
void setAPNetwork(char *ip, char *subnet);
String getAPParams();//WAP (11B|11BG|11BGN),SSID,(AUTO|C1...C11)
void setAPParams(char *mode, char *ssid, char *channel);
String getAPKey();//WAKEY (OPEN|WPA2PSK),(NONE|AES),key
void setAPKey(char* auth,char *encry,char *key);
String getAPMac();//WAMAC returns MAC
String getAPDHCP();//WADHCP (on|off)
void setAPDHCP(char *status);
String getAPPageDomain();//WADMN domain
void setAPPageDomain(char *domain);
void setPageDisplayMode(char *mode);//WEBSWITCH (iw|ew)
void setPageLanguage(char *lang);//PLANG CN|EN
String getUpgradeUrl();//UPURL url !!!DANGEROUS!!!
void setUpgradeUrl(char *url);//url,filename (filename is optional, if provided upgrade is auto started)
String getUpgradeFile();//UPFILE filename !!!DANGEROUS!!!
void setUpgradeFile(char *filename);
String startUpgrade();//UPST !!!DANGEROUS!!!
String getWebAuth();//WEBU user,pass
void setWebAuth(char *user, char *pass);
String getSleepMode();//MSLP normal|standby
void setSleepMode(char *mode);
void setModId(char *modid);//WRMID
String getWifiCfgPassword();//ASWD aswd
void setWifiCfgPassword(char *aswd);
private:
String readResponse(int contentLength);
bool startATSequence();
String aHeader;
String aBody;
//String lastHost;
int lastErr;
bool debugState;
};
#endif

View File

@@ -0,0 +1,4 @@
DigiFi
======
DigiX WiFi Library for the WIFI232-G Module

View File

@@ -0,0 +1,61 @@
// DigiX WiFi module example - released by Digistump LLC/Erik Kettenburg under CC-BY-SA 3.0
// Inspired by HttpClient library by MCQN Ltd.
#include <DigiFi.h>
DigiFi wifi;
void setup()
{
// initialize serial communications at 9600 bps:
Serial.begin(9600);
wifi.begin(9600);
//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");
while (wifi.ready() != 1)
{
Serial.println("Error connecting to network");
delay(15000);
}
Serial.println("Connected to wifi!");
//GET request example
if(wifi.get("digistump.com","/test.txt")){
String body = wifi.body();
Serial.println(body);
}
else{
Serial.println("error");
}
//POST request example
Serial.println("Sending tweet!");
//To use thingspeak for sending tweets see: http://community.thingspeak.com/documentation/apps/thingtweet/
if(wifi.post("api.thingspeak.com","/apps/thingtweet/1/statuses/update","api_key=[YOURTHINGTWEETAPIKEY]&status="+wifi.URLEncode("Tweet from my new DigiX! #digix #digistump http://digistump.com"))){
String body = wifi.body();
Serial.println(body);
}
else{
Serial.println("error");
}
wifi.close();
}
void loop()
{
}

View File

@@ -0,0 +1,77 @@
/*
Chat Server
A simple server that distributes any incoming messages to all
connected clients. To use telnet to your device's IP address and type.
You can see the client's input in the serial monitor as well.
Using a DigiX.
Circuit:
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified Dec 22, 2013 for use with DigiX by Erik Kettenburg
*/
#include <DigiFi.h>
DigiFi server;
boolean alreadyConnected = false; // whether or not the client was connected previously
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
//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);
}
// start listening for clients
server.begin();
server.server(8080); //connect to it on port 8080
while (server.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
Serial.print("Chat server address:");
Serial.println(server.localIP());
}
void loop() {
// wait for a new client:
// when the client sends the first byte, say hello:
if (server.available() > 0) {
if (!alreadyConnected) {
// clead out the input buffer:
server.flush();
Serial.println("We have a new client");
server.println("Hello, client!");
alreadyConnected = true;
}
// read the bytes incoming from the client:
char thisChar = server.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}

View File

@@ -0,0 +1,89 @@
/*
Telnet client
This sketch connects to a a telnet server (http://www.google.com)
using a DigiX. You'll need a telnet server
to test this with.
Processing's ChatServer example (part of the network library) works well,
running on port 10002. It can be found as part of the examples
in the Processing application, available at
http://processing.org/
created 14 Sep 2010
modified 9 Apr 2012
by Tom Igoe
modified Dec 22, 2013 for use with DigiX by Erik Kettenburg
*/
#include <DigiFi.h>
// Enter the IP address of the server you're connecting to:
IPAddress server(1, 1, 1, 1);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 23 is default for telnet;
// if you're using Processing's ChatServer, use port 10002):
DigiFi client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
//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("Connecting...");
// start the connection:
client.begin(9600);
client.connect(server,23);
Serial.println("Connected.");
//client.setDebug(true);
//wait for module to be ready
while (client.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// as long as there are bytes in the serial queue,
// read them and send them out the socket if it's open:
while (Serial.available() > 0) {
char inChar = Serial.read();
if (client.connected()) {
client.print(inChar);
}
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing:
while (true);
}
}

View File

@@ -0,0 +1,127 @@
/*
Udp NTP Client
Get the time from a Network Time Protocol (NTP) time server
Demonstrates use of UDP sendPacket and ReceivePacket
For more on NTP time servers and the messages needed to communicate with them,
see http://en.wikipedia.org/wiki/Network_Time_Protocol
created 4 Sep 2010
by Michael Margolis
modified 9 Apr 2012
by Tom Igoe
modified Dec 22, 2013 for use with DigiX by Erik Kettenburg
This code is in the public domain.
*/
#include <DigiFi.h>
char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
uint8_t packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
DigiFi client;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
//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);
}
// start the connection:
client.begin(9600);
//client.setDebug(true);
//wait for module to be ready
while (client.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
client.setMode(UDP); //must come before connect
Serial.println("Setting up UDP connection");
client.connect(timeServer,123);
}
void loop()
{
sendNTPpacket(); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
if ( client.available() ) {
// We've received a packet, read the data from it
client.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch % 60); // print the second
}
// wait ten seconds before asking for the time again
delay(10000);
}
// send an NTP request to the time server at the given address
unsigned long sendNTPpacket()
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
client.write(packetBuffer, NTP_PACKET_SIZE);
}

View File

@@ -0,0 +1,86 @@
/*
Web client
This sketch connects to a website (http://www.google.com)
using an DigiX.
Based on example by David A. Mellis, Tom Igoe, and Adrian McEwen
*/
#include <DigiFi.h>
// if you don't want to use DNS - though it is handeled by the WiFI module
//so there is no size penalty for using it -
// 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[] = "digistump.com"; // name address for Google (using DNS)
// Initialize the Wifi library (client/server/and main all in one)
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
DigiFi client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
//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);
}
// start the connection:
client.begin(9600);
//client.setDebug(true);
//wait for module to be ready
while (client.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /test.txt HTTP/1.1");
client.println("Host: www.digistump.com");
client.println("Connection: close");
client.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
//while(!Serial1.available()){}
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
}

View File

@@ -0,0 +1,100 @@
/*
Web Server
A simple web server that shows the value of the analog input pins.
Using a DigiX.
Circuit:
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified Dec 22, 2013 for use with DigiX by Erik Kettenburg
*/
#include <DigiFi.h>
// Initialize the DigiFi library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
DigiFi server;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
//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);
}
// start the server:
server.begin();
server.server(8080); //start server on port 8080
server.setTCPTimeout(1); //force wifi to close connection after idle for 1 second
//fix for not being able to close client connections
//see WebServerChunked for a better approach
while (server.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
Serial.print("server is at ");
Serial.println(server.localIP());
}
boolean currentLineIsBlank = false;
void loop() {
// listen for incoming
// an http request ends with a blank line
if (server.available()) {
char c = server.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
server.println("HTTP/1.1 200 OK");
server.println("Content-Type: text/html");
server.println("Connection: close"); // the connection will be closed after completion of the response
server.println("Refresh: 5"); // refresh the page automatically every 5 sec
server.println();
server.println("<!DOCTYPE HTML>");
server.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
server.print("analog input ");
server.print(analogChannel);
server.print(" is ");
server.print(sensorReading);
server.println("<br />");
}
server.println("</html>");
server.println("");
server.println("");
currentLineIsBlank = false;
}
else if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
// give the web browser time to receive the data
delay(1);
}

View File

@@ -0,0 +1,98 @@
/*
Web Server
A simple web server that shows the value of the analog input pins.
Using a DigiX.
Circuit:
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified Dec 22, 2013 for use with DigiX by Erik Kettenburg
*/
#include <DigiFi.h>
// Initialize the DigiFi library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
DigiFi server;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
//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);
}
// start the server:
server.begin();
server.server(8080); //start server on port 8080
while (server.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
Serial.print("server is at ");
Serial.println(server.localIP());
}
boolean currentLineIsBlank = false;
void loop() {
// listen for incoming
// an http request ends with a blank line
if (server.available()) {
char c = server.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
server.println("HTTP/1.1 200 OK");
server.println("Content-Type: text/html");
server.println("Connection: close"); // the connection will be closed after completion of the response
//server.println("Refresh: 5"); // refresh the page automatically every 5 sec
server.println("Transfer-Encoding: chunked");
server.println();
server.printChunk("<!DOCTYPE HTML>");
server.printChunk("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
server.printChunk("analog input ");
server.printChunk(analogChannel);
server.printChunk(" is ");
server.printChunk(sensorReading);
server.printChunk("<br />");
}
server.printChunk("</html>");
server.closeChunk();
currentLineIsBlank = false;
}
else if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
// give the web browser time to receive the data
delay(1);
}

View File

@@ -0,0 +1,118 @@
bool start = true;
String message = "";
#include <DigiFi.h>
DigiFi wifi;
//#define DEBUG
#include <Wire.h> // I2C Master lib for ATTinys which use USI - comment this out to use with standard arduinos
#include <LiquidCrystal_I2C.h> // for LCD w/ GPIO MODIFIED for the ATtiny85
#define GPIO_ADDR 0x27 // (PCA8574A A0-A2 @5V) typ. A0-A3 Gnd 0x20 / 0x38 for A - 0x27 is the address of the Digispark LCD modules.
LiquidCrystal_I2C lcd(GPIO_ADDR,16,2); // set address & 16 chars / 2 lines
// Require keyboard control library
#include <KeyboardController.h>
// Initialize USB Controller
USBHost usb;
// Attach keyboard controller to USB
KeyboardController keyboard(usb);
// This function intercepts key press
void keyPressed() {
}
// This function intercepts key release
void keyReleased() {
printKey();
}
void printKey() {
if(start){
lcd.clear();
lcd.home();
start = false;
}
if(keyboard.getOemKey()==40){//enter pressed
lcd.noAutoscroll();
lcd.clear();
lcd.home();
lcd.print("Sending tweet...");
if(wifi.post("api.thingspeak.com","/apps/thingtweet/1/statuses/update","api_key=[YOURTHINGTWEETAPIKEY]&status="+wifi.URLEncode(message))){
lcd.clear();
lcd.home();
lcd.print("Tweet sent!");
}
else{
lcd.clear();
lcd.home();
lcd.print("Error sending!");
}
delay(3000);
lcd.clear();
lcd.home();
lcd.print("DigiX - Ready!");
message ="";
start=true;
lcd.noAutoscroll();
}
else{
// getKey() returns the ASCII translation of OEM key
// combined with modifiers.
char nextChar = keyboard.getKey();
lcd.print(nextChar);
message += nextChar;
if(message.length()==16)
lcd.autoscroll();
}
}
void setup()
{
Wire1.begin(); // initialize I2C lib - comment this out to use with standard arduinos
lcd.init(); // initialize the lcd
lcd.backlight(); // Print a message to the LCD.
lcd.print("Starting....");
delay(5000); //give wifi some time to warm up
lcd.clear();
lcd.print("WiFi Starting...");
wifi.begin(9600);
delay(200);
while (wifi.ready() != 1)
{
lcd.home();
lcd.print("WiFi not ready");
delay(15000);
}
lcd.clear();
lcd.home();
lcd.print("DigiX - Ready!");
}
void loop()
{
// Process USB tasks
usb.Task();
}

View File

@@ -0,0 +1,44 @@
#include <DigiFi.h>
DigiFi wifi;
void setup()
{
Serial.begin(9600);
wifi.begin(9600);
//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");
while (wifi.ready() != 1)
{
Serial.println("Error connecting to network");
delay(15000);
}
Serial.println("Connected to wifi!");
Serial.print("Server running at: ");
String address = wifi.server(8080);//sets up server and returns IP
Serial.println(address);
// wifi.close();
}
void loop()
{
if ( wifi.serverRequest()){
Serial.print("Request for: ");
Serial.println(wifi.serverRequestPath());
if(wifi.serverRequestPath()!="/")
wifi.serverResponse("404 Not Found",404);
else
wifi.serverResponse("<html><body><h1>This is a test</h1></body></html>"); //defaults to 200
}
delay(10);
}

View File

@@ -0,0 +1,155 @@
/*
Udp NTP Client
Uses both Due_RTC library and DigiFi to connect to NTP server
get current time and set RTC to that time.
This code is in the public domain.
*/
#include <rtc_clock.h>
#include <DigiFi.h>
RTC_clock rtc_clock(XTAL);
char* daynames[]={"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
int hh,mm,ss,dow,dd,mon,yyyy;
char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
uint8_t packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
DigiFi client;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
//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);
}
rtc_clock.init();
// start the connection:
client.begin(9600);
//client.setDebug(true);
//wait for module to be ready
while (client.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
client.setMode(UDP); //must come before connect
rtc_clock.set_time(__TIME__);
Serial.println("Setting up UDP connection");
client.connect(timeServer,123);
unsigned long ntpUnixTime = 0;
while(ntpUnixTime == 0){
sendNTPpacket(); // send an NTP packet to a time server
delay(1000);
ntpUnixTime = getNTPpacket();
}
Serial.print("Got NTP Timestamp: ");
Serial.println(ntpUnixTime);
Serial.println("Setting RTC Clock");
rtc_clock.set_timestamp(ntpUnixTime);
}
void loop()
{
Serial.print("Time: ");
rtc_clock.get_time(&hh,&mm,&ss);
rtc_clock.get_date(&dow,&dd,&mon,&yyyy);
digitprint(hh, 2);
Serial.print(":");
digitprint(mm, 2);
Serial.print(":");
digitprint(ss, 2);
Serial.println("");
Serial.print("Date: ");
Serial.print(daynames[dow-1]);
Serial.print(" ");
digitprint(dd, 2);
Serial.print(".");
digitprint(mon, 2);
Serial.print(".");
Serial.println(yyyy);
Serial.println("");
delay(1000);
}
// send an NTP request to the time server at the given address
unsigned long sendNTPpacket()
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
client.write(packetBuffer, NTP_PACKET_SIZE);
}
unsigned long getNTPpacket(){
if ( client.available() ) {
// We've received a packet, read the data from it
client.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
//Serial.print("Seconds since Jan 1 1900 = " );
//Serial.println(secsSince1900);
// now convert NTP time into everyday time:
//Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
return epoch;
}
else{
return 0;
}
}
void digitprint(int value, int lenght){
for (int i = 0; i < (lenght - numdigits(value)); i++){
Serial.print("0");
}
Serial.print(value);
}
int numdigits(int i){
int digits;
if (i < 10)
digits = 1;
else
digits = (int)(log10((double)i)) + 1;
return digits;
}

View File

@@ -0,0 +1,99 @@
#include <DigiFi.h>
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "XXXMX2WYYR0EV68M";
const int updateThingSpeakInterval = 16 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
long lastConnectionTime = 0;
int failedCounter = 0;
// Initialize DigiFi
DigiFi client;
void setup()
{
// Start Serial for debugging on the Serial Monitor
Serial.begin(9600);
//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);
}
// Start DigiFi
startDigiFi();
}
void loop()
{
// Read value from Analog Input Pin 0
String analogPin0 = String(analogRead(A0), DEC);
// Update ThingSpeak
if(millis() - lastConnectionTime > updateThingSpeakInterval)
{
updateThingSpeak("field1="+analogPin0);
}
// Check if Arduino Ethernet needs to be restarted
if (failedCounter > 3 ) {startDigiFi();}
}
void updateThingSpeak(String tsData)
{
if (client.connect(thingSpeakAddress, 80))
{
lastConnectionTime = millis();
if(wifi.post("api.thingspeak.com","/update","api_key="++writeAPIKey++"&status="+wifi.URLEncode(tsData)))
{
Serial.println("Sent to ThingSpeak");
Serial.println();
failedCounter = 0;
Serial.println(wifi.body());
}
else
{
failedCounter++;
Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");
Serial.println();
}
}
else
{
failedCounter++;
Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
Serial.println();
lastConnectionTime = millis();
}
}
void startDigiFi()
{
Serial.println("Connecting Arduino to network...");
Serial.println();
delay(1000);
// Connect to network amd obtain an IP address using DHCP
client.begin();
client.setDebug(true);
while (client.ready() != 1)
{
Serial.println("Connecting to network...");
delay(1000);
}
delay(1000);
}

View File

@@ -0,0 +1,61 @@
// DigiX WiFi module example - released by Digistump LLC/Erik Kettenburg under CC-BY-SA 3.0
// Inspired by HttpClient library by MCQN Ltd.
#include <DigiFi.h>
DigiFi wifi;
void setup()
{
// initialize serial communications at 9600 bps:
Serial.begin(9600);
wifi.begin(9600);
//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");
while (wifi.ready() != 1)
{
Serial.println("Error connecting to network");
delay(15000);
}
Serial.println("Connected to wifi!");
//GET request example
if(wifi.get("digistump.com","/test.txt")){
String body = wifi.body();
Serial.println(body);
}
else{
Serial.println("error");
}
//POST request example
Serial.println("Sending tweet!");
//To use thingspeak for sending tweets see: http://community.thingspeak.com/documentation/apps/thingtweet/
if(wifi.post("api.thingspeak.com","/apps/thingtweet/1/statuses/update","api_key=[YOURTHINGTWEETAPIKEY]&status="+wifi.URLEncode("Tweet from my new DigiX! #digix #digistump http://digistump.com"))){
String body = wifi.body();
Serial.println(body);
}
else{
Serial.println("error");
}
wifi.close();
}
void loop()
{
}

View File

@@ -0,0 +1,33 @@
#include <DigiFi.h>
DigiFi wifi;
void setup()
{
Serial.begin(9600);
wifi.begin(9600);
//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");
while (wifi.ready() != 1)
{
Serial.println("Error connecting to network");
delay(15000);
}
Serial.println("Connected to wifi!");
wifi.startATMode();
Serial.println(wifi.ping("192.168.2.1"));
wifi.endATMode();
wifi.close();
}
void loop()
{
}