1
0
mirror of https://github.com/arduino/Arduino.git synced 2024-12-01 12:24:14 +01:00

Merge branch 'ide-1.5.x-library-to-new-format' into ide-1.5.x

This commit is contained in:
Cristian Maglie 2013-08-08 16:43:19 +02:00
commit e4e2a47e68
752 changed files with 167609 additions and 10266 deletions

View File

@ -27,6 +27,7 @@ ARDUINO 1.5.3 BETA
* sam: Added CAN library (still in early stage of development) (Palliser)
* sam: Bugfix SPI library: begin() after end() now works (stimmer)
* sam: Bugfix SPI library: incorrent pin configuration in non-extended mode.
* Ported all libraries to new 1.5 format
[firmwares]
* Arduino Due: fixed USB2Serial garbage at startup (https://github.com/arduino/Arduino/pull/1267)

View File

@ -1,165 +0,0 @@
#include "w5100.h"
#include "socket.h"
extern "C" {
#include "string.h"
}
#include "Arduino.h"
#include "Ethernet.h"
#include "EthernetClient.h"
#include "EthernetServer.h"
#include "Dns.h"
uint16_t EthernetClient::_srcport = 1024;
EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {
}
EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {
}
int EthernetClient::connect(const char* host, uint16_t port) {
// Look up the host first
int ret = 0;
DNSClient dns;
IPAddress remote_addr;
dns.begin(Ethernet.dnsServerIP());
ret = dns.getHostByName(host, remote_addr);
if (ret == 1) {
return connect(remote_addr, port);
} else {
return ret;
}
}
int EthernetClient::connect(IPAddress ip, uint16_t port) {
if (_sock != MAX_SOCK_NUM)
return 0;
for (int i = 0; i < MAX_SOCK_NUM; i++) {
uint8_t s = W5100.readSnSR(i);
if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
_sock = i;
break;
}
}
if (_sock == MAX_SOCK_NUM)
return 0;
_srcport++;
if (_srcport == 0) _srcport = 1024;
socket(_sock, SnMR::TCP, _srcport, 0);
if (!::connect(_sock, rawIPAddress(ip), port)) {
_sock = MAX_SOCK_NUM;
return 0;
}
while (status() != SnSR::ESTABLISHED) {
delay(1);
if (status() == SnSR::CLOSED) {
_sock = MAX_SOCK_NUM;
return 0;
}
}
return 1;
}
size_t EthernetClient::write(uint8_t b) {
return write(&b, 1);
}
size_t EthernetClient::write(const uint8_t *buf, size_t size) {
if (_sock == MAX_SOCK_NUM) {
setWriteError();
return 0;
}
if (!send(_sock, buf, size)) {
setWriteError();
return 0;
}
return size;
}
int EthernetClient::available() {
if (_sock != MAX_SOCK_NUM)
return W5100.getRXReceivedSize(_sock);
return 0;
}
int EthernetClient::read() {
uint8_t b;
if ( recv(_sock, &b, 1) > 0 )
{
// recv worked
return b;
}
else
{
// No data available
return -1;
}
}
int EthernetClient::read(uint8_t *buf, size_t size) {
return recv(_sock, buf, size);
}
int EthernetClient::peek() {
uint8_t b;
// Unlike recv, peek doesn't check to see if there's any data available, so we must
if (!available())
return -1;
::peek(_sock, &b);
return b;
}
void EthernetClient::flush() {
while (available())
read();
}
void EthernetClient::stop() {
if (_sock == MAX_SOCK_NUM)
return;
// attempt to close the connection gracefully (send a FIN to other side)
disconnect(_sock);
unsigned long start = millis();
// wait a second for the connection to close
while (status() != SnSR::CLOSED && millis() - start < 1000)
delay(1);
// if it hasn't closed, close it forcefully
if (status() != SnSR::CLOSED)
close(_sock);
EthernetClass::_server_port[_sock] = 0;
_sock = MAX_SOCK_NUM;
}
uint8_t EthernetClient::connected() {
if (_sock == MAX_SOCK_NUM) return 0;
uint8_t s = status();
return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
(s == SnSR::CLOSE_WAIT && !available()));
}
uint8_t EthernetClient::status() {
if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;
return W5100.readSnSR(_sock);
}
// the next function allows us to use the client returned by
// EthernetServer::available() as the condition in an if-statement.
EthernetClient::operator bool() {
return _sock != MAX_SOCK_NUM;
}

View File

@ -1,136 +0,0 @@
/*
Twitter Client with Strings
This sketch connects to Twitter using an Ethernet shield. It parses the XML
returned, and looks for <text>this is a tweet</text>
You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield,
either one will work, as long as it's got a Wiznet Ethernet module on board.
This example uses the DHCP routines in the Ethernet library which is part of the
Arduino core from version 1.0 beta 1
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 21 May 2011
modified 9 Apr 2012
by Tom Igoe
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
IPAddress ip(192,168,1,20);
// initialize the library instance:
EthernetClient client;
const unsigned long requestInterval = 60000; // delay between requests
char serverName[] = "api.twitter.com"; // twitter URL
boolean requested; // whether you've made a request since connecting
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
String currentLine = ""; // string to hold the text from server
String tweet = ""; // string to hold the tweet
boolean readingTweet = false; // if you're currently reading the tweet
void setup() {
// reserve space for the strings:
currentLine.reserve(256);
tweet.reserve(150);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// attempt a DHCP connection:
Serial.println("Attempting to get an IP address using DHCP:");
if (!Ethernet.begin(mac)) {
// if DHCP fails, start with a hard-coded address:
Serial.println("failed to get an IP address using DHCP, trying manually");
Ethernet.begin(mac, ip);
}
Serial.print("My address:");
Serial.println(Ethernet.localIP());
// connect to Twitter:
connectToServer();
}
void loop()
{
if (client.connected()) {
if (client.available()) {
// read incoming bytes:
char inChar = client.read();
// add incoming byte to end of line:
currentLine += inChar;
// if you get a newline, clear the line:
if (inChar == '\n') {
currentLine = "";
}
// if the current line ends with <text>, it will
// be followed by the tweet:
if ( currentLine.endsWith("<text>")) {
// tweet is beginning. Clear the tweet string:
readingTweet = true;
tweet = "";
}
// if you're currently reading the bytes of a tweet,
// add them to the tweet String:
if (readingTweet) {
if (inChar != '<') {
tweet += inChar;
}
else {
// if you got a "<" character,
// you've reached the end of the tweet:
readingTweet = false;
Serial.println(tweet);
// close the connection to the server:
client.stop();
}
}
}
}
else if (millis() - lastAttemptTime > requestInterval) {
// if you're not connected, and two minutes have passed since
// your last connection, then attempt to connect again:
connectToServer();
}
}
void connectToServer() {
// attempt to connect, and wait a millisecond:
Serial.println("connecting to server...");
if (client.connect(serverName, 80)) {
Serial.println("making HTTP request...");
// make HTTP GET request to twitter:
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1");
client.println("HOST: api.twitter.com");
client.println("Connection: close");
client.println();
}
// note the time of this connect attempt:
lastAttemptTime = millis();
}

View File

@ -1,41 +0,0 @@
#ifndef _SOCKET_H_
#define _SOCKET_H_
#include "w5100.h"
extern uint8_t socket(SOCKET s, uint8_t protocol, uint16_t port, uint8_t flag); // Opens a socket(TCP or UDP or IP_RAW mode)
extern void close(SOCKET s); // Close socket
extern uint8_t connect(SOCKET s, uint8_t * addr, uint16_t port); // Establish TCP connection (Active connection)
extern void disconnect(SOCKET s); // disconnect the connection
extern uint8_t listen(SOCKET s); // Establish TCP connection (Passive connection)
extern uint16_t send(SOCKET s, const uint8_t * buf, uint16_t len); // Send data (TCP)
extern int16_t recv(SOCKET s, uint8_t * buf, int16_t len); // Receive data (TCP)
extern uint16_t peek(SOCKET s, uint8_t *buf);
extern uint16_t sendto(SOCKET s, const uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); // Send data (UDP/IP RAW)
extern uint16_t recvfrom(SOCKET s, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); // Receive data (UDP/IP RAW)
extern uint16_t igmpsend(SOCKET s, const uint8_t * buf, uint16_t len);
// Functions to allow buffered UDP send (i.e. where the UDP datagram is built up over a
// number of calls before being sent
/*
@brief This function sets up a UDP datagram, the data for which will be provided by one
or more calls to bufferData and then finally sent with sendUDP.
@return 1 if the datagram was successfully set up, or 0 if there was an error
*/
extern int startUDP(SOCKET s, uint8_t* addr, uint16_t port);
/*
@brief This function copies up to len bytes of data from buf into a UDP datagram to be
sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls.
@return Number of bytes successfully buffered
*/
uint16_t bufferData(SOCKET s, uint16_t offset, const uint8_t* buf, uint16_t len);
/*
@brief Send a UDP datagram built up from a sequence of startUDP followed by one or more
calls to bufferData.
@return 1 if the datagram was successfully sent, or 0 if there was an error
*/
int sendUDP(SOCKET s);
#endif
/* _SOCKET_H_ */

View File

@ -1,14 +0,0 @@
- make Firmata a subclass of HardwareSerial
- per-pin digital callback, since the per-port callback is a bit complicated
for beginners (maybe Firmata is not for beginners...)
- simplify SimpleDigitalFirmata, take out the code that checks to see if the
data has changed, since it is a bit complicated for this example. Ideally
this example would be based on a call
- turn current SimpleDigitalFirmata into DigitalPortFirmata for a more complex
example using the code which checks for changes before doing anything
- test integration with Wiring

View File

@ -1,228 +0,0 @@
/*
* Firmata is a generic protocol for communicating with microcontrollers
* from software on a host computer. It is intended to work with
* any host computer software package.
*
* To download a host software package, please clink on the following link
* to open the download page in your default browser.
*
* http://firmata.org/wiki/Download
*/
/*
Copyright (C) 2009 Jeff Hoefs. All rights reserved.
Copyright (C) 2009 Shigeru Kobayashi. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
See file LICENSE.txt for further informations on licensing terms.
*/
#include <Wire.h>
#include <Firmata.h>
#define I2C_WRITE B00000000
#define I2C_READ B00001000
#define I2C_READ_CONTINUOUSLY B00010000
#define I2C_STOP_READING B00011000
#define I2C_READ_WRITE_MODE_MASK B00011000
#define MAX_QUERIES 8
unsigned long currentMillis; // store the current value from millis()
unsigned long previousMillis; // for comparison with currentMillis
unsigned int samplingInterval = 32; // default sampling interval is 33ms
unsigned int i2cReadDelayTime = 0; // default delay time between i2c read request and Wire.requestFrom()
unsigned int powerPinsEnabled = 0; // use as boolean to prevent enablePowerPins from being called more than once
#define MINIMUM_SAMPLING_INTERVAL 10
#define REGISTER_NOT_SPECIFIED -1
struct i2c_device_info {
byte addr;
byte reg;
byte bytes;
};
i2c_device_info query[MAX_QUERIES];
byte i2cRxData[32];
boolean readingContinuously = false;
byte queryIndex = 0;
void readAndReportData(byte address, int theRegister, byte numBytes)
{
if (theRegister != REGISTER_NOT_SPECIFIED) {
Wire.beginTransmission(address);
Wire.write((byte)theRegister);
Wire.endTransmission();
delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck
}
else {
theRegister = 0; // fill the register with a dummy value
}
Wire.requestFrom(address, numBytes);
// check to be sure correct number of bytes were returned by slave
if(numBytes == Wire.available()) {
i2cRxData[0] = address;
i2cRxData[1] = theRegister;
for (int i = 0; i < numBytes; i++) {
i2cRxData[2 + i] = Wire.read();
}
// send slave address, register and received bytes
Firmata.sendSysex(I2C_REPLY, numBytes + 2, i2cRxData);
}
else {
if(numBytes > Wire.available()) {
Firmata.sendString("I2C Read Error: Too many bytes received");
} else {
Firmata.sendString("I2C Read Error: Too few bytes received");
}
}
}
void sysexCallback(byte command, byte argc, byte *argv)
{
byte mode;
byte slaveAddress;
byte slaveRegister;
byte data;
int delayTime;
if (command == I2C_REQUEST) {
mode = argv[1] & I2C_READ_WRITE_MODE_MASK;
slaveAddress = argv[0];
switch(mode) {
case I2C_WRITE:
Wire.beginTransmission(slaveAddress);
for (byte i = 2; i < argc; i += 2) {
data = argv[i] + (argv[i + 1] << 7);
Wire.write(data);
}
Wire.endTransmission();
delayMicroseconds(70); // TODO is this needed?
break;
case I2C_READ:
if (argc == 6) {
// a slave register is specified
slaveRegister = argv[2] + (argv[3] << 7);
data = argv[4] + (argv[5] << 7); // bytes to read
readAndReportData(slaveAddress, (int)slaveRegister, data);
}
else {
// a slave register is NOT specified
data = argv[2] + (argv[3] << 7); // bytes to read
readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data);
}
break;
case I2C_READ_CONTINUOUSLY:
if ((queryIndex + 1) >= MAX_QUERIES) {
// too many queries, just ignore
Firmata.sendString("too many queries");
break;
}
query[queryIndex].addr = slaveAddress;
query[queryIndex].reg = argv[2] + (argv[3] << 7);
query[queryIndex].bytes = argv[4] + (argv[5] << 7);
readingContinuously = true;
queryIndex++;
break;
case I2C_STOP_READING:
readingContinuously = false;
queryIndex = 0;
break;
default:
break;
}
}
else if (command == SAMPLING_INTERVAL) {
samplingInterval = argv[0] + (argv[1] << 7);
if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) {
samplingInterval = MINIMUM_SAMPLING_INTERVAL;
}
samplingInterval -= 1;
Firmata.sendString("sampling interval");
}
else if (command == I2C_CONFIG) {
delayTime = (argv[4] + (argv[5] << 7)); // MSB
delayTime = (delayTime << 8) + (argv[2] + (argv[3] << 7)); // add LSB
if((argv[0] + (argv[1] << 7)) > 0) {
enablePowerPins(PORTC3, PORTC2);
}
if(delayTime > 0) {
i2cReadDelayTime = delayTime;
}
if(argc > 6) {
// If you extend I2C_Config, handle your data here
}
}
}
void systemResetCallback()
{
readingContinuously = false;
queryIndex = 0;
}
/* reference: BlinkM_funcs.h by Tod E. Kurt, ThingM, http://thingm.com/ */
// Enables Pins A2 and A3 to be used as GND and Power
// so that I2C devices can be plugged directly
// into Arduino header (pins A2 - A5)
static void enablePowerPins(byte pwrpin, byte gndpin)
{
if(powerPinsEnabled == 0) {
DDRC |= _BV(pwrpin) | _BV(gndpin);
PORTC &=~ _BV(gndpin);
PORTC |= _BV(pwrpin);
powerPinsEnabled = 1;
Firmata.sendString("Power pins enabled");
delay(100);
}
}
void setup()
{
Firmata.setFirmwareVersion(2, 0);
Firmata.attach(START_SYSEX, sysexCallback);
Firmata.attach(SYSTEM_RESET, systemResetCallback);
for (int i = 0; i < TOTAL_PINS; ++i) {
pinMode(i, OUTPUT);
}
Firmata.begin(57600);
Wire.begin();
}
void loop()
{
while (Firmata.available()) {
Firmata.processInput();
}
currentMillis = millis();
if (currentMillis - previousMillis > samplingInterval) {
previousMillis += samplingInterval;
for (byte i = 0; i < queryIndex; i++) {
readAndReportData(query[i].addr, query[i].reg, query[i].bytes);
}
}
}

View File

@ -1,162 +0,0 @@
/*
GSM Twitter Client with Strings
This sketch connects to Twitter using an Arduino GSM shield.
It parses the XML returned, and looks for the string <text>this is a tweet</text>
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan
created 8 Mar 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/GSMExamplesTwitterClient
This code is in the public domain.
*/
// libraries
#include <GSM.h>
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN "APN" // replace your GPRS APN
#define GPRS_LOGIN "LOGIN" // replace with your GPRS login
#define GPRS_PASSWORD "PASSWORD" // replace with your GPRS password
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;
const unsigned long requestInterval = 30*1000; // delay between requests: 30 seconds
// API Twitter URL
char server[] = "api.twitter.com";
boolean requested; // whether you've made a request since connecting
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
String currentLine = ""; // string to hold the text from server
String tweet = ""; // string to hold the tweet
boolean readingTweet = false; // if you're currently reading the tweet
void setup()
{
// reserve space for the strings:
currentLine.reserve(256);
tweet.reserve(150);
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("Connected to GPRS network");
Serial.println("connecting...");
connectToServer();
}
void loop()
{
char c;
if (client.connected())
{
if (client.available())
{
// read incoming bytes:
char inChar = client.read();
// add incoming byte to end of line:
currentLine += inChar;
// if you get a newline, clear the line:
if (inChar == '\n')
{
currentLine = "";
}
// if the current line ends with <text>, it will
// be followed by the tweet:
if (currentLine.endsWith("<text>"))
{
// tweet is beginning. Clear the tweet string:
readingTweet = true;
tweet = "";
}
// if you're currently reading the bytes of a tweet,
// add them to the tweet String:
if (readingTweet)
{
if (inChar != '<')
{
tweet += inChar;
}
else
{
// if you got a "<" character,
// you've reached the end of the tweet:
readingTweet = false;
Serial.println(tweet);
// close the connection to the server:
client.stop();
}
}
}
}
else if (millis() - lastAttemptTime > requestInterval)
{
// if you're not connected, and two minutes have passed since
// your last connection, then attempt to connect again:
connectToServer();
}
}
/*
Connect to API Twitter server and do a request for timeline
*/
void connectToServer()
{
// attempt to connect, and wait a millisecond:
Serial.println("connecting to server...");
if (client.connect(server, 80))
{
Serial.println("making HTTP request...");
// make HTTP GET request to twitter:
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1");
client.println("HOST: api.twitter.com");
client.println();
}
// note the time of this connect attempt:
lastAttemptTime = millis();
}

View File

@ -1,126 +0,0 @@
/*
This example connects to a WEP-encrypted Wifi network.
Then it prints the MAC address of the Wifi shield,
the IP address obtained, and other network details.
If you use 40-bit WEP, you need a key that is 10 characters long,
and the characters must be hexadecimal (0-9 or A-F).
e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work
(too short) and ABBAISDEAF won't work (I and S are not
hexadecimal characters).
For 128-bit, you need a string that is 26 characters long.
D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters,
all in the 0-9, A-F range.
Circuit:
* WiFi shield attached
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char key[] = "D0D0DEADF00DABBADEAFBEADED"; // your network key
int keyIndex = 0; // your network key Index number
int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WEP network, SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, keyIndex, key);
// wait 10 seconds for connection:
delay(10000);
}
// once you are connected :
Serial.print("You're connected to the network");
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
}
void printCurrentNet() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5],HEX);
Serial.print(":");
Serial.print(bssid[4],HEX);
Serial.print(":");
Serial.print(bssid[3],HEX);
Serial.print(":");
Serial.print(bssid[2],HEX);
Serial.print(":");
Serial.print(bssid[1],HEX);
Serial.print(":");
Serial.println(bssid[0],HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption,HEX);
Serial.println();
}

View File

@ -1,129 +0,0 @@
/*
WiFi Web Server LED Blink
A simple web server that lets you blink an LED via the web.
This sketch will print the IP address of your WiFi Shield (once connected)
to the Serial monitor. From there, you can open that address in a web browser
to turn on and off the LED on pin 9.
If the IP address of your shield is yourAddress:
http://yourAddress/H turns the LED on
http://yourAddress/L turns it off
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
Circuit:
* WiFi shield attached
* LED attached to pin 9
created 25 Nov 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(9, OUTPUT); // set the LED pin mode
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true); // don't continue
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the web server on port 80
printWifiStatus(); // you're connected now, so print out the status
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click <a href=\"/H\">here</a> turn the LED on pin 9 on<br>");
client.print("Click <a href=\"/L\">here</a> turn the LED on pin 9 off<br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else { // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
digitalWrite(9, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(9, LOW); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}

View File

@ -1,163 +0,0 @@
/*
Wifi Twitter Client with Strings
This sketch connects to Twitter using using an Arduino WiFi shield.
It parses the XML returned, and looks for <text>this is a tweet</text>
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* WiFi shield attached to pins 10, 11, 12, 13
created 23 apr 2012
modified 31 May 2012
by Tom Igoe
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS; // status of the wifi connection
// initialize the library instance:
WiFiClient client;
const unsigned long requestInterval = 30*1000; // delay between requests; 30 seconds
// 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(199,59,149,200); // numeric IP for api.twitter.com
char server[] = "api.twitter.com"; // name address for twitter API
boolean requested; // whether you've made a request since connecting
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
String currentLine = ""; // string to hold the text from server
String tweet = ""; // string to hold the tweet
boolean readingTweet = false; // if you're currently reading the tweet
void setup() {
// reserve space for the strings:
currentLine.reserve(256);
tweet.reserve(150);
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
connectToServer();
}
void loop()
{
if (client.connected()) {
if (client.available()) {
// read incoming bytes:
char inChar = client.read();
// add incoming byte to end of line:
currentLine += inChar;
// if you get a newline, clear the line:
if (inChar == '\n') {
currentLine = "";
}
// if the current line ends with <text>, it will
// be followed by the tweet:
if ( currentLine.endsWith("<text>")) {
// tweet is beginning. Clear the tweet string:
readingTweet = true;
tweet = "";
// break out of the loop so this character isn't added to the tweet:
return;
}
// if you're currently reading the bytes of a tweet,
// add them to the tweet String:
if (readingTweet) {
if (inChar != '<') {
tweet += inChar;
}
else {
// if you got a "<" character,
// you've reached the end of the tweet:
readingTweet = false;
Serial.println(tweet);
// close the connection to the server:
client.stop();
}
}
}
}
else if (millis() - lastAttemptTime > requestInterval) {
// if you're not connected, and two minutes have passed since
// your last connection, then attempt to connect again:
connectToServer();
}
}
void connectToServer() {
// attempt to connect, and wait a millisecond:
Serial.println("connecting to server...");
if (client.connect(server, 80)) {
Serial.println("making HTTP request...");
// make HTTP GET request to twitter:
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino HTTP/1.1");
client.println("Host: api.twitter.com");
client.println("Connection: close");
client.println();
}
// note the time of this connect attempt:
lastAttemptTime = millis();
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,20 +0,0 @@
/*
*
@file socket.c
@brief define function of socket API
*
*/
#include <inttypes.h>
#include "socket.h"
SOCKET socket(uint8 protocol) {return 0;} // Opens a socket(TCP or UDP or IP_RAW mode)
void close(SOCKET s) {} // Close socket
uint8 connect(SOCKET s, uint8 * addr, uint16 port) {return 0;} // Establish TCP connection (Active connection)
void disconnect(SOCKET s) {} // disconnect the connection
uint8 listen(SOCKET s) { return 0;} // Establish TCP connection (Passive connection)
uint16 send(SOCKET s, const uint8 * buf, uint16 len) { return 0;} // Send data (TCP)
uint16 recv(SOCKET s, uint8 * buf, uint16 len) {return 0;} // Receive data (TCP)
uint16 sendto(SOCKET s, const uint8 * buf, uint16 len, uint8 * addr, uint16 port) {return 0;} // Send data (UDP/IP RAW)
uint16 recvfrom(SOCKET s, uint8 * buf, uint16 len, uint8 * addr, uint16 *port) {return 0;} // Receive data (UDP/IP RAW)
uint16 igmpsend(SOCKET s, const uint8 * buf, uint16 len) {return 0;}

View File

@ -1,732 +0,0 @@
/*
Copyright (c) 2013 Arduino. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "CAN.h"
#include "sn65hvd234.h"
/** Define the timemark mask. */
#define TIMEMARK_MASK 0x0000ffff
/* CAN timeout for synchronization. */
#define CAN_TIMEOUT 100000
/** The max value for CAN baudrate prescale. */
#define CAN_BAUDRATE_MAX_DIV 128
/** Define the scope for TQ. */
#define CAN_MIN_TQ_NUM 8
#define CAN_MAX_TQ_NUM 25
/** Define the fixed bit time value. */
#define CAN_BIT_SYNC 1
#define CAN_BIT_IPT 2
typedef struct {
uint8_t uc_tq; //! CAN_BIT_SYNC + uc_prog + uc_phase1 + uc_phase2 = uc_tq, 8 <= uc_tq <= 25.
uint8_t uc_prog; //! Propagation segment, (3-bits + 1), 1~8;
uint8_t uc_phase1; //! Phase segment 1, (3-bits + 1), 1~8;
uint8_t uc_phase2; //! Phase segment 2, (3-bits + 1), 1~8, CAN_BIT_IPT <= uc_phase2;
uint8_t uc_sjw; //! Resynchronization jump width, (2-bits + 1), min(uc_phase1, 4);
uint8_t uc_sp; //! Sample point value, 0~100 in percent.
} can_bit_timing_t;
/** Values of bit time register for different baudrates, Sample point = ((1 + uc_prog + uc_phase1) / uc_tq) * 100%. */
const can_bit_timing_t can_bit_time[] = {
{8, (2 + 1), (1 + 1), (1 + 1), (2 + 1), 75},
{9, (1 + 1), (2 + 1), (2 + 1), (1 + 1), 67},
{10, (2 + 1), (2 + 1), (2 + 1), (2 + 1), 70},
{11, (3 + 1), (2 + 1), (2 + 1), (3 + 1), 72},
{12, (2 + 1), (3 + 1), (3 + 1), (3 + 1), 67},
{13, (3 + 1), (3 + 1), (3 + 1), (3 + 1), 77},
{14, (3 + 1), (3 + 1), (4 + 1), (3 + 1), 64},
{15, (3 + 1), (4 + 1), (4 + 1), (3 + 1), 67},
{16, (4 + 1), (4 + 1), (4 + 1), (3 + 1), 69},
{17, (5 + 1), (4 + 1), (4 + 1), (3 + 1), 71},
{18, (4 + 1), (5 + 1), (5 + 1), (3 + 1), 67},
{19, (5 + 1), (5 + 1), (5 + 1), (3 + 1), 68},
{20, (6 + 1), (5 + 1), (5 + 1), (3 + 1), 70},
{21, (7 + 1), (5 + 1), (5 + 1), (3 + 1), 71},
{22, (6 + 1), (6 + 1), (6 + 1), (3 + 1), 68},
{23, (7 + 1), (7 + 1), (6 + 1), (3 + 1), 70},
{24, (6 + 1), (7 + 1), (7 + 1), (3 + 1), 67},
{25, (7 + 1), (7 + 1), (7 + 1), (3 + 1), 68}
};
/**
* \brief Configure CAN baudrate.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param ul_mck The input main clock for the CAN module.
* \param ul_baudrate Baudrate value (kB/s), allowed values:
* 1000, 800, 500, 250, 125, 50, 25, 10, 5.
*
* \retval Set the baudrate successfully or not.
*/
uint32_t CANRaw::set_baudrate(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate)
{
uint8_t uc_tq;
uint8_t uc_prescale;
uint32_t ul_mod;
uint32_t ul_cur_mod;
can_bit_timing_t *p_bit_time;
/* Check whether the baudrate prescale will be greater than the max divide value. */
if (((ul_mck + (ul_baudrate * CAN_MAX_TQ_NUM * 1000 - 1)) /
(ul_baudrate * CAN_MAX_TQ_NUM * 1000)) > CAN_BAUDRATE_MAX_DIV) {
return 0;
}
/* Check whether the input MCK is too small. */
if (ul_mck < ul_baudrate * CAN_MIN_TQ_NUM * 1000) {
return 0;
}
/* Initialize it as the minimum Time Quantum. */
uc_tq = CAN_MIN_TQ_NUM;
/* Initialize the remainder as the max value. When the remainder is 0, get the right TQ number. */
ul_mod = 0xffffffff;
/* Find out the approximate Time Quantum according to the baudrate. */
for (uint8_t i = CAN_MIN_TQ_NUM; i <= CAN_MAX_TQ_NUM; i++) {
if ((ul_mck / (ul_baudrate * i * 1000)) <= CAN_BAUDRATE_MAX_DIV) {
ul_cur_mod = ul_mck % (ul_baudrate * i * 1000);
if (ul_cur_mod < ul_mod){
ul_mod = ul_cur_mod;
uc_tq = i;
if (!ul_mod) {
break;
}
}
}
}
/* Calculate the baudrate prescale value. */
uc_prescale = ul_mck / (ul_baudrate * uc_tq * 1000);
/* Get the right CAN BIT Timing group. */
p_bit_time = (can_bit_timing_t *)&can_bit_time[uc_tq - CAN_MIN_TQ_NUM];
/* Before modifying the CANBR register, disable the CAN controller. */
//can_disable(p_can);
p_can->CAN_MR &= ~CAN_MR_CANEN;
/* Write into the CAN baudrate register. */
p_can->CAN_BR = CAN_BR_PHASE2(p_bit_time->uc_phase2 - 1) |
CAN_BR_PHASE1(p_bit_time->uc_phase1 - 1) |
CAN_BR_PROPAG(p_bit_time->uc_prog - 1) |
CAN_BR_SJW(p_bit_time->uc_sjw - 1) |
CAN_BR_BRP(uc_prescale - 1);
return 1;
}
/**
* \brief Initialize CAN controller.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param ul_mck CAN module input clock.
* \param ul_baudrate CAN communication baudrate in kbs.
*
* \retval 0 If failed to initialize the CAN module; otherwise successful.
*
* \note PMC clock for CAN peripheral should be enabled before calling this function.
*/
uint32_t CANRaw::init(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate)
{
uint32_t ul_flag;
uint32_t ul_tick;
/* Initialize the baudrate for CAN module. */
ul_flag = set_baudrate(p_can, ul_mck, ul_baudrate);
if (ul_flag == 0) {
return 0;
}
/* Reset the CAN eight message mailbox. */
can_reset_all_mailbox(p_can);
/* Enable the CAN controller. */
can_enable(p_can);
/* Wait until the CAN is synchronized with the bus activity. */
ul_flag = 0;
ul_tick = 0;
while (!(ul_flag & CAN_SR_WAKEUP) && (ul_tick < CAN_TIMEOUT)) {
ul_flag = can_get_status(p_can);
ul_tick++;
}
/* Timeout or the CAN module has been synchronized with the bus. */
if (CAN_TIMEOUT == ul_tick) {
return 0;
} else {
return 1;
}
}
/**
* \brief Enable CAN Controller.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::enable(Can *p_can)
{
p_can->CAN_MR |= CAN_MR_CANEN;
}
/**
* \brief Disable CAN Controller.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::disable(Can *p_can)
{
p_can->CAN_MR &= ~CAN_MR_CANEN;
}
/**
* \brief Disable CAN Controller low power mode.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::disable_low_power_mode(Can *p_can)
{
p_can->CAN_MR &= ~CAN_MR_LPM;
}
/**
* \brief Enable CAN Controller low power mode.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::enable_low_power_mode(Can *p_can)
{
p_can->CAN_MR |= CAN_MR_LPM;
}
/**
* \brief Disable CAN Controller autobaud/listen mode.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::disable_autobaud_listen_mode(Can *p_can)
{
p_can->CAN_MR &= ~CAN_MR_ABM;
}
/**
* \brief Enable CAN Controller autobaud/listen mode.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::enable_autobaud_listen_mode(Can *p_can)
{
p_can->CAN_MR |= CAN_MR_ABM;
}
/**
* \brief CAN Controller won't generate overload frame.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::disable_overload_frame(Can *p_can)
{
p_can->CAN_MR &= ~CAN_MR_OVL;
}
/**
* \brief CAN Controller will generate an overload frame after each successful
* reception for mailboxes configured in Receive mode, Producer and Consumer.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::enable_overload_frame(Can *p_can)
{
p_can->CAN_MR |= CAN_MR_OVL;
}
/**
* \brief Configure the timestamp capture point, at the start or the end of frame.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param ul_flag 0: Timestamp is captured at each start of frame;
* 1: Timestamp is captured at each end of frame.
*/
void CANRaw::set_timestamp_capture_point(Can *p_can, uint32_t ul_flag)
{
if (ul_flag) {
p_can->CAN_MR |= CAN_MR_TEOF;
} else {
p_can->CAN_MR &= ~CAN_MR_TEOF;
}
}
/**
* \brief Disable CAN Controller time triggered mode.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::disable_time_triggered_mode(Can *p_can)
{
p_can->CAN_MR &= ~CAN_MR_TTM;
}
/**
* \brief Enable CAN Controller time triggered mode.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::enable_time_triggered_mode(Can *p_can)
{
p_can->CAN_MR |= CAN_MR_TTM;
}
/**
* \brief Disable CAN Controller timer freeze.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::disable_timer_freeze(Can *p_can)
{
p_can->CAN_MR &= ~CAN_MR_TIMFRZ;
}
/**
* \brief Enable CAN Controller timer freeze.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::enable_timer_freeze(Can *p_can)
{
p_can->CAN_MR |= CAN_MR_TIMFRZ;
}
/**
* \brief Disable CAN Controller transmit repeat function.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::disable_tx_repeat(Can *p_can)
{
p_can->CAN_MR |= CAN_MR_DRPT;
}
/**
* \brief Enable CAN Controller transmit repeat function.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::enable_tx_repeat(Can *p_can)
{
p_can->CAN_MR &= ~CAN_MR_DRPT;
}
/**
* \brief Configure CAN Controller reception synchronization stage.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param ul_stage The reception stage to be configured.
*
* \note This is just for debug purpose only.
*/
void CANRaw::set_rx_sync_stage(Can *p_can, uint32_t ul_stage)
{
p_can->CAN_MR = (p_can->CAN_MR & ~CAN_MR_RXSYNC_Msk) | ul_stage;
}
/**
* \brief Enable CAN interrupt.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param dw_mask Interrupt to be enabled.
*/
void CANRaw::enable_interrupt(Can *p_can, uint32_t dw_mask)
{
p_can->CAN_IER = dw_mask;
}
/**
* \brief Disable CAN interrupt.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param dw_mask Interrupt to be disabled.
*/
void CANRaw::disable_interrupt(Can *p_can, uint32_t dw_mask)
{
p_can->CAN_IDR = dw_mask;
}
/**
* \brief Get CAN Interrupt Mask.
*
* \param p_can Pointer to a CAN peripheral instance.
*
* \retval CAN interrupt mask.
*/
uint32_t CANRaw::get_interrupt_mask(Can *p_can)
{
return (p_can->CAN_IMR);
}
/**
* \brief Get CAN status.
*
* \param p_can Pointer to a CAN peripheral instance.
*
* \retval CAN status.
*/
uint32_t CANRaw::get_status(Can *p_can)
{
return (p_can->CAN_SR);
}
/**
* \brief Get the 16-bit free-running internal timer count.
*
* \param p_can Pointer to a CAN peripheral instance.
*
* \retval The internal CAN free-running timer counter.
*/
uint32_t CANRaw::get_internal_timer_value(Can *p_can)
{
return (p_can->CAN_TIM);
}
/**
* \brief Get CAN timestamp register value.
*
* \param p_can Pointer to a CAN peripheral instance.
*
* \retval The timestamp value.
*/
uint32_t CANRaw::get_timestamp_value(Can *p_can)
{
return (p_can->CAN_TIMESTP);
}
/**
* \brief Get CAN transmit error counter.
*
* \param p_can Pointer to a CAN peripheral instance.
*
* \retval Transmit error counter.
*/
uint8_t CANRaw::get_tx_error_cnt(Can *p_can)
{
return (uint8_t) (p_can->CAN_ECR >> CAN_ECR_TEC_Pos);
}
/**
* \brief Get CAN receive error counter.
*
* \param p_can Pointer to a CAN peripheral instance.
*
* \retval Receive error counter.
*/
uint8_t CANRaw::get_rx_error_cnt(Can *p_can)
{
return (uint8_t) (p_can->CAN_ECR >> CAN_ECR_REC_Pos);
}
/**
* \brief Reset the internal free-running 16-bit timer.
*
* \param p_can Pointer to a CAN peripheral instance.
*
* \note If the internal timer counter is frozen, this function automatically
* re-enables it.
*/
void CANRaw::reset_internal_timer(Can *p_can)
{
p_can->CAN_TCR |= CAN_TCR_TIMRST;
}
/**
* \brief Send global transfer request.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param uc_mask Mask for mailboxes that are requested to transfer.
*/
void CANRaw::global_send_transfer_cmd(Can *p_can, uint8_t uc_mask)
{
uint32_t ul_reg;
ul_reg = p_can->CAN_TCR & ((uint32_t)~GLOBAL_MAILBOX_MASK);
p_can->CAN_TCR = ul_reg | uc_mask;
}
/**
* \brief Send global abort request.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param uc_mask Mask for mailboxes that are requested to abort.
*/
void CANRaw::global_send_abort_cmd(Can *p_can, uint8_t uc_mask)
{
uint32_t ul_reg;
ul_reg = p_can->CAN_ACR & ((uint32_t)~GLOBAL_MAILBOX_MASK);
p_can->CAN_ACR = ul_reg | uc_mask;
}
/**
* \brief Configure the timemark for the mailbox.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param uc_index Indicate which mailbox is to be configured.
* \param us_cnt The timemark to be set.
*
* \note The timemark is active in Time Triggered mode only.
*/
void CANRaw::mailbox_set_timemark(Can *p_can, uint8_t uc_index, uint16_t us_cnt)
{
uint32_t ul_reg;
ul_reg = p_can->CAN_MB[uc_index].CAN_MMR & ((uint32_t)~TIMEMARK_MASK);
p_can->CAN_MB[uc_index].CAN_MMR = ul_reg | us_cnt;
}
/**
* \brief Get status of the mailbox.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param uc_index Indicate which mailbox is to be read.
*
* \retval The mailbox status.
*/
uint32_t CANRaw::mailbox_get_status(Can *p_can, uint8_t uc_index)
{
return (p_can->CAN_MB[uc_index].CAN_MSR);
}
/**
* \brief Send single mailbox transfer request.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param uc_index Indicate which mailbox is to be configured.
*/
void CANRaw::mailbox_send_transfer_cmd(Can *p_can, uint8_t uc_index)
{
p_can->CAN_MB[uc_index].CAN_MCR |= CAN_MCR_MTCR;
}
/**
* \brief Send single mailbox abort request.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param uc_index Indicate which mailbox is to be configured.
*/
void CANRaw::mailbox_send_abort_cmd(Can *p_can, uint8_t uc_index)
{
p_can->CAN_MB[uc_index].CAN_MCR |= CAN_MCR_MACR;
}
/**
* \brief Initialize the mailbox in different mode and set up related configuration.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param p_mailbox Pointer to a CAN mailbox instance.
*/
void CANRaw::mailbox_init(Can *p_can, can_mb_conf_t *p_mailbox)
{
uint8_t uc_index;
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
/* Check the object type of the mailbox. If it's used to disable the mailbox, reset the whole mailbox. */
if (!p_mailbox->uc_obj_type) {
p_can->CAN_MB[uc_index].CAN_MMR = 0;
p_can->CAN_MB[uc_index].CAN_MAM = 0;
p_can->CAN_MB[uc_index].CAN_MID = 0;
p_can->CAN_MB[uc_index].CAN_MDL = 0;
p_can->CAN_MB[uc_index].CAN_MDH = 0;
p_can->CAN_MB[uc_index].CAN_MCR = 0;
return;
}
/* Set the priority in Transmit mode. */
p_can->CAN_MB[uc_index].CAN_MMR = (p_can->CAN_MB[uc_index].CAN_MMR &
~CAN_MMR_PRIOR_Msk) | (p_mailbox-> uc_tx_prio << CAN_MMR_PRIOR_Pos);
/* Set the message ID and message acceptance mask for the mailbox in other modes. */
if (p_mailbox->uc_id_ver) {
p_can->CAN_MB[uc_index].CAN_MAM = p_mailbox->ul_id_msk | CAN_MAM_MIDE;
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id | CAN_MAM_MIDE;
} else {
p_can->CAN_MB[uc_index].CAN_MAM = p_mailbox->ul_id_msk;
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id;
}
/* Set up mailbox in one of the five different modes. */
p_can->CAN_MB[uc_index].CAN_MMR = (p_can->CAN_MB[uc_index].CAN_MMR &
~CAN_MMR_MOT_Msk) | (p_mailbox-> uc_obj_type << CAN_MMR_MOT_Pos);
}
/**
* \brief Read receive information for the mailbox.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param p_mailbox Pointer to a CAN mailbox instance.
*
* \retval Different CAN mailbox transfer status.
*
* \note Read the mailbox status before calling this function.
*/
uint32_t CANRaw::mailbox_read(Can *p_can, can_mb_conf_t *p_mailbox)
{
uint32_t ul_status;
uint8_t uc_index;
uint32_t ul_retval;
ul_retval = 0;
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
ul_status = p_mailbox->ul_status;
/* Check whether there is overwriting happening in Receive with Overwrite mode,
or there're messages lost in Receive mode. */
if ((ul_status & CAN_MSR_MRDY) && (ul_status & CAN_MSR_MMI)) {
ul_retval = CAN_MAILBOX_RX_OVER;
}
/* Read the message family ID. */
p_mailbox->ul_fid = p_can->CAN_MB[uc_index].CAN_MFID & CAN_MFID_MFID_Msk;
/* Read received data length. */
p_mailbox->uc_length = (ul_status & CAN_MSR_MDLC_Msk) >> CAN_MSR_MDLC_Pos;
/* Read received data. */
p_mailbox->ul_datal = p_can->CAN_MB[uc_index].CAN_MDL;
if (p_mailbox->uc_length > 4) {
p_mailbox->ul_datah = p_can->CAN_MB[uc_index].CAN_MDH;
}
/* Read the mailbox status again to check whether the software needs to re-read mailbox data register. */
p_mailbox->ul_status = p_can->CAN_MB[uc_index].CAN_MSR;
ul_status = p_mailbox->ul_status;
if (ul_status & CAN_MSR_MMI) {
ul_retval |= CAN_MAILBOX_RX_NEED_RD_AGAIN;
} else {
ul_retval |= CAN_MAILBOX_TRANSFER_OK;
}
/* Enable next receive process. */
can_mailbox_send_transfer_cmd(p_can, uc_index);
return ul_retval;
}
/**
* \brief Prepare transmit information and write them into the mailbox.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param p_mailbox Pointer to a CAN mailbox instance.
*
* \retval CAN_MAILBOX_NOT_READY: Failed because mailbox isn't ready.
* CAN_MAILBOX_TRANSFER_OK: Successfully write message into mailbox.
*
* \note After calling this function, the mailbox message won't be sent out until
* can_mailbox_send_transfer_cmd() is called.
*/
uint32_t CANRaw::mailbox_write(Can *p_can, can_mb_conf_t *p_mailbox)
{
uint32_t ul_status;
uint8_t uc_index;
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
/* Read the mailbox status firstly to check whether the mailbox is ready or not. */
p_mailbox->ul_status = can_mailbox_get_status(p_can, uc_index);
ul_status = p_mailbox->ul_status;
if (!(ul_status & CAN_MSR_MRDY)) {
return CAN_MAILBOX_NOT_READY;
}
/* Write transmit identifier. */
if (p_mailbox->uc_id_ver) {
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id | CAN_MAM_MIDE;
} else {
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id;
}
/* Write transmit data into mailbox data register. */
p_can->CAN_MB[uc_index].CAN_MDL = p_mailbox->ul_datal;
if (p_mailbox->uc_length > 4) {
p_can->CAN_MB[uc_index].CAN_MDH = p_mailbox->ul_datah;
}
/* Write transmit data length into mailbox control register. */
p_can->CAN_MB[uc_index].CAN_MCR = (p_can->CAN_MB[uc_index].CAN_MCR &
~CAN_MCR_MDLC_Msk) | CAN_MCR_MDLC(p_mailbox->uc_length);
return CAN_MAILBOX_TRANSFER_OK;
}
/**
* \brief Require to send out a remote frame.
*
* \param p_can Pointer to a CAN peripheral instance.
* \param p_mailbox Pointer to a CAN mailbox instance.
*
* \retval CAN_MAILBOX_NOT_READY: Failed because mailbox isn't ready for transmitting message.
* CAN_MAILBOX_TRANSFER_OK: Successfully send out a remote frame.
*/
uint32_t CANRaw::mailbox_tx_remote_frame(Can *p_can, can_mb_conf_t *p_mailbox)
{
uint32_t ul_status;
uint8_t uc_index;
uc_index = (uint8_t)p_mailbox->ul_mb_idx;
/* Read the mailbox status firstly to check whether the mailbox is ready or not. */
p_mailbox->ul_status = p_can->CAN_MB[uc_index].CAN_MSR;
ul_status = p_mailbox->ul_status;
if (!(ul_status & CAN_MSR_MRDY)) {
return CAN_MAILBOX_NOT_READY;
}
/* Write transmit identifier. */
if (p_mailbox->uc_id_ver) {
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id | CAN_MAM_MIDE;
} else {
p_can->CAN_MB[uc_index].CAN_MID = p_mailbox->ul_id;
}
/* Set the RTR bit in the sent frame. */
p_can->CAN_MB[uc_index].CAN_MCR |= CAN_MCR_MRTR;
/* Set the MBx bit in the Transfer Command Register to send out the remote frame. */
can_global_send_transfer_cmd(p_can, (1 << uc_index));
return CAN_MAILBOX_TRANSFER_OK;
}
/**
* \brief Reset the eight mailboxes.
*
* \param p_can Pointer to a CAN peripheral instance.
*/
void CANRaw::reset_all_mailbox(Can *p_can)
{
can_mb_conf_t mb_config_t;
/* Set the mailbox object type parameter to disable the mailbox. */
mb_config_t.uc_obj_type = CAN_MB_DISABLE_MODE;
for (uint8_t i = 0; i < CANMB_NUMBER; i++) {
mb_config_t.ul_mb_idx = i;
can_mailbox_init(p_can, &mb_config_t);
}
}

View File

@ -1,131 +0,0 @@
/*
Copyright (c) 2013 Arduino. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CAN_LIBRARY_
#define _CAN_LIBRARY_
#include "sn65hvd234.h"
/** Define the Mailbox mask for eight mailboxes. */
#define GLOBAL_MAILBOX_MASK 0x000000ff
/** Disable all interrupt mask */
#define CAN_DISABLE_ALL_INTERRUPT_MASK 0xffffffff
/** Define the typical baudrate for CAN communication in KHz. */
#define CAN_BPS_1000K 1000
#define CAN_BPS_800K 800
#define CAN_BPS_500K 500
#define CAN_BPS_250K 250
#define CAN_BPS_125K 125
#define CAN_BPS_50K 50
#define CAN_BPS_25K 25
#define CAN_BPS_10K 10
#define CAN_BPS_5K 5
/** Define the mailbox mode. */
#define CAN_MB_DISABLE_MODE 0
#define CAN_MB_RX_MODE 1
#define CAN_MB_RX_OVER_WR_MODE 2
#define CAN_MB_TX_MODE 3
#define CAN_MB_CONSUMER_MODE 4
#define CAN_MB_PRODUCER_MODE 5
/** Define CAN mailbox transfer status code. */
#define CAN_MAILBOX_TRANSFER_OK 0 //! Read from or write into mailbox successfully.
#define CAN_MAILBOX_NOT_READY 0x01 //! Receiver is empty or transmitter is busy.
#define CAN_MAILBOX_RX_OVER 0x02 //! Message overwriting happens or there're messages lost in different receive modes.
#define CAN_MAILBOX_RX_NEED_RD_AGAIN 0x04 //! Application needs to re-read the data register in Receive with Overwrite mode.
class CANRaw
{
protected:
/* CAN peripheral, set by constructor */
//Can* m_pCan ;
/* CAN Transceiver */
SSN65HVD234_Data m_Transceiver ;
/** CAN Transfer */
//can_mb_conf_t m_Mailbox;
private:
public:
// Constructor
//CANRawClass( Can* pCan ) ;
/**
* \defgroup sam_driver_can_group Controller Area Network (CAN) Driver
*
* See \ref sam_can_quickstart.
*
* \par Purpose
*
* The CAN controller provides all the features required to implement
* the serial communication protocol CAN defined by Robert Bosch GmbH,
* the CAN specification. This is a driver for configuration, enabling,
* disabling and use of the CAN peripheral.
*
* @{
*/
uint32_t set_baudrate(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate);
uint32_t init(Can *p_can, uint32_t ul_mck, uint32_t ul_baudrate);
void enable(Can *p_can);
void disable(Can *p_can);
void disable_low_power_mode(Can *p_can);
void enable_low_power_mode(Can *p_can);
void disable_autobaud_listen_mode(Can *p_can);
void enable_autobaud_listen_mode(Can *p_can);
void disable_overload_frame(Can *p_can);
void enable_overload_frame(Can *p_can);
void set_timestamp_capture_point(Can *p_can, uint32_t ul_flag);
void disable_time_triggered_mode(Can *p_can);
void enable_time_triggered_mode(Can *p_can);
void disable_timer_freeze(Can *p_can);
void enable_timer_freeze(Can *p_can);
void disable_tx_repeat(Can *p_can);
void enable_tx_repeat(Can *p_can);
void set_rx_sync_stage(Can *p_can, uint32_t ul_stage);
void enable_interrupt(Can *p_can, uint32_t dw_mask);
void disable_interrupt(Can *p_can, uint32_t dw_mask);
uint32_t get_interrupt_mask(Can *p_can);
uint32_t get_status(Can *p_can);
uint32_t get_internal_timer_value(Can *p_can);
uint32_t get_timestamp_value(Can *p_can);
uint8_t get_tx_error_cnt(Can *p_can);
uint8_t get_rx_error_cnt(Can *p_can);
void reset_internal_timer(Can *p_can);
void global_send_transfer_cmd(Can *p_can, uint8_t uc_mask);
void global_send_abort_cmd(Can *p_can, uint8_t uc_mask);
void mailbox_set_timemark(Can *p_can, uint8_t uc_index, uint16_t us_cnt);
uint32_t mailbox_get_status(Can *p_can, uint8_t uc_index);
void mailbox_send_transfer_cmd(Can *p_can, uint8_t uc_index);
void mailbox_send_abort_cmd(Can *p_can, uint8_t uc_index);
void mailbox_init(Can *p_can, can_mb_conf_t *p_mailbox);
uint32_t mailbox_read(Can *p_can, can_mb_conf_t *p_mailbox);
uint32_t mailbox_write(Can *p_can, can_mb_conf_t *p_mailbox);
uint32_t mailbox_tx_remote_frame(Can *p_can, can_mb_conf_t *p_mailbox);
void reset_all_mailbox(Can *p_can);
} ;
#endif // _CAN_LIBRARY_

View File

@ -1,37 +0,0 @@
Controller Area network (CAN) API for Arduino Due
This is a beta release of the CAN API for Arduino Due. It contains the necessary classes and functions to configure, enable, disable and use of the CAN peripherals controllers embedded in the SAM3X8E core inside Arduino Due, and the two external SN65HVD234 transceivers.
This CAN API for Arduino Due is released together with a CAN sample1 sketch for the Arduino IDE 1.5.2 and it shows how to configure the CAN controllers and how to manage CAN message transfers. The two CAN controllers (CAN0 and CAN1) and two mailboxes (mailbox 0 and mailbox 1) are used: CAN0 mailbox 0 is configured as transmitter, and CAN1 mailbox 0 is configured as receiver. The communication baudrate is 1Mbit/s. The CAN0 controller tries to send on the bus messages through the mailbox 0 and waits for messages from mailbox 1 on CAN1 controller.
It is required to use the two CAN pins in Arduino Due, connected to the two external SN65HVD234transceivers in loop mode via a pair cable. The CAN message transaction can be monitored by a serial UART connection (115.2 Kbps, 8 data bits, no parity, 1 stop bit, no flux control) or serial monitor of the Arduino IDE 1.5.2 with autoscroll and newline modes activated.
Source files:
- CAN.cpp
- CAN.h
- sn65hvd234.c
- sn65hvd234.h
- variant.cpp
- variant.h
CAN files (.cpp .h) contain the CANRaw class with 38 functions.
sn65hvd234 files (.c .h) contain 7 driver functions.
The variant files (.cpp .h) are updates to the IDE 1.5.2 ones. Added initialization of the CAN pins in variant.cpp
and CAN pins definition in variant.h.
Hardware requirements:
- Arduino Due board
- Dual CAN transceiver shield
- Twisted shielded pair cable
Software requirements:
- Arduino IDE 1.5.2
- CAN API library
To perform the CAN sample 1 test, the pair cable needs to be connected between the two CAN ports as follows:
CANRX0 <-> CANRX0
CANRX1 <-> CANRX1
Once the CAN sample 1 and the CAN library are loaded in Arduino IDE 1.5.2, after serial monitor open or after a reset of the Arduino board, the following message should be displayed in the monitor terminal: Type CAN message to send. Then, an 8 digit message can be typed and after a return stroke of the keyboard, the following message should be displayed: Sent value=XXXXXXXX, where XXXXXXXX is the typed message. If the message was sent/received successfully, the following message should be displayed: CAN message received=XXXXXXX and End of test. Otherwise, there is a CAN communication error.

View File

@ -1,128 +0,0 @@
// Arduino Due - CAN Sample 1
// Brief CAN example for Arduino Due
// Test the transmission from CAN0 Mailbox 0 to CAN1 Mailbox 0
// By Thibaut Viard/Wilfredo Molina 2012
// Required libraries
#include "variant.h"
#include <CAN.h>
#define TEST1_CAN_COMM_MB_IDX 0
#define TEST1_CAN_TRANSFER_ID 0x07
#define TEST1_CAN0_TX_PRIO 15
#define CAN_MSG_DUMMY_DATA 0x55AAAA55
// CAN frame max data length
#define MAX_CAN_FRAME_DATA_LEN 8
// CAN class
CANRaw CAN;
// Message variable to be send
uint32_t CAN_MSG_1 = 0;
// CAN0 Transceiver
SSN65HVD234_Data can0_transceiver;
// CAN1 Transceiver
SSN65HVD234_Data can1_transceiver;
// Define the struct for CAN message mailboxes needed
can_mb_conf_t can0_mailbox;
can_mb_conf_t can1_mailbox;
void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
Serial.println("Type CAN message to send");
while (Serial.available() == 0);
}
void loop(){
while (Serial.available() > 0) {
CAN_MSG_1 = Serial.parseInt();
if (Serial.read() == '\n') {
Serial.print("Sent value= ");
Serial.println(CAN_MSG_1);
}
}
// Initialize CAN0 Transceiver
SN65HVD234_Init(&can0_transceiver);
SN65HVD234_SetRs(&can0_transceiver, 61);
SN65HVD234_SetEN(&can0_transceiver, 62);
// Enable CAN0 Transceiver
SN65HVD234_DisableLowPower(&can0_transceiver);
SN65HVD234_Enable(&can0_transceiver);
// Initialize CAN1 Transceiver
SN65HVD234_Init(&can1_transceiver);
SN65HVD234_SetRs(&can1_transceiver, 63);
SN65HVD234_SetEN(&can1_transceiver, 64);
// Enable CAN1 Transceiver
SN65HVD234_DisableLowPower(&can1_transceiver);
SN65HVD234_Enable(&can1_transceiver);
// Enable CAN0 & CAN1 clock
pmc_enable_periph_clk(ID_CAN0);
pmc_enable_periph_clk(ID_CAN1);
// Initialize CAN0 and CAN1, baudrate is 1Mb/s
CAN.init(CAN0, SystemCoreClock, CAN_BPS_1000K);
CAN.init(CAN1, SystemCoreClock, CAN_BPS_1000K);
// Initialize CAN1 mailbox 0 as receiver, frame ID is 0x07
// can_reset_mailbox_data(&can1_mailbox);
can1_mailbox.ul_mb_idx = TEST1_CAN_COMM_MB_IDX;
can1_mailbox.uc_obj_type = CAN_MB_RX_MODE;
can1_mailbox.ul_id_msk = CAN_MAM_MIDvA_Msk | CAN_MAM_MIDvB_Msk;
can1_mailbox.ul_id = CAN_MID_MIDvA(TEST1_CAN_TRANSFER_ID);
CAN.mailbox_init(CAN1, &can1_mailbox);
// Initialize CAN0 mailbox 0 as transmitter, transmit priority is 15
// can_reset_mailbox_data(&can0_mailbox);
can0_mailbox.ul_mb_idx = TEST1_CAN_COMM_MB_IDX;
can0_mailbox.uc_obj_type = CAN_MB_TX_MODE;
can0_mailbox.uc_tx_prio = TEST1_CAN0_TX_PRIO;
can0_mailbox.uc_id_ver = 0;
can0_mailbox.ul_id_msk = 0;
CAN.mailbox_init(CAN0, &can0_mailbox);
// Prepare transmit ID, data and data length in CAN0 mailbox 0
can0_mailbox.ul_id = CAN_MID_MIDvA(TEST1_CAN_TRANSFER_ID);
can0_mailbox.ul_datal = CAN_MSG_1;
can0_mailbox.ul_datah = CAN_MSG_DUMMY_DATA;
can0_mailbox.uc_length = MAX_CAN_FRAME_DATA_LEN;
CAN.mailbox_write(CAN0, &can0_mailbox);
// Send out the information in the mailbox
CAN.global_send_transfer_cmd(CAN0, CAN_TCR_MB0);
// Wait for CAN1 mailbox 0 to receive the data
while (!(CAN.mailbox_get_status(CAN1, 0) & CAN_MSR_MRDY)) {
}
// Read the received data from CAN1 mailbox 0
CAN.mailbox_read(CAN1, &can1_mailbox);
Serial.print("CAN message received= ");
Serial.println(can1_mailbox.ul_datal);
// Disable CAN0 Controller
CAN.disable(CAN0);
// Disable CAN0 Transceiver
SN65HVD234_EnableLowPower(&can0_transceiver);
SN65HVD234_Disable(&can0_transceiver);
// Disable CAN1 Controller
CAN.disable(CAN1);
// Disable CAN1 Transceiver
SN65HVD234_EnableLowPower(&can1_transceiver);
SN65HVD234_Disable(&can1_transceiver);
Serial.print("End of test");
while (1) {
}
}

View File

@ -1,142 +0,0 @@
/*
Copyright (c) 2013 Arduino. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* \file
*
* Implementation of the SN65HVD234 drivers.
*
*/
#include "sn65hvd234.h"
#include <string.h>
/**
* \brief Initialize SN65HVD234 component data
*
* \param pComponent pointer on SSN65HVD234_Data
*
* \return 0 if OK
*/
extern uint32_t SN65HVD234_Init( SSN65HVD234_Data* pComponent )
{
pComponent->dwPin_Rs=0u ;
pComponent->dwPin_EN=0u ;
return 0u ;
}
/**
* \brief Initialize Rs pin of transceiver
*
* \param pComponent pointer on SSN65HVD234_Data
* \param pPIO_Rs pointer on PIOx base for transceiver Rs pin
* \param dwPin_Rs PIO pin index for transceiver Rs pin
*
* \return 0 if OK
*/
extern uint32_t SN65HVD234_SetRs( SSN65HVD234_Data* pComponent, uint32_t dwPin_Rs )
{
pComponent->dwPin_Rs=dwPin_Rs ;
pinMode( dwPin_Rs, OUTPUT ) ;
return 0u ;
}
/**
* \brief Initialize EN pin of transceiver
*
* \param pComponent pointer on SSN65HVD234_Data
* \param pPIO_EN pointer on PIOx base for transceiver EN pin
* \param dwPin_EN PIO pin index for transceiver EN pin
*
* \return 0 if OK
*/
extern uint32_t SN65HVD234_SetEN( SSN65HVD234_Data* pComponent, uint32_t dwPin_EN )
{
pComponent->dwPin_EN=dwPin_EN ;
pinMode( dwPin_EN, OUTPUT ) ;
return 0u ;
}
/**
* \brief Enable transceiver
*
* \param pComponent pointer on SSN65HVD234_Data
*
* \return 0 if OK
*/
extern uint32_t SN65HVD234_Enable( SSN65HVD234_Data* pComponent )
{
// Raise EN of SN65HVD234 to High Level (Vcc)
digitalWrite( pComponent->dwPin_EN, HIGH ) ;
return 0u ;
}
/**
* \brief Disable transceiver
*
* \param pComponent pointer on SSN65HVD234_Data
*
* \return 0 if OK
*/
extern uint32_t SN65HVD234_Disable( SSN65HVD234_Data* pComponent )
{
// Lower EN of SN65HVD234 to Low Level (0.0v)
digitalWrite( pComponent->dwPin_EN, LOW ) ;
return 0u ;
}
/**
* \brief Turn component into lowpower mode
*
* \param pComponent pointer on SSN65HVD234_Data
*
* \return 0 if OK
*/
extern uint32_t SN65HVD234_EnableLowPower( SSN65HVD234_Data* pComponent )
{
// Raise Rs of SN65HVD234 to more than 0.75v
digitalWrite( pComponent->dwPin_Rs, HIGH ) ;
// Now, SN65HVD234 is only listening
return 0u ;
}
/**
* \brief Restore Normal mode by leaving lowpower mode
*
* \param pComponent pointer on SSN65HVD234_Data
*
* \return 0 if OK
*/
extern uint32_t SN65HVD234_DisableLowPower( SSN65HVD234_Data* pComponent )
{
// Lower Rs of SN65HVD234 to 0.0v < 0.33v
digitalWrite( pComponent->dwPin_Rs, LOW ) ;
return 0u ;
}

View File

@ -1,58 +0,0 @@
/*
Copyright (c) 2013 Arduino. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* \file
*
* Include Defines & macros for the SN65HVD234.
*/
#ifndef _CAN_SN65HVD234_
#define _CAN_SN65HVD234_
#include "variant.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _SSN65HVD234_Data
{
/** Rs Pin on PIO */
uint32_t dwPin_Rs ;
/** EN Pin on PIO */
uint32_t dwPin_EN ;
} SSN65HVD234_Data ;
extern uint32_t SN65HVD234_Init( SSN65HVD234_Data* pComponent ) ;
extern uint32_t SN65HVD234_SetRs( SSN65HVD234_Data* pComponent, uint32_t dwPin_Rs ) ;
extern uint32_t SN65HVD234_SetEN( SSN65HVD234_Data* pComponent, uint32_t dwPin_EN ) ;
extern uint32_t SN65HVD234_Enable( SSN65HVD234_Data* pComponent ) ;
extern uint32_t SN65HVD234_Disable( SSN65HVD234_Data* pComponent ) ;
extern uint32_t SN65HVD234_EnableLowPower( SSN65HVD234_Data* pComponent ) ;
extern uint32_t SN65HVD234_DisableLowPower( SSN65HVD234_Data* pComponent ) ;
#ifdef __cplusplus
}
#endif
#endif /* _CAN_SN65HVD234_ */

View File

@ -1,480 +0,0 @@
// DHCP Library v0.3 - April 25, 2009
// Author: Jordan Terrell - blog.jordanterrell.com
#include "w5100.h"
#include <string.h>
#include <stdlib.h>
#include "Dhcp.h"
#include "Arduino.h"
#include "util.h"
int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
{
_dhcpLeaseTime=0;
_dhcpT1=0;
_dhcpT2=0;
_lastCheck=0;
_timeout = timeout;
_responseTimeout = responseTimeout;
// zero out _dhcpMacAddr
memset(_dhcpMacAddr, 0, 6);
reset_DHCP_lease();
memcpy((void*)_dhcpMacAddr, (void*)mac, 6);
_dhcp_state = STATE_DHCP_START;
return request_DHCP_lease();
}
void DhcpClass::reset_DHCP_lease(){
// zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp
memset(_dhcpLocalIp, 0, 20);
}
//return:0 on error, 1 if request is sent and response is received
int DhcpClass::request_DHCP_lease(){
uint8_t messageType = 0;
// Pick an initial transaction ID
_dhcpTransactionId = random(1UL, 2000UL);
_dhcpInitialTransactionId = _dhcpTransactionId;
_dhcpUdpSocket.stop();
if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0)
{
// Couldn't get a socket
return 0;
}
presend_DHCP();
int result = 0;
unsigned long startTime = millis();
while(_dhcp_state != STATE_DHCP_LEASED)
{
if(_dhcp_state == STATE_DHCP_START)
{
_dhcpTransactionId++;
send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000));
_dhcp_state = STATE_DHCP_DISCOVER;
}
else if(_dhcp_state == STATE_DHCP_REREQUEST){
_dhcpTransactionId++;
send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000));
_dhcp_state = STATE_DHCP_REQUEST;
}
else if(_dhcp_state == STATE_DHCP_DISCOVER)
{
uint32_t respId;
messageType = parseDHCPResponse(_responseTimeout, respId);
if(messageType == DHCP_OFFER)
{
// We'll use the transaction ID that the offer came with,
// rather than the one we were up to
_dhcpTransactionId = respId;
send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000));
_dhcp_state = STATE_DHCP_REQUEST;
}
}
else if(_dhcp_state == STATE_DHCP_REQUEST)
{
uint32_t respId;
messageType = parseDHCPResponse(_responseTimeout, respId);
if(messageType == DHCP_ACK)
{
_dhcp_state = STATE_DHCP_LEASED;
result = 1;
//use default lease time if we didn't get it
if(_dhcpLeaseTime == 0){
_dhcpLeaseTime = DEFAULT_LEASE;
}
//calculate T1 & T2 if we didn't get it
if(_dhcpT1 == 0){
//T1 should be 50% of _dhcpLeaseTime
_dhcpT1 = _dhcpLeaseTime >> 1;
}
if(_dhcpT2 == 0){
//T2 should be 87.5% (7/8ths) of _dhcpLeaseTime
_dhcpT2 = _dhcpT1 << 1;
}
_renewInSec = _dhcpT1;
_rebindInSec = _dhcpT2;
}
else if(messageType == DHCP_NAK)
_dhcp_state = STATE_DHCP_START;
}
if(messageType == 255)
{
messageType = 0;
_dhcp_state = STATE_DHCP_START;
}
if(result != 1 && ((millis() - startTime) > _timeout))
break;
}
// We're done with the socket now
_dhcpUdpSocket.stop();
_dhcpTransactionId++;
return result;
}
void DhcpClass::presend_DHCP()
{
}
void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed)
{
uint8_t buffer[32];
memset(buffer, 0, 32);
IPAddress dest_addr( 255, 255, 255, 255 ); // Broadcast address
if (-1 == _dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT))
{
// FIXME Need to return errors
return;
}
buffer[0] = DHCP_BOOTREQUEST; // op
buffer[1] = DHCP_HTYPE10MB; // htype
buffer[2] = DHCP_HLENETHERNET; // hlen
buffer[3] = DHCP_HOPS; // hops
// xid
unsigned long xid = htonl(_dhcpTransactionId);
memcpy(buffer + 4, &(xid), 4);
// 8, 9 - seconds elapsed
buffer[8] = ((secondsElapsed & 0xff00) >> 8);
buffer[9] = (secondsElapsed & 0x00ff);
// flags
unsigned short flags = htons(DHCP_FLAGSBROADCAST);
memcpy(buffer + 10, &(flags), 2);
// ciaddr: already zeroed
// yiaddr: already zeroed
// siaddr: already zeroed
// giaddr: already zeroed
//put data in W5100 transmit buffer
_dhcpUdpSocket.write(buffer, 28);
memset(buffer, 0, 32); // clear local buffer
memcpy(buffer, _dhcpMacAddr, 6); // chaddr
//put data in W5100 transmit buffer
_dhcpUdpSocket.write(buffer, 16);
memset(buffer, 0, 32); // clear local buffer
// leave zeroed out for sname && file
// put in W5100 transmit buffer x 6 (192 bytes)
for(int i = 0; i < 6; i++) {
_dhcpUdpSocket.write(buffer, 32);
}
// OPT - Magic Cookie
buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF);
buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF);
buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF);
buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF);
// OPT - message type
buffer[4] = dhcpMessageType;
buffer[5] = 0x01;
buffer[6] = messageType; //DHCP_REQUEST;
// OPT - client identifier
buffer[7] = dhcpClientIdentifier;
buffer[8] = 0x07;
buffer[9] = 0x01;
memcpy(buffer + 10, _dhcpMacAddr, 6);
// OPT - host name
buffer[16] = hostName;
buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address
strcpy((char*)&(buffer[18]), HOST_NAME);
printByte((char*)&(buffer[24]), _dhcpMacAddr[3]);
printByte((char*)&(buffer[26]), _dhcpMacAddr[4]);
printByte((char*)&(buffer[28]), _dhcpMacAddr[5]);
//put data in W5100 transmit buffer
_dhcpUdpSocket.write(buffer, 30);
if(messageType == DHCP_REQUEST)
{
buffer[0] = dhcpRequestedIPaddr;
buffer[1] = 0x04;
buffer[2] = _dhcpLocalIp[0];
buffer[3] = _dhcpLocalIp[1];
buffer[4] = _dhcpLocalIp[2];
buffer[5] = _dhcpLocalIp[3];
buffer[6] = dhcpServerIdentifier;
buffer[7] = 0x04;
buffer[8] = _dhcpDhcpServerIp[0];
buffer[9] = _dhcpDhcpServerIp[1];
buffer[10] = _dhcpDhcpServerIp[2];
buffer[11] = _dhcpDhcpServerIp[3];
//put data in W5100 transmit buffer
_dhcpUdpSocket.write(buffer, 12);
}
buffer[0] = dhcpParamRequest;
buffer[1] = 0x06;
buffer[2] = subnetMask;
buffer[3] = routersOnSubnet;
buffer[4] = dns;
buffer[5] = domainName;
buffer[6] = dhcpT1value;
buffer[7] = dhcpT2value;
buffer[8] = endOption;
//put data in W5100 transmit buffer
_dhcpUdpSocket.write(buffer, 9);
_dhcpUdpSocket.endPacket();
}
uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId)
{
uint8_t type = 0;
uint8_t opt_len = 0;
unsigned long startTime = millis();
while(_dhcpUdpSocket.parsePacket() <= 0)
{
if((millis() - startTime) > responseTimeout)
{
return 255;
}
delay(50);
}
// start reading in the packet
RIP_MSG_FIXED fixedMsg;
_dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED));
if(fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT)
{
transactionId = ntohl(fixedMsg.xid);
if(memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || (transactionId < _dhcpInitialTransactionId) || (transactionId > _dhcpTransactionId))
{
// Need to read the rest of the packet here regardless
_dhcpUdpSocket.flush();
return 0;
}
memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4);
// Skip to the option part
// Doing this a byte at a time so we don't have to put a big buffer
// on the stack (as we don't have lots of memory lying around)
for (int i =0; i < (240 - (int)sizeof(RIP_MSG_FIXED)); i++)
{
_dhcpUdpSocket.read(); // we don't care about the returned byte
}
while (_dhcpUdpSocket.available() > 0)
{
switch (_dhcpUdpSocket.read())
{
case endOption :
break;
case padOption :
break;
case dhcpMessageType :
opt_len = _dhcpUdpSocket.read();
type = _dhcpUdpSocket.read();
break;
case subnetMask :
opt_len = _dhcpUdpSocket.read();
_dhcpUdpSocket.read(_dhcpSubnetMask, 4);
break;
case routersOnSubnet :
opt_len = _dhcpUdpSocket.read();
_dhcpUdpSocket.read(_dhcpGatewayIp, 4);
for (int i = 0; i < opt_len-4; i++)
{
_dhcpUdpSocket.read();
}
break;
case dns :
opt_len = _dhcpUdpSocket.read();
_dhcpUdpSocket.read(_dhcpDnsServerIp, 4);
for (int i = 0; i < opt_len-4; i++)
{
_dhcpUdpSocket.read();
}
break;
case dhcpServerIdentifier :
opt_len = _dhcpUdpSocket.read();
if( *((uint32_t*)_dhcpDhcpServerIp) == 0 ||
IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() )
{
_dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp));
}
else
{
// Skip over the rest of this option
while (opt_len--)
{
_dhcpUdpSocket.read();
}
}
break;
case dhcpT1value :
opt_len = _dhcpUdpSocket.read();
_dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1));
_dhcpT1 = ntohl(_dhcpT1);
break;
case dhcpT2value :
opt_len = _dhcpUdpSocket.read();
_dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2));
_dhcpT2 = ntohl(_dhcpT2);
break;
case dhcpIPaddrLeaseTime :
opt_len = _dhcpUdpSocket.read();
_dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime));
_dhcpLeaseTime = ntohl(_dhcpLeaseTime);
_renewInSec = _dhcpLeaseTime;
break;
default :
opt_len = _dhcpUdpSocket.read();
// Skip over the rest of this option
while (opt_len--)
{
_dhcpUdpSocket.read();
}
break;
}
}
}
// Need to skip to end of the packet regardless here
_dhcpUdpSocket.flush();
return type;
}
/*
returns:
0/DHCP_CHECK_NONE: nothing happened
1/DHCP_CHECK_RENEW_FAIL: renew failed
2/DHCP_CHECK_RENEW_OK: renew success
3/DHCP_CHECK_REBIND_FAIL: rebind fail
4/DHCP_CHECK_REBIND_OK: rebind success
*/
int DhcpClass::checkLease(){
//this uses a signed / unsigned trick to deal with millis overflow
unsigned long now = millis();
signed long snow = (long)now;
int rc=DHCP_CHECK_NONE;
if (_lastCheck != 0){
signed long factor;
//calc how many ms past the timeout we are
factor = snow - (long)_secTimeout;
//if on or passed the timeout, reduce the counters
if ( factor >= 0 ){
//next timeout should be now plus 1000 ms minus parts of second in factor
_secTimeout = snow + 1000 - factor % 1000;
//how many seconds late are we, minimum 1
factor = factor / 1000 +1;
//reduce the counters by that mouch
//if we can assume that the cycle time (factor) is fairly constant
//and if the remainder is less than cycle time * 2
//do it early instead of late
if(_renewInSec < factor*2 )
_renewInSec = 0;
else
_renewInSec -= factor;
if(_rebindInSec < factor*2 )
_rebindInSec = 0;
else
_rebindInSec -= factor;
}
//if we have a lease but should renew, do it
if (_dhcp_state == STATE_DHCP_LEASED && _renewInSec <=0){
_dhcp_state = STATE_DHCP_REREQUEST;
rc = 1 + request_DHCP_lease();
}
//if we have a lease or is renewing but should bind, do it
if( (_dhcp_state == STATE_DHCP_LEASED || _dhcp_state == STATE_DHCP_START) && _rebindInSec <=0){
//this should basically restart completely
_dhcp_state = STATE_DHCP_START;
reset_DHCP_lease();
rc = 3 + request_DHCP_lease();
}
}
else{
_secTimeout = snow + 1000;
}
_lastCheck = now;
return rc;
}
IPAddress DhcpClass::getLocalIp()
{
return IPAddress(_dhcpLocalIp);
}
IPAddress DhcpClass::getSubnetMask()
{
return IPAddress(_dhcpSubnetMask);
}
IPAddress DhcpClass::getGatewayIp()
{
return IPAddress(_dhcpGatewayIp);
}
IPAddress DhcpClass::getDhcpServerIp()
{
return IPAddress(_dhcpDhcpServerIp);
}
IPAddress DhcpClass::getDnsServerIp()
{
return IPAddress(_dhcpDnsServerIp);
}
void DhcpClass::printByte(char * buf, uint8_t n ) {
char *str = &buf[1];
buf[0]='0';
do {
unsigned long m = n;
n /= 16;
char c = m - 16 * n;
*str-- = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
}

View File

@ -1,178 +0,0 @@
// DHCP Library v0.3 - April 25, 2009
// Author: Jordan Terrell - blog.jordanterrell.com
#ifndef Dhcp_h
#define Dhcp_h
#include "EthernetUdp.h"
/* DHCP state machine. */
#define STATE_DHCP_START 0
#define STATE_DHCP_DISCOVER 1
#define STATE_DHCP_REQUEST 2
#define STATE_DHCP_LEASED 3
#define STATE_DHCP_REREQUEST 4
#define STATE_DHCP_RELEASE 5
#define DHCP_FLAGSBROADCAST 0x8000
/* UDP port numbers for DHCP */
#define DHCP_SERVER_PORT 67 /* from server to client */
#define DHCP_CLIENT_PORT 68 /* from client to server */
/* DHCP message OP code */
#define DHCP_BOOTREQUEST 1
#define DHCP_BOOTREPLY 2
/* DHCP message type */
#define DHCP_DISCOVER 1
#define DHCP_OFFER 2
#define DHCP_REQUEST 3
#define DHCP_DECLINE 4
#define DHCP_ACK 5
#define DHCP_NAK 6
#define DHCP_RELEASE 7
#define DHCP_INFORM 8
#define DHCP_HTYPE10MB 1
#define DHCP_HTYPE100MB 2
#define DHCP_HLENETHERNET 6
#define DHCP_HOPS 0
#define DHCP_SECS 0
#define MAGIC_COOKIE 0x63825363
#define MAX_DHCP_OPT 16
#define HOST_NAME "WIZnet"
#define DEFAULT_LEASE (900) //default lease time in seconds
#define DHCP_CHECK_NONE (0)
#define DHCP_CHECK_RENEW_FAIL (1)
#define DHCP_CHECK_RENEW_OK (2)
#define DHCP_CHECK_REBIND_FAIL (3)
#define DHCP_CHECK_REBIND_OK (4)
enum
{
padOption = 0,
subnetMask = 1,
timerOffset = 2,
routersOnSubnet = 3,
/* timeServer = 4,
nameServer = 5,*/
dns = 6,
/*logServer = 7,
cookieServer = 8,
lprServer = 9,
impressServer = 10,
resourceLocationServer = 11,*/
hostName = 12,
/*bootFileSize = 13,
meritDumpFile = 14,*/
domainName = 15,
/*swapServer = 16,
rootPath = 17,
extentionsPath = 18,
IPforwarding = 19,
nonLocalSourceRouting = 20,
policyFilter = 21,
maxDgramReasmSize = 22,
defaultIPTTL = 23,
pathMTUagingTimeout = 24,
pathMTUplateauTable = 25,
ifMTU = 26,
allSubnetsLocal = 27,
broadcastAddr = 28,
performMaskDiscovery = 29,
maskSupplier = 30,
performRouterDiscovery = 31,
routerSolicitationAddr = 32,
staticRoute = 33,
trailerEncapsulation = 34,
arpCacheTimeout = 35,
ethernetEncapsulation = 36,
tcpDefaultTTL = 37,
tcpKeepaliveInterval = 38,
tcpKeepaliveGarbage = 39,
nisDomainName = 40,
nisServers = 41,
ntpServers = 42,
vendorSpecificInfo = 43,
netBIOSnameServer = 44,
netBIOSdgramDistServer = 45,
netBIOSnodeType = 46,
netBIOSscope = 47,
xFontServer = 48,
xDisplayManager = 49,*/
dhcpRequestedIPaddr = 50,
dhcpIPaddrLeaseTime = 51,
/*dhcpOptionOverload = 52,*/
dhcpMessageType = 53,
dhcpServerIdentifier = 54,
dhcpParamRequest = 55,
/*dhcpMsg = 56,
dhcpMaxMsgSize = 57,*/
dhcpT1value = 58,
dhcpT2value = 59,
/*dhcpClassIdentifier = 60,*/
dhcpClientIdentifier = 61,
endOption = 255
};
typedef struct _RIP_MSG_FIXED
{
uint8_t op;
uint8_t htype;
uint8_t hlen;
uint8_t hops;
uint32_t xid;
uint16_t secs;
uint16_t flags;
uint8_t ciaddr[4];
uint8_t yiaddr[4];
uint8_t siaddr[4];
uint8_t giaddr[4];
uint8_t chaddr[6];
}RIP_MSG_FIXED;
class DhcpClass {
private:
uint32_t _dhcpInitialTransactionId;
uint32_t _dhcpTransactionId;
uint8_t _dhcpMacAddr[6];
uint8_t _dhcpLocalIp[4];
uint8_t _dhcpSubnetMask[4];
uint8_t _dhcpGatewayIp[4];
uint8_t _dhcpDhcpServerIp[4];
uint8_t _dhcpDnsServerIp[4];
uint32_t _dhcpLeaseTime;
uint32_t _dhcpT1, _dhcpT2;
signed long _renewInSec;
signed long _rebindInSec;
signed long _lastCheck;
unsigned long _timeout;
unsigned long _responseTimeout;
unsigned long _secTimeout;
uint8_t _dhcp_state;
EthernetUDP _dhcpUdpSocket;
int request_DHCP_lease();
void reset_DHCP_lease();
void presend_DHCP();
void send_DHCP_MESSAGE(uint8_t, uint16_t);
void printByte(char *, uint8_t);
uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId);
public:
IPAddress getLocalIp();
IPAddress getSubnetMask();
IPAddress getGatewayIp();
IPAddress getDhcpServerIp();
IPAddress getDnsServerIp();
int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
int checkLease();
};
#endif

View File

@ -1,423 +0,0 @@
// Arduino DNS client for WizNet5100-based Ethernet shield
// (c) Copyright 2009-2010 MCQN Ltd.
// Released under Apache License, version 2.0
#include "w5100.h"
#include "EthernetUdp.h"
#include "util.h"
#include "Dns.h"
#include <string.h>
//#include <stdlib.h>
#include "Arduino.h"
#define SOCKET_NONE 255
// Various flags and header field values for a DNS message
#define UDP_HEADER_SIZE 8
#define DNS_HEADER_SIZE 12
#define TTL_SIZE 4
#define QUERY_FLAG (0)
#define RESPONSE_FLAG (1<<15)
#define QUERY_RESPONSE_MASK (1<<15)
#define OPCODE_STANDARD_QUERY (0)
#define OPCODE_INVERSE_QUERY (1<<11)
#define OPCODE_STATUS_REQUEST (2<<11)
#define OPCODE_MASK (15<<11)
#define AUTHORITATIVE_FLAG (1<<10)
#define TRUNCATION_FLAG (1<<9)
#define RECURSION_DESIRED_FLAG (1<<8)
#define RECURSION_AVAILABLE_FLAG (1<<7)
#define RESP_NO_ERROR (0)
#define RESP_FORMAT_ERROR (1)
#define RESP_SERVER_FAILURE (2)
#define RESP_NAME_ERROR (3)
#define RESP_NOT_IMPLEMENTED (4)
#define RESP_REFUSED (5)
#define RESP_MASK (15)
#define TYPE_A (0x0001)
#define CLASS_IN (0x0001)
#define LABEL_COMPRESSION_MASK (0xC0)
// Port number that DNS servers listen on
#define DNS_PORT 53
// Possible return codes from ProcessResponse
#define SUCCESS 1
#define TIMED_OUT -1
#define INVALID_SERVER -2
#define TRUNCATED -3
#define INVALID_RESPONSE -4
void DNSClient::begin(const IPAddress& aDNSServer)
{
iDNSServer = aDNSServer;
iRequestId = 0;
}
int DNSClient::inet_aton(const char* aIPAddrString, IPAddress& aResult)
{
// See if we've been given a valid IP address
const char* p =aIPAddrString;
while (*p &&
( (*p == '.') || (*p >= '0') || (*p <= '9') ))
{
p++;
}
if (*p == '\0')
{
// It's looking promising, we haven't found any invalid characters
p = aIPAddrString;
int segment =0;
int segmentValue =0;
while (*p && (segment < 4))
{
if (*p == '.')
{
// We've reached the end of a segment
if (segmentValue > 255)
{
// You can't have IP address segments that don't fit in a byte
return 0;
}
else
{
aResult[segment] = (byte)segmentValue;
segment++;
segmentValue = 0;
}
}
else
{
// Next digit
segmentValue = (segmentValue*10)+(*p - '0');
}
p++;
}
// We've reached the end of address, but there'll still be the last
// segment to deal with
if ((segmentValue > 255) || (segment > 3))
{
// You can't have IP address segments that don't fit in a byte,
// or more than four segments
return 0;
}
else
{
aResult[segment] = (byte)segmentValue;
return 1;
}
}
else
{
return 0;
}
}
int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult)
{
int ret =0;
// See if it's a numeric IP address
if (inet_aton(aHostname, aResult))
{
// It is, our work here is done
return 1;
}
// Check we've got a valid DNS server to use
if (iDNSServer == INADDR_NONE)
{
return INVALID_SERVER;
}
// Find a socket to use
if (iUdp.begin(1024+(millis() & 0xF)) == 1)
{
// Try up to three times
int retries = 0;
// while ((retries < 3) && (ret <= 0))
{
// Send DNS request
ret = iUdp.beginPacket(iDNSServer, DNS_PORT);
if (ret != 0)
{
// Now output the request data
ret = BuildRequest(aHostname);
if (ret != 0)
{
// And finally send the request
ret = iUdp.endPacket();
if (ret != 0)
{
// Now wait for a response
int wait_retries = 0;
ret = TIMED_OUT;
while ((wait_retries < 3) && (ret == TIMED_OUT))
{
ret = ProcessResponse(5000, aResult);
wait_retries++;
}
}
}
}
retries++;
}
// We're done with the socket now
iUdp.stop();
}
return ret;
}
uint16_t DNSClient::BuildRequest(const char* aName)
{
// Build header
// 1 1 1 1 1 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | ID |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | QDCOUNT |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | ANCOUNT |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | NSCOUNT |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | ARCOUNT |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// As we only support one request at a time at present, we can simplify
// some of this header
iRequestId = millis(); // generate a random ID
uint16_t twoByteBuffer;
// FIXME We should also check that there's enough space available to write to, rather
// FIXME than assume there's enough space (as the code does at present)
iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId));
twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG);
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
twoByteBuffer = htons(1); // One question record
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
twoByteBuffer = 0; // Zero answer records
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
// and zero additional records
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
// Build question
const char* start =aName;
const char* end =start;
uint8_t len;
// Run through the name being requested
while (*end)
{
// Find out how long this section of the name is
end = start;
while (*end && (*end != '.') )
{
end++;
}
if (end-start > 0)
{
// Write out the size of this section
len = end-start;
iUdp.write(&len, sizeof(len));
// And then write out the section
iUdp.write((uint8_t*)start, end-start);
}
start = end+1;
}
// We've got to the end of the question name, so
// terminate it with a zero-length section
len = 0;
iUdp.write(&len, sizeof(len));
// Finally the type and class of question
twoByteBuffer = htons(TYPE_A);
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
twoByteBuffer = htons(CLASS_IN); // Internet class of question
iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer));
// Success! Everything buffered okay
return 1;
}
uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress)
{
uint32_t startTime = millis();
// Wait for a response packet
while(iUdp.parsePacket() <= 0)
{
if((millis() - startTime) > aTimeout)
return TIMED_OUT;
delay(50);
}
// We've had a reply!
// Read the UDP header
uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header
// Check that it's a response from the right server and the right port
if ( (iDNSServer != iUdp.remoteIP()) ||
(iUdp.remotePort() != DNS_PORT) )
{
// It's not from who we expected
return INVALID_SERVER;
}
// Read through the rest of the response
if (iUdp.available() < DNS_HEADER_SIZE)
{
return TRUNCATED;
}
iUdp.read(header, DNS_HEADER_SIZE);
uint16_t header_flags = htons(*((uint16_t*)&header[2]));
// Check that it's a response to this request
if ( ( iRequestId != (*((uint16_t*)&header[0])) ) ||
((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) )
{
// Mark the entire packet as read
iUdp.flush();
return INVALID_RESPONSE;
}
// Check for any errors in the response (or in our request)
// although we don't do anything to get round these
if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) )
{
// Mark the entire packet as read
iUdp.flush();
return -5; //INVALID_RESPONSE;
}
// And make sure we've got (at least) one answer
uint16_t answerCount = htons(*((uint16_t*)&header[6]));
if (answerCount == 0 )
{
// Mark the entire packet as read
iUdp.flush();
return -6; //INVALID_RESPONSE;
}
// Skip over any questions
for (uint16_t i =0; i < htons(*((uint16_t*)&header[4])); i++)
{
// Skip over the name
uint8_t len;
do
{
iUdp.read(&len, sizeof(len));
if (len > 0)
{
// Don't need to actually read the data out for the string, just
// advance ptr to beyond it
while(len--)
{
iUdp.read(); // we don't care about the returned byte
}
}
} while (len != 0);
// Now jump over the type and class
for (int i =0; i < 4; i++)
{
iUdp.read(); // we don't care about the returned byte
}
}
// Now we're up to the bit we're interested in, the answer
// There might be more than one answer (although we'll just use the first
// type A answer) and some authority and additional resource records but
// we're going to ignore all of them.
for (uint16_t i =0; i < answerCount; i++)
{
// Skip the name
uint8_t len;
do
{
iUdp.read(&len, sizeof(len));
if ((len & LABEL_COMPRESSION_MASK) == 0)
{
// It's just a normal label
if (len > 0)
{
// And it's got a length
// Don't need to actually read the data out for the string,
// just advance ptr to beyond it
while(len--)
{
iUdp.read(); // we don't care about the returned byte
}
}
}
else
{
// This is a pointer to a somewhere else in the message for the
// rest of the name. We don't care about the name, and RFC1035
// says that a name is either a sequence of labels ended with a
// 0 length octet or a pointer or a sequence of labels ending in
// a pointer. Either way, when we get here we're at the end of
// the name
// Skip over the pointer
iUdp.read(); // we don't care about the returned byte
// And set len so that we drop out of the name loop
len = 0;
}
} while (len != 0);
// Check the type and class
uint16_t answerType;
uint16_t answerClass;
iUdp.read((uint8_t*)&answerType, sizeof(answerType));
iUdp.read((uint8_t*)&answerClass, sizeof(answerClass));
// Ignore the Time-To-Live as we don't do any caching
for (int i =0; i < TTL_SIZE; i++)
{
iUdp.read(); // we don't care about the returned byte
}
// And read out the length of this answer
// Don't need header_flags anymore, so we can reuse it here
iUdp.read((uint8_t*)&header_flags, sizeof(header_flags));
if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) )
{
if (htons(header_flags) != 4)
{
// It's a weird size
// Mark the entire packet as read
iUdp.flush();
return -9;//INVALID_RESPONSE;
}
iUdp.read(aAddress.raw_address(), 4);
return SUCCESS;
}
else
{
// This isn't an answer type we're after, move onto the next one
for (uint16_t i =0; i < htons(header_flags); i++)
{
iUdp.read(); // we don't care about the returned byte
}
}
}
// Mark the entire packet as read
iUdp.flush();
// If we get here then we haven't found an answer
return -10;//INVALID_RESPONSE;
}

View File

@ -1,41 +0,0 @@
// Arduino DNS client for WizNet5100-based Ethernet shield
// (c) Copyright 2009-2010 MCQN Ltd.
// Released under Apache License, version 2.0
#ifndef DNSClient_h
#define DNSClient_h
#include <EthernetUdp.h>
class DNSClient
{
public:
// ctor
void begin(const IPAddress& aDNSServer);
/** Convert a numeric IP address string into a four-byte IP address.
@param aIPAddrString IP address to convert
@param aResult IPAddress structure to store the returned IP address
@result 1 if aIPAddrString was successfully converted to an IP address,
else error code
*/
int inet_aton(const char *aIPAddrString, IPAddress& aResult);
/** Resolve the given hostname to an IP address.
@param aHostname Name to be resolved
@param aResult IPAddress structure to store the returned IP address
@result 1 if aIPAddrString was successfully converted to an IP address,
else error code
*/
int getHostByName(const char* aHostname, IPAddress& aResult);
protected:
uint16_t BuildRequest(const char* aName);
uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress);
IPAddress iDNSServer;
uint16_t iRequestId;
EthernetUDP iUdp;
};
#endif

View File

@ -1,122 +0,0 @@
#include "w5100.h"
#include "Ethernet.h"
#include "Dhcp.h"
// XXX: don't make assumptions about the value of MAX_SOCK_NUM.
uint8_t EthernetClass::_state[MAX_SOCK_NUM] = {
0, 0, 0, 0 };
uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = {
0, 0, 0, 0 };
int EthernetClass::begin(uint8_t *mac_address)
{
static DhcpClass s_dhcp;
_dhcp = &s_dhcp;
// Initialise the basic info
W5100.init();
W5100.setMACAddress(mac_address);
W5100.setIPAddress(IPAddress(0,0,0,0).raw_address());
// Now try to get our config info from a DHCP server
int ret = _dhcp->beginWithDHCP(mac_address);
if(ret == 1)
{
// We've successfully found a DHCP server and got our configuration info, so set things
// accordingly
W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
_dnsServerAddress = _dhcp->getDnsServerIp();
}
return ret;
}
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip)
{
// Assume the DNS server will be the machine on the same network as the local IP
// but with last octet being '1'
IPAddress dns_server = local_ip;
dns_server[3] = 1;
begin(mac_address, local_ip, dns_server);
}
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server)
{
// Assume the gateway will be the machine on the same network as the local IP
// but with last octet being '1'
IPAddress gateway = local_ip;
gateway[3] = 1;
begin(mac_address, local_ip, dns_server, gateway);
}
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
{
IPAddress subnet(255, 255, 255, 0);
begin(mac_address, local_ip, dns_server, gateway, subnet);
}
void EthernetClass::begin(uint8_t *mac, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet)
{
W5100.init();
W5100.setMACAddress(mac);
W5100.setIPAddress(local_ip._address);
W5100.setGatewayIp(gateway._address);
W5100.setSubnetMask(subnet._address);
_dnsServerAddress = dns_server;
}
int EthernetClass::maintain(){
int rc = DHCP_CHECK_NONE;
if(_dhcp != NULL){
//we have a pointer to dhcp, use it
rc = _dhcp->checkLease();
switch ( rc ){
case DHCP_CHECK_NONE:
//nothing done
break;
case DHCP_CHECK_RENEW_OK:
case DHCP_CHECK_REBIND_OK:
//we might have got a new IP.
W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
_dnsServerAddress = _dhcp->getDnsServerIp();
break;
default:
//this is actually a error, it will retry though
break;
}
}
return rc;
}
IPAddress EthernetClass::localIP()
{
IPAddress ret;
W5100.getIPAddress(ret.raw_address());
return ret;
}
IPAddress EthernetClass::subnetMask()
{
IPAddress ret;
W5100.getSubnetMask(ret.raw_address());
return ret;
}
IPAddress EthernetClass::gatewayIP()
{
IPAddress ret;
W5100.getGatewayIp(ret.raw_address());
return ret;
}
IPAddress EthernetClass::dnsServerIP()
{
return _dnsServerAddress;
}
EthernetClass Ethernet;

View File

@ -1,41 +0,0 @@
#ifndef ethernet_h
#define ethernet_h
#include <inttypes.h>
//#include "w5100.h"
#include "IPAddress.h"
#include "EthernetClient.h"
#include "EthernetServer.h"
#include "Dhcp.h"
#define MAX_SOCK_NUM 4
class EthernetClass {
private:
IPAddress _dnsServerAddress;
DhcpClass* _dhcp;
public:
static uint8_t _state[MAX_SOCK_NUM];
static uint16_t _server_port[MAX_SOCK_NUM];
// Initialise the Ethernet shield to use the provided MAC address and gain the rest of the
// configuration through DHCP.
// Returns 0 if the DHCP configuration failed, and 1 if it succeeded
int begin(uint8_t *mac_address);
void begin(uint8_t *mac_address, IPAddress local_ip);
void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server);
void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway);
void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet);
int maintain();
IPAddress localIP();
IPAddress subnetMask();
IPAddress gatewayIP();
IPAddress dnsServerIP();
friend class EthernetClient;
friend class EthernetServer;
};
extern EthernetClass Ethernet;
#endif

View File

@ -1,37 +0,0 @@
#ifndef ethernetclient_h
#define ethernetclient_h
#include "Arduino.h"
#include "Print.h"
#include "Client.h"
#include "IPAddress.h"
class EthernetClient : public Client {
public:
EthernetClient();
EthernetClient(uint8_t sock);
uint8_t status();
virtual int connect(IPAddress ip, uint16_t port);
virtual int connect(const char *host, uint16_t port);
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
virtual int available();
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek();
virtual void flush();
virtual void stop();
virtual uint8_t connected();
virtual operator bool();
friend class EthernetServer;
using Print::write;
private:
static uint16_t _srcport;
uint8_t _sock;
};
#endif

View File

@ -1,91 +0,0 @@
#include "w5100.h"
#include "socket.h"
extern "C" {
#include "string.h"
}
#include "Ethernet.h"
#include "EthernetClient.h"
#include "EthernetServer.h"
EthernetServer::EthernetServer(uint16_t port)
{
_port = port;
}
void EthernetServer::begin()
{
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
EthernetClient client(sock);
if (client.status() == SnSR::CLOSED) {
socket(sock, SnMR::TCP, _port, 0);
listen(sock);
EthernetClass::_server_port[sock] = _port;
break;
}
}
}
void EthernetServer::accept()
{
int listening = 0;
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
EthernetClient client(sock);
if (EthernetClass::_server_port[sock] == _port) {
if (client.status() == SnSR::LISTEN) {
listening = 1;
}
else if (client.status() == SnSR::CLOSE_WAIT && !client.available()) {
client.stop();
}
}
}
if (!listening) {
begin();
}
}
EthernetClient EthernetServer::available()
{
accept();
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
EthernetClient client(sock);
if (EthernetClass::_server_port[sock] == _port &&
(client.status() == SnSR::ESTABLISHED ||
client.status() == SnSR::CLOSE_WAIT)) {
if (client.available()) {
// XXX: don't always pick the lowest numbered socket.
return client;
}
}
}
return EthernetClient(MAX_SOCK_NUM);
}
size_t EthernetServer::write(uint8_t b)
{
return write(&b, 1);
}
size_t EthernetServer::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
accept();
for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
EthernetClient client(sock);
if (EthernetClass::_server_port[sock] == _port &&
client.status() == SnSR::ESTABLISHED) {
n += client.write(buffer, size);
}
}
return n;
}

View File

@ -1,22 +0,0 @@
#ifndef ethernetserver_h
#define ethernetserver_h
#include "Server.h"
class EthernetClient;
class EthernetServer :
public Server {
private:
uint16_t _port;
void accept();
public:
EthernetServer(uint16_t);
EthernetClient available();
virtual void begin();
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
using Print::write;
};
#endif

View File

@ -1,218 +0,0 @@
/*
* Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield.
* This version only offers minimal wrapping of socket.c/socket.h
* Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/
*
* MIT License:
* Copyright (c) 2008 Bjoern Hartmann
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* bjoern@cs.stanford.edu 12/30/2008
*/
#include "w5100.h"
#include "socket.h"
#include "Ethernet.h"
#include "Udp.h"
#include "Dns.h"
/* Constructor */
EthernetUDP::EthernetUDP() : _sock(MAX_SOCK_NUM) {}
/* Start EthernetUDP socket, listening at local port PORT */
uint8_t EthernetUDP::begin(uint16_t port) {
if (_sock != MAX_SOCK_NUM)
return 0;
for (int i = 0; i < MAX_SOCK_NUM; i++) {
uint8_t s = W5100.readSnSR(i);
if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT) {
_sock = i;
break;
}
}
if (_sock == MAX_SOCK_NUM)
return 0;
_port = port;
_remaining = 0;
socket(_sock, SnMR::UDP, _port, 0);
return 1;
}
/* return number of bytes available in the current packet,
will return zero if parsePacket hasn't been called yet */
int EthernetUDP::available() {
return _remaining;
}
/* Release any resources being used by this EthernetUDP instance */
void EthernetUDP::stop()
{
if (_sock == MAX_SOCK_NUM)
return;
close(_sock);
EthernetClass::_server_port[_sock] = 0;
_sock = MAX_SOCK_NUM;
}
int EthernetUDP::beginPacket(const char *host, uint16_t port)
{
// Look up the host first
int ret = 0;
DNSClient dns;
IPAddress remote_addr;
dns.begin(Ethernet.dnsServerIP());
ret = dns.getHostByName(host, remote_addr);
if (ret == 1) {
return beginPacket(remote_addr, port);
} else {
return ret;
}
}
int EthernetUDP::beginPacket(IPAddress ip, uint16_t port)
{
_offset = 0;
return startUDP(_sock, rawIPAddress(ip), port);
}
int EthernetUDP::endPacket()
{
return sendUDP(_sock);
}
size_t EthernetUDP::write(uint8_t byte)
{
return write(&byte, 1);
}
size_t EthernetUDP::write(const uint8_t *buffer, size_t size)
{
uint16_t bytes_written = bufferData(_sock, _offset, buffer, size);
_offset += bytes_written;
return bytes_written;
}
int EthernetUDP::parsePacket()
{
// discard any remaining bytes in the last packet
flush();
if (W5100.getRXReceivedSize(_sock) > 0)
{
//HACK - hand-parse the UDP packet using TCP recv method
uint8_t tmpBuf[8];
int ret =0;
//read 8 header bytes and get IP and port from it
ret = recv(_sock,tmpBuf,8);
if (ret > 0)
{
_remoteIP = tmpBuf;
_remotePort = tmpBuf[4];
_remotePort = (_remotePort << 8) + tmpBuf[5];
_remaining = tmpBuf[6];
_remaining = (_remaining << 8) + tmpBuf[7];
// When we get here, any remaining bytes are the data
ret = _remaining;
}
return ret;
}
// There aren't any packets available
return 0;
}
int EthernetUDP::read()
{
uint8_t byte;
if ((_remaining > 0) && (recv(_sock, &byte, 1) > 0))
{
// We read things without any problems
_remaining--;
return byte;
}
// If we get here, there's no data available
return -1;
}
int EthernetUDP::read(unsigned char* buffer, size_t len)
{
if (_remaining > 0)
{
int got;
if (_remaining <= len)
{
// data should fit in the buffer
got = recv(_sock, buffer, _remaining);
}
else
{
// too much data for the buffer,
// grab as much as will fit
got = recv(_sock, buffer, len);
}
if (got > 0)
{
_remaining -= got;
return got;
}
}
// If we get here, there's no data available or recv failed
return -1;
}
int EthernetUDP::peek()
{
uint8_t b;
// Unlike recv, peek doesn't check to see if there's any data available, so we must.
// If the user hasn't called parsePacket yet then return nothing otherwise they
// may get the UDP header
if (!_remaining)
return -1;
::peek(_sock, &b);
return b;
}
void EthernetUDP::flush()
{
// could this fail (loop endlessly) if _remaining > 0 and recv in read fails?
// should only occur if recv fails after telling us the data is there, lets
// hope the w5100 always behaves :)
while (_remaining)
{
read();
}
}

View File

@ -1,99 +0,0 @@
/*
* Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield.
* This version only offers minimal wrapping of socket.c/socket.h
* Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/
*
* NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these)
* 1) UDP does not guarantee the order in which assembled UDP packets are received. This
* might not happen often in practice, but in larger network topologies, a UDP
* packet can be received out of sequence.
* 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being
* aware of it. Again, this may not be a concern in practice on small local networks.
* For more information, see http://www.cafeaulait.org/course/week12/35.html
*
* MIT License:
* Copyright (c) 2008 Bjoern Hartmann
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* bjoern@cs.stanford.edu 12/30/2008
*/
#ifndef ethernetudp_h
#define ethernetudp_h
#include <Udp.h>
#define UDP_TX_PACKET_MAX_SIZE 24
class EthernetUDP : public UDP {
private:
uint8_t _sock; // socket ID for Wiz5100
uint16_t _port; // local port to listen on
IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed
uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed
uint16_t _offset; // offset into the packet being sent
uint16_t _remaining; // remaining bytes of incoming packet yet to be processed
public:
EthernetUDP(); // Constructor
virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
virtual void stop(); // Finish with the UDP socket
// Sending UDP packets
// Start building up a packet to send to the remote host specific in ip and port
// Returns 1 if successful, 0 if there was a problem with the supplied IP address or port
virtual int beginPacket(IPAddress ip, uint16_t port);
// Start building up a packet to send to the remote host specific in host and port
// Returns 1 if successful, 0 if there was a problem resolving the hostname or port
virtual int beginPacket(const char *host, uint16_t port);
// Finish off this packet and send it
// Returns 1 if the packet was sent successfully, 0 if there was an error
virtual int endPacket();
// Write a single byte into the packet
virtual size_t write(uint8_t);
// Write size bytes from buffer into the packet
virtual size_t write(const uint8_t *buffer, size_t size);
using Print::write;
// Start processing the next available incoming packet
// Returns the size of the packet in bytes, or 0 if no packets are available
virtual int parsePacket();
// Number of bytes remaining in the current packet
virtual int available();
// Read a single byte from the current packet
virtual int read();
// Read up to len bytes from the current packet and place them into buffer
// Returns the number of bytes read, or 0 if none are available
virtual int read(unsigned char* buffer, size_t len);
// Read up to len characters from the current packet and place them into buffer
// Returns the number of characters read, or 0 if none are available
virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); };
// Return the next byte from the current packet without moving on to the next byte
virtual int peek();
virtual void flush(); // Finish reading the current packet
// Return the IP address of the host who sent the current incoming packet
virtual IPAddress remoteIP() { return _remoteIP; };
// Return the port of the host who sent the current incoming packet
virtual uint16_t remotePort() { return _remotePort; };
};
#endif

View File

@ -1,222 +0,0 @@
/*
SCP1000 Barometric Pressure Sensor Display
Serves the output of a Barometric Pressure Sensor as a web page.
Uses the SPI library. For details on the sensor, see:
http://www.sparkfun.com/commerce/product_info.php?products_id=8161
http://www.vti.fi/en/support/obsolete_products/pressure_sensors/
This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
Circuit:
SCP1000 sensor attached to pins 6,7, and 11 - 13:
DRDY: pin 6
CSB: pin 7
MOSI: pin 11
MISO: pin 12
SCK: pin 13
created 31 July 2010
by Tom Igoe
*/
#include <Ethernet.h>
// the sensor communicates using SPI, so include the library:
#include <SPI.h>
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// assign an IP address for the controller:
IPAddress ip(192,168,1,20);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255, 255, 255, 0);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
//Sensor's memory register addresses:
const int PRESSURE = 0x1F; //3 most significant bits of pressure
const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure
const int TEMPERATURE = 0x21; //16 bit temperature reading
// pins used for the connection with the sensor
// the others you need are controlled by the SPI library):
const int dataReadyPin = 6;
const int chipSelectPin = 7;
float temperature = 0.0;
long pressure = 0;
long lastReadingTime = 0;
void setup() {
// start the SPI library:
SPI.begin();
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
// initalize the data ready and chip select pins:
pinMode(dataReadyPin, INPUT);
pinMode(chipSelectPin, OUTPUT);
Serial.begin(9600);
//Configure SCP1000 for low noise configuration:
writeRegister(0x02, 0x2D);
writeRegister(0x01, 0x03);
writeRegister(0x03, 0x02);
// give the sensor and Ethernet shield time to set up:
delay(1000);
//Set the sensor to high resolution mode tp start readings:
writeRegister(0x03, 0x0A);
}
void loop() {
// check for a reading no more than once a second.
if (millis() - lastReadingTime > 1000){
// if there's a reading ready, read it:
// don't do anything until the data ready pin is high:
if (digitalRead(dataReadyPin) == HIGH) {
getData();
// timestamp the last time you got a reading:
lastReadingTime = millis();
}
}
// listen for incoming Ethernet connections:
listenForEthernetClients();
}
void getData() {
Serial.println("Getting reading");
//Read the temperature data
int tempData = readRegister(0x21, 2);
// convert the temperature to celsius and display it:
temperature = (float)tempData / 20.0;
//Read the pressure data highest 3 bits:
byte pressureDataHigh = readRegister(0x1F, 1);
pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0
//Read the pressure data lower 16 bits:
unsigned int pressureDataLow = readRegister(0x20, 2);
//combine the two parts into one 19-bit number:
pressure = ((pressureDataHigh << 16) | pressureDataLow)/4;
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" degrees C");
Serial.print("Pressure: " + String(pressure));
Serial.println(" Pa");
}
void listenForEthernetClients() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("Got a client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// 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
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
// print the current readings, in HTML format:
client.print("Temperature: ");
client.print(temperature);
client.print(" degrees C");
client.println("<br />");
client.print("Pressure: " + String(pressure));
client.print(" Pa");
client.println("<br />");
break;
}
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);
// close the connection:
client.stop();
}
}
//Send a write command to SCP1000
void writeRegister(byte registerName, byte registerValue) {
// SCP1000 expects the register name in the upper 6 bits
// of the byte:
registerName <<= 2;
// command (read or write) goes in the lower two bits:
registerName |= 0b00000010; //Write command
// take the chip select low to select the device:
digitalWrite(chipSelectPin, LOW);
SPI.transfer(registerName); //Send register location
SPI.transfer(registerValue); //Send value to record into register
// take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH);
}
//Read register from the SCP1000:
unsigned int readRegister(byte registerName, int numBytes) {
byte inByte = 0; // incoming from the SPI read
unsigned int result = 0; // result to return
// SCP1000 expects the register name in the upper 6 bits
// of the byte:
registerName <<= 2;
// command (read or write) goes in the lower two bits:
registerName &= 0b11111100; //Read command
// take the chip select low to select the device:
digitalWrite(chipSelectPin, LOW);
// send the device the register you want to read:
int command = SPI.transfer(registerName);
// send a value of 0 to read the first byte returned:
inByte = SPI.transfer(0x00);
result = inByte;
// if there's more than one byte returned,
// shift the first byte then get the second byte:
if (numBytes > 1){
result = inByte << 8;
inByte = SPI.transfer(0x00);
result = result |inByte;
}
// take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH);
// return the result:
return(result);
}

View File

@ -1,79 +0,0 @@
/*
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 an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 177);
IPAddress gateway(192,168,1, 1);
IPAddress subnet(255, 255, 0, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean alreadyConnected = false; // whether or not the client was connected previously
void setup() {
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Chat server address:");
Serial.println(Ethernet.localIP());
}
void loop() {
// wait for a new client:
EthernetClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clead out the input buffer:
client.flush();
Serial.println("We have a new client");
client.println("Hello, client!");
alreadyConnected = true;
}
if (client.available() > 0) {
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
}

View File

@ -1,160 +0,0 @@
/*
Cosm sensor client
This sketch connects an analog sensor to Cosm (http://www.cosm.com)
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
the Adafruit Ethernet shield, either one will work, as long as it's got
a Wiznet Ethernet module on board.
This example has been updated to use version 2.0 of the cosm.com API.
To make it work, create a feed with a datastream, and give it the ID
sensor1. Or change the code below to match your feed.
Circuit:
* Analog sensor attached to analog in 0
* Ethernet shield attached to pins 10, 11, 12, 13
created 15 March 2010
updated 14 May 2012
by Tom Igoe with input from Usman Haque and Joe Saavedra
http://arduino.cc/en/Tutorial/CosmClient
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
#define APIKEY "YOUR API KEY GOES HERE" // replace your Cosm api key here
#define FEEDID 00000 // replace your feed ID
#define USERAGENT "My Project" // user agent is the project name
// assign a MAC address for the ethernet controller.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(10,0,1,20);
// initialize the library instance:
EthernetClient client;
// 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(216,52,233,121); // numeric IP for api.cosm.com
char server[] = "api.cosm.com"; // name address for cosm API
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10L*1000L; // delay between updates to cosm.com
// the "L" is needed to use long type numbers
void setup() {
// start serial port:
Serial.begin(9600);
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// DHCP failed, so use a fixed IP address:
Ethernet.begin(mac, ip);
}
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
sendData(sensorReading);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void sendData(int thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.cosm.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 8 bytes for "sensor1," + number of digits of the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("sensor1,");
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}

View File

@ -1,147 +0,0 @@
/*
Cosm sensor client with Strings
This sketch connects an analog sensor to Cosm (http://www.cosm.com)
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
the Adafruit Ethernet shield, either one will work, as long as it's got
a Wiznet Ethernet module on board.
This example has been updated to use version 2.0 of the Cosm.com API.
To make it work, create a feed with two datastreams, and give them the IDs
sensor1 and sensor2. Or change the code below to match your feed.
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* Analog sensor attached to analog in 0
* Ethernet shield attached to pins 10, 11, 12, 13
created 15 March 2010
updated 14 May 2012
by Tom Igoe with input from Usman Haque and Joe Saavedra
http://arduino.cc/en/Tutorial/CosmClientString
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
#define APIKEY "YOUR API KEY GOES HERE" // replace your Cosm api key here
#define FEEDID 00000 // replace your feed ID
#define USERAGENT "My Project" // user agent is the project name
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(10,0,1,20);
// initialize the library instance:
EthernetClient client;
// 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(216,52,233,121); // numeric IP for api.cosm.com
char server[] = "api.cosm.com"; // name address for Cosm API
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10L*1000L; // delay between updates to Cosm.com
// the "L" is needed to use long type numbers
void setup() {
// start serial port:
Serial.begin(9600);
// give the ethernet module time to boot up:
delay(1000);
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// DHCP failed, so use a fixed IP address:
Ethernet.begin(mac, ip);
}
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// convert the data to a String to send it:
String dataString = "sensor1,";
dataString += sensorReading;
// you can append multiple readings to this String if your
// Cosm feed is set up to handle multiple values:
int otherSensorReading = analogRead(A1);
dataString += "\nsensor2,";
dataString += otherSensorReading;
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
sendData(dataString);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.cosm.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(thisData.length());
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}

View File

@ -1,59 +0,0 @@
/*
DHCP-based IP printer
This sketch uses the DHCP extensions to the Ethernet library
to get an IP address via DHCP and print the address obtained.
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 12 April 2011
modified 9 Apr 2012
by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
// 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;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// this check is only needed on the Leonardo:
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for(;;)
;
}
// print your local IP address:
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
void loop() {
}

View File

@ -1,87 +0,0 @@
/*
DHCP 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 an Arduino Wiznet Ethernet shield.
THis version attempts to get an IP address using DHCP
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 21 May 2011
modified 9 Apr 2012
by Tom Igoe
Based on ChatServer example by David A. Mellis
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
IPAddress ip(192,168,1,177);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,0,0);
// telnet defaults to port 23
EthernetServer server(23);
boolean gotAMessage = false; // whether or not you got a message from the client yet
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// this check is only needed on the Leonardo:
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
Serial.println("Trying to get an IP address using DHCP");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// initialize the ethernet device not using DHCP:
Ethernet.begin(mac, ip, gateway, subnet);
}
// print your local IP address:
Serial.print("My IP address: ");
ip = Ethernet.localIP();
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(ip[thisByte], DEC);
Serial.print(".");
}
Serial.println();
// start listening for clients
server.begin();
}
void loop() {
// wait for a new client:
EthernetClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!gotAMessage) {
Serial.println("We have a new client");
client.println("Hello, client!");
gotAMessage = true;
}
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.print(thisChar);
}
}

View File

@ -1,80 +0,0 @@
/*
DNS and DHCP-based 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 <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
char serverName[] = "www.google.com";
// 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;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
while(true);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(serverName, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
}
else {
// if 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:
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

@ -1,163 +0,0 @@
/*
Pachube sensor client
This sketch connects an analog sensor to Pachube (http://www.pachube.com)
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
the Adafruit Ethernet shield, either one will work, as long as it's got
a Wiznet Ethernet module on board.
This example has been updated to use version 2.0 of the Pachube.com API.
To make it work, create a feed with a datastream, and give it the ID
sensor1. Or change the code below to match your feed.
Circuit:
* Analog sensor attached to analog in 0
* Ethernet shield attached to pins 10, 11, 12, 13
created 15 March 2010
modified 9 Apr 2012
by Tom Igoe with input from Usman Haque and Joe Saavedra
http://arduino.cc/en/Tutorial/PachubeClient
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here
#define FEEDID 00000 // replace your feed ID
#define USERAGENT "My Project" // user agent is the project name
// assign a MAC address for the ethernet controller.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(10,0,1,20);
// initialize the library instance:
EthernetClient client;
// 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(216,52,233,122); // numeric IP for api.pachube.com
//char server[] = "api.pachube.com"; // name address for pachube API
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// DHCP failed, so use a fixed IP address:
Ethernet.begin(mac, ip);
}
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
sendData(sensorReading);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void sendData(int thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.pachube.com");
client.print("X-PachubeApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 8 bytes for "sensor1," + number of digits of the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("sensor1,");
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}

View File

@ -1,154 +0,0 @@
/*
Pachube sensor client with Strings
This sketch connects an analog sensor to Pachube (http://www.pachube.com)
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
the Adafruit Ethernet shield, either one will work, as long as it's got
a Wiznet Ethernet module on board.
This example has been updated to use version 2.0 of the pachube.com API.
To make it work, create a feed with two datastreams, and give them the IDs
sensor1 and sensor2. Or change the code below to match your feed.
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* Analog sensor attached to analog in 0
* Ethernet shield attached to pins 10, 11, 12, 13
created 15 March 2010
modified 9 Apr 2012
by Tom Igoe with input from Usman Haque and Joe Saavedra
modified 8 September 2012
by Scott Fitzgerald
http://arduino.cc/en/Tutorial/PachubeClientString
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
#define APIKEY "YOUR API KEY GOES HERE" // replace your Pachube api key here
#define FEEDID 00000 // replace your feed ID
#define USERAGENT "My Project" // user agent is the project name
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(10,0,1,20);
// initialize the library instance:
EthernetClient client;
// 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(216,52,233,121); // numeric IP for api.pachube.com
//char server[] = "api.pachube.com"; // name address for pachube API
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// give the ethernet module time to boot up:
delay(1000);
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// DHCP failed, so use a fixed IP address:
Ethernet.begin(mac, ip);
}
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// convert the data to a String to send it:
String dataString = "sensor1,";
dataString += sensorReading;
// you can append multiple readings to this String if your
// pachube feed is set up to handle multiple values:
int otherSensorReading = analogRead(A1);
dataString += "\nsensor2,";
dataString += otherSensorReading;
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
sendData(dataString);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.pachube.com");
client.print("X-pachubeApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(thisData.length());
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}

View File

@ -1,93 +0,0 @@
/*
Telnet client
This sketch connects to a a telnet server (http://www.google.com)
using an Arduino Wiznet Ethernet shield. 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/
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 14 Sep 2010
modified 9 Apr 2012
by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177);
// 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):
EthernetClient client;
void setup() {
// start the Ethernet connection:
Ethernet.begin(mac, ip);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 10002)) {
Serial.println("connected");
}
else {
// if 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:
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

@ -1,135 +0,0 @@
/*
Twitter Client with Strings
This sketch connects to Twitter using an Ethernet shield. It parses the XML
returned, and looks for <text>this is a tweet</text>
You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield,
either one will work, as long as it's got a Wiznet Ethernet module on board.
This example uses the DHCP routines in the Ethernet library which is part of the
Arduino core from version 1.0 beta 1
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 21 May 2011
modified 9 Apr 2012
by Tom Igoe
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
IPAddress ip(192,168,1,20);
// initialize the library instance:
EthernetClient client;
const unsigned long requestInterval = 60000; // delay between requests
char serverName[] = "api.twitter.com"; // twitter URL
boolean requested; // whether you've made a request since connecting
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
String currentLine = ""; // string to hold the text from server
String tweet = ""; // string to hold the tweet
boolean readingTweet = false; // if you're currently reading the tweet
void setup() {
// reserve space for the strings:
currentLine.reserve(256);
tweet.reserve(150);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// attempt a DHCP connection:
Serial.println("Attempting to get an IP address using DHCP:");
if (!Ethernet.begin(mac)) {
// if DHCP fails, start with a hard-coded address:
Serial.println("failed to get an IP address using DHCP, trying manually");
Ethernet.begin(mac, ip);
}
Serial.print("My address:");
Serial.println(Ethernet.localIP());
// connect to Twitter:
connectToServer();
}
void loop()
{
if (client.connected()) {
if (client.available()) {
// read incoming bytes:
char inChar = client.read();
// add incoming byte to end of line:
currentLine += inChar;
// if you get a newline, clear the line:
if (inChar == '\n') {
currentLine = "";
}
// if the current line ends with <text>, it will
// be followed by the tweet:
if ( currentLine.endsWith("<text>")) {
// tweet is beginning. Clear the tweet string:
readingTweet = true;
tweet = "";
}
// if you're currently reading the bytes of a tweet,
// add them to the tweet String:
if (readingTweet) {
if (inChar != '<') {
tweet += inChar;
}
else {
// if you got a "<" character,
// you've reached the end of the tweet:
readingTweet = false;
Serial.println(tweet);
// close the connection to the server:
client.stop();
}
}
}
}
else if (millis() - lastAttemptTime > requestInterval) {
// if you're not connected, and two minutes have passed since
// your last connection, then attempt to connect again:
connectToServer();
}
}
void connectToServer() {
// attempt to connect, and wait a millisecond:
Serial.println("connecting to server...");
if (client.connect(serverName, 80)) {
Serial.println("making HTTP request...");
// make HTTP GET request to twitter:
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1");
client.println("HOST: api.twitter.com");
client.println();
}
// note the time of this connect attempt:
lastAttemptTime = millis();
}

View File

@ -1,120 +0,0 @@
/*
UDPSendReceive
This sketch receives UDP message strings, prints them to the serial port
and sends an "acknowledge" string back to the sender
A Processing sketch is included at the end of file that can be used to send
and received messages for testing with a computer.
created 21 Aug 2010
by Michael Margolis
This code is in the public domain.
*/
#include <SPI.h> // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168,1,177);
unsigned int localPort = 8888; // local port to listen on
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged"; // a string to send back
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
Serial.begin(9600);
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
delay(10);
}
/*
Processing sketch to run with this example
=====================================================
// Processing UDP example to send and receive string data from Arduino
// press any key to send the "Hello Arduino" message
import hypermedia.net.*;
UDP udp; // define the UDP object
void setup() {
udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000
//udp.log( true ); // <-- printout the connection activity
udp.listen( true ); // and wait for incoming message
}
void draw()
{
}
void keyPressed() {
String ip = "192.168.1.177"; // the remote IP address
int port = 8888; // the destination port
udp.send("Hello World", ip, port ); // the message to send
}
void receive( byte[] data ) { // <-- default handler
//void receive( byte[] data, String ip, int port ) { // <-- extended handler
for(int i=0; i < data.length; i++)
print(char(data[i]));
println();
}
*/

View File

@ -1,149 +0,0 @@
/*
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
Warning: NTP Servers are subject to temporary failure or IP address change.
Plese check
http://tf.nist.gov/tf-cgi/servers.cgi
if the time server used in the example didn't work.
created 4 Sep 2010
by Michael Margolis
modified 9 Apr 2012
by Tom Igoe
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// 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 };
unsigned int localPort = 8888; // local port to listen for UDP packets
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov NTP server
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start Ethernet and UDP
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for(;;)
;
}
Udp.begin(localPort);
}
void loop()
{
sendNTPpacket(timeServer); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
if ( Udp.parsePacket() ) {
// We've received a packet, read the data from it
Udp.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(IPAddress& address)
{
// 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:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer,NTP_PACKET_SIZE);
Udp.endPacket();
}

View File

@ -1,80 +0,0 @@
/*
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
modified 9 Apr 2012
by David A. Mellis
*/
#include <SPI.h>
#include <Ethernet.h>
// 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 };
IPAddress server(173,194,33,104); // Google
// 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;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for(;;)
;
}
// give the Ethernet shield a second to initialize:
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 /search?q=arduino HTTP/1.0");
client.println();
}
else {
// if 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:
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:
for(;;)
;
}
}

View File

@ -1,111 +0,0 @@
/*
Repeating Web client
This sketch connects to a a web server and makes a request
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
the Adafruit Ethernet shield, either one will work, as long as it's got
a Wiznet Ethernet module on board.
This example uses DNS, by assigning the Ethernet client with a MAC address,
IP address, and DNS address.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 19 Apr 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/WebClientRepeating
This code is in the public domain.
*/
#include <SPI.h>
#include <Ethernet.h>
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(10,0,0,20);
// fill in your Domain Name Server address here:
IPAddress myDns(1,1,1,1);
// initialize the library instance:
EthernetClient client;
char server[] = "www.arduino.cc";
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 60L*1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers
void setup() {
// start serial port:
Serial.begin(9600);
// give the ethernet module time to boot up:
delay(1000);
// start the Ethernet connection using a fixed IP address and DNS server:
Ethernet.begin(mac, ip, myDns);
// print the Ethernet board/shield's IP address:
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
}
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
httpRequest();
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void httpRequest() {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.println("GET /latest.txt HTTP/1.1");
client.println("Host: www.arduino.cc");
client.println("User-Agent: arduino-ethernet");
client.println("Connection: close");
client.println();
// note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println("disconnecting.");
client.stop();
}
}

View File

@ -1,101 +0,0 @@
/*
Web Server
A simple web server that shows the value of the analog input pins.
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.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
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// add a meta refresh tag, so the browser pulls again every 5 seconds:
client.println("<meta http-equiv=\"refresh\" content=\"5\">");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
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);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}

View File

@ -1,143 +0,0 @@
/*
SCP1000 Barometric Pressure Sensor Display
Shows the output of a Barometric Pressure Sensor on a
Uses the SPI library. For details on the sensor, see:
http://www.sparkfun.com/commerce/product_info.php?products_id=8161
http://www.vti.fi/en/support/obsolete_products/pressure_sensors/
This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
Circuit:
SCP1000 sensor attached to pins 6, 7, 10 - 13:
DRDY: pin 6
CSB: pin 7
MOSI: pin 11
MISO: pin 12
SCK: pin 13
created 31 July 2010
modified 14 August 2010
by Tom Igoe
*/
// the sensor communicates using SPI, so include the library:
#include <SPI.h>
//Sensor's memory register addresses:
const int PRESSURE = 0x1F; //3 most significant bits of pressure
const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure
const int TEMPERATURE = 0x21; //16 bit temperature reading
const byte READ = 0b11111100; // SCP1000's read command
const byte WRITE = 0b00000010; // SCP1000's write command
// pins used for the connection with the sensor
// the other you need are controlled by the SPI library):
const int dataReadyPin = 6;
const int chipSelectPin = 7;
void setup() {
Serial.begin(9600);
// start the SPI library:
SPI.begin();
// initalize the data ready and chip select pins:
pinMode(dataReadyPin, INPUT);
pinMode(chipSelectPin, OUTPUT);
//Configure SCP1000 for low noise configuration:
writeRegister(0x02, 0x2D);
writeRegister(0x01, 0x03);
writeRegister(0x03, 0x02);
// give the sensor time to set up:
delay(100);
}
void loop() {
//Select High Resolution Mode
writeRegister(0x03, 0x0A);
// don't do anything until the data ready pin is high:
if (digitalRead(dataReadyPin) == HIGH) {
//Read the temperature data
int tempData = readRegister(0x21, 2);
// convert the temperature to celsius and display it:
float realTemp = (float)tempData / 20.0;
Serial.print("Temp[C]=");
Serial.print(realTemp);
//Read the pressure data highest 3 bits:
byte pressure_data_high = readRegister(0x1F, 1);
pressure_data_high &= 0b00000111; //you only needs bits 2 to 0
//Read the pressure data lower 16 bits:
unsigned int pressure_data_low = readRegister(0x20, 2);
//combine the two parts into one 19-bit number:
long pressure = ((pressure_data_high << 16) | pressure_data_low)/4;
// display the temperature:
Serial.println("\tPressure [Pa]=" + String(pressure));
}
}
//Read from or write to register from the SCP1000:
unsigned int readRegister(byte thisRegister, int bytesToRead ) {
byte inByte = 0; // incoming byte from the SPI
unsigned int result = 0; // result to return
Serial.print(thisRegister, BIN);
Serial.print("\t");
// SCP1000 expects the register name in the upper 6 bits
// of the byte. So shift the bits left by two bits:
thisRegister = thisRegister << 2;
// now combine the address and the command into one byte
byte dataToSend = thisRegister & READ;
Serial.println(thisRegister, BIN);
// take the chip select low to select the device:
digitalWrite(chipSelectPin, LOW);
// send the device the register you want to read:
SPI.transfer(dataToSend);
// send a value of 0 to read the first byte returned:
result = SPI.transfer(0x00);
// decrement the number of bytes left to read:
bytesToRead--;
// if you still have another byte to read:
if (bytesToRead > 0) {
// shift the first byte left, then get the second byte:
result = result << 8;
inByte = SPI.transfer(0x00);
// combine the byte you just got with the previous one:
result = result | inByte;
// decrement the number of bytes left to read:
bytesToRead--;
}
// take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH);
// return the result:
return(result);
}
//Sends a write command to SCP1000
void writeRegister(byte thisRegister, byte thisValue) {
// SCP1000 expects the register address in the upper 6 bits
// of the byte. So shift the bits left by two bits:
thisRegister = thisRegister << 2;
// now combine the register address and the command into one byte:
byte dataToSend = thisRegister | WRITE;
// take the chip select low to select the device:
digitalWrite(chipSelectPin, LOW);
SPI.transfer(dataToSend); //Send register location
SPI.transfer(thisValue); //Send value to record into register
// take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH);
}

View File

@ -1,71 +0,0 @@
/*
Digital Pot Control
This example controls an Analog Devices AD5206 digital potentiometer.
The AD5206 has 6 potentiometer channels. Each channel's pins are labeled
A - connect this to voltage
W - this is the pot's wiper, which changes when you set it
B - connect this to ground.
The AD5206 is SPI-compatible,and to command it, you send two bytes,
one with the channel number (0 - 5) and one with the resistance value for the
channel (0 - 255).
The circuit:
* All A pins of AD5206 connected to +5V
* All B pins of AD5206 connected to ground
* An LED and a 220-ohm resisor in series connected from each W pin to ground
* CS - to digital pin 10 (SS pin)
* SDI - to digital pin 11 (MOSI pin)
* CLK - to digital pin 13 (SCK pin)
created 10 Aug 2010
by Tom Igoe
Thanks to Heather Dewey-Hagborg for the original tutorial, 2005
*/
// inslude the SPI library:
#include <SPI.h>
// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;
void setup() {
// set the slaveSelectPin as an output:
pinMode (slaveSelectPin, OUTPUT);
// initialize SPI:
SPI.begin();
}
void loop() {
// go through the six channels of the digital pot:
for (int channel = 0; channel < 6; channel++) {
// change the resistance on this channel from min to max:
for (int level = 0; level < 255; level++) {
digitalPotWrite(channel, level);
delay(10);
}
// wait a second at the top:
delay(100);
// change the resistance on this channel from max to min:
for (int level = 0; level < 255; level++) {
digitalPotWrite(channel, 255 - level);
delay(10);
}
}
}
int digitalPotWrite(int address, int value) {
// take the SS pin low to select the chip:
digitalWrite(slaveSelectPin,LOW);
// send in the address and value via SPI:
SPI.transfer(address);
SPI.transfer(value);
// take the SS pin high to de-select the chip:
digitalWrite(slaveSelectPin,HIGH);
}

View File

@ -1,155 +0,0 @@
/*
Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2
Copyright (c) 2009 Michael Margolis. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method.
The servos are pulsed in the background using the value most recently written using the write() method
Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.
The sequence used to sieze timers is defined in timers.h
The methods are:
Servo - Class for manipulating servo motors connected to Arduino pins.
attach(pin ) - Attaches a servo motor to an i/o pin.
attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds
default min is 544, max is 2400
write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds)
writeMicroseconds() - Sets the servo pulse width in microseconds
read() - Gets the last written servo pulse width as an angle between 0 and 180.
readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release)
attached() - Returns true if there is a servo attached.
detach() - Stops an attached servos from pulsing its i/o pin.
*/
#ifndef Servo_h
#define Servo_h
#include <inttypes.h>
/*
* Defines for 16 bit timers used with Servo library
*
* If _useTimerX is defined then TimerX is a 16 bit timer on the current board
* timer16_Sequence_t enumerates the sequence that the timers should be allocated
* _Nbr_16timers indicates how many 16 bit timers are available.
*/
// For SAM3X:
#define _useTimer1
#define _useTimer2
#define _useTimer3
#define _useTimer4
#define _useTimer5
/*
TC0, chan 0 => TC0_Handler
TC0, chan 1 => TC1_Handler
TC0, chan 2 => TC2_Handler
TC1, chan 0 => TC3_Handler
TC1, chan 1 => TC4_Handler
TC1, chan 2 => TC5_Handler
TC2, chan 0 => TC6_Handler
TC2, chan 1 => TC7_Handler
TC2, chan 2 => TC8_Handler
*/
#if defined (_useTimer1)
#define TC_FOR_TIMER1 TC1
#define CHANNEL_FOR_TIMER1 0
#define ID_TC_FOR_TIMER1 ID_TC3
#define IRQn_FOR_TIMER1 TC3_IRQn
#define HANDLER_FOR_TIMER1 TC3_Handler
#endif
#if defined (_useTimer2)
#define TC_FOR_TIMER2 TC1
#define CHANNEL_FOR_TIMER2 1
#define ID_TC_FOR_TIMER2 ID_TC4
#define IRQn_FOR_TIMER2 TC4_IRQn
#define HANDLER_FOR_TIMER2 TC4_Handler
#endif
#if defined (_useTimer3)
#define TC_FOR_TIMER3 TC1
#define CHANNEL_FOR_TIMER3 2
#define ID_TC_FOR_TIMER3 ID_TC5
#define IRQn_FOR_TIMER3 TC5_IRQn
#define HANDLER_FOR_TIMER3 TC5_Handler
#endif
#if defined (_useTimer4)
#define TC_FOR_TIMER4 TC0
#define CHANNEL_FOR_TIMER4 2
#define ID_TC_FOR_TIMER4 ID_TC2
#define IRQn_FOR_TIMER4 TC2_IRQn
#define HANDLER_FOR_TIMER4 TC2_Handler
#endif
#if defined (_useTimer5)
#define TC_FOR_TIMER5 TC0
#define CHANNEL_FOR_TIMER5 0
#define ID_TC_FOR_TIMER5 ID_TC0
#define IRQn_FOR_TIMER5 TC0_IRQn
#define HANDLER_FOR_TIMER5 TC0_Handler
#endif
typedef enum { _timer1, _timer2, _timer3, _timer4, _timer5, _Nbr_16timers } timer16_Sequence_t ;
#define Servo_VERSION 2 // software version of this library
#define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo (0.544ms)
#define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo (2,4ms)
#define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached (1.5ms)
#define REFRESH_INTERVAL 20000 // minimum time to refresh servos in microseconds (20ms)
#define SERVOS_PER_TIMER 12 // the maximum number of servos controlled by one timer
#define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER)
#define INVALID_SERVO 255 // flag indicating an invalid servo index
typedef struct {
uint8_t nbr :6 ; // a pin number from 0 to 63
uint8_t isActive :1 ; // true if this channel is enabled, pin not pulsed if false
} ServoPin_t ;
typedef struct {
ServoPin_t Pin;
volatile unsigned int ticks;
} servo_t;
class Servo
{
public:
Servo();
uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure
uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes.
void detach();
void write(int value); // if value is < 200 its treated as an angle, otherwise as pulse width in microseconds
void writeMicroseconds(int value); // Write pulse width in microseconds
int read(); // returns current pulse width as an angle between 0 and 180 degrees
int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release)
bool attached(); // return true if this servo is attached, otherwise false
private:
uint8_t servoIndex; // index into the channel data for this servo
int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH
int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH
};
#endif

View File

@ -1,22 +0,0 @@
// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
}

View File

@ -1,31 +0,0 @@
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

View File

@ -1,24 +0,0 @@
#######################################
# Syntax Coloring Map Servo
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
Servo KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
attach KEYWORD2
detach KEYWORD2
write KEYWORD2
read KEYWORD2
attached KEYWORD2
writeMicroseconds KEYWORD2
readMicroseconds KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -1,199 +0,0 @@
#include "wifi_drv.h"
#include "WiFi.h"
extern "C" {
#include "utility/wl_definitions.h"
#include "utility/wl_types.h"
#include "debug.h"
}
// XXX: don't make assumptions about the value of MAX_SOCK_NUM.
int16_t WiFiClass::_state[MAX_SOCK_NUM] = { 0, 0, 0, 0 };
uint16_t WiFiClass::_server_port[MAX_SOCK_NUM] = { 0, 0, 0, 0 };
WiFiClass::WiFiClass()
{
// Driver initialization
init();
}
void WiFiClass::init()
{
WiFiDrv::wifiDriverInit();
}
uint8_t WiFiClass::getSocket()
{
for (uint8_t i = 0; i < MAX_SOCK_NUM; ++i)
{
if (WiFiClass::_server_port[i] == 0)
{
return i;
}
}
return NO_SOCKET_AVAIL;
}
char* WiFiClass::firmwareVersion()
{
return WiFiDrv::getFwVersion();
}
int WiFiClass::begin(char* ssid)
{
uint8_t status = WL_IDLE_STATUS;
uint8_t attempts = WL_MAX_ATTEMPT_CONNECTION;
if (WiFiDrv::wifiSetNetwork(ssid, strlen(ssid)) != WL_FAILURE)
{
do
{
delay(WL_DELAY_START_CONNECTION);
status = WiFiDrv::getConnectionStatus();
}
while ((( status == WL_IDLE_STATUS)||(status == WL_SCAN_COMPLETED))&&(--attempts>0));
}else
{
status = WL_CONNECT_FAILED;
}
return status;
}
int WiFiClass::begin(char* ssid, uint8_t key_idx, const char *key)
{
uint8_t status = WL_IDLE_STATUS;
uint8_t attempts = WL_MAX_ATTEMPT_CONNECTION;
// set encryption key
if (WiFiDrv::wifiSetKey(ssid, strlen(ssid), key_idx, key, strlen(key)) != WL_FAILURE)
{
do
{
delay(WL_DELAY_START_CONNECTION);
status = WiFiDrv::getConnectionStatus();
}
while ((( status == WL_IDLE_STATUS)||(status == WL_SCAN_COMPLETED))&&(--attempts>0));
}else{
status = WL_CONNECT_FAILED;
}
return status;
}
int WiFiClass::begin(char* ssid, const char *passphrase)
{
uint8_t status = WL_IDLE_STATUS;
uint8_t attempts = WL_MAX_ATTEMPT_CONNECTION;
// set passphrase
if (WiFiDrv::wifiSetPassphrase(ssid, strlen(ssid), passphrase, strlen(passphrase))!= WL_FAILURE)
{
do
{
delay(WL_DELAY_START_CONNECTION);
status = WiFiDrv::getConnectionStatus();
}
while ((( status == WL_IDLE_STATUS)||(status == WL_SCAN_COMPLETED))&&(--attempts>0));
}else{
status = WL_CONNECT_FAILED;
}
return status;
}
int WiFiClass::disconnect()
{
return WiFiDrv::disconnect();
}
uint8_t* WiFiClass::macAddress(uint8_t* mac)
{
uint8_t* _mac = WiFiDrv::getMacAddress();
memcpy(mac, _mac, WL_MAC_ADDR_LENGTH);
return mac;
}
IPAddress WiFiClass::localIP()
{
IPAddress ret;
WiFiDrv::getIpAddress(ret);
return ret;
}
IPAddress WiFiClass::subnetMask()
{
IPAddress ret;
WiFiDrv::getSubnetMask(ret);
return ret;
}
IPAddress WiFiClass::gatewayIP()
{
IPAddress ret;
WiFiDrv::getGatewayIP(ret);
return ret;
}
char* WiFiClass::SSID()
{
return WiFiDrv::getCurrentSSID();
}
uint8_t* WiFiClass::BSSID(uint8_t* bssid)
{
uint8_t* _bssid = WiFiDrv::getCurrentBSSID();
memcpy(bssid, _bssid, WL_MAC_ADDR_LENGTH);
return bssid;
}
int32_t WiFiClass::RSSI()
{
return WiFiDrv::getCurrentRSSI();
}
uint8_t WiFiClass::encryptionType()
{
return WiFiDrv::getCurrentEncryptionType();
}
int8_t WiFiClass::scanNetworks()
{
uint8_t attempts = 10;
uint8_t numOfNetworks = 0;
if (WiFiDrv::startScanNetworks() == WL_FAILURE)
return WL_FAILURE;
do
{
delay(2000);
numOfNetworks = WiFiDrv::getScanNetworks();
}
while (( numOfNetworks == 0)&&(--attempts>0));
return numOfNetworks;
}
char* WiFiClass::SSID(uint8_t networkItem)
{
return WiFiDrv::getSSIDNetoworks(networkItem);
}
int32_t WiFiClass::RSSI(uint8_t networkItem)
{
return WiFiDrv::getRSSINetoworks(networkItem);
}
uint8_t WiFiClass::encryptionType(uint8_t networkItem)
{
return WiFiDrv::getEncTypeNetowrks(networkItem);
}
uint8_t WiFiClass::status()
{
return WiFiDrv::getConnectionStatus();
}
int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult)
{
return WiFiDrv::getHostByName(aHostname, aResult);
}
WiFiClass WiFi;

View File

@ -1,183 +0,0 @@
#ifndef WiFi_h
#define WiFi_h
#include <inttypes.h>
extern "C" {
#include "utility/wl_definitions.h"
#include "utility/wl_types.h"
}
#include "IPAddress.h"
#include "WiFiClient.h"
#include "WiFiServer.h"
class WiFiClass
{
private:
static void init();
public:
static int16_t _state[MAX_SOCK_NUM];
static uint16_t _server_port[MAX_SOCK_NUM];
WiFiClass();
/*
* Get the first socket available
*/
static uint8_t getSocket();
/*
* Get firmware version
*/
static char* firmwareVersion();
/* Start Wifi connection for OPEN networks
*
* param ssid: Pointer to the SSID string.
*/
int begin(char* ssid);
/* Start Wifi connection with WEP encryption.
* Configure a key into the device. The key type (WEP-40, WEP-104)
* is determined by the size of the key (5 bytes for WEP-40, 13 bytes for WEP-104).
*
* param ssid: Pointer to the SSID string.
* param key_idx: The key index to set. Valid values are 0-3.
* param key: Key input buffer.
*/
int begin(char* ssid, uint8_t key_idx, const char* key);
/* Start Wifi connection with passphrase
* the most secure supported mode will be automatically selected
*
* param ssid: Pointer to the SSID string.
* param passphrase: Passphrase. Valid characters in a passphrase
* must be between ASCII 32-126 (decimal).
*/
int begin(char* ssid, const char *passphrase);
/*
* Disconnect from the network
*
* return: one value of wl_status_t enum
*/
int disconnect(void);
/*
* Get the interface MAC address.
*
* return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
*/
uint8_t* macAddress(uint8_t* mac);
/*
* Get the interface IP address.
*
* return: Ip address value
*/
IPAddress localIP();
/*
* Get the interface subnet mask address.
*
* return: subnet mask address value
*/
IPAddress subnetMask();
/*
* Get the gateway ip address.
*
* return: gateway ip address value
*/
IPAddress gatewayIP();
/*
* Return the current SSID associated with the network
*
* return: ssid string
*/
char* SSID();
/*
* Return the current BSSID associated with the network.
* It is the MAC address of the Access Point
*
* return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
*/
uint8_t* BSSID(uint8_t* bssid);
/*
* Return the current RSSI /Received Signal Strength in dBm)
* associated with the network
*
* return: signed value
*/
int32_t RSSI();
/*
* Return the Encryption Type associated with the network
*
* return: one value of wl_enc_type enum
*/
uint8_t encryptionType();
/*
* Start scan WiFi networks available
*
* return: Number of discovered networks
*/
int8_t scanNetworks();
/*
* Return the SSID discovered during the network scan.
*
* param networkItem: specify from which network item want to get the information
*
* return: ssid string of the specified item on the networks scanned list
*/
char* SSID(uint8_t networkItem);
/*
* Return the encryption type of the networks discovered during the scanNetworks
*
* param networkItem: specify from which network item want to get the information
*
* return: encryption type (enum wl_enc_type) of the specified item on the networks scanned list
*/
uint8_t encryptionType(uint8_t networkItem);
/*
* Return the RSSI of the networks discovered during the scanNetworks
*
* param networkItem: specify from which network item want to get the information
*
* return: signed value of RSSI of the specified item on the networks scanned list
*/
int32_t RSSI(uint8_t networkItem);
/*
* Return Connection status.
*
* return: one of the value defined in wl_status_t
*/
uint8_t status();
/*
* Resolve the given hostname to an IP address.
* param aHostname: Name to be resolved
* param aResult: IPAddress structure to store the returned IP address
* result: 1 if aIPAddrString was successfully converted to an IP address,
* else error code
*/
int hostByName(const char* aHostname, IPAddress& aResult);
friend class WiFiClient;
friend class WiFiServer;
};
extern WiFiClass WiFi;
#endif

View File

@ -1,40 +0,0 @@
#ifndef wificlient_h
#define wificlient_h
#include "Arduino.h"
#include "Print.h"
#include "Client.h"
#include "IPAddress.h"
class WiFiClient : public Client {
public:
WiFiClient();
WiFiClient(uint8_t sock);
uint8_t status();
virtual int connect(IPAddress ip, uint16_t port);
virtual int connect(const char *host, uint16_t port);
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
virtual int available();
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek();
virtual void flush();
virtual void stop();
virtual uint8_t connected();
virtual operator bool();
friend class WiFiServer;
using Print::write;
private:
static uint16_t _srcport;
uint8_t _sock; //not used
uint16_t _socket;
uint8_t getFirstSocket();
};
#endif

View File

@ -1,88 +0,0 @@
#include <string.h>
#include "server_drv.h"
extern "C" {
#include "utility/debug.h"
}
#include "WiFi.h"
#include "WiFiClient.h"
#include "WiFiServer.h"
WiFiServer::WiFiServer(uint16_t port)
{
_port = port;
}
void WiFiServer::begin()
{
uint8_t _sock = WiFiClass::getSocket();
if (_sock != NO_SOCKET_AVAIL)
{
ServerDrv::startServer(_port, _sock);
WiFiClass::_server_port[_sock] = _port;
}
}
WiFiClient WiFiServer::available(byte* status)
{
static int cycle_server_down = 0;
const int TH_SERVER_DOWN = 50;
for (int sock = 0; sock < MAX_SOCK_NUM; sock++)
{
if (WiFiClass::_server_port[sock] == _port)
{
WiFiClient client(sock);
uint8_t _status = client.status();
uint8_t _ser_status = this->status();
if (status != NULL)
*status = _status;
//server not in listen state, restart it
if ((_ser_status == 0)&&(cycle_server_down++ > TH_SERVER_DOWN))
{
ServerDrv::startServer(_port, sock);
cycle_server_down = 0;
}
if (_status == ESTABLISHED)
{
return client; //TODO
}
}
}
return WiFiClient(255);
}
uint8_t WiFiServer::status() {
return ServerDrv::getServerState(0);
}
size_t WiFiServer::write(uint8_t b)
{
return write(&b, 1);
}
size_t WiFiServer::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
for (int sock = 0; sock < MAX_SOCK_NUM; sock++)
{
if (WiFiClass::_server_port[sock] != 0)
{
WiFiClient client(sock);
if (WiFiClass::_server_port[sock] == _port &&
client.status() == ESTABLISHED)
{
n+=client.write(buffer, size);
}
}
}
return n;
}

View File

@ -1,27 +0,0 @@
#ifndef wifiserver_h
#define wifiserver_h
extern "C" {
#include "utility/wl_definitions.h"
}
#include "Server.h"
class WiFiClient;
class WiFiServer : public Server {
private:
uint16_t _port;
void* pcb;
public:
WiFiServer(uint16_t);
WiFiClient available(uint8_t* status = NULL);
void begin();
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
uint8_t status();
using Print::write;
};
#endif

View File

@ -1,123 +0,0 @@
/*
This example connects to an unencrypted Wifi network.
Then it prints the MAC address of the Wifi shield,
the IP address obtained, and other network details.
Circuit:
* WiFi shield attached
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // the name of your network
int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to open SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network");
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print("NetMask: ");
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print("Gateway: ");
Serial.println(gateway);
}
void printCurrentNet() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5],HEX);
Serial.print(":");
Serial.print(bssid[4],HEX);
Serial.print(":");
Serial.print(bssid[3],HEX);
Serial.print(":");
Serial.print(bssid[2],HEX);
Serial.print(":");
Serial.print(bssid[1],HEX);
Serial.print(":");
Serial.println(bssid[0],HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption,HEX);
}

View File

@ -1,118 +0,0 @@
/*
This example connects to an unencrypted Wifi network.
Then it prints the MAC address of the Wifi shield,
the IP address obtained, and other network details.
Circuit:
* WiFi shield attached
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network");
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
}
void printCurrentNet() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5],HEX);
Serial.print(":");
Serial.print(bssid[4],HEX);
Serial.print(":");
Serial.print(bssid[3],HEX);
Serial.print(":");
Serial.print(bssid[2],HEX);
Serial.print(":");
Serial.print(bssid[1],HEX);
Serial.print(":");
Serial.println(bssid[0],HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption,HEX);
Serial.println();
}

View File

@ -1,118 +0,0 @@
/*
This example prints the Wifi shield's MAC address, and
scans for available Wifi networks using the Wifi shield.
Every ten seconds, it scans again. It doesn't actually
connect to any network, so no encryption scheme is specified.
Circuit:
* WiFi shield attached
created 13 July 2010
by dlf (Metodo2 srl)
modified 21 Junn 2012
by Tom Igoe and Jaymes Dec
*/
#include <SPI.h>
#include <WiFi.h>
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// Print WiFi MAC address:
printMacAddress();
// scan for existing networks:
Serial.println("Scanning available networks...");
listNetworks();
}
void loop() {
delay(10000);
// scan for existing networks:
Serial.println("Scanning available networks...");
listNetworks();
}
void printMacAddress() {
// the MAC address of your Wifi shield
byte mac[6];
// print your MAC address:
WiFi.macAddress(mac);
Serial.print("MAC: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
}
void listNetworks() {
// scan for nearby networks:
Serial.println("** Scan Networks **");
int numSsid = WiFi.scanNetworks();
if (numSsid == -1)
{
Serial.println("Couldn't get a wifi connection");
while(true);
}
// print the list of networks seen:
Serial.print("number of available networks:");
Serial.println(numSsid);
// print the network number and name for each network found:
for (int thisNet = 0; thisNet<numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(") ");
Serial.print(WiFi.SSID(thisNet));
Serial.print("\tSignal: ");
Serial.print(WiFi.RSSI(thisNet));
Serial.print(" dBm");
Serial.print("\tEncryption: ");
printEncryptionType(WiFi.encryptionType(thisNet));
}
}
void printEncryptionType(int thisType) {
// read the encryption type and print out the name:
switch (thisType) {
case ENC_TYPE_WEP:
Serial.println("WEP");
break;
case ENC_TYPE_TKIP:
Serial.println("WPA");
break;
case ENC_TYPE_CCMP:
Serial.println("WPA2");
break;
case ENC_TYPE_NONE:
Serial.println("None");
break;
case ENC_TYPE_AUTO:
Serial.println("Auto");
break;
}
}

View File

@ -1,111 +0,0 @@
/*
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.
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
Circuit:
* WiFi shield attached
created 18 Dec 2009
by David A. Mellis
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(23);
boolean alreadyConnected = false; // whether or not the client was connected previously
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// start the server:
server.begin();
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// wait for a new client:
WiFiClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clead out the input buffer:
client.flush();
Serial.println("We have a new client");
client.println("Hello, client!");
alreadyConnected = true;
}
if (client.available() > 0) {
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,191 +0,0 @@
/*
Wifi Pachube sensor client
This sketch connects an analog sensor to Pachube (http://www.pachube.com)
using an Arduino Wifi shield.
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
This example has been updated to use version 2.0 of the Pachube API.
To make it work, create a feed with a datastream, and give it the ID
sensor1. Or change the code below to match your feed.
Circuit:
* Analog sensor attached to analog in 0
* Wifi shield attached to pins 10, 11, 12, 13
created 13 Mar 2012
modified 31 May 2012
by Tom Igoe
modified 8 Sept 2012
by Scott Fitzgerald
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here
#define FEEDID 00000 // replace your feed ID
#define USERAGENT "My Arduino Project" // user agent is the project name
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int status = WL_IDLE_STATUS;
// initialize the library instance:
WiFiClient client;
// 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(216,52,233,121); // numeric IP for api.pachube.com
//char server[] = "api.pachube.com"; // name address for pachube API
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
while (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
sendData(sensorReading);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void sendData(int thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.pachube.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 8 bytes for "sensor1," + number of digits of the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("sensor1,");
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,177 +0,0 @@
/*
Wifi Pachube sensor client with Strings
This sketch connects an analog sensor to Pachube (http://www.pachube.com)
using a Arduino Wifi shield.
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
This example has been updated to use version 2.0 of the pachube.com API.
To make it work, create a feed with a datastream, and give it the ID
sensor1. Or change the code below to match your feed.
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* Analog sensor attached to analog in 0
* Wifi shield attached to pins 10, 11, 12, 13
created 16 Mar 2012
modified 31 May 2012
by Tom Igoe
modified 8 Sept 2012
by Scott Fitzgerald
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here
#define FEEDID 00000 // replace your feed ID
#define USERAGENT "My Arduino Project" // user agent is the project name
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int status = WL_IDLE_STATUS;
// initialize the library instance:
WiFiClient client;
// 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(216,52,233,121); // numeric IP for api.pachube.com
char server[] = "api.pachube.com"; // name address for pachube API
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// read the analog sensor:
int sensorReading = analogRead(A0);
// convert the data to a String to send it:
String dataString = "sensor1,";
dataString += sensorReading;
// you can append multiple readings to this String if your
// pachube feed is set up to handle multiple values:
int otherSensorReading = analogRead(A1);
dataString += "\nsensor2,";
dataString += otherSensorReading;
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
while (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
sendData(dataString);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.pachube.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(thisData.length());
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.println(thisData);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,164 +0,0 @@
/*
Wifi Twitter Client with Strings
This sketch connects to Twitter using using an Arduino WiFi shield.
It parses the XML returned, and looks for <text>this is a tweet</text>
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
This example uses the String library, which is part of the Arduino core from
version 0019.
Circuit:
* WiFi shield attached to pins 10, 11, 12, 13
created 23 apr 2012
modified 31 May 2012
by Tom Igoe
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS; // status of the wifi connection
// initialize the library instance:
WiFiClient client;
const unsigned long requestInterval = 30*1000; // delay between requests; 30 seconds
// 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(199,59,149,200); // numeric IP for api.twitter.com
char server[] = "api.twitter.com"; // name address for twitter API
boolean requested; // whether you've made a request since connecting
unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds
String currentLine = ""; // string to hold the text from server
String tweet = ""; // string to hold the tweet
boolean readingTweet = false; // if you're currently reading the tweet
void setup() {
// reserve space for the strings:
currentLine.reserve(256);
tweet.reserve(150);
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
connectToServer();
}
void loop()
{
if (client.connected()) {
if (client.available()) {
// read incoming bytes:
char inChar = client.read();
// add incoming byte to end of line:
currentLine += inChar;
// if you get a newline, clear the line:
if (inChar == '\n') {
currentLine = "";
}
// if the current line ends with <text>, it will
// be followed by the tweet:
if ( currentLine.endsWith("<text>")) {
// tweet is beginning. Clear the tweet string:
readingTweet = true;
tweet = "";
// break out of the loop so this character isn't added to the tweet:
return;
}
// if you're currently reading the bytes of a tweet,
// add them to the tweet String:
if (readingTweet) {
if (inChar != '<') {
tweet += inChar;
}
else {
// if you got a "<" character,
// you've reached the end of the tweet:
readingTweet = false;
Serial.println(tweet);
// close the connection to the server:
client.stop();
}
}
}
}
else if (millis() - lastAttemptTime > requestInterval) {
// if you're not connected, and two minutes have passed since
// your last connection, then attempt to connect again:
connectToServer();
}
}
void connectToServer() {
// attempt to connect, and wait a millisecond:
Serial.println("connecting to server...");
if (client.connect(server, 80)) {
Serial.println("making HTTP request...");
// make HTTP GET request to twitter:
client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino HTTP/1.1");
client.println("Host:api.twitter.com");
client.println("Connection:close");
client.println();
}
// note the time of this connect attempt:
lastAttemptTime = millis();
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,120 +0,0 @@
/*
Web client
This sketch connects to a website (http://www.google.com)
using a WiFi shield.
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
Circuit:
* WiFi shield attached
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// 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(173,194,73,105); // numeric IP for Google (no DNS)
//char server[] = "www.google.com"; // name address for Google (using DNS)
// 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):
WiFiClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected to server");
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host:www.google.com");
client.println("Connection: close");
client.println();
}
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting from server.");
client.stop();
// do nothing forevermore:
while(true);
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,138 +0,0 @@
/*
Repeating Wifi Web client
This sketch connects to a a web server and makes a request
using an Arduino Wifi shield.
Circuit:
* Wifi shield attached to pins 10, 11, 12, 13
created 23 April 2012
modifide 31 May 2012
by Tom Igoe
http://arduino.cc/en/Tutorial/WifiWebClientRepeating
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// Initialize the Wifi client library
WiFiClient client;
// server address:
char server[] = "www.arduino.cc";
//IPAddress server(64,131,82,241);
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
httpRequest();
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
// this method makes a HTTP connection to the server:
void httpRequest() {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.println("GET /latest.txt HTTP/1.1");
client.println("Host: www.arduino.cc");
client.println("User-Agent: arduino-ethernet");
client.println("Connection: close");
client.println();
// note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println("disconnecting.");
client.stop();
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,132 +0,0 @@
/*
Web Server
A simple web server that shows the value of the analog input pins.
using a WiFi shield.
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
Circuit:
* WiFi shield attached
* Analog inputs attached to pins A0 through A5 (optional)
created 13 July 2010
by dlf (Metodo2 srl)
modified 31 May 2012
by Tom Igoe
*/
#inlcude <SPI.h>
#include <WiFi.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin();
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() {
// listen for incoming clients
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.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
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// add a meta refresh tag, so the browser pulls again every 5 seconds:
client.println("<meta http-equiv=\"refresh\" content=\"5\">");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
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);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

View File

@ -1,43 +0,0 @@
#######################################
# Syntax Coloring Map For WiFi
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
WiFi KEYWORD1
Client KEYWORD1
Server KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
status KEYWORD2
connect KEYWORD2
write KEYWORD2
available KEYWORD2
read KEYWORD2
flush KEYWORD2
stop KEYWORD2
connected KEYWORD2
begin KEYWORD2
disconnect KEYWORD2
macAddress KEYWORD2
localIP KEYWORD2
subnetMask KEYWORD2
gatewayIP KEYWORD2
SSID KEYWORD2
BSSID KEYWORD2
RSSI KEYWORD2
encryptionType KEYWORD2
getResult KEYWORD2
getSocket KEYWORD2
WiFiClient KEYWORD2
WiFiServer KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -1,77 +0,0 @@
//*********************************************/
//
// File: debug.h
//
// Author: dlf (Metodo2 srl)
//
//********************************************/
#ifndef Debug_H
#define Debug_H
#include <stdio.h>
#include <string.h>
#define PRINT_FILE_LINE() do { \
Serial.print("[");Serial.print(__FILE__); \
Serial.print("::");Serial.print(__LINE__);Serial.print("]");\
}while (0);
#ifdef _DEBUG_
#define INFO(format, args...) do { \
char buf[250]; \
sprintf(buf, format, args); \
Serial.println(buf); \
} while(0);
#define INFO1(x) do { PRINT_FILE_LINE() Serial.print("-I-");\
Serial.println(x); \
}while (0);
#define INFO2(x,y) do { PRINT_FILE_LINE() Serial.print("-I-");\
Serial.print(x,16);Serial.print(",");Serial.println(y,16); \
}while (0);
#else
#define INFO1(x) do {} while(0);
#define INFO2(x,y) do {} while(0);
#define INFO(format, args...) do {} while(0);
#endif
#if 0
#define WARN(args) do { PRINT_FILE_LINE() \
Serial.print("-W-"); Serial.println(args); \
}while (0);
#else
#define WARN(args) do {} while (0);
#endif
#if _DEBUG_SPI_
#define DBG_PIN2 5
#define DBG_PIN 4
#define START() digitalWrite(DBG_PIN2, HIGH);
#define END() digitalWrite(DBG_PIN2, LOW);
#define SET_TRIGGER() digitalWrite(DBG_PIN, HIGH);
#define RST_TRIGGER() digitalWrite(DBG_PIN, LOW);
#define INIT_TRIGGER() pinMode(DBG_PIN, OUTPUT); \
pinMode(DBG_PIN2, OUTPUT); \
RST_TRIGGER()
#define TOGGLE_TRIGGER() SET_TRIGGER() \
delayMicroseconds(2); \
RST_TRIGGER()
#else
#define START()
#define END()
#define SET_TRIGGER()
#define RST_TRIGGER()
#define INIT_TRIGGER()
#define TOGGLE_TRIGGER()
#endif
#endif

View File

@ -1,260 +0,0 @@
//#define _DEBUG_
#include "server_drv.h"
#include "Arduino.h"
#include "spi_drv.h"
extern "C" {
#include "wl_types.h"
#include "debug.h"
}
// Start server TCP on port specified
void ServerDrv::startServer(uint16_t port, uint8_t sock)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(START_SERVER_TCP_CMD, PARAM_NUMS_2);
SpiDrv::sendParam(port);
SpiDrv::sendParam(&sock, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(START_SERVER_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
}
// Start server TCP on port specified
void ServerDrv::startClient(uint32_t ipAddress, uint16_t port, uint8_t sock)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(START_CLIENT_TCP_CMD, PARAM_NUMS_3);
SpiDrv::sendParam((uint8_t*)&ipAddress, sizeof(ipAddress));
SpiDrv::sendParam(port);
SpiDrv::sendParam(&sock, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(START_CLIENT_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
}
// Start server TCP on port specified
void ServerDrv::stopClient(uint8_t sock)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(STOP_CLIENT_TCP_CMD, PARAM_NUMS_1);
SpiDrv::sendParam(&sock, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(STOP_CLIENT_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
}
uint8_t ServerDrv::getServerState(uint8_t sock)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_STATE_TCP_CMD, PARAM_NUMS_1);
SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(GET_STATE_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
return _data;
}
uint8_t ServerDrv::getClientState(uint8_t sock)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_CLIENT_STATE_TCP_CMD, PARAM_NUMS_1);
SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(GET_CLIENT_STATE_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
return _data;
}
uint8_t ServerDrv::availData(uint8_t sock)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(AVAIL_DATA_TCP_CMD, PARAM_NUMS_1);
SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(AVAIL_DATA_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
if (_dataLen!=0)
{
return (_data == 1);
}
return false;
}
bool ServerDrv::getData(uint8_t sock, uint8_t *data, uint8_t peek)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_DATA_TCP_CMD, PARAM_NUMS_2);
SpiDrv::sendParam(&sock, sizeof(sock));
SpiDrv::sendParam(peek, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseData8(GET_DATA_TCP_CMD, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
if (_dataLen!=0)
{
*data = _data;
return true;
}
return false;
}
bool ServerDrv::getDataBuf(uint8_t sock, uint8_t *_data, uint16_t *_dataLen)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_DATABUF_TCP_CMD, PARAM_NUMS_1);
SpiDrv::sendBuffer(&sock, sizeof(sock), LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
if (!SpiDrv::waitResponseData16(GET_DATABUF_TCP_CMD, _data, _dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
if (*_dataLen!=0)
{
return true;
}
return false;
}
bool ServerDrv::sendData(uint8_t sock, const uint8_t *data, uint16_t len)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(SEND_DATA_TCP_CMD, PARAM_NUMS_2);
SpiDrv::sendBuffer(&sock, sizeof(sock));
SpiDrv::sendBuffer((uint8_t *)data, len, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseData8(SEND_DATA_TCP_CMD, &_data, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
if (_dataLen!=0)
{
return (_data == 1);
}
return false;
}
uint8_t ServerDrv::checkDataSent(uint8_t sock)
{
const uint16_t TIMEOUT_DATA_SENT = 25;
uint16_t timeout = 0;
uint8_t _data = 0;
uint8_t _dataLen = 0;
do {
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(DATA_SENT_TCP_CMD, PARAM_NUMS_1);
SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
if (!SpiDrv::waitResponseCmd(DATA_SENT_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse isDataSent");
}
SpiDrv::spiSlaveDeselect();
if (_data) timeout = 0;
else{
++timeout;
delay(100);
}
}while((_data==0)&&(timeout<TIMEOUT_DATA_SENT));
return (timeout==TIMEOUT_DATA_SENT)?0:1;
}
ServerDrv serverDrv;

View File

@ -1,34 +0,0 @@
#ifndef Server_Drv_h
#define Server_Drv_h
#include <inttypes.h>
#include "wifi_spi.h"
class ServerDrv
{
public:
// Start server TCP on port specified
static void startServer(uint16_t port, uint8_t sock);
static void startClient(uint32_t ipAddress, uint16_t port, uint8_t sock);
static void stopClient(uint8_t sock);
static uint8_t getServerState(uint8_t sock);
static uint8_t getClientState(uint8_t sock);
static bool getData(uint8_t sock, uint8_t *data, uint8_t peek = 0);
static bool getDataBuf(uint8_t sock, uint8_t *data, uint16_t *len);
static bool sendData(uint8_t sock, const uint8_t *data, uint16_t len);
static uint8_t availData(uint8_t sock);
static uint8_t checkDataSent(uint8_t sock);
};
extern ServerDrv serverDrv;
#endif

View File

@ -1,83 +0,0 @@
#ifndef SPI_Drv_h
#define SPI_Drv_h
#include <inttypes.h>
#include "wifi_spi.h"
#define SPI_START_CMD_DELAY 12
#define NO_LAST_PARAM 0
#define LAST_PARAM 1
#define DUMMY_DATA 0xFF
#define WAIT_FOR_SLAVE_SELECT() \
SpiDrv::waitForSlaveReady(); \
SpiDrv::spiSlaveSelect();
class SpiDrv
{
private:
//static bool waitSlaveReady();
static void waitForSlaveSign();
static void getParam(uint8_t* param);
public:
static void begin();
static void end();
static void spiDriverInit();
static void spiSlaveSelect();
static void spiSlaveDeselect();
static char spiTransfer(volatile char data);
static void waitForSlaveReady();
//static int waitSpiChar(char waitChar, char* readChar);
static int waitSpiChar(unsigned char waitChar);
static int readAndCheckChar(char checkChar, char* readChar);
static char readChar();
static int waitResponseParams(uint8_t cmd, uint8_t numParam, tParam* params);
static int waitResponseCmd(uint8_t cmd, uint8_t numParam, uint8_t* param, uint8_t* param_len);
static int waitResponseData8(uint8_t cmd, uint8_t* param, uint8_t* param_len);
static int waitResponseData16(uint8_t cmd, uint8_t* param, uint16_t* param_len);
/*
static int waitResponse(uint8_t cmd, tParam* params, uint8_t* numParamRead, uint8_t maxNumParams);
static int waitResponse(uint8_t cmd, uint8_t numParam, uint8_t* param, uint16_t* param_len);
*/
static int waitResponse(uint8_t cmd, uint8_t* numParamRead, uint8_t** params, uint8_t maxNumParams);
static void sendParam(uint8_t* param, uint8_t param_len, uint8_t lastParam = NO_LAST_PARAM);
static void sendParamLen8(uint8_t param_len);
static void sendParamLen16(uint16_t param_len);
static uint8_t readParamLen8(uint8_t* param_len = NULL);
static uint16_t readParamLen16(uint16_t* param_len = NULL);
static void sendBuffer(uint8_t* param, uint16_t param_len, uint8_t lastParam = NO_LAST_PARAM);
static void sendParam(uint16_t param, uint8_t lastParam = NO_LAST_PARAM);
static void sendCmd(uint8_t cmd, uint8_t numParam);
};
extern SpiDrv spiDrv;
#endif

View File

@ -1,491 +0,0 @@
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "Arduino.h"
#include "spi_drv.h"
#include "wifi_drv.h"
#define _DEBUG_
extern "C" {
#include "wifi_spi.h"
#include "wl_types.h"
#include "debug.h"
}
// Array of data to cache the information related to the networks discovered
char WiFiDrv::_networkSsid[][WL_SSID_MAX_LENGTH] = {{"1"},{"2"},{"3"},{"4"},{"5"}};
int32_t WiFiDrv::_networkRssi[WL_NETWORKS_LIST_MAXNUM] = { 0 };
uint8_t WiFiDrv::_networkEncr[WL_NETWORKS_LIST_MAXNUM] = { 0 };
// Cached values of retrieved data
char WiFiDrv::_ssid[] = {0};
uint8_t WiFiDrv::_bssid[] = {0};
uint8_t WiFiDrv::_mac[] = {0};
uint8_t WiFiDrv::_localIp[] = {0};
uint8_t WiFiDrv::_subnetMask[] = {0};
uint8_t WiFiDrv::_gatewayIp[] = {0};
// Firmware version
char WiFiDrv::fwVersion[] = {0};
// Private Methods
void WiFiDrv::getNetworkData(uint8_t *ip, uint8_t *mask, uint8_t *gwip)
{
tParam params[PARAM_NUMS_3] = { {0, (char*)ip}, {0, (char*)mask}, {0, (char*)gwip}};
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_IPADDR_CMD, PARAM_NUMS_1);
uint8_t _dummy = DUMMY_DATA;
SpiDrv::sendParam(&_dummy, sizeof(_dummy), LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
SpiDrv::waitResponseParams(GET_IPADDR_CMD, PARAM_NUMS_3, params);
SpiDrv::spiSlaveDeselect();
}
// Public Methods
void WiFiDrv::wifiDriverInit()
{
SpiDrv::begin();
}
int8_t WiFiDrv::wifiSetNetwork(char* ssid, uint8_t ssid_len)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(SET_NET_CMD, PARAM_NUMS_1);
SpiDrv::sendParam((uint8_t*)ssid, ssid_len, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(SET_NET_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
_data = WL_FAILURE;
}
SpiDrv::spiSlaveDeselect();
return(_data == WIFI_SPI_ACK) ? WL_SUCCESS : WL_FAILURE;
}
int8_t WiFiDrv::wifiSetPassphrase(char* ssid, uint8_t ssid_len, const char *passphrase, const uint8_t len)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(SET_PASSPHRASE_CMD, PARAM_NUMS_2);
SpiDrv::sendParam((uint8_t*)ssid, ssid_len, NO_LAST_PARAM);
SpiDrv::sendParam((uint8_t*)passphrase, len, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(SET_PASSPHRASE_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
_data = WL_FAILURE;
}
SpiDrv::spiSlaveDeselect();
return _data;
}
int8_t WiFiDrv::wifiSetKey(char* ssid, uint8_t ssid_len, uint8_t key_idx, const void *key, const uint8_t len)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(SET_KEY_CMD, PARAM_NUMS_3);
SpiDrv::sendParam((uint8_t*)ssid, ssid_len, NO_LAST_PARAM);
SpiDrv::sendParam(&key_idx, KEY_IDX_LEN, NO_LAST_PARAM);
SpiDrv::sendParam((uint8_t*)key, len, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(SET_KEY_CMD, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
_data = WL_FAILURE;
}
SpiDrv::spiSlaveDeselect();
return _data;
}
int8_t WiFiDrv::disconnect()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(DISCONNECT_CMD, PARAM_NUMS_1);
uint8_t _dummy = DUMMY_DATA;
SpiDrv::sendParam(&_dummy, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
int8_t result = SpiDrv::waitResponseCmd(DISCONNECT_CMD, PARAM_NUMS_1, &_data, &_dataLen);
SpiDrv::spiSlaveDeselect();
return result;
}
uint8_t WiFiDrv::getConnectionStatus()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_CONN_STATUS_CMD, PARAM_NUMS_0);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = -1;
uint8_t _dataLen = 0;
SpiDrv::waitResponseCmd(GET_CONN_STATUS_CMD, PARAM_NUMS_1, &_data, &_dataLen);
SpiDrv::spiSlaveDeselect();
return _data;
}
uint8_t* WiFiDrv::getMacAddress()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_MACADDR_CMD, PARAM_NUMS_1);
uint8_t _dummy = DUMMY_DATA;
SpiDrv::sendParam(&_dummy, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _dataLen = 0;
SpiDrv::waitResponseCmd(GET_MACADDR_CMD, PARAM_NUMS_1, _mac, &_dataLen);
SpiDrv::spiSlaveDeselect();
return _mac;
}
void WiFiDrv::getIpAddress(IPAddress& ip)
{
getNetworkData(_localIp, _subnetMask, _gatewayIp);
ip = _localIp;
}
void WiFiDrv::getSubnetMask(IPAddress& mask)
{
getNetworkData(_localIp, _subnetMask, _gatewayIp);
mask = _subnetMask;
}
void WiFiDrv::getGatewayIP(IPAddress& ip)
{
getNetworkData(_localIp, _subnetMask, _gatewayIp);
ip = _gatewayIp;
}
char* WiFiDrv::getCurrentSSID()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_CURR_SSID_CMD, PARAM_NUMS_1);
uint8_t _dummy = DUMMY_DATA;
SpiDrv::sendParam(&_dummy, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _dataLen = 0;
SpiDrv::waitResponseCmd(GET_CURR_SSID_CMD, PARAM_NUMS_1, (uint8_t*)_ssid, &_dataLen);
SpiDrv::spiSlaveDeselect();
return _ssid;
}
uint8_t* WiFiDrv::getCurrentBSSID()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_CURR_BSSID_CMD, PARAM_NUMS_1);
uint8_t _dummy = DUMMY_DATA;
SpiDrv::sendParam(&_dummy, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _dataLen = 0;
SpiDrv::waitResponseCmd(GET_CURR_BSSID_CMD, PARAM_NUMS_1, _bssid, &_dataLen);
SpiDrv::spiSlaveDeselect();
return _bssid;
}
int32_t WiFiDrv::getCurrentRSSI()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_CURR_RSSI_CMD, PARAM_NUMS_1);
uint8_t _dummy = DUMMY_DATA;
SpiDrv::sendParam(&_dummy, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _dataLen = 0;
int32_t rssi = 0;
SpiDrv::waitResponseCmd(GET_CURR_RSSI_CMD, PARAM_NUMS_1, (uint8_t*)&rssi, &_dataLen);
SpiDrv::spiSlaveDeselect();
return rssi;
}
uint8_t WiFiDrv::getCurrentEncryptionType()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_CURR_ENCT_CMD, PARAM_NUMS_1);
uint8_t _dummy = DUMMY_DATA;
SpiDrv::sendParam(&_dummy, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t dataLen = 0;
uint8_t encType = 0;
SpiDrv::waitResponseCmd(GET_CURR_ENCT_CMD, PARAM_NUMS_1, (uint8_t*)&encType, &dataLen);
SpiDrv::spiSlaveDeselect();
return encType;
}
int8_t WiFiDrv::startScanNetworks()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(START_SCAN_NETWORKS, PARAM_NUMS_0);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(START_SCAN_NETWORKS, PARAM_NUMS_1, &_data, &_dataLen))
{
WARN("error waitResponse");
_data = WL_FAILURE;
}
SpiDrv::spiSlaveDeselect();
return (_data == WL_FAILURE)? _data : WL_SUCCESS;
}
uint8_t WiFiDrv::getScanNetworks()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(SCAN_NETWORKS, PARAM_NUMS_0);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t ssidListNum = 0;
SpiDrv::waitResponse(SCAN_NETWORKS, &ssidListNum, (uint8_t**)_networkSsid, WL_NETWORKS_LIST_MAXNUM);
SpiDrv::spiSlaveDeselect();
return ssidListNum;
}
char* WiFiDrv::getSSIDNetoworks(uint8_t networkItem)
{
if (networkItem >= WL_NETWORKS_LIST_MAXNUM)
return NULL;
return _networkSsid[networkItem];
}
uint8_t WiFiDrv::getEncTypeNetowrks(uint8_t networkItem)
{
if (networkItem >= WL_NETWORKS_LIST_MAXNUM)
return NULL;
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_IDX_ENCT_CMD, PARAM_NUMS_1);
SpiDrv::sendParam(&networkItem, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t dataLen = 0;
uint8_t encType = 0;
SpiDrv::waitResponseCmd(GET_IDX_ENCT_CMD, PARAM_NUMS_1, (uint8_t*)&encType, &dataLen);
SpiDrv::spiSlaveDeselect();
return encType;
}
int32_t WiFiDrv::getRSSINetoworks(uint8_t networkItem)
{
if (networkItem >= WL_NETWORKS_LIST_MAXNUM)
return NULL;
int32_t networkRssi = 0;
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_IDX_RSSI_CMD, PARAM_NUMS_1);
SpiDrv::sendParam(&networkItem, 1, LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t dataLen = 0;
SpiDrv::waitResponseCmd(GET_IDX_RSSI_CMD, PARAM_NUMS_1, (uint8_t*)&networkRssi, &dataLen);
SpiDrv::spiSlaveDeselect();
return networkRssi;
}
uint8_t WiFiDrv::reqHostByName(const char* aHostname)
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(REQ_HOST_BY_NAME_CMD, PARAM_NUMS_1);
SpiDrv::sendParam((uint8_t*)aHostname, strlen(aHostname), LAST_PARAM);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _data = 0;
uint8_t _dataLen = 0;
uint8_t result = SpiDrv::waitResponseCmd(REQ_HOST_BY_NAME_CMD, PARAM_NUMS_1, &_data, &_dataLen);
SpiDrv::spiSlaveDeselect();
return result;
}
int WiFiDrv::getHostByName(IPAddress& aResult)
{
uint8_t _ipAddr[WL_IPV4_LENGTH];
IPAddress dummy(0xFF,0xFF,0xFF,0xFF);
int result = 0;
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_HOST_BY_NAME_CMD, PARAM_NUMS_0);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(GET_HOST_BY_NAME_CMD, PARAM_NUMS_1, _ipAddr, &_dataLen))
{
WARN("error waitResponse");
}else{
aResult = _ipAddr;
result = (aResult != dummy);
}
SpiDrv::spiSlaveDeselect();
return result;
}
int WiFiDrv::getHostByName(const char* aHostname, IPAddress& aResult)
{
uint8_t retry = 10;
if (reqHostByName(aHostname))
{
while(!getHostByName(aResult) && --retry > 0)
{
delay(1000);
}
}else{
return 0;
}
return (retry>0);
}
char* WiFiDrv::getFwVersion()
{
WAIT_FOR_SLAVE_SELECT();
// Send Command
SpiDrv::sendCmd(GET_FW_VERSION_CMD, PARAM_NUMS_0);
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
// Wait for reply
uint8_t _dataLen = 0;
if (!SpiDrv::waitResponseCmd(GET_FW_VERSION_CMD, PARAM_NUMS_1, (uint8_t*)fwVersion, &_dataLen))
{
WARN("error waitResponse");
}
SpiDrv::spiSlaveDeselect();
return fwVersion;
}
WiFiDrv wiFiDrv;

View File

@ -1,219 +0,0 @@
#ifndef WiFi_Drv_h
#define WiFi_Drv_h
#include <inttypes.h>
#include "wifi_spi.h"
#include "IPAddress.h"
// Key index length
#define KEY_IDX_LEN 1
// 5 secs of delay to have the connection established
#define WL_DELAY_START_CONNECTION 5000
// firmware version string length
#define WL_FW_VER_LENGTH 6
class WiFiDrv
{
private:
// settings of requested network
static char _networkSsid[WL_NETWORKS_LIST_MAXNUM][WL_SSID_MAX_LENGTH];
static int32_t _networkRssi[WL_NETWORKS_LIST_MAXNUM];
static uint8_t _networkEncr[WL_NETWORKS_LIST_MAXNUM];
// firmware version string in the format a.b.c
static char fwVersion[WL_FW_VER_LENGTH];
// settings of current selected network
static char _ssid[WL_SSID_MAX_LENGTH];
static uint8_t _bssid[WL_MAC_ADDR_LENGTH];
static uint8_t _mac[WL_MAC_ADDR_LENGTH];
static uint8_t _localIp[WL_IPV4_LENGTH];
static uint8_t _subnetMask[WL_IPV4_LENGTH];
static uint8_t _gatewayIp[WL_IPV4_LENGTH];
/*
* Get network Data information
*/
static void getNetworkData(uint8_t *ip, uint8_t *mask, uint8_t *gwip);
static uint8_t reqHostByName(const char* aHostname);
static int getHostByName(IPAddress& aResult);
public:
/*
* Driver initialization
*/
static void wifiDriverInit();
/*
* Set the desired network which the connection manager should try to
* connect to.
*
* The ssid of the desired network should be specified.
*
* param ssid: The ssid of the desired network.
* param ssid_len: Lenght of ssid string.
* return: WL_SUCCESS or WL_FAILURE
*/
static int8_t wifiSetNetwork(char* ssid, uint8_t ssid_len);
/* Start Wifi connection with passphrase
* the most secure supported mode will be automatically selected
*
* param ssid: Pointer to the SSID string.
* param ssid_len: Lenght of ssid string.
* param passphrase: Passphrase. Valid characters in a passphrase
* must be between ASCII 32-126 (decimal).
* param len: Lenght of passphrase string.
* return: WL_SUCCESS or WL_FAILURE
*/
static int8_t wifiSetPassphrase(char* ssid, uint8_t ssid_len, const char *passphrase, const uint8_t len);
/* Start Wifi connection with WEP encryption.
* Configure a key into the device. The key type (WEP-40, WEP-104)
* is determined by the size of the key (5 bytes for WEP-40, 13 bytes for WEP-104).
*
* param ssid: Pointer to the SSID string.
* param ssid_len: Lenght of ssid string.
* param key_idx: The key index to set. Valid values are 0-3.
* param key: Key input buffer.
* param len: Lenght of key string.
* return: WL_SUCCESS or WL_FAILURE
*/
static int8_t wifiSetKey(char* ssid, uint8_t ssid_len, uint8_t key_idx, const void *key, const uint8_t len);
/*
* Disconnect from the network
*
* return: WL_SUCCESS or WL_FAILURE
*/
static int8_t disconnect();
/*
* Disconnect from the network
*
* return: one value of wl_status_t enum
*/
static uint8_t getConnectionStatus();
/*
* Get the interface MAC address.
*
* return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
*/
static uint8_t* getMacAddress();
/*
* Get the interface IP address.
*
* return: copy the ip address value in IPAddress object
*/
static void getIpAddress(IPAddress& ip);
/*
* Get the interface subnet mask address.
*
* return: copy the subnet mask address value in IPAddress object
*/
static void getSubnetMask(IPAddress& mask);
/*
* Get the gateway ip address.
*
* return: copy the gateway ip address value in IPAddress object
*/
static void getGatewayIP(IPAddress& ip);
/*
* Return the current SSID associated with the network
*
* return: ssid string
*/
static char* getCurrentSSID();
/*
* Return the current BSSID associated with the network.
* It is the MAC address of the Access Point
*
* return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
*/
static uint8_t* getCurrentBSSID();
/*
* Return the current RSSI /Received Signal Strength in dBm)
* associated with the network
*
* return: signed value
*/
static int32_t getCurrentRSSI();
/*
* Return the Encryption Type associated with the network
*
* return: one value of wl_enc_type enum
*/
static uint8_t getCurrentEncryptionType();
/*
* Start scan WiFi networks available
*
* return: Number of discovered networks
*/
static int8_t startScanNetworks();
/*
* Get the networks available
*
* return: Number of discovered networks
*/
static uint8_t getScanNetworks();
/*
* Return the SSID discovered during the network scan.
*
* param networkItem: specify from which network item want to get the information
*
* return: ssid string of the specified item on the networks scanned list
*/
static char* getSSIDNetoworks(uint8_t networkItem);
/*
* Return the RSSI of the networks discovered during the scanNetworks
*
* param networkItem: specify from which network item want to get the information
*
* return: signed value of RSSI of the specified item on the networks scanned list
*/
static int32_t getRSSINetoworks(uint8_t networkItem);
/*
* Return the encryption type of the networks discovered during the scanNetworks
*
* param networkItem: specify from which network item want to get the information
*
* return: encryption type (enum wl_enc_type) of the specified item on the networks scanned list
*/
static uint8_t getEncTypeNetowrks(uint8_t networkItem);
/*
* Resolve the given hostname to an IP address.
* param aHostname: Name to be resolved
* param aResult: IPAddress structure to store the returned IP address
* result: 1 if aIPAddrString was successfully converted to an IP address,
* else error code
*/
static int getHostByName(const char* aHostname, IPAddress& aResult);
/*
* Get the firmware version
* result: version as string with this format a.b.c
*/
static char* getFwVersion();
};
extern WiFiDrv wiFiDrv;
#endif

View File

@ -1,31 +0,0 @@
/*
* wl_types.h
*
* Created on: Jul 30, 2010
* Author: dlafauci
*/
#ifndef _WL_TYPES_H_
#define _WL_TYPES_H_
#include <inttypes.h>
typedef enum {
WL_FAILURE = -1,
WL_SUCCESS = 1,
} wl_error_code_t;
/* Authentication modes */
enum wl_auth_mode {
AUTH_MODE_INVALID,
AUTH_MODE_AUTO,
AUTH_MODE_OPEN_SYSTEM,
AUTH_MODE_SHARED_KEY,
AUTH_MODE_WPA,
AUTH_MODE_WPA2,
AUTH_MODE_WPA_PSK,
AUTH_MODE_WPA2_PSK
};
#endif //_WL_TYPES_H_

View File

@ -6,7 +6,8 @@
Hardware required :
* Arduino shield with a SD card on CS4
* A sound file named "test.wav" in the root directory of the SD card
* Speaker attched to ground and DAC0
* An audio amplifier to connect to the DAC0 and ground
* A speaker to connect to the audio amplifier
Original by Massimo Banzi September 20, 2012
Modified by Scott Fitzgerald October 19, 2012

View File

@ -0,0 +1,10 @@
name=Audio
author=cmaglie
email=Cristian Maglie <c.maglie@bug.st>
sentence=Play audio files through the DAC outputs of the Arduino Due.
paragraph=With this library you can use the Arduino Due DAC outputs to play audio files.<br />The audio files must be in the raw .wav format.
url=http://arduino.cc/en/Reference/Audio
architectures=sam
version=1.0
dependencies=
core-dependencies=arduino (>=1.5.0)

View File

@ -0,0 +1,10 @@
name=EEPROM
author=Arduino
email=info@arduino.cc
sentence=Read/Write the EEPROM memory on the AVR-based Arduino boards.
paragraph=With this library you can read and write bytes to the EEPROM memory, that is available on the AVR microcontrollers mounted on the Arduino boards.
url=http://arduino.cc/en/Reference/EEPROM
architectures=avr
version=1.0
dependencies=
core-dependencies=arduino (>=1.5.0)

Some files were not shown because too many files have changed in this diff Show More