.ino files commit
This commit is contained in:
parent
d777cf6f61
commit
a279af3883
8
Arduino/Blink/.theia/launch.json
Normal file
8
Arduino/Blink/.theia/launch.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
]
|
||||
}
|
16
Arduino/Blink/Blink.ino
Normal file
16
Arduino/Blink/Blink.ino
Normal file
@ -0,0 +1,16 @@
|
||||
void setup() {
|
||||
pinMode(13, OUTPUT);
|
||||
|
||||
}
|
||||
|
||||
void loop() {
|
||||
digitalWrite(13, HIGH);
|
||||
delay(3000);
|
||||
digitalWrite(13, LOW);
|
||||
delay(3000);
|
||||
digitalWrite(13, HIGH);
|
||||
delay(3000);
|
||||
digitalWrite(13, LOW);
|
||||
delay(3000);
|
||||
Serial.println("Hello");
|
||||
}
|
BIN
Arduino/E-lego Manual.pdf
Normal file
BIN
Arduino/E-lego Manual.pdf
Normal file
Binary file not shown.
8
Arduino/Interlock/interrupt_seq_2/.theia/launch.json
Normal file
8
Arduino/Interlock/interrupt_seq_2/.theia/launch.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
]
|
||||
}
|
81
Arduino/Interlock/interrupt_seq_2/interrupt_seq_2.ino
Normal file
81
Arduino/Interlock/interrupt_seq_2/interrupt_seq_2.ino
Normal file
@ -0,0 +1,81 @@
|
||||
#include <SPI.h>
|
||||
#include <Ethernet3.h>
|
||||
|
||||
// Configure MAC address and IP:
|
||||
byte mac[] = {0x61, 0x2C, 0xF2, 0x09, 0x73, 0xBE};
|
||||
|
||||
// the real one IPAddress ip(10, 11, 1, 22); // Static IP
|
||||
|
||||
|
||||
// Define CS and RST pins:
|
||||
#define W5500_CS_PIN 10 // 8 in E LEGO
|
||||
#define W5500_RST_PIN 9 //10 in E LEGO
|
||||
|
||||
IPAddress serverIP(169, 254, 246, 15); // Computer
|
||||
IPAddress W5500_ip(169, 254, 246, 16); // Change the last digit
|
||||
|
||||
// Don't change
|
||||
const int port = 5005;
|
||||
|
||||
// Definitions for interrupt sequence
|
||||
int interrupt_pin = 2; // 24 in E LEGO
|
||||
volatile int interrupt_flag;
|
||||
|
||||
EthernetClient client;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
|
||||
// Reset W5500
|
||||
pinMode(W5500_RST_PIN, OUTPUT);
|
||||
digitalWrite(W5500_RST_PIN, HIGH);
|
||||
delay(250);
|
||||
digitalWrite(W5500_RST_PIN, LOW);
|
||||
delay(250);
|
||||
digitalWrite(W5500_RST_PIN, HIGH);
|
||||
delay(1000);
|
||||
|
||||
// Initialize Ethernet:
|
||||
Ethernet.init(W5500_CS_PIN);
|
||||
Ethernet.begin(mac, W5500_ip);
|
||||
delay (1500);
|
||||
|
||||
Serial.print("W5500 IP: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
|
||||
// Send a message through socket
|
||||
if (client.connect (serverIP, port)) {
|
||||
client.write("test");
|
||||
client.stop();
|
||||
Serial.print("Test Message sent");
|
||||
} else {
|
||||
Serial.print ("Connection failed");
|
||||
}
|
||||
|
||||
|
||||
// Interrupt sequence
|
||||
pinMode(interrupt_pin, INPUT_PULLUP);
|
||||
attachInterrupt(digitalPinToInterrupt(interrupt_pin), ISR_button, CHANGE);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// put your main code here, to run repeatedly:
|
||||
|
||||
if (interrupt_flag) {
|
||||
interrupt_flag = 0;
|
||||
|
||||
if (client.connect(serverIP, port)) {
|
||||
client.println("Leak");
|
||||
client.stop();
|
||||
Serial.println("Leak update sent to server.");
|
||||
} else {
|
||||
Serial.println("Connection failed.");
|
||||
}
|
||||
}
|
||||
|
||||
delay(10);
|
||||
}
|
||||
|
||||
void ISR_button () {
|
||||
interrupt_flag = 1;
|
||||
}
|
62
Arduino/Interlock/interrupt_sequence/interrupt_sequence.ino
Normal file
62
Arduino/Interlock/interrupt_sequence/interrupt_sequence.ino
Normal file
@ -0,0 +1,62 @@
|
||||
#include <SPI.h>
|
||||
#include <Ethernet3.h>
|
||||
|
||||
// Configure MAC address and IP:
|
||||
byte mac[] = {0x61, 0x2C, 0xF2, 0x09, 0x73, 0xBE};
|
||||
IPAddress ip(10, 11, 1, 22); // Static IP
|
||||
|
||||
// Change when connecting to the internet
|
||||
IPAddress serverIP(192, 168, 1, 100); // computer
|
||||
// Don't change
|
||||
unsigned int port = 5005;
|
||||
|
||||
// Define CS and RST pins:
|
||||
#define W5500_CS_PIN 10
|
||||
#define W5500_RST_PIN 9
|
||||
|
||||
// Definitions for interrupt sequence
|
||||
int interrupt_pin = 2; // Wired
|
||||
volatile int interrupt_flag;
|
||||
|
||||
EthernetClient client;
|
||||
//client.connect ()
|
||||
|
||||
void setup() {
|
||||
// put your setup code here, to run once:
|
||||
|
||||
Serial.begin(9600);
|
||||
|
||||
// Reset W5500
|
||||
pinMode(W5500_RST_PIN, OUTPUT);
|
||||
digitalWrite(W5500_RST_PIN, HIGH);
|
||||
delay(250);
|
||||
digitalWrite(W5500_RST_PIN, LOW);
|
||||
delay(250);
|
||||
digitalWrite(W5500_RST_PIN, HIGH);
|
||||
delay(1000);
|
||||
|
||||
Serial.print("Sending a message");
|
||||
// Initialize Ethernet:
|
||||
Ethernet.init(W5500_CS_PIN);
|
||||
Ethernet.begin(mac, ip);
|
||||
|
||||
// Try to send a message through socket
|
||||
|
||||
//client.write("hey", 3);
|
||||
|
||||
// Initialize interrupt
|
||||
pinMode(interrupt_pin, INPUT_PULLUP);
|
||||
attachInterrupt(digitalPinToInterrupt(interrupt_pin), ISR_button, CHANGE);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// put your main code here, to run repeatedly:
|
||||
if (interrupt_flag) {
|
||||
|
||||
interrupt_flag = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void ISR_button () {
|
||||
interrupt_flag = 1;
|
||||
}
|
56
Arduino/Interlock/leak_detector/leak_detector.ino
Normal file
56
Arduino/Interlock/leak_detector/leak_detector.ino
Normal file
@ -0,0 +1,56 @@
|
||||
#include <SPI.h>
|
||||
#include <Ethernet3.h>
|
||||
|
||||
// Configure MAC address and IP:
|
||||
byte mac[] = {0x61, 0x2C, 0xF2, 0x09, 0x73, 0xBE};
|
||||
IPAddress ip(10, 11, 1, 22);
|
||||
|
||||
// Define CS and RST pins:
|
||||
#define W5500_CS_PIN 10
|
||||
#define W5500_RST_PIN 9
|
||||
|
||||
const int pin_5V = 6;
|
||||
const int pin_GND = 4;
|
||||
|
||||
EthernetClient client;
|
||||
|
||||
void setup() {
|
||||
// put your setup code here, to run once:
|
||||
pinMode(pin_5V, OUTPUT);
|
||||
pinMode(pin_GND, OUTPUT);
|
||||
|
||||
digitalWrite(pin_5V, HIGH);
|
||||
digitalWrite(pin_GND, LOW);
|
||||
|
||||
Serial.begin(9600);
|
||||
|
||||
// Reset W5500:
|
||||
pinMode(W5500_RST_PIN, OUTPUT);
|
||||
digitalWrite(W5500_RST_PIN, HIGH);
|
||||
delay(250);
|
||||
digitalWrite(W5500_RST_PIN, LOW);
|
||||
delay(250);
|
||||
digitalWrite(W5500_RST_PIN, HIGH);
|
||||
delay(1000);
|
||||
|
||||
// Initialize Ethernet:
|
||||
Ethernet.init(W5500_CS_PIN);
|
||||
Ethernet.begin(mac, ip);
|
||||
|
||||
Serial.print("IP: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// put your main code here, to run repeatedly:
|
||||
pinMode(pin_5V, INPUT);
|
||||
int state = digitalRead(pin_5V);
|
||||
pinMode(pin_5V, OUTPUT);
|
||||
|
||||
if (state == HIGH) {
|
||||
Serial.println("1");
|
||||
} else {
|
||||
Serial.println("0");
|
||||
}
|
||||
delay (250)
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
void setup() {
|
||||
// put your setup code here, to run once:
|
||||
Serial.begin(9600);
|
||||
while (!Serial);
|
||||
Serial.println("Hello");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// put your main code here, to run repeatedly:
|
||||
|
||||
}
|
8
Arduino/Interlock/spi_test/.theia/launch.json
Normal file
8
Arduino/Interlock/spi_test/.theia/launch.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
]
|
||||
}
|
23
Arduino/Interlock/spi_test/spi_test.ino
Normal file
23
Arduino/Interlock/spi_test/spi_test.ino
Normal file
@ -0,0 +1,23 @@
|
||||
#include <SPI.h>
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
while (!Serial);
|
||||
|
||||
SPI.begin();
|
||||
|
||||
pinMode(10, OUTPUT);
|
||||
digitalWrite(10, LOW); // Select W5500
|
||||
|
||||
Serial.println("Testing SPI...");
|
||||
|
||||
byte response = SPI.transfer(0x00); // Send dummy byte and read response
|
||||
|
||||
Serial.print("SPI Response: ");
|
||||
Serial.println(response, HEX);
|
||||
|
||||
digitalWrite(10, HIGH); // Deselect W5500
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
30
Arduino/Scan_I2C/Scan_I2C.ino
Normal file
30
Arduino/Scan_I2C/Scan_I2C.ino
Normal file
@ -0,0 +1,30 @@
|
||||
#include <Wire.h>
|
||||
|
||||
void setup() {
|
||||
Wire.begin();
|
||||
Serial.begin(9600);
|
||||
while (!Serial);
|
||||
Serial.println("I2C Scanner");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
byte error, address;
|
||||
int count = 0;
|
||||
|
||||
for (address = 1; address < 127; address++) {
|
||||
Serial.println("Scanning address {address}");
|
||||
Wire.beginTransmission(address);
|
||||
error = Wire.endTransmission();
|
||||
Serial.print(error);
|
||||
|
||||
if (error == 0) {
|
||||
Serial.print("I2C device found at 0x");
|
||||
Serial.println(address, HEX);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (count == 0) Serial.println("No I2C devices found");
|
||||
|
||||
delay(2000);
|
||||
}
|
40
Arduino/Temp. sensors/Ard_mic_SHT31/Ard_mic_SHT31.ino
Normal file
40
Arduino/Temp. sensors/Ard_mic_SHT31/Ard_mic_SHT31.ino
Normal file
@ -0,0 +1,40 @@
|
||||
#include "Adafruit_SHT31.h"
|
||||
|
||||
Adafruit_SHT31 sht31 = Adafruit_SHT31();
|
||||
|
||||
#define SHT31_RST_PIN 16
|
||||
|
||||
void resetSensor() {
|
||||
pinMode(SHT31_RST_PIN, OUTPUT);
|
||||
digitalWrite(SHT31_RST_PIN, LOW);
|
||||
delay(10);
|
||||
digitalWrite(SHT31_RST_PIN, HIGH);
|
||||
delay(10);
|
||||
}
|
||||
|
||||
void setup() {
|
||||
// put your setup code here, to run once:
|
||||
|
||||
Serial.begin(9600);
|
||||
while (!Serial);
|
||||
Serial.println ("Initiating test");
|
||||
|
||||
if (!sht31.begin(0X44)) {
|
||||
Serial.println("Couldn't find SHT31");
|
||||
while (1) delay(100);
|
||||
}
|
||||
Serial.println("SHT31 Found!");
|
||||
float t = sht31.readTemperature();
|
||||
float h = sht31.readHumidity();
|
||||
|
||||
if (!isnan(t)) {
|
||||
Serial.print("Temperature (C)= "); Serial.println(t);}
|
||||
|
||||
if (!isnan(h)) {
|
||||
Serial.print("Humidity = "); Serial.println(h); }
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// put your main code here, to run repeatedly:
|
||||
|
||||
}
|
384
Arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp
Normal file
384
Arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp
Normal file
@ -0,0 +1,384 @@
|
||||
#include <Adafruit_BusIO_Register.h>
|
||||
|
||||
#if !defined(SPI_INTERFACES_COUNT) || \
|
||||
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
|
||||
|
||||
/*!
|
||||
* @brief Create a register we access over an I2C Device (which defines the
|
||||
* bus and address)
|
||||
* @param i2cdevice The I2CDevice to use for underlying I2C access
|
||||
* @param reg_addr The address pointer value for the I2C/SMBus register, can
|
||||
* be 8 or 16 bits
|
||||
* @param width The width of the register data itself, defaults to 1 byte
|
||||
* @param byteorder The byte order of the register (used when width is > 1),
|
||||
* defaults to LSBFIRST
|
||||
* @param address_width The width of the register address itself, defaults
|
||||
* to 1 byte
|
||||
*/
|
||||
Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice,
|
||||
uint16_t reg_addr,
|
||||
uint8_t width,
|
||||
uint8_t byteorder,
|
||||
uint8_t address_width) {
|
||||
_i2cdevice = i2cdevice;
|
||||
_spidevice = nullptr;
|
||||
_addrwidth = address_width;
|
||||
_address = reg_addr;
|
||||
_byteorder = byteorder;
|
||||
_width = width;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Create a register we access over an SPI Device (which defines the
|
||||
* bus and CS pin)
|
||||
* @param spidevice The SPIDevice to use for underlying SPI access
|
||||
* @param reg_addr The address pointer value for the SPI register, can
|
||||
* be 8 or 16 bits
|
||||
* @param type The method we use to read/write data to SPI (which is not
|
||||
* as well defined as I2C)
|
||||
* @param width The width of the register data itself, defaults to 1 byte
|
||||
* @param byteorder The byte order of the register (used when width is > 1),
|
||||
* defaults to LSBFIRST
|
||||
* @param address_width The width of the register address itself, defaults
|
||||
* to 1 byte
|
||||
*/
|
||||
Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice,
|
||||
uint16_t reg_addr,
|
||||
Adafruit_BusIO_SPIRegType type,
|
||||
uint8_t width,
|
||||
uint8_t byteorder,
|
||||
uint8_t address_width) {
|
||||
_spidevice = spidevice;
|
||||
_spiregtype = type;
|
||||
_i2cdevice = nullptr;
|
||||
_addrwidth = address_width;
|
||||
_address = reg_addr;
|
||||
_byteorder = byteorder;
|
||||
_width = width;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Create a register we access over an I2C or SPI Device. This is a
|
||||
* handy function because we can pass in nullptr for the unused interface,
|
||||
* allowing libraries to mass-define all the registers
|
||||
* @param i2cdevice The I2CDevice to use for underlying I2C access, if
|
||||
* nullptr we use SPI
|
||||
* @param spidevice The SPIDevice to use for underlying SPI access, if
|
||||
* nullptr we use I2C
|
||||
* @param reg_addr The address pointer value for the I2C/SMBus/SPI register,
|
||||
* can be 8 or 16 bits
|
||||
* @param type The method we use to read/write data to SPI (which is not
|
||||
* as well defined as I2C)
|
||||
* @param width The width of the register data itself, defaults to 1 byte
|
||||
* @param byteorder The byte order of the register (used when width is > 1),
|
||||
* defaults to LSBFIRST
|
||||
* @param address_width The width of the register address itself, defaults
|
||||
* to 1 byte
|
||||
*/
|
||||
Adafruit_BusIO_Register::Adafruit_BusIO_Register(
|
||||
Adafruit_I2CDevice *i2cdevice, Adafruit_SPIDevice *spidevice,
|
||||
Adafruit_BusIO_SPIRegType type, uint16_t reg_addr, uint8_t width,
|
||||
uint8_t byteorder, uint8_t address_width) {
|
||||
_spidevice = spidevice;
|
||||
_i2cdevice = i2cdevice;
|
||||
_spiregtype = type;
|
||||
_addrwidth = address_width;
|
||||
_address = reg_addr;
|
||||
_byteorder = byteorder;
|
||||
_width = width;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Create a register we access over a GenericDevice
|
||||
* @param genericdevice Generic device to use
|
||||
* @param reg_addr Register address we will read/write
|
||||
* @param width Width of the register in bytes (1-4)
|
||||
* @param byteorder Byte order of register data (LSBFIRST or MSBFIRST)
|
||||
* @param address_width Width of the register address in bytes (1 or 2)
|
||||
*/
|
||||
Adafruit_BusIO_Register::Adafruit_BusIO_Register(
|
||||
Adafruit_GenericDevice *genericdevice, uint16_t reg_addr, uint8_t width,
|
||||
uint8_t byteorder, uint8_t address_width) {
|
||||
_i2cdevice = nullptr;
|
||||
_spidevice = nullptr;
|
||||
_genericdevice = genericdevice;
|
||||
_addrwidth = address_width;
|
||||
_address = reg_addr;
|
||||
_byteorder = byteorder;
|
||||
_width = width;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write a buffer of data to the register location
|
||||
* @param buffer Pointer to data to write
|
||||
* @param len Number of bytes to write
|
||||
* @return True on successful write (only really useful for I2C as SPI is
|
||||
* uncheckable)
|
||||
*/
|
||||
bool Adafruit_BusIO_Register::write(uint8_t *buffer, uint8_t len) {
|
||||
uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF),
|
||||
(uint8_t)(_address >> 8)};
|
||||
if (_i2cdevice) {
|
||||
return _i2cdevice->write(buffer, len, true, addrbuffer, _addrwidth);
|
||||
}
|
||||
if (_spidevice) {
|
||||
if (_spiregtype == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) {
|
||||
// very special case!
|
||||
// pass the special opcode address which we set as the high byte of the
|
||||
// regaddr
|
||||
addrbuffer[0] =
|
||||
(uint8_t)(_address >> 8) & ~0x01; // set bottom bit low to write
|
||||
// the 'actual' reg addr is the second byte then
|
||||
addrbuffer[1] = (uint8_t)(_address & 0xFF);
|
||||
// the address appears to be a byte longer
|
||||
return _spidevice->write(buffer, len, addrbuffer, _addrwidth + 1);
|
||||
}
|
||||
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
|
||||
addrbuffer[0] &= ~0x80;
|
||||
}
|
||||
if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) {
|
||||
addrbuffer[0] |= 0x80;
|
||||
}
|
||||
if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) {
|
||||
addrbuffer[0] &= ~0x80;
|
||||
addrbuffer[0] |= 0x40;
|
||||
}
|
||||
return _spidevice->write(buffer, len, addrbuffer, _addrwidth);
|
||||
}
|
||||
if (_genericdevice) {
|
||||
return _genericdevice->writeRegister(addrbuffer, _addrwidth, buffer, len);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write up to 4 bytes of data to the register location
|
||||
* @param value Data to write
|
||||
* @param numbytes How many bytes from 'value' to write
|
||||
* @return True on successful write (only really useful for I2C as SPI is
|
||||
* uncheckable)
|
||||
*/
|
||||
bool Adafruit_BusIO_Register::write(uint32_t value, uint8_t numbytes) {
|
||||
if (numbytes == 0) {
|
||||
numbytes = _width;
|
||||
}
|
||||
if (numbytes > 4) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// store a copy
|
||||
_cached = value;
|
||||
|
||||
for (int i = 0; i < numbytes; i++) {
|
||||
if (_byteorder == LSBFIRST) {
|
||||
_buffer[i] = value & 0xFF;
|
||||
} else {
|
||||
_buffer[numbytes - i - 1] = value & 0xFF;
|
||||
}
|
||||
value >>= 8;
|
||||
}
|
||||
return write(_buffer, numbytes);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Read data from the register location. This does not do any error
|
||||
* checking!
|
||||
* @return Returns 0xFFFFFFFF on failure, value otherwise
|
||||
*/
|
||||
uint32_t Adafruit_BusIO_Register::read(void) {
|
||||
if (!read(_buffer, _width)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint32_t value = 0;
|
||||
|
||||
for (int i = 0; i < _width; i++) {
|
||||
value <<= 8;
|
||||
if (_byteorder == LSBFIRST) {
|
||||
value |= _buffer[_width - i - 1];
|
||||
} else {
|
||||
value |= _buffer[i];
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Read cached data from last time we wrote to this register
|
||||
* @return Returns 0xFFFFFFFF on failure, value otherwise
|
||||
*/
|
||||
uint32_t Adafruit_BusIO_Register::readCached(void) { return _cached; }
|
||||
|
||||
/*!
|
||||
@brief Read a number of bytes from a register into a buffer
|
||||
@param buffer Buffer to read data into
|
||||
@param len Number of bytes to read into the buffer
|
||||
@return true on successful read, otherwise false
|
||||
*/
|
||||
bool Adafruit_BusIO_Register::read(uint8_t *buffer, uint8_t len) {
|
||||
uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF),
|
||||
(uint8_t)(_address >> 8)};
|
||||
if (_i2cdevice) {
|
||||
return _i2cdevice->write_then_read(addrbuffer, _addrwidth, buffer, len);
|
||||
}
|
||||
if (_spidevice) {
|
||||
if (_spiregtype == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) {
|
||||
// very special case!
|
||||
// pass the special opcode address which we set as the high byte of the
|
||||
// regaddr
|
||||
addrbuffer[0] =
|
||||
(uint8_t)(_address >> 8) | 0x01; // set bottom bit high to read
|
||||
// the 'actual' reg addr is the second byte then
|
||||
addrbuffer[1] = (uint8_t)(_address & 0xFF);
|
||||
// the address appears to be a byte longer
|
||||
return _spidevice->write_then_read(addrbuffer, _addrwidth + 1, buffer,
|
||||
len);
|
||||
}
|
||||
if (_spiregtype == ADDRBIT8_HIGH_TOREAD) {
|
||||
addrbuffer[0] |= 0x80;
|
||||
}
|
||||
if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) {
|
||||
addrbuffer[0] &= ~0x80;
|
||||
}
|
||||
if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) {
|
||||
addrbuffer[0] |= 0x80 | 0x40;
|
||||
}
|
||||
return _spidevice->write_then_read(addrbuffer, _addrwidth, buffer, len);
|
||||
}
|
||||
if (_genericdevice) {
|
||||
return _genericdevice->readRegister(addrbuffer, _addrwidth, buffer, len);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Read 2 bytes of data from the register location
|
||||
* @param value Pointer to uint16_t variable to read into
|
||||
* @return True on successful write (only really useful for I2C as SPI is
|
||||
* uncheckable)
|
||||
*/
|
||||
bool Adafruit_BusIO_Register::read(uint16_t *value) {
|
||||
if (!read(_buffer, 2)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_byteorder == LSBFIRST) {
|
||||
*value = _buffer[1];
|
||||
*value <<= 8;
|
||||
*value |= _buffer[0];
|
||||
} else {
|
||||
*value = _buffer[0];
|
||||
*value <<= 8;
|
||||
*value |= _buffer[1];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Read 1 byte of data from the register location
|
||||
* @param value Pointer to uint8_t variable to read into
|
||||
* @return True on successful write (only really useful for I2C as SPI is
|
||||
* uncheckable)
|
||||
*/
|
||||
bool Adafruit_BusIO_Register::read(uint8_t *value) {
|
||||
if (!read(_buffer, 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*value = _buffer[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Pretty printer for this register
|
||||
* @param s The Stream to print to, defaults to &Serial
|
||||
*/
|
||||
void Adafruit_BusIO_Register::print(Stream *s) {
|
||||
uint32_t val = read();
|
||||
s->print("0x");
|
||||
s->print(val, HEX);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Pretty printer for this register
|
||||
* @param s The Stream to print to, defaults to &Serial
|
||||
*/
|
||||
void Adafruit_BusIO_Register::println(Stream *s) {
|
||||
print(s);
|
||||
s->println();
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Create a slice of the register that we can address without
|
||||
* touching other bits
|
||||
* @param reg The Adafruit_BusIO_Register which defines the bus/register
|
||||
* @param bits The number of bits wide we are slicing
|
||||
* @param shift The number of bits that our bit-slice is shifted from LSB
|
||||
*/
|
||||
Adafruit_BusIO_RegisterBits::Adafruit_BusIO_RegisterBits(
|
||||
Adafruit_BusIO_Register *reg, uint8_t bits, uint8_t shift) {
|
||||
_register = reg;
|
||||
_bits = bits;
|
||||
_shift = shift;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Read 4 bytes of data from the register
|
||||
* @return data The 4 bytes to read
|
||||
*/
|
||||
uint32_t Adafruit_BusIO_RegisterBits::read(void) {
|
||||
uint32_t val = _register->read();
|
||||
val >>= _shift;
|
||||
return val & ((1 << (_bits)) - 1);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write 4 bytes of data to the register
|
||||
* @param data The 4 bytes to write
|
||||
* @return True on successful write (only really useful for I2C as SPI is
|
||||
* uncheckable)
|
||||
*/
|
||||
bool Adafruit_BusIO_RegisterBits::write(uint32_t data) {
|
||||
uint32_t val = _register->read();
|
||||
|
||||
// mask off the data before writing
|
||||
uint32_t mask = (1 << (_bits)) - 1;
|
||||
data &= mask;
|
||||
|
||||
mask <<= _shift;
|
||||
val &= ~mask; // remove the current data at that spot
|
||||
val |= data << _shift; // and add in the new data
|
||||
|
||||
return _register->write(val, _register->width());
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief The width of the register data, helpful for doing calculations
|
||||
* @returns The data width used when initializing the register
|
||||
*/
|
||||
uint8_t Adafruit_BusIO_Register::width(void) { return _width; }
|
||||
|
||||
/*!
|
||||
* @brief Set the default width of data
|
||||
* @param width the default width of data read from register
|
||||
*/
|
||||
void Adafruit_BusIO_Register::setWidth(uint8_t width) { _width = width; }
|
||||
|
||||
/*!
|
||||
* @brief Set register address
|
||||
* @param address the address from register
|
||||
*/
|
||||
void Adafruit_BusIO_Register::setAddress(uint16_t address) {
|
||||
_address = address;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Set the width of register address
|
||||
* @param address_width the width for register address
|
||||
*/
|
||||
void Adafruit_BusIO_Register::setAddressWidth(uint16_t address_width) {
|
||||
_addrwidth = address_width;
|
||||
}
|
||||
|
||||
#endif // SPI exists
|
112
Arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h
Normal file
112
Arduino/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h
Normal file
@ -0,0 +1,112 @@
|
||||
#ifndef Adafruit_BusIO_Register_h
|
||||
#define Adafruit_BusIO_Register_h
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#if !defined(SPI_INTERFACES_COUNT) || \
|
||||
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
|
||||
|
||||
#include <Adafruit_GenericDevice.h>
|
||||
#include <Adafruit_I2CDevice.h>
|
||||
#include <Adafruit_SPIDevice.h>
|
||||
|
||||
typedef enum _Adafruit_BusIO_SPIRegType {
|
||||
ADDRBIT8_HIGH_TOREAD = 0,
|
||||
/*!<
|
||||
* ADDRBIT8_HIGH_TOREAD
|
||||
* When reading a register you must actually send the value 0x80 + register
|
||||
* address to the device. e.g. To read the register 0x0B the register value
|
||||
* 0x8B is sent and to write 0x0B is sent.
|
||||
*/
|
||||
AD8_HIGH_TOREAD_AD7_HIGH_TOINC = 1,
|
||||
|
||||
/*!<
|
||||
* ADDRBIT8_HIGH_TOWRITE
|
||||
* When writing to a register you must actually send the value 0x80 +
|
||||
* the register address to the device. e.g. To write to the register 0x19 the
|
||||
* register value 0x99 is sent and to read 0x19 is sent.
|
||||
*/
|
||||
ADDRBIT8_HIGH_TOWRITE = 2,
|
||||
|
||||
/*!<
|
||||
* ADDRESSED_OPCODE_LOWBIT_TO_WRITE
|
||||
* Used by the MCP23S series, we send 0x40 |'rd with the opcode
|
||||
* Then set the lowest bit to write
|
||||
*/
|
||||
ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE = 3,
|
||||
|
||||
} Adafruit_BusIO_SPIRegType;
|
||||
|
||||
/*!
|
||||
* @brief The class which defines a device register (a location to read/write
|
||||
* data from)
|
||||
*/
|
||||
class Adafruit_BusIO_Register {
|
||||
public:
|
||||
Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, uint16_t reg_addr,
|
||||
uint8_t width = 1, uint8_t byteorder = LSBFIRST,
|
||||
uint8_t address_width = 1);
|
||||
|
||||
Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice, uint16_t reg_addr,
|
||||
Adafruit_BusIO_SPIRegType type, uint8_t width = 1,
|
||||
uint8_t byteorder = LSBFIRST,
|
||||
uint8_t address_width = 1);
|
||||
|
||||
Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice,
|
||||
Adafruit_SPIDevice *spidevice,
|
||||
Adafruit_BusIO_SPIRegType type, uint16_t reg_addr,
|
||||
uint8_t width = 1, uint8_t byteorder = LSBFIRST,
|
||||
uint8_t address_width = 1);
|
||||
|
||||
Adafruit_BusIO_Register(Adafruit_GenericDevice *genericdevice,
|
||||
uint16_t reg_addr, uint8_t width = 1,
|
||||
uint8_t byteorder = LSBFIRST,
|
||||
uint8_t address_width = 1);
|
||||
|
||||
bool read(uint8_t *buffer, uint8_t len);
|
||||
bool read(uint8_t *value);
|
||||
bool read(uint16_t *value);
|
||||
uint32_t read(void);
|
||||
uint32_t readCached(void);
|
||||
bool write(uint8_t *buffer, uint8_t len);
|
||||
bool write(uint32_t value, uint8_t numbytes = 0);
|
||||
|
||||
uint8_t width(void);
|
||||
|
||||
void setWidth(uint8_t width);
|
||||
void setAddress(uint16_t address);
|
||||
void setAddressWidth(uint16_t address_width);
|
||||
|
||||
void print(Stream *s = &Serial);
|
||||
void println(Stream *s = &Serial);
|
||||
|
||||
private:
|
||||
Adafruit_I2CDevice *_i2cdevice;
|
||||
Adafruit_SPIDevice *_spidevice;
|
||||
Adafruit_GenericDevice *_genericdevice;
|
||||
Adafruit_BusIO_SPIRegType _spiregtype;
|
||||
uint16_t _address;
|
||||
uint8_t _width, _addrwidth, _byteorder;
|
||||
uint8_t _buffer[4]; // we won't support anything larger than uint32 for
|
||||
// non-buffered read
|
||||
uint32_t _cached = 0;
|
||||
};
|
||||
|
||||
/*!
|
||||
* @brief The class which defines a slice of bits from within a device register
|
||||
* (a location to read/write data from)
|
||||
*/
|
||||
class Adafruit_BusIO_RegisterBits {
|
||||
public:
|
||||
Adafruit_BusIO_RegisterBits(Adafruit_BusIO_Register *reg, uint8_t bits,
|
||||
uint8_t shift);
|
||||
bool write(uint32_t value);
|
||||
uint32_t read(void);
|
||||
|
||||
private:
|
||||
Adafruit_BusIO_Register *_register;
|
||||
uint8_t _bits, _shift;
|
||||
};
|
||||
|
||||
#endif // SPI exists
|
||||
#endif // BusIO_Register_h
|
82
Arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.cpp
Normal file
82
Arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.cpp
Normal file
@ -0,0 +1,82 @@
|
||||
/*
|
||||
Written with help by Claude!
|
||||
https://claude.ai/chat/335f50b1-3dd8-435e-9139-57ec7ca26a3c (at this time
|
||||
chats are not shareable :(
|
||||
*/
|
||||
|
||||
#include "Adafruit_GenericDevice.h"
|
||||
|
||||
/*!
|
||||
* @brief Create a Generic device with the provided read/write functions
|
||||
* @param obj Pointer to object instance
|
||||
* @param read_func Function pointer for reading raw data
|
||||
* @param write_func Function pointer for writing raw data
|
||||
* @param readreg_func Function pointer for reading registers (optional)
|
||||
* @param writereg_func Function pointer for writing registers (optional) */
|
||||
Adafruit_GenericDevice::Adafruit_GenericDevice(
|
||||
void *obj, busio_genericdevice_read_t read_func,
|
||||
busio_genericdevice_write_t write_func,
|
||||
busio_genericdevice_readreg_t readreg_func,
|
||||
busio_genericdevice_writereg_t writereg_func) {
|
||||
_obj = obj;
|
||||
_read_func = read_func;
|
||||
_write_func = write_func;
|
||||
_readreg_func = readreg_func;
|
||||
_writereg_func = writereg_func;
|
||||
_begun = false;
|
||||
}
|
||||
|
||||
/*! @brief Simple begin function (doesn't do much at this time)
|
||||
@return true always
|
||||
*/
|
||||
bool Adafruit_GenericDevice::begin(void) {
|
||||
_begun = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/*! @brief Write a buffer of data
|
||||
@param buffer Pointer to buffer of data to write
|
||||
@param len Number of bytes to write
|
||||
@return true if write was successful, otherwise false */
|
||||
bool Adafruit_GenericDevice::write(const uint8_t *buffer, size_t len) {
|
||||
if (!_begun)
|
||||
return false;
|
||||
return _write_func(_obj, buffer, len);
|
||||
}
|
||||
|
||||
/*! @brief Read data into a buffer
|
||||
@param buffer Pointer to buffer to read data into
|
||||
@param len Number of bytes to read
|
||||
@return true if read was successful, otherwise false */
|
||||
bool Adafruit_GenericDevice::read(uint8_t *buffer, size_t len) {
|
||||
if (!_begun)
|
||||
return false;
|
||||
return _read_func(_obj, buffer, len);
|
||||
}
|
||||
|
||||
/*! @brief Read from a register location
|
||||
@param addr_buf Buffer containing register address
|
||||
@param addrsiz Size of register address in bytes
|
||||
@param buf Buffer to store read data
|
||||
@param bufsiz Size of data to read in bytes
|
||||
@return true if read was successful, otherwise false */
|
||||
bool Adafruit_GenericDevice::readRegister(uint8_t *addr_buf, uint8_t addrsiz,
|
||||
uint8_t *buf, uint16_t bufsiz) {
|
||||
if (!_begun || !_readreg_func)
|
||||
return false;
|
||||
return _readreg_func(_obj, addr_buf, addrsiz, buf, bufsiz);
|
||||
}
|
||||
|
||||
/*! @brief Write to a register location
|
||||
@param addr_buf Buffer containing register address
|
||||
@param addrsiz Size of register address in bytes
|
||||
@param buf Buffer containing data to write
|
||||
@param bufsiz Size of data to write in bytes
|
||||
@return true if write was successful, otherwise false */
|
||||
bool Adafruit_GenericDevice::writeRegister(uint8_t *addr_buf, uint8_t addrsiz,
|
||||
const uint8_t *buf,
|
||||
uint16_t bufsiz) {
|
||||
if (!_begun || !_writereg_func)
|
||||
return false;
|
||||
return _writereg_func(_obj, addr_buf, addrsiz, buf, bufsiz);
|
||||
}
|
55
Arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.h
Normal file
55
Arduino/libraries/Adafruit_BusIO/Adafruit_GenericDevice.h
Normal file
@ -0,0 +1,55 @@
|
||||
#ifndef ADAFRUIT_GENERICDEVICE_H
|
||||
#define ADAFRUIT_GENERICDEVICE_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
typedef bool (*busio_genericdevice_read_t)(void *obj, uint8_t *buffer,
|
||||
size_t len);
|
||||
typedef bool (*busio_genericdevice_write_t)(void *obj, const uint8_t *buffer,
|
||||
size_t len);
|
||||
typedef bool (*busio_genericdevice_readreg_t)(void *obj, uint8_t *addr_buf,
|
||||
uint8_t addrsiz, uint8_t *data,
|
||||
uint16_t datalen);
|
||||
typedef bool (*busio_genericdevice_writereg_t)(void *obj, uint8_t *addr_buf,
|
||||
uint8_t addrsiz,
|
||||
const uint8_t *data,
|
||||
uint16_t datalen);
|
||||
|
||||
/*!
|
||||
* @brief Class for communicating with a device via generic read/write functions
|
||||
*/
|
||||
class Adafruit_GenericDevice {
|
||||
public:
|
||||
Adafruit_GenericDevice(
|
||||
void *obj, busio_genericdevice_read_t read_func,
|
||||
busio_genericdevice_write_t write_func,
|
||||
busio_genericdevice_readreg_t readreg_func = nullptr,
|
||||
busio_genericdevice_writereg_t writereg_func = nullptr);
|
||||
|
||||
bool begin(void);
|
||||
|
||||
bool read(uint8_t *buffer, size_t len);
|
||||
bool write(const uint8_t *buffer, size_t len);
|
||||
bool readRegister(uint8_t *addr_buf, uint8_t addrsiz, uint8_t *buf,
|
||||
uint16_t bufsiz);
|
||||
bool writeRegister(uint8_t *addr_buf, uint8_t addrsiz, const uint8_t *buf,
|
||||
uint16_t bufsiz);
|
||||
|
||||
protected:
|
||||
/*! @brief Function pointer for reading raw data from the device */
|
||||
busio_genericdevice_read_t _read_func;
|
||||
/*! @brief Function pointer for writing raw data to the device */
|
||||
busio_genericdevice_write_t _write_func;
|
||||
/*! @brief Function pointer for reading a 'register' from the device */
|
||||
busio_genericdevice_readreg_t _readreg_func;
|
||||
/*! @brief Function pointer for writing a 'register' to the device */
|
||||
busio_genericdevice_writereg_t _writereg_func;
|
||||
|
||||
bool _begun; ///< whether we have initialized yet (in case the function needs
|
||||
///< to do something)
|
||||
|
||||
private:
|
||||
void *_obj; ///< Pointer to object instance
|
||||
};
|
||||
|
||||
#endif // ADAFRUIT_GENERICDEVICE_H
|
320
Arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp
Normal file
320
Arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp
Normal file
@ -0,0 +1,320 @@
|
||||
#include "Adafruit_I2CDevice.h"
|
||||
|
||||
// #define DEBUG_SERIAL Serial
|
||||
|
||||
/*!
|
||||
* @brief Create an I2C device at a given address
|
||||
* @param addr The 7-bit I2C address for the device
|
||||
* @param theWire The I2C bus to use, defaults to &Wire
|
||||
*/
|
||||
Adafruit_I2CDevice::Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire) {
|
||||
_addr = addr;
|
||||
_wire = theWire;
|
||||
_begun = false;
|
||||
#ifdef ARDUINO_ARCH_SAMD
|
||||
_maxBufferSize = 250; // as defined in Wire.h's RingBuffer
|
||||
#elif defined(ESP32)
|
||||
_maxBufferSize = I2C_BUFFER_LENGTH;
|
||||
#else
|
||||
_maxBufferSize = 32;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Initializes and does basic address detection
|
||||
* @param addr_detect Whether we should attempt to detect the I2C address
|
||||
* with a scan. 99% of sensors/devices don't mind, but once in a while they
|
||||
* don't respond well to a scan!
|
||||
* @return True if I2C initialized and a device with the addr found
|
||||
*/
|
||||
bool Adafruit_I2CDevice::begin(bool addr_detect) {
|
||||
_wire->begin();
|
||||
_begun = true;
|
||||
|
||||
if (addr_detect) {
|
||||
return detected();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief De-initialize device, turn off the Wire interface
|
||||
*/
|
||||
void Adafruit_I2CDevice::end(void) {
|
||||
// Not all port implement Wire::end(), such as
|
||||
// - ESP8266
|
||||
// - AVR core without WIRE_HAS_END
|
||||
// - ESP32: end() is implemented since 2.0.1 which is latest at the moment.
|
||||
// Temporarily disable for now to give time for user to update.
|
||||
#if !(defined(ESP8266) || \
|
||||
(defined(ARDUINO_ARCH_AVR) && !defined(WIRE_HAS_END)) || \
|
||||
defined(ARDUINO_ARCH_ESP32))
|
||||
_wire->end();
|
||||
_begun = false;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Scans I2C for the address - note will give a false-positive
|
||||
* if there's no pullups on I2C
|
||||
* @return True if I2C initialized and a device with the addr found
|
||||
*/
|
||||
bool Adafruit_I2CDevice::detected(void) {
|
||||
// Init I2C if not done yet
|
||||
if (!_begun && !begin()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A basic scanner, see if it ACK's
|
||||
_wire->beginTransmission(_addr);
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.print(F("Address 0x"));
|
||||
DEBUG_SERIAL.print(_addr, HEX);
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_MBED
|
||||
_wire->write(0); // forces a write request instead of a read
|
||||
#endif
|
||||
if (_wire->endTransmission() == 0) {
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.println(F(" Detected"));
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.println(F(" Not detected"));
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write a buffer or two to the I2C device. Cannot be more than
|
||||
* maxBufferSize() bytes.
|
||||
* @param buffer Pointer to buffer of data to write. This is const to
|
||||
* ensure the content of this buffer doesn't change.
|
||||
* @param len Number of bytes from buffer to write
|
||||
* @param prefix_buffer Pointer to optional array of data to write before
|
||||
* buffer. Cannot be more than maxBufferSize() bytes. This is const to
|
||||
* ensure the content of this buffer doesn't change.
|
||||
* @param prefix_len Number of bytes from prefix buffer to write
|
||||
* @param stop Whether to send an I2C STOP signal on write
|
||||
* @return True if write was successful, otherwise false.
|
||||
*/
|
||||
bool Adafruit_I2CDevice::write(const uint8_t *buffer, size_t len, bool stop,
|
||||
const uint8_t *prefix_buffer,
|
||||
size_t prefix_len) {
|
||||
if ((len + prefix_len) > maxBufferSize()) {
|
||||
// currently not guaranteed to work if more than 32 bytes!
|
||||
// we will need to find out if some platforms have larger
|
||||
// I2C buffer sizes :/
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.println(F("\tI2CDevice could not write such a large buffer"));
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
_wire->beginTransmission(_addr);
|
||||
|
||||
// Write the prefix data (usually an address)
|
||||
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
|
||||
if (_wire->write(prefix_buffer, prefix_len) != prefix_len) {
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.println(F("\tI2CDevice failed to write"));
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Write the data itself
|
||||
if (_wire->write(buffer, len) != len) {
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.println(F("\tI2CDevice failed to write"));
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
|
||||
DEBUG_SERIAL.print(F("\tI2CWRITE @ 0x"));
|
||||
DEBUG_SERIAL.print(_addr, HEX);
|
||||
DEBUG_SERIAL.print(F(" :: "));
|
||||
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
|
||||
for (uint16_t i = 0; i < prefix_len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(prefix_buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
}
|
||||
}
|
||||
for (uint16_t i = 0; i < len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
if (i % 32 == 31) {
|
||||
DEBUG_SERIAL.println();
|
||||
}
|
||||
}
|
||||
|
||||
if (stop) {
|
||||
DEBUG_SERIAL.print("\tSTOP");
|
||||
}
|
||||
#endif
|
||||
|
||||
if (_wire->endTransmission(stop) == 0) {
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.println();
|
||||
// DEBUG_SERIAL.println("Sent!");
|
||||
#endif
|
||||
return true;
|
||||
} else {
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.println("\tFailed to send!");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Read from I2C into a buffer from the I2C device.
|
||||
* Cannot be more than maxBufferSize() bytes.
|
||||
* @param buffer Pointer to buffer of data to read into
|
||||
* @param len Number of bytes from buffer to read.
|
||||
* @param stop Whether to send an I2C STOP signal on read
|
||||
* @return True if read was successful, otherwise false.
|
||||
*/
|
||||
bool Adafruit_I2CDevice::read(uint8_t *buffer, size_t len, bool stop) {
|
||||
size_t pos = 0;
|
||||
while (pos < len) {
|
||||
size_t read_len =
|
||||
((len - pos) > maxBufferSize()) ? maxBufferSize() : (len - pos);
|
||||
bool read_stop = (pos < (len - read_len)) ? false : stop;
|
||||
if (!_read(buffer + pos, read_len, read_stop))
|
||||
return false;
|
||||
pos += read_len;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Adafruit_I2CDevice::_read(uint8_t *buffer, size_t len, bool stop) {
|
||||
#if defined(TinyWireM_h)
|
||||
size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len);
|
||||
#elif defined(ARDUINO_ARCH_MEGAAVR)
|
||||
size_t recv = _wire->requestFrom(_addr, len, stop);
|
||||
#else
|
||||
size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len, (uint8_t)stop);
|
||||
#endif
|
||||
|
||||
if (recv != len) {
|
||||
// Not enough data available to fulfill our obligation!
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.print(F("\tI2CDevice did not receive enough data: "));
|
||||
DEBUG_SERIAL.println(recv);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
for (uint16_t i = 0; i < len; i++) {
|
||||
buffer[i] = _wire->read();
|
||||
}
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.print(F("\tI2CREAD @ 0x"));
|
||||
DEBUG_SERIAL.print(_addr, HEX);
|
||||
DEBUG_SERIAL.print(F(" :: "));
|
||||
for (uint16_t i = 0; i < len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
if (len % 32 == 31) {
|
||||
DEBUG_SERIAL.println();
|
||||
}
|
||||
}
|
||||
DEBUG_SERIAL.println();
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write some data, then read some data from I2C into another buffer.
|
||||
* Cannot be more than maxBufferSize() bytes. The buffers can point to
|
||||
* same/overlapping locations.
|
||||
* @param write_buffer Pointer to buffer of data to write from
|
||||
* @param write_len Number of bytes from buffer to write.
|
||||
* @param read_buffer Pointer to buffer of data to read into.
|
||||
* @param read_len Number of bytes from buffer to read.
|
||||
* @param stop Whether to send an I2C STOP signal between the write and read
|
||||
* @return True if write & read was successful, otherwise false.
|
||||
*/
|
||||
bool Adafruit_I2CDevice::write_then_read(const uint8_t *write_buffer,
|
||||
size_t write_len, uint8_t *read_buffer,
|
||||
size_t read_len, bool stop) {
|
||||
if (!write(write_buffer, write_len, stop)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return read(read_buffer, read_len);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Returns the 7-bit address of this device
|
||||
* @return The 7-bit address of this device
|
||||
*/
|
||||
uint8_t Adafruit_I2CDevice::address(void) { return _addr; }
|
||||
|
||||
/*!
|
||||
* @brief Change the I2C clock speed to desired (relies on
|
||||
* underlying Wire support!
|
||||
* @param desiredclk The desired I2C SCL frequency
|
||||
* @return True if this platform supports changing I2C speed.
|
||||
* Not necessarily that the speed was achieved!
|
||||
*/
|
||||
bool Adafruit_I2CDevice::setSpeed(uint32_t desiredclk) {
|
||||
#if defined(__AVR_ATmega328__) || \
|
||||
defined(__AVR_ATmega328P__) // fix arduino core set clock
|
||||
// calculate TWBR correctly
|
||||
|
||||
if ((F_CPU / 18) < desiredclk) {
|
||||
#ifdef DEBUG_SERIAL
|
||||
Serial.println(F("I2C.setSpeed too high."));
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
uint32_t atwbr = ((F_CPU / desiredclk) - 16) / 2;
|
||||
if (atwbr > 16320) {
|
||||
#ifdef DEBUG_SERIAL
|
||||
Serial.println(F("I2C.setSpeed too low."));
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
if (atwbr <= 255) {
|
||||
atwbr /= 1;
|
||||
TWSR = 0x0;
|
||||
} else if (atwbr <= 1020) {
|
||||
atwbr /= 4;
|
||||
TWSR = 0x1;
|
||||
} else if (atwbr <= 4080) {
|
||||
atwbr /= 16;
|
||||
TWSR = 0x2;
|
||||
} else { // if (atwbr <= 16320)
|
||||
atwbr /= 64;
|
||||
TWSR = 0x3;
|
||||
}
|
||||
TWBR = atwbr;
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
Serial.print(F("TWSR prescaler = "));
|
||||
Serial.println(pow(4, TWSR));
|
||||
Serial.print(F("TWBR = "));
|
||||
Serial.println(atwbr);
|
||||
#endif
|
||||
return true;
|
||||
#elif (ARDUINO >= 157) && !defined(ARDUINO_STM32_FEATHER) && \
|
||||
!defined(TinyWireM_h)
|
||||
_wire->setClock(desiredclk);
|
||||
return true;
|
||||
|
||||
#else
|
||||
(void)desiredclk;
|
||||
return false;
|
||||
#endif
|
||||
}
|
36
Arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h
Normal file
36
Arduino/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h
Normal file
@ -0,0 +1,36 @@
|
||||
#ifndef Adafruit_I2CDevice_h
|
||||
#define Adafruit_I2CDevice_h
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
|
||||
///< The class which defines how we will talk to this device over I2C
|
||||
class Adafruit_I2CDevice {
|
||||
public:
|
||||
Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire = &Wire);
|
||||
uint8_t address(void);
|
||||
bool begin(bool addr_detect = true);
|
||||
void end(void);
|
||||
bool detected(void);
|
||||
|
||||
bool read(uint8_t *buffer, size_t len, bool stop = true);
|
||||
bool write(const uint8_t *buffer, size_t len, bool stop = true,
|
||||
const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0);
|
||||
bool write_then_read(const uint8_t *write_buffer, size_t write_len,
|
||||
uint8_t *read_buffer, size_t read_len,
|
||||
bool stop = false);
|
||||
bool setSpeed(uint32_t desiredclk);
|
||||
|
||||
/*! @brief How many bytes we can read in a transaction
|
||||
* @return The size of the Wire receive/transmit buffer */
|
||||
size_t maxBufferSize() { return _maxBufferSize; }
|
||||
|
||||
private:
|
||||
uint8_t _addr;
|
||||
TwoWire *_wire;
|
||||
bool _begun;
|
||||
size_t _maxBufferSize;
|
||||
bool _read(uint8_t *buffer, size_t len, bool stop);
|
||||
};
|
||||
|
||||
#endif // Adafruit_I2CDevice_h
|
10
Arduino/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h
Normal file
10
Arduino/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h
Normal file
@ -0,0 +1,10 @@
|
||||
#ifndef _ADAFRUIT_I2C_REGISTER_H_
|
||||
#define _ADAFRUIT_I2C_REGISTER_H_
|
||||
|
||||
#include <Adafruit_BusIO_Register.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
typedef Adafruit_BusIO_Register Adafruit_I2CRegister;
|
||||
typedef Adafruit_BusIO_RegisterBits Adafruit_I2CRegisterBits;
|
||||
|
||||
#endif
|
508
Arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp
Normal file
508
Arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp
Normal file
@ -0,0 +1,508 @@
|
||||
#include "Adafruit_SPIDevice.h"
|
||||
|
||||
// #define DEBUG_SERIAL Serial
|
||||
|
||||
/*!
|
||||
* @brief Create an SPI device with the given CS pin and settings
|
||||
* @param cspin The arduino pin number to use for chip select
|
||||
* @param freq The SPI clock frequency to use, defaults to 1MHz
|
||||
* @param dataOrder The SPI data order to use for bits within each byte,
|
||||
* defaults to SPI_BITORDER_MSBFIRST
|
||||
* @param dataMode The SPI mode to use, defaults to SPI_MODE0
|
||||
* @param theSPI The SPI bus to use, defaults to &theSPI
|
||||
*/
|
||||
Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, uint32_t freq,
|
||||
BusIOBitOrder dataOrder,
|
||||
uint8_t dataMode, SPIClass *theSPI) {
|
||||
#ifdef BUSIO_HAS_HW_SPI
|
||||
_cs = cspin;
|
||||
_sck = _mosi = _miso = -1;
|
||||
_spi = theSPI;
|
||||
_begun = false;
|
||||
_spiSetting = new SPISettings(freq, dataOrder, dataMode);
|
||||
_freq = freq;
|
||||
_dataOrder = dataOrder;
|
||||
_dataMode = dataMode;
|
||||
#else
|
||||
// unused, but needed to suppress compiler warns
|
||||
(void)cspin;
|
||||
(void)freq;
|
||||
(void)dataOrder;
|
||||
(void)dataMode;
|
||||
(void)theSPI;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Create an SPI device with the given CS pin and settings
|
||||
* @param cspin The arduino pin number to use for chip select
|
||||
* @param sckpin The arduino pin number to use for SCK
|
||||
* @param misopin The arduino pin number to use for MISO, set to -1 if not
|
||||
* used
|
||||
* @param mosipin The arduino pin number to use for MOSI, set to -1 if not
|
||||
* used
|
||||
* @param freq The SPI clock frequency to use, defaults to 1MHz
|
||||
* @param dataOrder The SPI data order to use for bits within each byte,
|
||||
* defaults to SPI_BITORDER_MSBFIRST
|
||||
* @param dataMode The SPI mode to use, defaults to SPI_MODE0
|
||||
*/
|
||||
Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, int8_t sckpin,
|
||||
int8_t misopin, int8_t mosipin,
|
||||
uint32_t freq, BusIOBitOrder dataOrder,
|
||||
uint8_t dataMode) {
|
||||
_cs = cspin;
|
||||
_sck = sckpin;
|
||||
_miso = misopin;
|
||||
_mosi = mosipin;
|
||||
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
csPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(cspin));
|
||||
csPinMask = digitalPinToBitMask(cspin);
|
||||
if (mosipin != -1) {
|
||||
mosiPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(mosipin));
|
||||
mosiPinMask = digitalPinToBitMask(mosipin);
|
||||
}
|
||||
if (misopin != -1) {
|
||||
misoPort = (BusIO_PortReg *)portInputRegister(digitalPinToPort(misopin));
|
||||
misoPinMask = digitalPinToBitMask(misopin);
|
||||
}
|
||||
clkPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(sckpin));
|
||||
clkPinMask = digitalPinToBitMask(sckpin);
|
||||
#endif
|
||||
|
||||
_freq = freq;
|
||||
_dataOrder = dataOrder;
|
||||
_dataMode = dataMode;
|
||||
_begun = false;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Release memory allocated in constructors
|
||||
*/
|
||||
Adafruit_SPIDevice::~Adafruit_SPIDevice() {
|
||||
if (_spiSetting)
|
||||
delete _spiSetting;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Initializes SPI bus and sets CS pin high
|
||||
* @return Always returns true because there's no way to test success of SPI
|
||||
* init
|
||||
*/
|
||||
bool Adafruit_SPIDevice::begin(void) {
|
||||
if (_cs != -1) {
|
||||
pinMode(_cs, OUTPUT);
|
||||
digitalWrite(_cs, HIGH);
|
||||
}
|
||||
|
||||
if (_spi) { // hardware SPI
|
||||
#ifdef BUSIO_HAS_HW_SPI
|
||||
_spi->begin();
|
||||
#endif
|
||||
} else {
|
||||
pinMode(_sck, OUTPUT);
|
||||
|
||||
if ((_dataMode == SPI_MODE0) || (_dataMode == SPI_MODE1)) {
|
||||
// idle low on mode 0 and 1
|
||||
digitalWrite(_sck, LOW);
|
||||
} else {
|
||||
// idle high on mode 2 or 3
|
||||
digitalWrite(_sck, HIGH);
|
||||
}
|
||||
if (_mosi != -1) {
|
||||
pinMode(_mosi, OUTPUT);
|
||||
digitalWrite(_mosi, HIGH);
|
||||
}
|
||||
if (_miso != -1) {
|
||||
pinMode(_miso, INPUT);
|
||||
}
|
||||
}
|
||||
|
||||
_begun = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Transfer (send/receive) a buffer over hard/soft SPI, without
|
||||
* transaction management
|
||||
* @param buffer The buffer to send and receive at the same time
|
||||
* @param len The number of bytes to transfer
|
||||
*/
|
||||
void Adafruit_SPIDevice::transfer(uint8_t *buffer, size_t len) {
|
||||
//
|
||||
// HARDWARE SPI
|
||||
//
|
||||
if (_spi) {
|
||||
#ifdef BUSIO_HAS_HW_SPI
|
||||
#if defined(SPARK)
|
||||
_spi->transfer(buffer, buffer, len, nullptr);
|
||||
#elif defined(STM32)
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
_spi->transfer(buffer[i]);
|
||||
}
|
||||
#else
|
||||
_spi->transfer(buffer, len);
|
||||
#endif
|
||||
return;
|
||||
#endif
|
||||
}
|
||||
|
||||
//
|
||||
// SOFTWARE SPI
|
||||
//
|
||||
uint8_t startbit;
|
||||
if (_dataOrder == SPI_BITORDER_LSBFIRST) {
|
||||
startbit = 0x1;
|
||||
} else {
|
||||
startbit = 0x80;
|
||||
}
|
||||
|
||||
bool towrite, lastmosi = !(buffer[0] & startbit);
|
||||
uint8_t bitdelay_us = (1000000 / _freq) / 2;
|
||||
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
uint8_t reply = 0;
|
||||
uint8_t send = buffer[i];
|
||||
|
||||
/*
|
||||
Serial.print("\tSending software SPI byte 0x");
|
||||
Serial.print(send, HEX);
|
||||
Serial.print(" -> 0x");
|
||||
*/
|
||||
|
||||
// Serial.print(send, HEX);
|
||||
for (uint8_t b = startbit; b != 0;
|
||||
b = (_dataOrder == SPI_BITORDER_LSBFIRST) ? b << 1 : b >> 1) {
|
||||
|
||||
if (bitdelay_us) {
|
||||
delayMicroseconds(bitdelay_us);
|
||||
}
|
||||
|
||||
if (_dataMode == SPI_MODE0 || _dataMode == SPI_MODE2) {
|
||||
towrite = send & b;
|
||||
if ((_mosi != -1) && (lastmosi != towrite)) {
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
if (towrite)
|
||||
*mosiPort = *mosiPort | mosiPinMask;
|
||||
else
|
||||
*mosiPort = *mosiPort & ~mosiPinMask;
|
||||
#else
|
||||
digitalWrite(_mosi, towrite);
|
||||
#endif
|
||||
lastmosi = towrite;
|
||||
}
|
||||
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
*clkPort = *clkPort | clkPinMask; // Clock high
|
||||
#else
|
||||
digitalWrite(_sck, HIGH);
|
||||
#endif
|
||||
|
||||
if (bitdelay_us) {
|
||||
delayMicroseconds(bitdelay_us);
|
||||
}
|
||||
|
||||
if (_miso != -1) {
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
if (*misoPort & misoPinMask) {
|
||||
#else
|
||||
if (digitalRead(_miso)) {
|
||||
#endif
|
||||
reply |= b;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
*clkPort = *clkPort & ~clkPinMask; // Clock low
|
||||
#else
|
||||
digitalWrite(_sck, LOW);
|
||||
#endif
|
||||
} else { // if (_dataMode == SPI_MODE1 || _dataMode == SPI_MODE3)
|
||||
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
*clkPort = *clkPort | clkPinMask; // Clock high
|
||||
#else
|
||||
digitalWrite(_sck, HIGH);
|
||||
#endif
|
||||
|
||||
if (bitdelay_us) {
|
||||
delayMicroseconds(bitdelay_us);
|
||||
}
|
||||
|
||||
if (_mosi != -1) {
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
if (send & b)
|
||||
*mosiPort = *mosiPort | mosiPinMask;
|
||||
else
|
||||
*mosiPort = *mosiPort & ~mosiPinMask;
|
||||
#else
|
||||
digitalWrite(_mosi, send & b);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
*clkPort = *clkPort & ~clkPinMask; // Clock low
|
||||
#else
|
||||
digitalWrite(_sck, LOW);
|
||||
#endif
|
||||
|
||||
if (_miso != -1) {
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
if (*misoPort & misoPinMask) {
|
||||
#else
|
||||
if (digitalRead(_miso)) {
|
||||
#endif
|
||||
reply |= b;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_miso != -1) {
|
||||
buffer[i] = reply;
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Transfer (send/receive) one byte over hard/soft SPI, without
|
||||
* transaction management
|
||||
* @param send The byte to send
|
||||
* @return The byte received while transmitting
|
||||
*/
|
||||
uint8_t Adafruit_SPIDevice::transfer(uint8_t send) {
|
||||
uint8_t data = send;
|
||||
transfer(&data, 1);
|
||||
return data;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Manually begin a transaction (calls beginTransaction if hardware
|
||||
* SPI)
|
||||
*/
|
||||
void Adafruit_SPIDevice::beginTransaction(void) {
|
||||
if (_spi) {
|
||||
#ifdef BUSIO_HAS_HW_SPI
|
||||
_spi->beginTransaction(*_spiSetting);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Manually end a transaction (calls endTransaction if hardware SPI)
|
||||
*/
|
||||
void Adafruit_SPIDevice::endTransaction(void) {
|
||||
if (_spi) {
|
||||
#ifdef BUSIO_HAS_HW_SPI
|
||||
_spi->endTransaction();
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Assert/Deassert the CS pin if it is defined
|
||||
* @param value The state the CS is set to
|
||||
*/
|
||||
void Adafruit_SPIDevice::setChipSelect(int value) {
|
||||
if (_cs != -1) {
|
||||
digitalWrite(_cs, value);
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write a buffer or two to the SPI device, with transaction
|
||||
* management.
|
||||
* @brief Manually begin a transaction (calls beginTransaction if hardware
|
||||
* SPI) with asserting the CS pin
|
||||
*/
|
||||
void Adafruit_SPIDevice::beginTransactionWithAssertingCS() {
|
||||
beginTransaction();
|
||||
setChipSelect(LOW);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Manually end a transaction (calls endTransaction if hardware SPI)
|
||||
* with deasserting the CS pin
|
||||
*/
|
||||
void Adafruit_SPIDevice::endTransactionWithDeassertingCS() {
|
||||
setChipSelect(HIGH);
|
||||
endTransaction();
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write a buffer or two to the SPI device, with transaction
|
||||
* management.
|
||||
* @param buffer Pointer to buffer of data to write
|
||||
* @param len Number of bytes from buffer to write
|
||||
* @param prefix_buffer Pointer to optional array of data to write before
|
||||
* buffer.
|
||||
* @param prefix_len Number of bytes from prefix buffer to write
|
||||
* @return Always returns true because there's no way to test success of SPI
|
||||
* writes
|
||||
*/
|
||||
bool Adafruit_SPIDevice::write(const uint8_t *buffer, size_t len,
|
||||
const uint8_t *prefix_buffer,
|
||||
size_t prefix_len) {
|
||||
beginTransactionWithAssertingCS();
|
||||
|
||||
// do the writing
|
||||
#if defined(ARDUINO_ARCH_ESP32)
|
||||
if (_spi) {
|
||||
if (prefix_len > 0) {
|
||||
_spi->transferBytes((uint8_t *)prefix_buffer, nullptr, prefix_len);
|
||||
}
|
||||
if (len > 0) {
|
||||
_spi->transferBytes((uint8_t *)buffer, nullptr, len);
|
||||
}
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
for (size_t i = 0; i < prefix_len; i++) {
|
||||
transfer(prefix_buffer[i]);
|
||||
}
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
transfer(buffer[i]);
|
||||
}
|
||||
}
|
||||
endTransactionWithDeassertingCS();
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.print(F("\tSPIDevice Wrote: "));
|
||||
if ((prefix_len != 0) && (prefix_buffer != nullptr)) {
|
||||
for (uint16_t i = 0; i < prefix_len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(prefix_buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
}
|
||||
}
|
||||
for (uint16_t i = 0; i < len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
if (i % 32 == 31) {
|
||||
DEBUG_SERIAL.println();
|
||||
}
|
||||
}
|
||||
DEBUG_SERIAL.println();
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Read from SPI into a buffer from the SPI device, with transaction
|
||||
* management.
|
||||
* @param buffer Pointer to buffer of data to read into
|
||||
* @param len Number of bytes from buffer to read.
|
||||
* @param sendvalue The 8-bits of data to write when doing the data read,
|
||||
* defaults to 0xFF
|
||||
* @return Always returns true because there's no way to test success of SPI
|
||||
* writes
|
||||
*/
|
||||
bool Adafruit_SPIDevice::read(uint8_t *buffer, size_t len, uint8_t sendvalue) {
|
||||
memset(buffer, sendvalue, len); // clear out existing buffer
|
||||
|
||||
beginTransactionWithAssertingCS();
|
||||
transfer(buffer, len);
|
||||
endTransactionWithDeassertingCS();
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.print(F("\tSPIDevice Read: "));
|
||||
for (uint16_t i = 0; i < len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
if (len % 32 == 31) {
|
||||
DEBUG_SERIAL.println();
|
||||
}
|
||||
}
|
||||
DEBUG_SERIAL.println();
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write some data, then read some data from SPI into another buffer,
|
||||
* with transaction management. The buffers can point to same/overlapping
|
||||
* locations. This does not transmit-receive at the same time!
|
||||
* @param write_buffer Pointer to buffer of data to write from
|
||||
* @param write_len Number of bytes from buffer to write.
|
||||
* @param read_buffer Pointer to buffer of data to read into.
|
||||
* @param read_len Number of bytes from buffer to read.
|
||||
* @param sendvalue The 8-bits of data to write when doing the data read,
|
||||
* defaults to 0xFF
|
||||
* @return Always returns true because there's no way to test success of SPI
|
||||
* writes
|
||||
*/
|
||||
bool Adafruit_SPIDevice::write_then_read(const uint8_t *write_buffer,
|
||||
size_t write_len, uint8_t *read_buffer,
|
||||
size_t read_len, uint8_t sendvalue) {
|
||||
beginTransactionWithAssertingCS();
|
||||
// do the writing
|
||||
#if defined(ARDUINO_ARCH_ESP32)
|
||||
if (_spi) {
|
||||
if (write_len > 0) {
|
||||
_spi->transferBytes((uint8_t *)write_buffer, nullptr, write_len);
|
||||
}
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
for (size_t i = 0; i < write_len; i++) {
|
||||
transfer(write_buffer[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.print(F("\tSPIDevice Wrote: "));
|
||||
for (uint16_t i = 0; i < write_len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(write_buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
if (write_len % 32 == 31) {
|
||||
DEBUG_SERIAL.println();
|
||||
}
|
||||
}
|
||||
DEBUG_SERIAL.println();
|
||||
#endif
|
||||
|
||||
// do the reading
|
||||
for (size_t i = 0; i < read_len; i++) {
|
||||
read_buffer[i] = transfer(sendvalue);
|
||||
}
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
DEBUG_SERIAL.print(F("\tSPIDevice Read: "));
|
||||
for (uint16_t i = 0; i < read_len; i++) {
|
||||
DEBUG_SERIAL.print(F("0x"));
|
||||
DEBUG_SERIAL.print(read_buffer[i], HEX);
|
||||
DEBUG_SERIAL.print(F(", "));
|
||||
if (read_len % 32 == 31) {
|
||||
DEBUG_SERIAL.println();
|
||||
}
|
||||
}
|
||||
DEBUG_SERIAL.println();
|
||||
#endif
|
||||
|
||||
endTransactionWithDeassertingCS();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Write some data and read some data at the same time from SPI
|
||||
* into the same buffer, with transaction management. This is basicaly a wrapper
|
||||
* for transfer() with CS-pin and transaction management. This /does/
|
||||
* transmit-receive at the same time!
|
||||
* @param buffer Pointer to buffer of data to write/read to/from
|
||||
* @param len Number of bytes from buffer to write/read.
|
||||
* @return Always returns true because there's no way to test success of SPI
|
||||
* writes
|
||||
*/
|
||||
bool Adafruit_SPIDevice::write_and_read(uint8_t *buffer, size_t len) {
|
||||
beginTransactionWithAssertingCS();
|
||||
transfer(buffer, len);
|
||||
endTransactionWithDeassertingCS();
|
||||
|
||||
return true;
|
||||
}
|
149
Arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h
Normal file
149
Arduino/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h
Normal file
@ -0,0 +1,149 @@
|
||||
#ifndef Adafruit_SPIDevice_h
|
||||
#define Adafruit_SPIDevice_h
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#if !defined(SPI_INTERFACES_COUNT) || \
|
||||
(defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0))
|
||||
// HW SPI available
|
||||
#include <SPI.h>
|
||||
#define BUSIO_HAS_HW_SPI
|
||||
#else
|
||||
// SW SPI ONLY
|
||||
enum { SPI_MODE0, SPI_MODE1, SPI_MODE2, _SPI_MODE4 };
|
||||
typedef uint8_t SPIClass;
|
||||
#endif
|
||||
|
||||
// some modern SPI definitions don't have BitOrder enum
|
||||
#if (defined(__AVR__) && !defined(ARDUINO_ARCH_MEGAAVR)) || \
|
||||
defined(ESP8266) || defined(TEENSYDUINO) || defined(SPARK) || \
|
||||
defined(ARDUINO_ARCH_SPRESENSE) || defined(MEGATINYCORE) || \
|
||||
defined(DXCORE) || defined(ARDUINO_AVR_ATmega4809) || \
|
||||
defined(ARDUINO_AVR_ATmega4808) || defined(ARDUINO_AVR_ATmega3209) || \
|
||||
defined(ARDUINO_AVR_ATmega3208) || defined(ARDUINO_AVR_ATmega1609) || \
|
||||
defined(ARDUINO_AVR_ATmega1608) || defined(ARDUINO_AVR_ATmega809) || \
|
||||
defined(ARDUINO_AVR_ATmega808) || defined(ARDUINO_ARCH_ARC32) || \
|
||||
defined(ARDUINO_ARCH_XMC)
|
||||
|
||||
typedef enum _BitOrder {
|
||||
SPI_BITORDER_MSBFIRST = MSBFIRST,
|
||||
SPI_BITORDER_LSBFIRST = LSBFIRST,
|
||||
} BusIOBitOrder;
|
||||
|
||||
#elif defined(ESP32) || defined(__ASR6501__) || defined(__ASR6502__)
|
||||
|
||||
// some modern SPI definitions don't have BitOrder enum and have different SPI
|
||||
// mode defines
|
||||
typedef enum _BitOrder {
|
||||
SPI_BITORDER_MSBFIRST = SPI_MSBFIRST,
|
||||
SPI_BITORDER_LSBFIRST = SPI_LSBFIRST,
|
||||
} BusIOBitOrder;
|
||||
|
||||
#else
|
||||
// Some platforms have a BitOrder enum but its named MSBFIRST/LSBFIRST
|
||||
#define SPI_BITORDER_MSBFIRST MSBFIRST
|
||||
#define SPI_BITORDER_LSBFIRST LSBFIRST
|
||||
typedef BitOrder BusIOBitOrder;
|
||||
#endif
|
||||
|
||||
#if defined(__IMXRT1062__) // Teensy 4.x
|
||||
// *Warning* I disabled the usage of FAST_PINIO as the set/clear operations
|
||||
// used in the cpp file are not atomic and can effect multiple IO pins
|
||||
// and if an interrupt happens in between the time the code reads the register
|
||||
// and writes out the updated value, that changes one or more other IO pins
|
||||
// on that same IO port, those change will be clobbered when the updated
|
||||
// values are written back. A fast version can be implemented that uses the
|
||||
// ports set and clear registers which are atomic.
|
||||
// typedef volatile uint32_t BusIO_PortReg;
|
||||
// typedef uint32_t BusIO_PortMask;
|
||||
// #define BUSIO_USE_FAST_PINIO
|
||||
|
||||
#elif defined(__MBED__) || defined(__ZEPHYR__)
|
||||
// Boards based on RTOS cores like mbed or Zephyr are not going to expose the
|
||||
// low level registers needed for fast pin manipulation
|
||||
#undef BUSIO_USE_FAST_PINIO
|
||||
|
||||
#elif defined(ARDUINO_ARCH_XMC)
|
||||
#undef BUSIO_USE_FAST_PINIO
|
||||
|
||||
#elif defined(__AVR__) || defined(TEENSYDUINO)
|
||||
typedef volatile uint8_t BusIO_PortReg;
|
||||
typedef uint8_t BusIO_PortMask;
|
||||
#define BUSIO_USE_FAST_PINIO
|
||||
|
||||
#elif defined(ESP8266) || defined(ESP32) || defined(__SAM3X8E__) || \
|
||||
defined(ARDUINO_ARCH_SAMD)
|
||||
typedef volatile uint32_t BusIO_PortReg;
|
||||
typedef uint32_t BusIO_PortMask;
|
||||
#define BUSIO_USE_FAST_PINIO
|
||||
|
||||
#elif (defined(__arm__) || defined(ARDUINO_FEATHER52)) && \
|
||||
!defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_SILABS) && \
|
||||
!defined(ARDUINO_UNOR4_MINIMA) && !defined(ARDUINO_UNOR4_WIFI) && \
|
||||
!defined(PORTDUINO)
|
||||
typedef volatile uint32_t BusIO_PortReg;
|
||||
typedef uint32_t BusIO_PortMask;
|
||||
#if !defined(__ASR6501__) && !defined(__ASR6502__)
|
||||
#define BUSIO_USE_FAST_PINIO
|
||||
#endif
|
||||
|
||||
#else
|
||||
#undef BUSIO_USE_FAST_PINIO
|
||||
#endif
|
||||
|
||||
/**! The class which defines how we will talk to this device over SPI **/
|
||||
class Adafruit_SPIDevice {
|
||||
public:
|
||||
#ifdef BUSIO_HAS_HW_SPI
|
||||
Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000,
|
||||
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
|
||||
uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = &SPI);
|
||||
#else
|
||||
Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000,
|
||||
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
|
||||
uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = nullptr);
|
||||
#endif
|
||||
Adafruit_SPIDevice(int8_t cspin, int8_t sck, int8_t miso, int8_t mosi,
|
||||
uint32_t freq = 1000000,
|
||||
BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST,
|
||||
uint8_t dataMode = SPI_MODE0);
|
||||
~Adafruit_SPIDevice();
|
||||
|
||||
bool begin(void);
|
||||
bool read(uint8_t *buffer, size_t len, uint8_t sendvalue = 0xFF);
|
||||
bool write(const uint8_t *buffer, size_t len,
|
||||
const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0);
|
||||
bool write_then_read(const uint8_t *write_buffer, size_t write_len,
|
||||
uint8_t *read_buffer, size_t read_len,
|
||||
uint8_t sendvalue = 0xFF);
|
||||
bool write_and_read(uint8_t *buffer, size_t len);
|
||||
|
||||
uint8_t transfer(uint8_t send);
|
||||
void transfer(uint8_t *buffer, size_t len);
|
||||
void beginTransaction(void);
|
||||
void endTransaction(void);
|
||||
void beginTransactionWithAssertingCS();
|
||||
void endTransactionWithDeassertingCS();
|
||||
|
||||
private:
|
||||
#ifdef BUSIO_HAS_HW_SPI
|
||||
SPIClass *_spi = nullptr;
|
||||
SPISettings *_spiSetting = nullptr;
|
||||
#else
|
||||
uint8_t *_spi = nullptr;
|
||||
uint8_t *_spiSetting = nullptr;
|
||||
#endif
|
||||
uint32_t _freq;
|
||||
BusIOBitOrder _dataOrder;
|
||||
uint8_t _dataMode;
|
||||
void setChipSelect(int value);
|
||||
|
||||
int8_t _cs, _sck, _mosi, _miso;
|
||||
#ifdef BUSIO_USE_FAST_PINIO
|
||||
BusIO_PortReg *mosiPort, *clkPort, *misoPort, *csPort;
|
||||
BusIO_PortMask mosiPinMask, misoPinMask, clkPinMask, csPinMask;
|
||||
#endif
|
||||
bool _begun;
|
||||
};
|
||||
|
||||
#endif // Adafruit_SPIDevice_h
|
11
Arduino/libraries/Adafruit_BusIO/CMakeLists.txt
Normal file
11
Arduino/libraries/Adafruit_BusIO/CMakeLists.txt
Normal file
@ -0,0 +1,11 @@
|
||||
# Adafruit Bus IO Library
|
||||
# https://github.com/adafruit/Adafruit_BusIO
|
||||
# MIT License
|
||||
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
idf_component_register(SRCS "Adafruit_I2CDevice.cpp" "Adafruit_BusIO_Register.cpp" "Adafruit_SPIDevice.cpp" "Adafruit_GenericDevice.cpp"
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES arduino-esp32)
|
||||
|
||||
project(Adafruit_BusIO)
|
21
Arduino/libraries/Adafruit_BusIO/LICENSE
Normal file
21
Arduino/libraries/Adafruit_BusIO/LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017 Adafruit Industries
|
||||
|
||||
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.
|
8
Arduino/libraries/Adafruit_BusIO/README.md
Normal file
8
Arduino/libraries/Adafruit_BusIO/README.md
Normal file
@ -0,0 +1,8 @@
|
||||
# Adafruit Bus IO Library [](https://github.com/adafruit/Adafruit_BusIO/actions)
|
||||
|
||||
|
||||
This is a helper library to abstract away I2C, SPI, and 'generic transport' (e.g. UART) transactions and registers
|
||||
|
||||
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
|
||||
|
||||
MIT license, all text above must be included in any redistribution
|
1
Arduino/libraries/Adafruit_BusIO/component.mk
Normal file
1
Arduino/libraries/Adafruit_BusIO/component.mk
Normal file
@ -0,0 +1 @@
|
||||
COMPONENT_ADD_INCLUDEDIRS = .
|
@ -0,0 +1,219 @@
|
||||
/*
|
||||
Advanced example of using bstracted transport for reading and writing
|
||||
register data from a UART-based device such as a TMC2209
|
||||
|
||||
Written with help by Claude!
|
||||
https://claude.ai/chat/335f50b1-3dd8-435e-9139-57ec7ca26a3c (at this time
|
||||
chats are not shareable :(
|
||||
*/
|
||||
|
||||
#include "Adafruit_BusIO_Register.h"
|
||||
#include "Adafruit_GenericDevice.h"
|
||||
|
||||
// Debugging macros
|
||||
#define DEBUG_SERIAL Serial
|
||||
|
||||
#ifdef DEBUG_SERIAL
|
||||
#define DEBUG_PRINT(x) DEBUG_SERIAL.print(x)
|
||||
#define DEBUG_PRINTLN(x) DEBUG_SERIAL.println(x)
|
||||
#define DEBUG_PRINT_HEX(x) \
|
||||
do { \
|
||||
if (x < 0x10) \
|
||||
DEBUG_SERIAL.print('0'); \
|
||||
DEBUG_SERIAL.print(x, HEX); \
|
||||
DEBUG_SERIAL.print(' '); \
|
||||
} while (0)
|
||||
#else
|
||||
#define DEBUG_PRINT(x)
|
||||
#define DEBUG_PRINTLN(x)
|
||||
#define DEBUG_PRINT_HEX(x)
|
||||
#endif
|
||||
|
||||
#define TMC2209_IOIN 0x06
|
||||
|
||||
class TMC2209_UART {
|
||||
private:
|
||||
Stream *_uart_stream;
|
||||
uint8_t _addr;
|
||||
|
||||
static bool uart_read(void *thiz, uint8_t *buffer, size_t len) {
|
||||
TMC2209_UART *dev = (TMC2209_UART *)thiz;
|
||||
uint16_t timeout = 100;
|
||||
while (dev->_uart_stream->available() < len && timeout--) {
|
||||
delay(1);
|
||||
}
|
||||
if (timeout == 0) {
|
||||
DEBUG_PRINTLN("Read timeout!");
|
||||
return false;
|
||||
}
|
||||
|
||||
DEBUG_PRINT("Reading: ");
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
buffer[i] = dev->_uart_stream->read();
|
||||
DEBUG_PRINT_HEX(buffer[i]);
|
||||
}
|
||||
DEBUG_PRINTLN("");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool uart_write(void *thiz, const uint8_t *buffer, size_t len) {
|
||||
TMC2209_UART *dev = (TMC2209_UART *)thiz;
|
||||
DEBUG_PRINT("Writing: ");
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
DEBUG_PRINT_HEX(buffer[i]);
|
||||
}
|
||||
DEBUG_PRINTLN("");
|
||||
|
||||
dev->_uart_stream->write(buffer, len);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool uart_readreg(void *thiz, uint8_t *addr_buf, uint8_t addrsiz,
|
||||
uint8_t *data, uint16_t datalen) {
|
||||
TMC2209_UART *dev = (TMC2209_UART *)thiz;
|
||||
while (dev->_uart_stream->available())
|
||||
dev->_uart_stream->read();
|
||||
|
||||
uint8_t packet[4] = {0x05, uint8_t(dev->_addr << 1), addr_buf[0], 0x00};
|
||||
|
||||
packet[3] = calcCRC(packet, 3);
|
||||
if (!uart_write(thiz, packet, 4))
|
||||
return false;
|
||||
|
||||
// Read back echo
|
||||
uint8_t echo[4];
|
||||
if (!uart_read(thiz, echo, 4))
|
||||
return false;
|
||||
|
||||
// Verify echo
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
if (echo[i] != packet[i]) {
|
||||
DEBUG_PRINTLN("Echo mismatch");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t response[8]; // sync + 0xFF + reg + 4 data bytes + CRC
|
||||
if (!uart_read(thiz, response, 8))
|
||||
return false;
|
||||
|
||||
// Verify response
|
||||
if (response[0] != 0x05) {
|
||||
DEBUG_PRINTLN("Invalid sync byte");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (response[1] != 0xFF) {
|
||||
DEBUG_PRINTLN("Invalid reply address");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (response[2] != addr_buf[0]) {
|
||||
DEBUG_PRINTLN("Register mismatch");
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t crc = calcCRC(response, 7);
|
||||
if (crc != response[7]) {
|
||||
DEBUG_PRINTLN("CRC mismatch");
|
||||
return false;
|
||||
}
|
||||
|
||||
memcpy(data, &response[3], 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool uart_writereg(void *thiz, uint8_t *addr_buf, uint8_t addrsiz,
|
||||
const uint8_t *data, uint16_t datalen) {
|
||||
TMC2209_UART *dev = (TMC2209_UART *)thiz;
|
||||
while (dev->_uart_stream->available())
|
||||
dev->_uart_stream->read();
|
||||
|
||||
uint8_t packet[8] = {0x05,
|
||||
uint8_t(dev->_addr << 1),
|
||||
uint8_t(addr_buf[0] | 0x80),
|
||||
data[0],
|
||||
data[1],
|
||||
data[2],
|
||||
data[3],
|
||||
0x00};
|
||||
|
||||
packet[7] = calcCRC(packet, 7);
|
||||
if (!uart_write(thiz, packet, 8))
|
||||
return false;
|
||||
|
||||
uint8_t echo[8];
|
||||
if (!uart_read(thiz, echo, 8))
|
||||
return false;
|
||||
|
||||
for (uint8_t i = 0; i < 8; i++) {
|
||||
if (echo[i] != packet[i]) {
|
||||
DEBUG_PRINTLN("Write echo mismatch");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static uint8_t calcCRC(uint8_t *data, uint8_t length) {
|
||||
uint8_t crc = 0;
|
||||
for (uint8_t i = 0; i < length; i++) {
|
||||
uint8_t currentByte = data[i];
|
||||
for (uint8_t j = 0; j < 8; j++) {
|
||||
if ((crc >> 7) ^ (currentByte & 0x01)) {
|
||||
crc = (crc << 1) ^ 0x07;
|
||||
} else {
|
||||
crc = crc << 1;
|
||||
}
|
||||
currentByte = currentByte >> 1;
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
public:
|
||||
TMC2209_UART(Stream *serial, uint8_t addr)
|
||||
: _uart_stream(serial), _addr(addr) {}
|
||||
|
||||
Adafruit_GenericDevice *createDevice() {
|
||||
return new Adafruit_GenericDevice(this, uart_read, uart_write, uart_readreg,
|
||||
uart_writereg);
|
||||
}
|
||||
};
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
delay(100);
|
||||
Serial.println("TMC2209 Generic Device register read/write test!");
|
||||
|
||||
Serial1.begin(115200);
|
||||
|
||||
TMC2209_UART uart(&Serial1, 0);
|
||||
Adafruit_GenericDevice *device = uart.createDevice();
|
||||
device->begin();
|
||||
|
||||
// Create register object for IOIN
|
||||
Adafruit_BusIO_Register ioin_reg(device,
|
||||
TMC2209_IOIN, // device and register address
|
||||
4, // width = 4 bytes
|
||||
MSBFIRST, // byte order
|
||||
1); // address width = 1 byte
|
||||
Serial.print("IOIN = 0x");
|
||||
Serial.println(ioin_reg.read(), HEX);
|
||||
|
||||
// Create RegisterBits for VERSION field (bits 31:24)
|
||||
Adafruit_BusIO_RegisterBits version_bits(
|
||||
&ioin_reg, 8, 24); // 8 bits wide, starting at bit 24
|
||||
|
||||
Serial.println("Reading VERSION...");
|
||||
uint8_t version = version_bits.read();
|
||||
|
||||
Serial.print("VERSION = 0x");
|
||||
Serial.println(version, HEX);
|
||||
}
|
||||
|
||||
void loop() { delay(1000); }
|
@ -0,0 +1,98 @@
|
||||
/*
|
||||
Abstracted transport for reading and writing data from a UART-based
|
||||
device such as a TMC2209
|
||||
|
||||
Written with help by Claude!
|
||||
https://claude.ai/chat/335f50b1-3dd8-435e-9139-57ec7ca26a3c (at this time
|
||||
chats are not shareable :(
|
||||
*/
|
||||
|
||||
#include "Adafruit_GenericDevice.h"
|
||||
|
||||
/**
|
||||
* Basic UART device class that demonstrates using GenericDevice with a Stream
|
||||
* interface. This example shows how to wrap a Stream (like HardwareSerial or
|
||||
* SoftwareSerial) with read/write callbacks that can be used by BusIO's
|
||||
* register functions.
|
||||
*/
|
||||
class UARTDevice {
|
||||
public:
|
||||
UARTDevice(Stream *serial) : _serial(serial) {}
|
||||
|
||||
// Static callback for writing data to UART
|
||||
// Called by GenericDevice when data needs to be sent
|
||||
static bool uart_write(void *thiz, const uint8_t *buffer, size_t len) {
|
||||
UARTDevice *dev = (UARTDevice *)thiz;
|
||||
dev->_serial->write(buffer, len);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Static callback for reading data from UART
|
||||
// Includes timeout and will return false if not enough data available
|
||||
static bool uart_read(void *thiz, uint8_t *buffer, size_t len) {
|
||||
UARTDevice *dev = (UARTDevice *)thiz;
|
||||
uint16_t timeout = 100;
|
||||
while (dev->_serial->available() < len && timeout--) {
|
||||
delay(1);
|
||||
}
|
||||
if (timeout == 0) {
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
buffer[i] = dev->_serial->read();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Create a GenericDevice instance using our callbacks
|
||||
Adafruit_GenericDevice *createDevice() {
|
||||
return new Adafruit_GenericDevice(this, uart_read, uart_write);
|
||||
}
|
||||
|
||||
private:
|
||||
Stream *_serial; // Underlying Stream instance (HardwareSerial, etc)
|
||||
};
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
delay(100);
|
||||
|
||||
Serial.println("Generic Device test!");
|
||||
|
||||
// Initialize UART for device communication
|
||||
Serial1.begin(115200);
|
||||
|
||||
// Create UART wrapper and BusIO device
|
||||
UARTDevice uart(&Serial1);
|
||||
Adafruit_GenericDevice *device = uart.createDevice();
|
||||
device->begin();
|
||||
|
||||
// Test write/read cycle
|
||||
uint8_t write_buf[4] = {0x5, 0x0, 0x0, 0x48};
|
||||
uint8_t read_buf[8];
|
||||
|
||||
Serial.println("Writing data...");
|
||||
if (!device->write(write_buf, 4)) {
|
||||
Serial.println("Write failed!");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.println("Reading response...");
|
||||
if (!device->read(read_buf, 8)) {
|
||||
Serial.println("Read failed!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Print response bytes
|
||||
Serial.print("Got response: ");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
Serial.print("0x");
|
||||
Serial.print(read_buf[i], HEX);
|
||||
Serial.print(" ");
|
||||
}
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
void loop() { delay(1000); }
|
@ -0,0 +1,22 @@
|
||||
#include <Adafruit_I2CDevice.h>
|
||||
|
||||
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(0x10);
|
||||
|
||||
void setup() {
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("I2C address detection test");
|
||||
|
||||
if (!i2c_dev.begin()) {
|
||||
Serial.print("Did not find device at 0x");
|
||||
Serial.println(i2c_dev.address(), HEX);
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
Serial.print("Device found on address 0x");
|
||||
Serial.println(i2c_dev.address(), HEX);
|
||||
}
|
||||
|
||||
void loop() {}
|
@ -0,0 +1,45 @@
|
||||
#include <Adafruit_I2CDevice.h>
|
||||
|
||||
#define I2C_ADDRESS 0x60
|
||||
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS);
|
||||
|
||||
void setup() {
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("I2C device read and write test");
|
||||
|
||||
if (!i2c_dev.begin()) {
|
||||
Serial.print("Did not find device at 0x");
|
||||
Serial.println(i2c_dev.address(), HEX);
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
Serial.print("Device found on address 0x");
|
||||
Serial.println(i2c_dev.address(), HEX);
|
||||
|
||||
uint8_t buffer[32];
|
||||
// Try to read 32 bytes
|
||||
i2c_dev.read(buffer, 32);
|
||||
Serial.print("Read: ");
|
||||
for (uint8_t i = 0; i < 32; i++) {
|
||||
Serial.print("0x");
|
||||
Serial.print(buffer[i], HEX);
|
||||
Serial.print(", ");
|
||||
}
|
||||
Serial.println();
|
||||
|
||||
// read a register by writing first, then reading
|
||||
buffer[0] = 0x0C; // we'll reuse the same buffer
|
||||
i2c_dev.write_then_read(buffer, 1, buffer, 2, false);
|
||||
Serial.print("Write then Read: ");
|
||||
for (uint8_t i = 0; i < 2; i++) {
|
||||
Serial.print("0x");
|
||||
Serial.print(buffer[i], HEX);
|
||||
Serial.print(", ");
|
||||
}
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
void loop() {}
|
@ -0,0 +1,43 @@
|
||||
#include <Adafruit_BusIO_Register.h>
|
||||
#include <Adafruit_I2CDevice.h>
|
||||
|
||||
#define I2C_ADDRESS 0x60
|
||||
Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS);
|
||||
|
||||
void setup() {
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("I2C device register test");
|
||||
|
||||
if (!i2c_dev.begin()) {
|
||||
Serial.print("Did not find device at 0x");
|
||||
Serial.println(i2c_dev.address(), HEX);
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
Serial.print("Device found on address 0x");
|
||||
Serial.println(i2c_dev.address(), HEX);
|
||||
|
||||
Adafruit_BusIO_Register id_reg =
|
||||
Adafruit_BusIO_Register(&i2c_dev, 0x0C, 2, LSBFIRST);
|
||||
uint16_t id;
|
||||
id_reg.read(&id);
|
||||
Serial.print("ID register = 0x");
|
||||
Serial.println(id, HEX);
|
||||
|
||||
Adafruit_BusIO_Register thresh_reg =
|
||||
Adafruit_BusIO_Register(&i2c_dev, 0x01, 2, LSBFIRST);
|
||||
uint16_t thresh;
|
||||
thresh_reg.read(&thresh);
|
||||
Serial.print("Initial threshold register = 0x");
|
||||
Serial.println(thresh, HEX);
|
||||
|
||||
thresh_reg.write(~thresh);
|
||||
|
||||
Serial.print("Post threshold register = 0x");
|
||||
Serial.println(thresh_reg.read(), HEX);
|
||||
}
|
||||
|
||||
void loop() {}
|
@ -0,0 +1,40 @@
|
||||
#include <Adafruit_BusIO_Register.h>
|
||||
|
||||
// Define which interface to use by setting the unused interface to NULL!
|
||||
|
||||
#define SPIDEVICE_CS 10
|
||||
Adafruit_SPIDevice *spi_dev = NULL; // new Adafruit_SPIDevice(SPIDEVICE_CS);
|
||||
|
||||
#define I2C_ADDRESS 0x5D
|
||||
Adafruit_I2CDevice *i2c_dev = new Adafruit_I2CDevice(I2C_ADDRESS);
|
||||
|
||||
void setup() {
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("I2C or SPI device register test");
|
||||
|
||||
if (spi_dev && !spi_dev->begin()) {
|
||||
Serial.println("Could not initialize SPI device");
|
||||
}
|
||||
|
||||
if (i2c_dev) {
|
||||
if (i2c_dev->begin()) {
|
||||
Serial.print("Device found on I2C address 0x");
|
||||
Serial.println(i2c_dev->address(), HEX);
|
||||
} else {
|
||||
Serial.print("Did not find I2C device at 0x");
|
||||
Serial.println(i2c_dev->address(), HEX);
|
||||
}
|
||||
}
|
||||
|
||||
Adafruit_BusIO_Register id_reg =
|
||||
Adafruit_BusIO_Register(i2c_dev, spi_dev, ADDRBIT8_HIGH_TOREAD, 0x0F);
|
||||
uint8_t id = 0;
|
||||
id_reg.read(&id);
|
||||
Serial.print("ID register = 0x");
|
||||
Serial.println(id, HEX);
|
||||
}
|
||||
|
||||
void loop() {}
|
@ -0,0 +1,35 @@
|
||||
#include <Adafruit_SPIDevice.h>
|
||||
|
||||
#define SPIDEVICE_CS 10
|
||||
Adafruit_SPIDevice spi_dev =
|
||||
Adafruit_SPIDevice(SPIDEVICE_CS, 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1);
|
||||
// Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS, 13, 12, 11,
|
||||
// 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1);
|
||||
|
||||
void setup() {
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("SPI device mode test");
|
||||
|
||||
if (!spi_dev.begin()) {
|
||||
Serial.println("Could not initialize SPI device");
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
Serial.println("\n\nTransfer test");
|
||||
for (uint16_t x = 0; x <= 0xFF; x++) {
|
||||
uint8_t i = x;
|
||||
Serial.print("0x");
|
||||
Serial.print(i, HEX);
|
||||
spi_dev.read(&i, 1, i);
|
||||
Serial.print("/");
|
||||
Serial.print(i, HEX);
|
||||
Serial.print(", ");
|
||||
delay(25);
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
#include <Adafruit_SPIDevice.h>
|
||||
|
||||
#define SPIDEVICE_CS 10
|
||||
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS);
|
||||
|
||||
void setup() {
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("SPI device read and write test");
|
||||
|
||||
if (!spi_dev.begin()) {
|
||||
Serial.println("Could not initialize SPI device");
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
|
||||
uint8_t buffer[32];
|
||||
|
||||
// Try to read 32 bytes
|
||||
spi_dev.read(buffer, 32);
|
||||
Serial.print("Read: ");
|
||||
for (uint8_t i = 0; i < 32; i++) {
|
||||
Serial.print("0x");
|
||||
Serial.print(buffer[i], HEX);
|
||||
Serial.print(", ");
|
||||
}
|
||||
Serial.println();
|
||||
|
||||
// read a register by writing first, then reading
|
||||
buffer[0] = 0x8F; // we'll reuse the same buffer
|
||||
spi_dev.write_then_read(buffer, 1, buffer, 2, false);
|
||||
Serial.print("Write then Read: ");
|
||||
for (uint8_t i = 0; i < 2; i++) {
|
||||
Serial.print("0x");
|
||||
Serial.print(buffer[i], HEX);
|
||||
Serial.print(", ");
|
||||
}
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
void loop() {}
|
@ -0,0 +1,268 @@
|
||||
/***************************************************
|
||||
|
||||
This is an example for how to use Adafruit_BusIO_RegisterBits from
|
||||
Adafruit_BusIO library.
|
||||
|
||||
Designed specifically to work with the Adafruit RTD Sensor
|
||||
----> https://www.adafruit.com/products/3328
|
||||
uisng a MAX31865 RTD-to-Digital Converter
|
||||
----> https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf
|
||||
|
||||
This sensor uses SPI to communicate, 4 pins are required to
|
||||
interface.
|
||||
A fifth pin helps to detect when a new conversion is ready.
|
||||
|
||||
Adafruit invests time and resources providing this open source code,
|
||||
please support Adafruit and open-source hardware by purchasing
|
||||
products from Adafruit!
|
||||
|
||||
Example written (2020/3) by Andreas Hardtung/AnHard.
|
||||
BSD license, all text above must be included in any redistribution
|
||||
****************************************************/
|
||||
|
||||
#include <Adafruit_BusIO_Register.h>
|
||||
#include <Adafruit_SPIDevice.h>
|
||||
|
||||
#define MAX31865_SPI_SPEED (5000000)
|
||||
#define MAX31865_SPI_BITORDER (SPI_BITORDER_MSBFIRST)
|
||||
#define MAX31865_SPI_MODE (SPI_MODE1)
|
||||
|
||||
#define MAX31865_SPI_CS (10)
|
||||
#define MAX31865_READY_PIN (2)
|
||||
|
||||
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(
|
||||
MAX31865_SPI_CS, MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER,
|
||||
MAX31865_SPI_MODE, &SPI); // Hardware SPI
|
||||
// Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice( MAX31865_SPI_CS, 13, 12, 11,
|
||||
// MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER, MAX31865_SPI_MODE); // Software
|
||||
// SPI
|
||||
|
||||
// MAX31865 chip related
|
||||
// *********************************************************************************************
|
||||
Adafruit_BusIO_Register config_reg =
|
||||
Adafruit_BusIO_Register(&spi_dev, 0x00, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST);
|
||||
Adafruit_BusIO_RegisterBits bias_bit =
|
||||
Adafruit_BusIO_RegisterBits(&config_reg, 1, 7);
|
||||
Adafruit_BusIO_RegisterBits auto_bit =
|
||||
Adafruit_BusIO_RegisterBits(&config_reg, 1, 6);
|
||||
Adafruit_BusIO_RegisterBits oneS_bit =
|
||||
Adafruit_BusIO_RegisterBits(&config_reg, 1, 5);
|
||||
Adafruit_BusIO_RegisterBits wire_bit =
|
||||
Adafruit_BusIO_RegisterBits(&config_reg, 1, 4);
|
||||
Adafruit_BusIO_RegisterBits faultT_bits =
|
||||
Adafruit_BusIO_RegisterBits(&config_reg, 2, 2);
|
||||
Adafruit_BusIO_RegisterBits faultR_bit =
|
||||
Adafruit_BusIO_RegisterBits(&config_reg, 1, 1);
|
||||
Adafruit_BusIO_RegisterBits fi50hz_bit =
|
||||
Adafruit_BusIO_RegisterBits(&config_reg, 1, 0);
|
||||
|
||||
Adafruit_BusIO_Register rRatio_reg =
|
||||
Adafruit_BusIO_Register(&spi_dev, 0x01, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
|
||||
Adafruit_BusIO_RegisterBits rRatio_bits =
|
||||
Adafruit_BusIO_RegisterBits(&rRatio_reg, 15, 1);
|
||||
Adafruit_BusIO_RegisterBits fault_bit =
|
||||
Adafruit_BusIO_RegisterBits(&rRatio_reg, 1, 0);
|
||||
|
||||
Adafruit_BusIO_Register maxRratio_reg =
|
||||
Adafruit_BusIO_Register(&spi_dev, 0x03, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
|
||||
Adafruit_BusIO_RegisterBits maxRratio_bits =
|
||||
Adafruit_BusIO_RegisterBits(&maxRratio_reg, 15, 1);
|
||||
|
||||
Adafruit_BusIO_Register minRratio_reg =
|
||||
Adafruit_BusIO_Register(&spi_dev, 0x05, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST);
|
||||
Adafruit_BusIO_RegisterBits minRratio_bits =
|
||||
Adafruit_BusIO_RegisterBits(&minRratio_reg, 15, 1);
|
||||
|
||||
Adafruit_BusIO_Register fault_reg =
|
||||
Adafruit_BusIO_Register(&spi_dev, 0x07, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST);
|
||||
Adafruit_BusIO_RegisterBits range_high_fault_bit =
|
||||
Adafruit_BusIO_RegisterBits(&fault_reg, 1, 7);
|
||||
Adafruit_BusIO_RegisterBits range_low_fault_bit =
|
||||
Adafruit_BusIO_RegisterBits(&fault_reg, 1, 6);
|
||||
Adafruit_BusIO_RegisterBits refin_high_fault_bit =
|
||||
Adafruit_BusIO_RegisterBits(&fault_reg, 1, 5);
|
||||
Adafruit_BusIO_RegisterBits refin_low_fault_bit =
|
||||
Adafruit_BusIO_RegisterBits(&fault_reg, 1, 4);
|
||||
Adafruit_BusIO_RegisterBits rtdin_low_fault_bit =
|
||||
Adafruit_BusIO_RegisterBits(&fault_reg, 1, 3);
|
||||
Adafruit_BusIO_RegisterBits voltage_fault_bit =
|
||||
Adafruit_BusIO_RegisterBits(&fault_reg, 1, 2);
|
||||
|
||||
// Print the details of the configuration register.
|
||||
void printConfig(void) {
|
||||
Serial.print("BIAS: ");
|
||||
if (bias_bit.read())
|
||||
Serial.print("ON");
|
||||
else
|
||||
Serial.print("OFF");
|
||||
Serial.print(", AUTO: ");
|
||||
if (auto_bit.read())
|
||||
Serial.print("ON");
|
||||
else
|
||||
Serial.print("OFF");
|
||||
Serial.print(", ONES: ");
|
||||
if (oneS_bit.read())
|
||||
Serial.print("ON");
|
||||
else
|
||||
Serial.print("OFF");
|
||||
Serial.print(", WIRE: ");
|
||||
if (wire_bit.read())
|
||||
Serial.print("3");
|
||||
else
|
||||
Serial.print("2/4");
|
||||
Serial.print(", FAULTCLEAR: ");
|
||||
if (faultR_bit.read())
|
||||
Serial.print("ON");
|
||||
else
|
||||
Serial.print("OFF");
|
||||
Serial.print(", ");
|
||||
if (fi50hz_bit.read())
|
||||
Serial.print("50HZ");
|
||||
else
|
||||
Serial.print("60HZ");
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
// Check and print faults. Then clear them.
|
||||
void checkFaults(void) {
|
||||
if (fault_bit.read()) {
|
||||
Serial.print("MAX: ");
|
||||
Serial.println(maxRratio_bits.read());
|
||||
Serial.print("VAL: ");
|
||||
Serial.println(rRatio_bits.read());
|
||||
Serial.print("MIN: ");
|
||||
Serial.println(minRratio_bits.read());
|
||||
|
||||
if (range_high_fault_bit.read())
|
||||
Serial.println("Range high fault");
|
||||
if (range_low_fault_bit.read())
|
||||
Serial.println("Range low fault");
|
||||
if (refin_high_fault_bit.read())
|
||||
Serial.println("REFIN high fault");
|
||||
if (refin_low_fault_bit.read())
|
||||
Serial.println("REFIN low fault");
|
||||
if (rtdin_low_fault_bit.read())
|
||||
Serial.println("RTDIN low fault");
|
||||
if (voltage_fault_bit.read())
|
||||
Serial.println("Voltage fault");
|
||||
|
||||
faultR_bit.write(1); // clear fault
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
#if (MAX31865_1_READY_PIN != -1)
|
||||
pinMode(MAX31865_READY_PIN, INPUT_PULLUP);
|
||||
#endif
|
||||
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("SPI Adafruit_BusIO_RegisterBits test on MAX31865");
|
||||
|
||||
if (!spi_dev.begin()) {
|
||||
Serial.println("Could not initialize SPI device");
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
|
||||
// Set up for automode 50Hz. We don't care about selfheating. We want the
|
||||
// highest possible sampling rate.
|
||||
auto_bit.write(0); // Don't switch filtermode while auto_mode is on.
|
||||
fi50hz_bit.write(1); // Set filter to 50Hz mode.
|
||||
faultR_bit.write(1); // Clear faults.
|
||||
bias_bit.write(1); // In automode we want to have the bias current always on.
|
||||
delay(5); // Wait until bias current settles down.
|
||||
// 10.5 time constants of the input RC network is required.
|
||||
// 10ms worst case for 10kω reference resistor and a 0.1µF capacitor
|
||||
// across the RTD inputs. Adafruit Module has 0.1µF and only
|
||||
// 430/4300ω So here 0.43/4.3ms
|
||||
auto_bit.write(
|
||||
1); // Now we can set automode. Automatically starting first conversion.
|
||||
|
||||
// Test the READY_PIN
|
||||
#if (defined(MAX31865_READY_PIN) && (MAX31865_READY_PIN != -1))
|
||||
int i = 0;
|
||||
while (digitalRead(MAX31865_READY_PIN) && i++ <= 100) {
|
||||
delay(1);
|
||||
}
|
||||
if (i >= 100) {
|
||||
Serial.print("ERROR: Max31865 Pin detection does not work. PIN:");
|
||||
Serial.println(MAX31865_READY_PIN);
|
||||
}
|
||||
#else
|
||||
delay(100);
|
||||
#endif
|
||||
|
||||
// Set ratio range.
|
||||
// Setting the temperatures would need some more calculation - not related to
|
||||
// Adafruit_BusIO_RegisterBits.
|
||||
uint16_t ratio = rRatio_bits.read();
|
||||
maxRratio_bits.write((ratio < 0x8fffu - 1000u) ? ratio + 1000u : 0x8fffu);
|
||||
minRratio_bits.write((ratio > 1000u) ? ratio - 1000u : 0u);
|
||||
|
||||
printConfig();
|
||||
checkFaults();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
#if (defined(MAX31865_READY_PIN) && (MAX31865_1_READY_PIN != -1))
|
||||
// Is conversion ready?
|
||||
if (!digitalRead(MAX31865_READY_PIN))
|
||||
#else
|
||||
// Warant conversion is ready.
|
||||
delay(21); // 21ms for 50Hz-mode. 19ms in 60Hz-mode.
|
||||
#endif
|
||||
{
|
||||
// Read ratio, calculate temperature, scale, filter and print.
|
||||
Serial.println(rRatio2C(rRatio_bits.read()) * 100.0f,
|
||||
0); // Temperature scaled by 100
|
||||
// Check, print, clear faults.
|
||||
checkFaults();
|
||||
}
|
||||
|
||||
// Do something else.
|
||||
// delay(15000);
|
||||
}
|
||||
|
||||
// Module/Sensor related. Here Adafruit PT100 module with a 2_Wire PT100 Class C
|
||||
// *****************************
|
||||
float rRatio2C(uint16_t ratio) {
|
||||
// A simple linear conversion.
|
||||
const float R0 = 100.0f;
|
||||
const float Rref = 430.0f;
|
||||
const float alphaPT = 0.003850f;
|
||||
const float ADCmax = (1u << 15) - 1.0f;
|
||||
const float rscale = Rref / ADCmax;
|
||||
// Measured temperature in boiling water 101.08°C with factor a = 1 and b = 0.
|
||||
// Rref and MAX at about 22±2°C. Measured temperature in ice/water bath 0.76°C
|
||||
// with factor a = 1 and b = 0. Rref and MAX at about 22±2°C.
|
||||
// const float a = 1.0f / (alphaPT * R0);
|
||||
const float a = (100.0f / 101.08f) / (alphaPT * R0);
|
||||
// const float b = 0.0f; // 101.08
|
||||
const float b = -0.76f; // 100.32 > 101.08
|
||||
|
||||
return filterRing(((ratio * rscale) - R0) * a + b);
|
||||
}
|
||||
|
||||
// General purpose
|
||||
// *********************************************************************************************
|
||||
#define RINGLENGTH 250
|
||||
float filterRing(float newVal) {
|
||||
static float ring[RINGLENGTH] = {0.0};
|
||||
static uint8_t ringIndex = 0;
|
||||
static bool ringFull = false;
|
||||
|
||||
if (ringIndex == RINGLENGTH) {
|
||||
ringFull = true;
|
||||
ringIndex = 0;
|
||||
}
|
||||
ring[ringIndex] = newVal;
|
||||
uint8_t loopEnd = (ringFull) ? RINGLENGTH : ringIndex + 1;
|
||||
float ringSum = 0.0f;
|
||||
for (uint8_t i = 0; i < loopEnd; i++)
|
||||
ringSum += ring[i];
|
||||
ringIndex++;
|
||||
return ringSum / loopEnd;
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
#include <Adafruit_BusIO_Register.h>
|
||||
#include <Adafruit_SPIDevice.h>
|
||||
|
||||
#define SPIDEVICE_CS 10
|
||||
Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS);
|
||||
|
||||
void setup() {
|
||||
while (!Serial) {
|
||||
delay(10);
|
||||
}
|
||||
Serial.begin(115200);
|
||||
Serial.println("SPI device register test");
|
||||
|
||||
if (!spi_dev.begin()) {
|
||||
Serial.println("Could not initialize SPI device");
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
|
||||
Adafruit_BusIO_Register id_reg =
|
||||
Adafruit_BusIO_Register(&spi_dev, 0x0F, ADDRBIT8_HIGH_TOREAD);
|
||||
uint8_t id = 0;
|
||||
id_reg.read(&id);
|
||||
Serial.print("ID register = 0x");
|
||||
Serial.println(id, HEX);
|
||||
|
||||
Adafruit_BusIO_Register thresh_reg = Adafruit_BusIO_Register(
|
||||
&spi_dev, 0x0C, ADDRBIT8_HIGH_TOREAD, 2, LSBFIRST);
|
||||
uint16_t thresh = 0;
|
||||
thresh_reg.read(&thresh);
|
||||
Serial.print("Initial threshold register = 0x");
|
||||
Serial.println(thresh, HEX);
|
||||
|
||||
thresh_reg.write(~thresh);
|
||||
|
||||
Serial.print("Post threshold register = 0x");
|
||||
Serial.println(thresh_reg.read(), HEX);
|
||||
}
|
||||
|
||||
void loop() {}
|
9
Arduino/libraries/Adafruit_BusIO/library.properties
Normal file
9
Arduino/libraries/Adafruit_BusIO/library.properties
Normal file
@ -0,0 +1,9 @@
|
||||
name=Adafruit BusIO
|
||||
version=1.17.1
|
||||
author=Adafruit
|
||||
maintainer=Adafruit <info@adafruit.com>
|
||||
sentence=This is a library for abstracting away UART, I2C and SPI interfacing
|
||||
paragraph=This is a library for abstracting away UART, I2C and SPI interfacing
|
||||
category=Signal Input/Output
|
||||
url=https://github.com/adafruit/Adafruit_BusIO
|
||||
architectures=*
|
245
Arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.cpp
Normal file
245
Arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.cpp
Normal file
@ -0,0 +1,245 @@
|
||||
/*!
|
||||
* @file Adafruit_SHT31.cpp
|
||||
*
|
||||
* @mainpage Adafruit SHT31 Digital Humidity & Temp Sensor
|
||||
*
|
||||
* @section intro_sec Introduction
|
||||
*
|
||||
* This is a library for the SHT31 Digital Humidity & Temp Sensor
|
||||
*
|
||||
* Designed specifically to work with the SHT31 Digital sensor from Adafruit
|
||||
*
|
||||
* Pick one up today in the adafruit shop!
|
||||
* ------> https://www.adafruit.com/product/2857
|
||||
*
|
||||
* These sensors use I2C to communicate, 2 pins are required to interface
|
||||
*
|
||||
* Adafruit invests time and resources providing this open source code,
|
||||
* please support Adafruit andopen-source hardware by purchasing products
|
||||
* from Adafruit!
|
||||
*
|
||||
* @section author Author
|
||||
*
|
||||
* Limor Fried/Ladyada (Adafruit Industries).
|
||||
*
|
||||
* @section license License
|
||||
*
|
||||
* BSD license, all text above must be included in any redistribution
|
||||
*/
|
||||
|
||||
#include "Adafruit_SHT31.h"
|
||||
|
||||
/*!
|
||||
* @brief SHT31 constructor using i2c
|
||||
* @param *theWire
|
||||
* optional wire
|
||||
*/
|
||||
Adafruit_SHT31::Adafruit_SHT31(TwoWire *theWire) {
|
||||
_wire = theWire;
|
||||
|
||||
humidity = NAN;
|
||||
temp = NAN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destructor to free memory in use.
|
||||
*/
|
||||
Adafruit_SHT31::~Adafruit_SHT31() {
|
||||
if (i2c_dev) {
|
||||
delete i2c_dev; // remove old interface
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialises the I2C bus, and assigns the I2C address to us.
|
||||
*
|
||||
* @param i2caddr The I2C address to use for the sensor.
|
||||
*
|
||||
* @return True if initialisation was successful, otherwise False.
|
||||
*/
|
||||
bool Adafruit_SHT31::begin(uint8_t i2caddr) {
|
||||
if (i2c_dev) {
|
||||
delete i2c_dev; // remove old interface
|
||||
}
|
||||
|
||||
i2c_dev = new Adafruit_I2CDevice(i2caddr, _wire);
|
||||
|
||||
if (!i2c_dev->begin()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
reset();
|
||||
return readStatus() != 0xFFFF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current status register contents.
|
||||
*
|
||||
* @return The 16-bit status register.
|
||||
*/
|
||||
uint16_t Adafruit_SHT31::readStatus(void) {
|
||||
writeCommand(SHT31_READSTATUS);
|
||||
|
||||
uint8_t data[3];
|
||||
i2c_dev->read(data, 3);
|
||||
|
||||
uint16_t stat = data[0];
|
||||
stat <<= 8;
|
||||
stat |= data[1];
|
||||
// Serial.println(stat, HEX);
|
||||
return stat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a reset of the sensor to put it into a known state.
|
||||
*/
|
||||
void Adafruit_SHT31::reset(void) {
|
||||
writeCommand(SHT31_SOFTRESET);
|
||||
delay(10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables or disabled the heating element.
|
||||
*
|
||||
* @param h True to enable the heater, False to disable it.
|
||||
*/
|
||||
void Adafruit_SHT31::heater(bool h) {
|
||||
if (h)
|
||||
writeCommand(SHT31_HEATEREN);
|
||||
else
|
||||
writeCommand(SHT31_HEATERDIS);
|
||||
delay(1);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief Return sensor heater state
|
||||
* @return heater state (TRUE = enabled, FALSE = disabled)
|
||||
*/
|
||||
bool Adafruit_SHT31::isHeaterEnabled() {
|
||||
uint16_t regValue = readStatus();
|
||||
return (bool)bitRead(regValue, SHT31_REG_HEATER_BIT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a single temperature reading from the sensor.
|
||||
*
|
||||
* @return A float value indicating the temperature.
|
||||
*/
|
||||
float Adafruit_SHT31::readTemperature(void) {
|
||||
if (!readTempHum())
|
||||
return NAN;
|
||||
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a single relative humidity reading from the sensor.
|
||||
*
|
||||
* @return A float value representing relative humidity.
|
||||
*/
|
||||
float Adafruit_SHT31::readHumidity(void) {
|
||||
if (!readTempHum())
|
||||
return NAN;
|
||||
|
||||
return humidity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a reading of both temperature and relative humidity from the sensor.
|
||||
*
|
||||
* @param temperature_out Where to write the temperature float.
|
||||
* @param humidity_out Where to write the relative humidity float.
|
||||
* @return True if the read was successful, false otherwise
|
||||
*/
|
||||
bool Adafruit_SHT31::readBoth(float *temperature_out, float *humidity_out) {
|
||||
if (!readTempHum()) {
|
||||
*temperature_out = *humidity_out = NAN;
|
||||
return false;
|
||||
}
|
||||
|
||||
*temperature_out = temp;
|
||||
*humidity_out = humidity;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a CRC8 calculation on the supplied values.
|
||||
*
|
||||
* @param data Pointer to the data to use when calculating the CRC8.
|
||||
* @param len The number of bytes in 'data'.
|
||||
*
|
||||
* @return The computed CRC8 value.
|
||||
*/
|
||||
static uint8_t crc8(const uint8_t *data, int len) {
|
||||
/*
|
||||
*
|
||||
* CRC-8 formula from page 14 of SHT spec pdf
|
||||
*
|
||||
* Test data 0xBE, 0xEF should yield 0x92
|
||||
*
|
||||
* Initialization data 0xFF
|
||||
* Polynomial 0x31 (x8 + x5 +x4 +1)
|
||||
* Final XOR 0x00
|
||||
*/
|
||||
|
||||
const uint8_t POLYNOMIAL(0x31);
|
||||
uint8_t crc(0xFF);
|
||||
|
||||
for (int j = len; j; --j) {
|
||||
crc ^= *data++;
|
||||
|
||||
for (int i = 8; i; --i) {
|
||||
crc = (crc & 0x80) ? (crc << 1) ^ POLYNOMIAL : (crc << 1);
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal function to perform a temp + humidity read.
|
||||
*
|
||||
* @return True if successful, otherwise false.
|
||||
*/
|
||||
bool Adafruit_SHT31::readTempHum(void) {
|
||||
uint8_t readbuffer[6];
|
||||
|
||||
if (!writeCommand(SHT31_MEAS_HIGHREP))
|
||||
return false;
|
||||
|
||||
delay(20);
|
||||
|
||||
if (!i2c_dev->read(readbuffer, sizeof(readbuffer)))
|
||||
return false;
|
||||
|
||||
if (readbuffer[2] != crc8(readbuffer, 2) ||
|
||||
readbuffer[5] != crc8(readbuffer + 3, 2))
|
||||
return false;
|
||||
|
||||
int32_t stemp = (int32_t)(((uint32_t)readbuffer[0] << 8) | readbuffer[1]);
|
||||
// simplified (65536 instead of 65535) integer version of:
|
||||
// temp = (stemp * 175.0f) / 65535.0f - 45.0f;
|
||||
stemp = ((4375 * stemp) >> 14) - 4500;
|
||||
temp = (float)stemp / 100.0f;
|
||||
|
||||
uint32_t shum = ((uint32_t)readbuffer[3] << 8) | readbuffer[4];
|
||||
// simplified (65536 instead of 65535) integer version of:
|
||||
// humidity = (shum * 100.0f) / 65535.0f;
|
||||
shum = (625 * shum) >> 12;
|
||||
humidity = (float)shum / 100.0f;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal function to perform and I2C write.
|
||||
*
|
||||
* @param cmd The 16-bit command ID to send.
|
||||
*/
|
||||
bool Adafruit_SHT31::writeCommand(uint16_t command) {
|
||||
uint8_t cmd[2];
|
||||
|
||||
cmd[0] = command >> 8;
|
||||
cmd[1] = command & 0xFF;
|
||||
|
||||
return i2c_dev->write(cmd, 2);
|
||||
}
|
84
Arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.h
Normal file
84
Arduino/libraries/Adafruit_SHT31_Library/Adafruit_SHT31.h
Normal file
@ -0,0 +1,84 @@
|
||||
/*!
|
||||
* @file Adafruit_SHT31.h
|
||||
*
|
||||
* This is a library for the SHT31 Digital Humidity & Temp Sensor
|
||||
*
|
||||
* Designed specifically to work with the Digital Humidity & Temp Sensor
|
||||
* -----> https://www.adafruit.com/product/2857
|
||||
*
|
||||
* These sensors use I2C to communicate, 2 pins are required to interface
|
||||
*
|
||||
* Adafruit invests time and resources providing this open source code,
|
||||
* please support Adafruit andopen-source hardware by purchasing products
|
||||
* from Adafruit!
|
||||
*
|
||||
* Limor Fried/Ladyada (Adafruit Industries).
|
||||
*
|
||||
* BSD license, all text above must be included in any redistribution
|
||||
*/
|
||||
|
||||
#ifndef ADAFRUIT_SHT31_H
|
||||
#define ADAFRUIT_SHT31_H
|
||||
|
||||
#include "Arduino.h"
|
||||
#include <Adafruit_I2CDevice.h>
|
||||
|
||||
#define SHT31_DEFAULT_ADDR 0x44 /**< SHT31 Default Address */
|
||||
#define SHT31_MEAS_HIGHREP_STRETCH \
|
||||
0x2C06 /**< Measurement High Repeatability with Clock Stretch Enabled */
|
||||
#define SHT31_MEAS_MEDREP_STRETCH \
|
||||
0x2C0D /**< Measurement Medium Repeatability with Clock Stretch Enabled */
|
||||
#define SHT31_MEAS_LOWREP_STRETCH \
|
||||
0x2C10 /**< Measurement Low Repeatability with Clock Stretch Enabled*/
|
||||
#define SHT31_MEAS_HIGHREP \
|
||||
0x2400 /**< Measurement High Repeatability with Clock Stretch Disabled */
|
||||
#define SHT31_MEAS_MEDREP \
|
||||
0x240B /**< Measurement Medium Repeatability with Clock Stretch Disabled */
|
||||
#define SHT31_MEAS_LOWREP \
|
||||
0x2416 /**< Measurement Low Repeatability with Clock Stretch Disabled */
|
||||
#define SHT31_READSTATUS 0xF32D /**< Read Out of Status Register */
|
||||
#define SHT31_CLEARSTATUS 0x3041 /**< Clear Status */
|
||||
#define SHT31_SOFTRESET 0x30A2 /**< Soft Reset */
|
||||
#define SHT31_HEATEREN 0x306D /**< Heater Enable */
|
||||
#define SHT31_HEATERDIS 0x3066 /**< Heater Disable */
|
||||
#define SHT31_REG_HEATER_BIT 0x0d /**< Status Register Heater Bit */
|
||||
|
||||
extern TwoWire Wire; /**< Forward declarations of Wire for board/variant
|
||||
combinations that don't have a default 'Wire' */
|
||||
|
||||
/**
|
||||
* Driver for the Adafruit SHT31-D Temperature and Humidity breakout board.
|
||||
*/
|
||||
class Adafruit_SHT31 {
|
||||
public:
|
||||
Adafruit_SHT31(TwoWire *theWire = &Wire);
|
||||
~Adafruit_SHT31();
|
||||
|
||||
bool begin(uint8_t i2caddr = SHT31_DEFAULT_ADDR);
|
||||
float readTemperature(void);
|
||||
float readHumidity(void);
|
||||
bool readBoth(float *temperature_out, float *humidity_out);
|
||||
uint16_t readStatus(void);
|
||||
void reset(void);
|
||||
void heater(bool h);
|
||||
bool isHeaterEnabled();
|
||||
|
||||
private:
|
||||
/**
|
||||
* Placeholder to track humidity internally.
|
||||
*/
|
||||
float humidity;
|
||||
|
||||
/**
|
||||
* Placeholder to track temperature internally.
|
||||
*/
|
||||
float temp;
|
||||
|
||||
bool readTempHum(void);
|
||||
bool writeCommand(uint16_t cmd);
|
||||
|
||||
TwoWire *_wire; /**< Wire object */
|
||||
Adafruit_I2CDevice *i2c_dev = NULL; ///< Pointer to I2C bus interface
|
||||
};
|
||||
|
||||
#endif
|
26
Arduino/libraries/Adafruit_SHT31_Library/README.md
Normal file
26
Arduino/libraries/Adafruit_SHT31_Library/README.md
Normal file
@ -0,0 +1,26 @@
|
||||
# Adafruit SHT31-D Temperature and Humidity Sensor Breakout [](https://github.com/adafruit/Adafruit_SHT31/actions)[](http://adafruit.github.io/Adafruit_SHT31/html/index.html)
|
||||
|
||||
<a href="https://www.adafruit.com/product/2857"><img src="assets/board.jpg?raw=true" width="500px"></a>
|
||||
|
||||
This is a library for the SHT31 Digital Humidity + Temp sensor.
|
||||
|
||||
It is designed specifically to work with the SHT31 Digital in the Adafruit shop:
|
||||
|
||||
* https://www.adafruit.com/products/2857
|
||||
|
||||
These sensors use **I2C** to communicate, 2 pins are required to interface
|
||||
|
||||
Adafruit invests time and resources providing this open source code,
|
||||
please support Adafruit and open-source hardware by purchasing
|
||||
products from Adafruit!
|
||||
|
||||
Written by Limor Fried/Ladyada for Adafruit Industries.
|
||||
BSD license, all text above must be included in any redistribution
|
||||
|
||||
Check out the links above for our tutorials and wiring diagrams
|
||||
|
||||
## Installation
|
||||
|
||||
Use the Arduino Library Manager to install this library. If you're unfamiliar
|
||||
with how this works, we have a great tutorial on Arduino library installation
|
||||
at: http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use
|
BIN
Arduino/libraries/Adafruit_SHT31_Library/assets/board.jpg
Normal file
BIN
Arduino/libraries/Adafruit_SHT31_Library/assets/board.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 421 KiB |
@ -0,0 +1,72 @@
|
||||
/***************************************************
|
||||
This is an example for the SHT31-D Humidity & Temp Sensor
|
||||
|
||||
Designed specifically to work with the SHT31-D sensor from Adafruit
|
||||
----> https://www.adafruit.com/products/2857
|
||||
|
||||
These sensors use I2C to communicate, 2 pins are required to
|
||||
interface
|
||||
****************************************************/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
#include "Adafruit_SHT31.h"
|
||||
|
||||
bool enableHeater = false;
|
||||
uint8_t loopCnt = 0;
|
||||
|
||||
Adafruit_SHT31 sht31 = Adafruit_SHT31();
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
|
||||
while (!Serial)
|
||||
delay(10); // will pause Zero, Leonardo, etc until serial console opens
|
||||
|
||||
Serial.println("SHT31 test");
|
||||
if (! sht31.begin(0x44)) { // Set to 0x45 for alternate i2c addr
|
||||
Serial.println("Couldn't find SHT31");
|
||||
while (1) delay(1);
|
||||
}
|
||||
|
||||
Serial.print("Heater Enabled State: ");
|
||||
if (sht31.isHeaterEnabled())
|
||||
Serial.println("ENABLED");
|
||||
else
|
||||
Serial.println("DISABLED");
|
||||
}
|
||||
|
||||
|
||||
void loop() {
|
||||
float t = sht31.readTemperature();
|
||||
float h = sht31.readHumidity();
|
||||
|
||||
if (! isnan(t)) { // check if 'is not a number'
|
||||
Serial.print("Temp *C = "); Serial.print(t); Serial.print("\t\t");
|
||||
} else {
|
||||
Serial.println("Failed to read temperature");
|
||||
}
|
||||
|
||||
if (! isnan(h)) { // check if 'is not a number'
|
||||
Serial.print("Hum. % = "); Serial.println(h);
|
||||
} else {
|
||||
Serial.println("Failed to read humidity");
|
||||
}
|
||||
|
||||
delay(1000);
|
||||
|
||||
// Toggle heater enabled state every 30 seconds
|
||||
// An ~3.0 degC temperature increase can be noted when heater is enabled
|
||||
if (loopCnt >= 30) {
|
||||
enableHeater = !enableHeater;
|
||||
sht31.heater(enableHeater);
|
||||
Serial.print("Heater Enabled State: ");
|
||||
if (sht31.isHeaterEnabled())
|
||||
Serial.println("ENABLED");
|
||||
else
|
||||
Serial.println("DISABLED");
|
||||
|
||||
loopCnt = 0;
|
||||
}
|
||||
loopCnt++;
|
||||
}
|
10
Arduino/libraries/Adafruit_SHT31_Library/library.properties
Normal file
10
Arduino/libraries/Adafruit_SHT31_Library/library.properties
Normal file
@ -0,0 +1,10 @@
|
||||
name=Adafruit SHT31 Library
|
||||
version=2.2.2
|
||||
author=Adafruit
|
||||
maintainer=Adafruit <info@adafruit.com>
|
||||
sentence=Arduino library for SHT31 temperature & humidity sensor.
|
||||
paragraph=Arduino library for SHT31 temperature & humidity sensor.
|
||||
category=Sensors
|
||||
url=https://github.com/adafruit/Adafruit_SHT31
|
||||
architectures=*
|
||||
depends=Adafruit BusIO
|
26
Arduino/libraries/Adafruit_SHT31_Library/license.txt
Normal file
26
Arduino/libraries/Adafruit_SHT31_Library/license.txt
Normal file
@ -0,0 +1,26 @@
|
||||
Software License Agreement (BSD License)
|
||||
|
||||
Copyright (c) 2012, Adafruit Industries
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holders nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
36
Arduino/libraries/Ethernet/AUTHORS
Normal file
36
Arduino/libraries/Ethernet/AUTHORS
Normal file
@ -0,0 +1,36 @@
|
||||
Alberto Panu https://github.com/bigjohnson
|
||||
Alasdair Allan https://github.com/aallan
|
||||
Alice Pintus https://github.com/00alis
|
||||
Adrian McEwen https://github.com/amcewen
|
||||
Arduino LLC https://arduino.cc/
|
||||
Arnie97 https://github.com/Arnie97
|
||||
Arturo Guadalupi https://github.com/agdl
|
||||
Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/
|
||||
chaveiro https://github.com/chaveiro
|
||||
Cristian Maglie https://github.com/cmaglie
|
||||
David A. Mellis https://github.com/damellis
|
||||
Dino Tinitigan https://github.com/bigdinotech
|
||||
Eddy https://github.com/eddyst
|
||||
Federico Vanzati https://github.com/Fede85
|
||||
Federico Fissore https://github.com/ffissore
|
||||
Jack Christensen https://github.com/JChristensen
|
||||
Johann Richard https://github.com/johannrichard
|
||||
Jordan Terrell https://github.com/iSynaptic
|
||||
Justin Paulin https://github.com/interwho
|
||||
lathoub https://github.com/lathoub
|
||||
Martino Facchin https://github.com/facchinm
|
||||
Matthias Hertel https://github.com/mathertel
|
||||
Matthijs Kooijman https://github.com/matthijskooijman
|
||||
Matt Robinson https://github.com/ribbons
|
||||
MCQN Ltd. http://mcqn.com/
|
||||
Michael Amie https://github.com/michaelamie
|
||||
Michael Margolis https://github.com/michaelmargolis
|
||||
Norbert Truchsess https://github.com/ntruchsess
|
||||
Paul Stoffregen https://github.com/PaulStoffregen
|
||||
per1234 https://github.com/per1234
|
||||
Richard Sim
|
||||
Scott Fitzgerald https://github.com/shfitz
|
||||
Thibaut Viard https://github.com/aethaniel
|
||||
Tom Igoe https://github.com/tigoe
|
||||
WIZnet http://www.wiznet.co.kr
|
||||
Zach Eveland https://github.com/zeveland
|
31
Arduino/libraries/Ethernet/README.adoc
Normal file
31
Arduino/libraries/Ethernet/README.adoc
Normal file
@ -0,0 +1,31 @@
|
||||
:repository-owner: arduino-libraries
|
||||
:repository-name: Ethernet
|
||||
|
||||
= {repository-name} Library for Arduino =
|
||||
|
||||
image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml/badge.svg["Check Arduino status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml"]
|
||||
image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml/badge.svg["Compile Examples status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml"]
|
||||
image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml/badge.svg["Spell Check status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml"]
|
||||
|
||||
With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet.
|
||||
|
||||
For more information about this library please visit us at
|
||||
https://www.arduino.cc/en/Reference/{repository-name}
|
||||
|
||||
== License ==
|
||||
|
||||
Copyright (c) 2010 Arduino LLC. 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
|
2607
Arduino/libraries/Ethernet/docs/api.md
Normal file
2607
Arduino/libraries/Ethernet/docs/api.md
Normal file
File diff suppressed because it is too large
Load Diff
BIN
Arduino/libraries/Ethernet/docs/arduino_mega_ethernet_pins.png
Normal file
BIN
Arduino/libraries/Ethernet/docs/arduino_mega_ethernet_pins.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 19 KiB |
BIN
Arduino/libraries/Ethernet/docs/arduino_uno_ethernet_pins.png
Normal file
BIN
Arduino/libraries/Ethernet/docs/arduino_uno_ethernet_pins.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 11 KiB |
16
Arduino/libraries/Ethernet/docs/readme.md
Normal file
16
Arduino/libraries/Ethernet/docs/readme.md
Normal file
@ -0,0 +1,16 @@
|
||||
# Ethernet Library
|
||||
|
||||
This library is designed to work with the Arduino Ethernet Shield, Arduino Ethernet Shield 2, Leonardo Ethernet, and any other W5100/W5200/W5500-based devices. The library allows an Arduino board to connect to the Internet. The board can serve as either a server accepting incoming connections or a client making outgoing ones. The library supports up to eight (W5100 and boards with <= 2 kB SRAM are limited to four) concurrent connections (incoming, outgoing, or a combination).
|
||||
|
||||
The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
To use this library
|
||||
|
||||
```
|
||||
#include <SPI.h>
|
||||
#include <Ethernet.h>
|
||||
```
|
@ -0,0 +1,119 @@
|
||||
/*
|
||||
Advanced Chat Server
|
||||
|
||||
A more advanced server that distributes any incoming messages
|
||||
to all connected clients but the client the message comes from.
|
||||
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
|
||||
|
||||
created 18 Dec 2009
|
||||
by David A. Mellis
|
||||
modified 9 Apr 2012
|
||||
by Tom Igoe
|
||||
redesigned to make use of operator== 25 Nov 2013
|
||||
by Norbert Truchsess
|
||||
|
||||
*/
|
||||
|
||||
#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 myDns(192, 168, 1, 1);
|
||||
IPAddress gateway(192, 168, 1, 1);
|
||||
IPAddress subnet(255, 255, 0, 0);
|
||||
|
||||
|
||||
// telnet defaults to port 23
|
||||
EthernetServer server(23);
|
||||
|
||||
EthernetClient clients[8];
|
||||
|
||||
void setup() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// initialize the Ethernet device
|
||||
Ethernet.begin(mac, ip, myDns, gateway, subnet);
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port only
|
||||
}
|
||||
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
|
||||
// start listening for clients
|
||||
server.begin();
|
||||
|
||||
Serial.print("Chat server address:");
|
||||
Serial.println(Ethernet.localIP());
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// check for any new client connecting, and say hello (before any incoming data)
|
||||
EthernetClient newClient = server.accept();
|
||||
if (newClient) {
|
||||
for (byte i=0; i < 8; i++) {
|
||||
if (!clients[i]) {
|
||||
Serial.print("We have a new client #");
|
||||
Serial.println(i);
|
||||
newClient.print("Hello, client number: ");
|
||||
newClient.println(i);
|
||||
// Once we "accept", the client is no longer tracked by EthernetServer
|
||||
// so we must store it into our list of clients
|
||||
clients[i] = newClient;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// check for incoming data from all clients
|
||||
for (byte i=0; i < 8; i++) {
|
||||
if (clients[i] && clients[i].available() > 0) {
|
||||
// read bytes from a client
|
||||
byte buffer[80];
|
||||
int count = clients[i].read(buffer, 80);
|
||||
// write the bytes to all other connected clients
|
||||
for (byte j=0; j < 8; j++) {
|
||||
if (j != i && clients[j].connected()) {
|
||||
clients[j].write(buffer, count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stop any clients which disconnect
|
||||
for (byte i=0; i < 8; i++) {
|
||||
if (clients[i] && !clients[i].connected()) {
|
||||
Serial.print("disconnect client #");
|
||||
Serial.println(i);
|
||||
clients[i].stop();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,247 @@
|
||||
/*
|
||||
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
|
||||
|
||||
This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
|
||||
http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
|
||||
|
||||
TODO: this hardware is long obsolete. This example program should
|
||||
be rewritten to use https://www.sparkfun.com/products/9721
|
||||
|
||||
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);
|
||||
|
||||
|
||||
// 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() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// start the SPI library:
|
||||
SPI.begin();
|
||||
|
||||
// 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 native USB port only
|
||||
}
|
||||
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
|
||||
// start listening for clients
|
||||
server.begin();
|
||||
|
||||
// initialize 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 and Ethernet shield time to set up:
|
||||
delay(1000);
|
||||
|
||||
//Set the sensor to high resolution mode to 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
|
||||
bool 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:
|
||||
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);
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
/*
|
||||
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
|
||||
|
||||
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 myDns(192, 168, 1, 1);
|
||||
IPAddress gateway(192, 168, 1, 1);
|
||||
IPAddress subnet(255, 255, 0, 0);
|
||||
|
||||
|
||||
// telnet defaults to port 23
|
||||
EthernetServer server(23);
|
||||
bool alreadyConnected = false; // whether or not the client was connected previously
|
||||
|
||||
void setup() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// initialize the Ethernet device
|
||||
Ethernet.begin(mac, ip, myDns, gateway, subnet);
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port only
|
||||
}
|
||||
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
|
||||
// start listening for clients
|
||||
server.begin();
|
||||
|
||||
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) {
|
||||
// clear 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);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
/*
|
||||
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
|
||||
modified 02 Sept 2015
|
||||
by Arturo Guadalupi
|
||||
|
||||
*/
|
||||
|
||||
#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
|
||||
};
|
||||
|
||||
void setup() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port only
|
||||
}
|
||||
|
||||
// start the Ethernet connection:
|
||||
Serial.println("Initialize Ethernet with DHCP:");
|
||||
if (Ethernet.begin(mac) == 0) {
|
||||
Serial.println("Failed to configure Ethernet using DHCP");
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
} else if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
// no point in carrying on, so do nothing forevermore:
|
||||
while (true) {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
// print your local IP address:
|
||||
Serial.print("My IP address: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
}
|
||||
|
||||
void loop() {
|
||||
switch (Ethernet.maintain()) {
|
||||
case 1:
|
||||
//renewed fail
|
||||
Serial.println("Error: renewed fail");
|
||||
break;
|
||||
|
||||
case 2:
|
||||
//renewed success
|
||||
Serial.println("Renewed success");
|
||||
//print your local IP address:
|
||||
Serial.print("My IP address: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
break;
|
||||
|
||||
case 3:
|
||||
//rebind fail
|
||||
Serial.println("Error: rebind fail");
|
||||
break;
|
||||
|
||||
case 4:
|
||||
//rebind success
|
||||
Serial.println("Rebind success");
|
||||
//print your local IP address:
|
||||
Serial.print("My IP address: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
break;
|
||||
|
||||
default:
|
||||
//nothing happened
|
||||
break;
|
||||
}
|
||||
}
|
@ -0,0 +1,101 @@
|
||||
/*
|
||||
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
|
||||
modified 02 Sept 2015
|
||||
by Arturo Guadalupi
|
||||
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[] = {
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
|
||||
};
|
||||
IPAddress ip(192, 168, 1, 177);
|
||||
IPAddress myDns(192, 168, 1, 1);
|
||||
IPAddress gateway(192, 168, 1, 1);
|
||||
IPAddress subnet(255, 255, 0, 0);
|
||||
|
||||
// telnet defaults to port 23
|
||||
EthernetServer server(23);
|
||||
bool gotAMessage = false; // whether or not you got a message from the client yet
|
||||
|
||||
void setup() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port 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");
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
// initialize the Ethernet device not using DHCP:
|
||||
Ethernet.begin(mac, ip, myDns, gateway, subnet);
|
||||
}
|
||||
// print your local IP address:
|
||||
Serial.print("My IP address: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
|
||||
// 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);
|
||||
Ethernet.maintain();
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
/*
|
||||
Link Status
|
||||
|
||||
This sketch prints the Ethernet link status. When the
|
||||
Ethernet cable is connected the link status should go to "ON".
|
||||
NOTE: Only WIZnet W5200 and W5500 are capable of reporting
|
||||
the link status. W5100 will report "Unknown".
|
||||
Hardware:
|
||||
- Ethernet shield or equivalent board/shield with WIZnet W5200/W5500
|
||||
Written by Cristian Maglie
|
||||
This example is public domain.
|
||||
*/
|
||||
|
||||
#include <SPI.h>
|
||||
#include <Ethernet.h>
|
||||
|
||||
void setup() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
Serial.begin(9600);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
auto link = Ethernet.linkStatus();
|
||||
Serial.print("Link status: ");
|
||||
switch (link) {
|
||||
case Unknown:
|
||||
Serial.println("Unknown");
|
||||
break;
|
||||
case LinkON:
|
||||
Serial.println("ON");
|
||||
break;
|
||||
case LinkOFF:
|
||||
Serial.println("OFF");
|
||||
break;
|
||||
}
|
||||
delay(1000);
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
/*
|
||||
Pager Server
|
||||
|
||||
A simple server that echoes any incoming messages to all
|
||||
connected clients. Connect two or more telnet sessions
|
||||
to see how server.available() and server.print() works.
|
||||
|
||||
created in September 2020 for the Ethernet library
|
||||
by Juraj Andrassy https://github.com/jandrassy
|
||||
|
||||
*/
|
||||
#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 };
|
||||
|
||||
// Set the static IP address to use if the DHCP fails to assign
|
||||
IPAddress ip(192, 168, 0, 177);
|
||||
|
||||
EthernetServer server(2323);
|
||||
|
||||
void setup() {
|
||||
|
||||
Serial.begin(9600);
|
||||
while (!Serial);
|
||||
|
||||
// start the Ethernet connection:
|
||||
Serial.println("Initialize Ethernet with DHCP:");
|
||||
if (Ethernet.begin(mac) == 0) {
|
||||
Serial.println("Failed to configure Ethernet using DHCP");
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
// try to configure using IP address instead of DHCP:
|
||||
Ethernet.begin(mac, ip);
|
||||
} else {
|
||||
Serial.print(" DHCP assigned IP ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
}
|
||||
|
||||
server.begin();
|
||||
|
||||
IPAddress ip = Ethernet.localIP();
|
||||
Serial.println();
|
||||
Serial.print("To access the server, connect with Telnet client to ");
|
||||
Serial.print(ip);
|
||||
Serial.println(" 2323");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
EthernetClient client = server.available(); // returns first client which has data to read or a 'false' client
|
||||
if (client) { // client is true only if it is connected and has data to read
|
||||
String s = client.readStringUntil('\n'); // read the message incoming from one of the clients
|
||||
s.trim(); // trim eventual \r
|
||||
Serial.println(s); // print the message to Serial Monitor
|
||||
client.print("echo: "); // this is only for the sending client
|
||||
server.println(s); // send the message to all connected clients
|
||||
#ifndef ARDUINO_ARCH_SAM
|
||||
server.flush(); // flush the buffers
|
||||
#endif /* !defined(ARDUINO_ARCH_SAM) */
|
||||
}
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
/*
|
||||
Telnet client
|
||||
|
||||
This sketch connects to 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
|
||||
https://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() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// 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 native USB port only
|
||||
}
|
||||
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
while (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
delay(500);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,138 @@
|
||||
/*
|
||||
UDPSendReceiveString
|
||||
|
||||
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 receive messages for testing with a computer.
|
||||
|
||||
created 21 Aug 2010
|
||||
by Michael Margolis
|
||||
|
||||
This code is in the public domain.
|
||||
*/
|
||||
|
||||
|
||||
#include <Ethernet.h>
|
||||
#include <EthernetUdp.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);
|
||||
|
||||
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() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// start the Ethernet
|
||||
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 native USB port only
|
||||
}
|
||||
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
|
||||
// start UDP
|
||||
Udp.begin(localPort);
|
||||
}
|
||||
|
||||
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 packetBuffer
|
||||
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();
|
||||
}
|
||||
*/
|
@ -0,0 +1,145 @@
|
||||
/*
|
||||
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 https://en.wikipedia.org/wiki/Network_Time_Protocol
|
||||
|
||||
created 4 Sep 2010
|
||||
by Michael Margolis
|
||||
modified 9 Apr 2012
|
||||
by Tom Igoe
|
||||
modified 02 Sept 2015
|
||||
by Arturo Guadalupi
|
||||
|
||||
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
|
||||
|
||||
const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server
|
||||
|
||||
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
|
||||
|
||||
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() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port only
|
||||
}
|
||||
|
||||
// start Ethernet and UDP
|
||||
if (Ethernet.begin(mac) == 0) {
|
||||
Serial.println("Failed to configure Ethernet using DHCP");
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
} else if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
// no point in carrying on, so do nothing forevermore:
|
||||
while (true) {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
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, extract 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);
|
||||
Ethernet.maintain();
|
||||
}
|
||||
|
||||
// send an NTP request to the time server at the given address
|
||||
void sendNTPpacket(const char * 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();
|
||||
}
|
136
Arduino/libraries/Ethernet/examples/WebClient/WebClient.ino
Normal file
136
Arduino/libraries/Ethernet/examples/WebClient/WebClient.ino
Normal file
@ -0,0 +1,136 @@
|
||||
/*
|
||||
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[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
|
||||
|
||||
// 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(74,125,232,128); // numeric IP for Google (no DNS)
|
||||
char server[] = "www.google.com"; // name address for Google (using DNS)
|
||||
|
||||
// Set the static IP address to use if the DHCP fails to assign
|
||||
IPAddress ip(192, 168, 0, 177);
|
||||
IPAddress myDns(192, 168, 0, 1);
|
||||
|
||||
// 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;
|
||||
|
||||
// Variables to measure the speed
|
||||
unsigned long beginMicros, endMicros;
|
||||
unsigned long byteCount = 0;
|
||||
bool printWebData = true; // set to false for better speed measurement
|
||||
|
||||
void setup() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port only
|
||||
}
|
||||
|
||||
// start the Ethernet connection:
|
||||
Serial.println("Initialize Ethernet with DHCP:");
|
||||
if (Ethernet.begin(mac) == 0) {
|
||||
Serial.println("Failed to configure Ethernet using DHCP");
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
// try to configure using IP address instead of DHCP:
|
||||
Ethernet.begin(mac, ip, myDns);
|
||||
} else {
|
||||
Serial.print(" DHCP assigned IP ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
}
|
||||
// give the Ethernet shield a second to initialize:
|
||||
delay(1000);
|
||||
Serial.print("connecting to ");
|
||||
Serial.print(server);
|
||||
Serial.println("...");
|
||||
|
||||
// if you get a connection, report back via serial:
|
||||
if (client.connect(server, 80)) {
|
||||
Serial.print("connected to ");
|
||||
Serial.println(client.remoteIP());
|
||||
// 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();
|
||||
} else {
|
||||
// if you didn't get a connection to the server:
|
||||
Serial.println("connection failed");
|
||||
}
|
||||
beginMicros = micros();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// if there are incoming bytes available
|
||||
// from the server, read them and print them:
|
||||
int len = client.available();
|
||||
if (len > 0) {
|
||||
byte buffer[80];
|
||||
if (len > 80) len = 80;
|
||||
client.read(buffer, len);
|
||||
if (printWebData) {
|
||||
Serial.write(buffer, len); // show in the serial monitor (slows some boards)
|
||||
}
|
||||
byteCount = byteCount + len;
|
||||
}
|
||||
|
||||
// if the server's disconnected, stop the client:
|
||||
if (!client.connected()) {
|
||||
endMicros = micros();
|
||||
Serial.println();
|
||||
Serial.println("disconnecting.");
|
||||
client.stop();
|
||||
Serial.print("Received ");
|
||||
Serial.print(byteCount);
|
||||
Serial.print(" bytes in ");
|
||||
float seconds = (float)(endMicros - beginMicros) / 1000000.0;
|
||||
Serial.print(seconds, 4);
|
||||
float rate = (float)byteCount / seconds / 1000.0;
|
||||
Serial.print(", rate = ");
|
||||
Serial.print(rate);
|
||||
Serial.print(" kbytes/second");
|
||||
Serial.println();
|
||||
|
||||
// do nothing forevermore:
|
||||
while (true) {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,126 @@
|
||||
/*
|
||||
Repeating Web client
|
||||
|
||||
This sketch connects to 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
|
||||
modified 21 Jan 2014
|
||||
by Federico Vanzati
|
||||
|
||||
https://www.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
|
||||
};
|
||||
// Set the static IP address to use if the DHCP fails to assign
|
||||
IPAddress ip(192, 168, 0, 177);
|
||||
IPAddress myDns(192, 168, 0, 1);
|
||||
|
||||
// initialize the library instance:
|
||||
EthernetClient client;
|
||||
|
||||
char server[] = "www.arduino.cc"; // also change the Host line in httpRequest()
|
||||
//IPAddress server(64,131,82,241);
|
||||
|
||||
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
|
||||
const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds
|
||||
|
||||
void setup() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// start serial port:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port only
|
||||
}
|
||||
|
||||
// start the Ethernet connection:
|
||||
Serial.println("Initialize Ethernet with DHCP:");
|
||||
if (Ethernet.begin(mac) == 0) {
|
||||
Serial.println("Failed to configure Ethernet using DHCP");
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
// try to configure using IP address instead of DHCP:
|
||||
Ethernet.begin(mac, ip, myDns);
|
||||
Serial.print("My IP address: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
} else {
|
||||
Serial.print(" DHCP assigned IP ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
}
|
||||
// give the Ethernet shield a second to initialize:
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
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.write(c);
|
||||
}
|
||||
|
||||
// if ten seconds have passed since your last connection,
|
||||
// then connect again and send data:
|
||||
if (millis() - lastConnectionTime > postingInterval) {
|
||||
httpRequest();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// this method makes a HTTP connection to the server:
|
||||
void httpRequest() {
|
||||
// close any connection before send a new request.
|
||||
// This will free the socket on the Ethernet shield
|
||||
client.stop();
|
||||
|
||||
// if there's a successful connection:
|
||||
if (client.connect(server, 80)) {
|
||||
Serial.println("connecting...");
|
||||
// send the HTTP GET 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");
|
||||
}
|
||||
}
|
122
Arduino/libraries/Ethernet/examples/WebServer/WebServer.ino
Normal file
122
Arduino/libraries/Ethernet/examples/WebServer/WebServer.ino
Normal file
@ -0,0 +1,122 @@
|
||||
/*
|
||||
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
|
||||
modified 02 Sept 2015
|
||||
by Arturo Guadalupi
|
||||
|
||||
*/
|
||||
|
||||
#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() {
|
||||
// You can use Ethernet.init(pin) to configure the CS pin
|
||||
//Ethernet.init(10); // Most Arduino shields
|
||||
//Ethernet.init(5); // MKR ETH Shield
|
||||
//Ethernet.init(0); // Teensy 2.0
|
||||
//Ethernet.init(20); // Teensy++ 2.0
|
||||
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
|
||||
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
|
||||
|
||||
// Open serial communications and wait for port to open:
|
||||
Serial.begin(9600);
|
||||
while (!Serial) {
|
||||
; // wait for serial port to connect. Needed for native USB port only
|
||||
}
|
||||
Serial.println("Ethernet WebServer Example");
|
||||
|
||||
// start the Ethernet connection and the server:
|
||||
Ethernet.begin(mac, ip);
|
||||
|
||||
// Check for Ethernet hardware present
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
|
||||
while (true) {
|
||||
delay(1); // do nothing, no point running without Ethernet hardware
|
||||
}
|
||||
}
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Ethernet cable is not connected.");
|
||||
}
|
||||
|
||||
// start the server
|
||||
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
|
||||
bool 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"); // the connection will be closed after completion of the response
|
||||
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
|
||||
client.println();
|
||||
client.println("<!DOCTYPE HTML>");
|
||||
client.println("<html>");
|
||||
// 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 disconnected");
|
||||
}
|
||||
}
|
67
Arduino/libraries/Ethernet/keywords.txt
Normal file
67
Arduino/libraries/Ethernet/keywords.txt
Normal file
@ -0,0 +1,67 @@
|
||||
#######################################
|
||||
# Syntax Coloring Map For Ethernet
|
||||
#######################################
|
||||
|
||||
#######################################
|
||||
# Datatypes (KEYWORD1)
|
||||
#######################################
|
||||
|
||||
Ethernet KEYWORD1 Ethernet
|
||||
EthernetClient KEYWORD1 EthernetClient
|
||||
EthernetServer KEYWORD1 EthernetServer
|
||||
IPAddress KEYWORD1 EthernetIPAddress
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
status KEYWORD2
|
||||
connect KEYWORD2
|
||||
write KEYWORD2
|
||||
available KEYWORD2
|
||||
availableForWrite KEYWORD2
|
||||
read KEYWORD2
|
||||
peek KEYWORD2
|
||||
flush KEYWORD2
|
||||
stop KEYWORD2
|
||||
connected KEYWORD2
|
||||
accept KEYWORD2
|
||||
begin KEYWORD2
|
||||
beginMulticast KEYWORD2
|
||||
beginPacket KEYWORD2
|
||||
endPacket KEYWORD2
|
||||
parsePacket KEYWORD2
|
||||
remoteIP KEYWORD2
|
||||
remotePort KEYWORD2
|
||||
getSocketNumber KEYWORD2
|
||||
localIP KEYWORD2
|
||||
localPort KEYWORD2
|
||||
maintain KEYWORD2
|
||||
linkStatus KEYWORD2
|
||||
hardwareStatus KEYWORD2
|
||||
MACAddress KEYWORD2
|
||||
subnetMask KEYWORD2
|
||||
gatewayIP KEYWORD2
|
||||
dnsServerIP KEYWORD2
|
||||
setMACAddress KEYWORD2
|
||||
setLocalIP KEYWORD2
|
||||
setSubnetMask KEYWORD2
|
||||
setGatewayIP KEYWORD2
|
||||
setDnsServerIP KEYWORD2
|
||||
setRetransmissionTimeout KEYWORD2
|
||||
setRetransmissionCount KEYWORD2
|
||||
setConnectionTimeout KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
#######################################
|
||||
|
||||
EthernetLinkStatus LITERAL1
|
||||
Unknown LITERAL1
|
||||
LinkON LITERAL1
|
||||
LinkOFF LITERAL1
|
||||
EthernetHardwareStatus LITERAL1
|
||||
EthernetNoHardware LITERAL1
|
||||
EthernetW5100 LITERAL1
|
||||
EthernetW5200 LITERAL1
|
||||
EthernetW5500 LITERAL1
|
10
Arduino/libraries/Ethernet/library.properties
Normal file
10
Arduino/libraries/Ethernet/library.properties
Normal file
@ -0,0 +1,10 @@
|
||||
name=Ethernet
|
||||
version=2.0.2
|
||||
author=Various (see AUTHORS file for details)
|
||||
maintainer=Arduino <info@arduino.cc>
|
||||
sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield.
|
||||
paragraph=With this library you can use the Arduino Ethernet (shield or board) to connect to Internet. The library provides both client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS.
|
||||
category=Communication
|
||||
url=https://www.arduino.cc/en/Reference/Ethernet
|
||||
architectures=*
|
||||
includes=Ethernet.h
|
433
Arduino/libraries/Ethernet/src/Dhcp.cpp
Normal file
433
Arduino/libraries/Ethernet/src/Dhcp.cpp
Normal file
@ -0,0 +1,433 @@
|
||||
// DHCP Library v0.3 - April 25, 2009
|
||||
// Author: Jordan Terrell - blog.jordanterrell.com
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "Dhcp.h"
|
||||
#include "utility/w5100.h"
|
||||
|
||||
int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
|
||||
{
|
||||
_dhcpLeaseTime=0;
|
||||
_dhcpT1=0;
|
||||
_dhcpT2=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 = _dhcpLeaseTime - (_dhcpLeaseTime >> 3);
|
||||
}
|
||||
_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++;
|
||||
|
||||
_lastCheckLeaseMillis = millis();
|
||||
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 (_dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT) == -1) {
|
||||
//Serial.printf("DHCP transmit error\n");
|
||||
// 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(); // FIXME
|
||||
return 0;
|
||||
}
|
||||
|
||||
memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4);
|
||||
|
||||
// Skip to the option part
|
||||
_dhcpUdpSocket.read((uint8_t *)NULL, 240 - (int)sizeof(RIP_MSG_FIXED));
|
||||
|
||||
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);
|
||||
_dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4);
|
||||
break;
|
||||
|
||||
case dns :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpUdpSocket.read(_dhcpDnsServerIp, 4);
|
||||
_dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4);
|
||||
break;
|
||||
|
||||
case dhcpServerIdentifier :
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
if ( IPAddress(_dhcpDhcpServerIp) == IPAddress((uint32_t)0) ||
|
||||
IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) {
|
||||
_dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp));
|
||||
} else {
|
||||
// Skip over the rest of this option
|
||||
_dhcpUdpSocket.read((uint8_t *)NULL, opt_len);
|
||||
}
|
||||
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
|
||||
_dhcpUdpSocket.read((uint8_t *)NULL, opt_len);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Need to skip to end of the packet regardless here
|
||||
_dhcpUdpSocket.flush(); // FIXME
|
||||
|
||||
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()
|
||||
{
|
||||
int rc = DHCP_CHECK_NONE;
|
||||
|
||||
unsigned long now = millis();
|
||||
unsigned long elapsed = now - _lastCheckLeaseMillis;
|
||||
|
||||
// if more then one sec passed, reduce the counters accordingly
|
||||
if (elapsed >= 1000) {
|
||||
// set the new timestamps
|
||||
_lastCheckLeaseMillis = now - (elapsed % 1000);
|
||||
elapsed = elapsed / 1000;
|
||||
|
||||
// decrease the counters by elapsed seconds
|
||||
// we assume that the cycle time (elapsed) is fairly constant
|
||||
// if the remainder is less than cycle time * 2
|
||||
// do it early instead of late
|
||||
if (_renewInSec < elapsed * 2) {
|
||||
_renewInSec = 0;
|
||||
} else {
|
||||
_renewInSec -= elapsed;
|
||||
}
|
||||
if (_rebindInSec < elapsed * 2) {
|
||||
_rebindInSec = 0;
|
||||
} else {
|
||||
_rebindInSec -= elapsed;
|
||||
}
|
||||
}
|
||||
|
||||
// if we have a lease but should renew, do it
|
||||
if (_renewInSec == 0 &&_dhcp_state == STATE_DHCP_LEASED) {
|
||||
_dhcp_state = STATE_DHCP_REREQUEST;
|
||||
rc = 1 + request_DHCP_lease();
|
||||
}
|
||||
|
||||
// if we have a lease or is renewing but should bind, do it
|
||||
if (_rebindInSec == 0 && (_dhcp_state == STATE_DHCP_LEASED ||
|
||||
_dhcp_state == STATE_DHCP_START)) {
|
||||
// this should basically restart completely
|
||||
_dhcp_state = STATE_DHCP_START;
|
||||
reset_DHCP_lease();
|
||||
rc = 3 + request_DHCP_lease();
|
||||
}
|
||||
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);
|
||||
}
|
137
Arduino/libraries/Ethernet/src/Dhcp.h
Normal file
137
Arduino/libraries/Ethernet/src/Dhcp.h
Normal file
@ -0,0 +1,137 @@
|
||||
// DHCP Library v0.3 - April 25, 2009
|
||||
// Author: Jordan Terrell - blog.jordanterrell.com
|
||||
|
||||
#ifndef Dhcp_h
|
||||
#define Dhcp_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;
|
||||
|
||||
#endif
|
353
Arduino/libraries/Ethernet/src/Dns.cpp
Normal file
353
Arduino/libraries/Ethernet/src/Dns.cpp
Normal file
@ -0,0 +1,353 @@
|
||||
// Arduino DNS client for WIZnet W5100-based Ethernet shield
|
||||
// (c) Copyright 2009-2010 MCQN Ltd.
|
||||
// Released under Apache License, version 2.0
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "Dns.h"
|
||||
#include "utility/w5100.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* address, IPAddress& result)
|
||||
{
|
||||
uint16_t acc = 0; // Accumulator
|
||||
uint8_t dots = 0;
|
||||
|
||||
while (*address) {
|
||||
char c = *address++;
|
||||
if (c >= '0' && c <= '9') {
|
||||
acc = acc * 10 + (c - '0');
|
||||
if (acc > 255) {
|
||||
// Value out of [0..255] range
|
||||
return 0;
|
||||
}
|
||||
} else if (c == '.') {
|
||||
if (dots == 3) {
|
||||
// Too much dots (there must be 3 dots)
|
||||
return 0;
|
||||
}
|
||||
result[dots++] = acc;
|
||||
acc = 0;
|
||||
} else {
|
||||
// Invalid char
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (dots != 3) {
|
||||
// Too few dots (there must be 3 dots)
|
||||
return 0;
|
||||
}
|
||||
result[3] = acc;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout)
|
||||
{
|
||||
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(timeout, 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
|
||||
union {
|
||||
uint8_t byte[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header
|
||||
uint16_t word[DNS_HEADER_SIZE/2];
|
||||
} 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.byte, DNS_HEADER_SIZE);
|
||||
|
||||
uint16_t header_flags = htons(header.word[1]);
|
||||
// Check that it's a response to this request
|
||||
if ((iRequestId != (header.word[0])) ||
|
||||
((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) {
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush(); // FIXME
|
||||
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(); // FIXME
|
||||
return -5; //INVALID_RESPONSE;
|
||||
}
|
||||
|
||||
// And make sure we've got (at least) one answer
|
||||
uint16_t answerCount = htons(header.word[3]);
|
||||
if (answerCount == 0) {
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush(); // FIXME
|
||||
return -6; //INVALID_RESPONSE;
|
||||
}
|
||||
|
||||
// Skip over any questions
|
||||
for (uint16_t i=0; i < htons(header.word[2]); 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
|
||||
iUdp.read((uint8_t *)NULL, (size_t)len);
|
||||
}
|
||||
} while (len != 0);
|
||||
|
||||
// Now jump over the type and class
|
||||
iUdp.read((uint8_t *)NULL, 4);
|
||||
}
|
||||
|
||||
// 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
|
||||
iUdp.read((uint8_t *)NULL, len);
|
||||
}
|
||||
} 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((uint8_t *)NULL, 1); // we don't care about the 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
|
||||
iUdp.read((uint8_t *)NULL, TTL_SIZE); // don't care about the returned bytes
|
||||
|
||||
// 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(); // FIXME
|
||||
return -9;//INVALID_RESPONSE;
|
||||
}
|
||||
// FIXME: seems to lock up here on ESP8266, but why??
|
||||
iUdp.read(aAddress.raw_address(), 4);
|
||||
return SUCCESS;
|
||||
} else {
|
||||
// This isn't an answer type we're after, move onto the next one
|
||||
iUdp.read((uint8_t *)NULL, htons(header_flags));
|
||||
}
|
||||
}
|
||||
|
||||
// Mark the entire packet as read
|
||||
iUdp.flush(); // FIXME
|
||||
|
||||
// If we get here then we haven't found an answer
|
||||
return -10; //INVALID_RESPONSE;
|
||||
}
|
40
Arduino/libraries/Ethernet/src/Dns.h
Normal file
40
Arduino/libraries/Ethernet/src/Dns.h
Normal file
@ -0,0 +1,40 @@
|
||||
// Arduino DNS client for WIZnet W5100-based Ethernet shield
|
||||
// (c) Copyright 2009-2010 MCQN Ltd.
|
||||
// Released under Apache License, version 2.0
|
||||
|
||||
#ifndef DNSClient_h
|
||||
#define DNSClient_h
|
||||
|
||||
#include "Ethernet.h"
|
||||
|
||||
class DNSClient
|
||||
{
|
||||
public:
|
||||
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, uint16_t timeout=5000);
|
||||
|
||||
protected:
|
||||
uint16_t BuildRequest(const char* aName);
|
||||
uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress);
|
||||
|
||||
IPAddress iDNSServer;
|
||||
uint16_t iRequestId;
|
||||
EthernetUDP iUdp;
|
||||
};
|
||||
|
||||
#endif
|
236
Arduino/libraries/Ethernet/src/Ethernet.cpp
Normal file
236
Arduino/libraries/Ethernet/src/Ethernet.cpp
Normal file
@ -0,0 +1,236 @@
|
||||
/* Copyright 2018 Paul Stoffregen
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "utility/w5100.h"
|
||||
#include "Dhcp.h"
|
||||
|
||||
IPAddress EthernetClass::_dnsServerAddress;
|
||||
DhcpClass* EthernetClass::_dhcp = NULL;
|
||||
|
||||
int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
|
||||
{
|
||||
static DhcpClass s_dhcp;
|
||||
_dhcp = &s_dhcp;
|
||||
|
||||
// Initialise the basic info
|
||||
if (W5100.init() == 0) return 0;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.setMACAddress(mac);
|
||||
W5100.setIPAddress(IPAddress(0,0,0,0).raw_address());
|
||||
SPI.endTransaction();
|
||||
|
||||
// Now try to get our config info from a DHCP server
|
||||
int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout);
|
||||
if (ret == 1) {
|
||||
// We've successfully found a DHCP server and got our configuration
|
||||
// info, so set things accordingly
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
|
||||
W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
|
||||
W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
|
||||
SPI.endTransaction();
|
||||
_dnsServerAddress = _dhcp->getDnsServerIp();
|
||||
socketPortRand(micros());
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac, IPAddress 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 = ip;
|
||||
dns[3] = 1;
|
||||
begin(mac, ip, dns);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns)
|
||||
{
|
||||
// Assume the gateway will be the machine on the same network as the local IP
|
||||
// but with last octet being '1'
|
||||
IPAddress gateway = ip;
|
||||
gateway[3] = 1;
|
||||
begin(mac, ip, dns, gateway);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway)
|
||||
{
|
||||
IPAddress subnet(255, 255, 255, 0);
|
||||
begin(mac, ip, dns, gateway, subnet);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet)
|
||||
{
|
||||
if (W5100.init() == 0) return;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.setMACAddress(mac);
|
||||
W5100.setIPAddress(ip.raw_address());
|
||||
W5100.setGatewayIp(gateway.raw_address());
|
||||
W5100.setSubnetMask(subnet.raw_address());
|
||||
SPI.endTransaction();
|
||||
_dnsServerAddress = dns;
|
||||
}
|
||||
|
||||
void EthernetClass::init(uint8_t sspin)
|
||||
{
|
||||
W5100.setSS(sspin);
|
||||
}
|
||||
|
||||
EthernetLinkStatus EthernetClass::linkStatus()
|
||||
{
|
||||
switch (W5100.getLinkStatus()) {
|
||||
case UNKNOWN: return Unknown;
|
||||
case LINK_ON: return LinkON;
|
||||
case LINK_OFF: return LinkOFF;
|
||||
default: return Unknown;
|
||||
}
|
||||
}
|
||||
|
||||
EthernetHardwareStatus EthernetClass::hardwareStatus()
|
||||
{
|
||||
switch (W5100.getChip()) {
|
||||
case 51: return EthernetW5100;
|
||||
case 52: return EthernetW5200;
|
||||
case 55: return EthernetW5500;
|
||||
default: return EthernetNoHardware;
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
|
||||
W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
|
||||
W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
|
||||
SPI.endTransaction();
|
||||
_dnsServerAddress = _dhcp->getDnsServerIp();
|
||||
break;
|
||||
default:
|
||||
//this is actually an error, it will retry though
|
||||
break;
|
||||
}
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
|
||||
void EthernetClass::MACAddress(uint8_t *mac_address)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.getMACAddress(mac_address);
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::localIP()
|
||||
{
|
||||
IPAddress ret;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.getIPAddress(ret.raw_address());
|
||||
SPI.endTransaction();
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::subnetMask()
|
||||
{
|
||||
IPAddress ret;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.getSubnetMask(ret.raw_address());
|
||||
SPI.endTransaction();
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::gatewayIP()
|
||||
{
|
||||
IPAddress ret;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.getGatewayIp(ret.raw_address());
|
||||
SPI.endTransaction();
|
||||
return ret;
|
||||
}
|
||||
|
||||
void EthernetClass::setMACAddress(const uint8_t *mac_address)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.setMACAddress(mac_address);
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
void EthernetClass::setLocalIP(const IPAddress local_ip)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
IPAddress ip = local_ip;
|
||||
W5100.setIPAddress(ip.raw_address());
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
void EthernetClass::setSubnetMask(const IPAddress subnet)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
IPAddress ip = subnet;
|
||||
W5100.setSubnetMask(ip.raw_address());
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
void EthernetClass::setGatewayIP(const IPAddress gateway)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
IPAddress ip = gateway;
|
||||
W5100.setGatewayIp(ip.raw_address());
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds)
|
||||
{
|
||||
if (milliseconds > 6553) milliseconds = 6553;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.setRetransmissionTime(milliseconds * 10);
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
void EthernetClass::setRetransmissionCount(uint8_t num)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.setRetransmissionCount(num);
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
EthernetClass Ethernet;
|
323
Arduino/libraries/Ethernet/src/Ethernet.h
Normal file
323
Arduino/libraries/Ethernet/src/Ethernet.h
Normal file
@ -0,0 +1,323 @@
|
||||
/* Copyright 2018 Paul Stoffregen
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#ifndef ethernet_h_
|
||||
#define ethernet_h_
|
||||
|
||||
// All symbols exposed to Arduino sketches are contained in this header file
|
||||
//
|
||||
// Older versions had much of this stuff in EthernetClient.h, EthernetServer.h,
|
||||
// and socket.h. Including headers in different order could cause trouble, so
|
||||
// these "friend" classes are now defined in the same header file. socket.h
|
||||
// was removed to avoid possible conflict with the C library header files.
|
||||
|
||||
|
||||
// Configure the maximum number of sockets to support. W5100 chips can have
|
||||
// up to 4 sockets. W5200 & W5500 can have up to 8 sockets. Several bytes
|
||||
// of RAM are used for each socket. Reducing the maximum can save RAM, but
|
||||
// you are limited to fewer simultaneous connections.
|
||||
#if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048)
|
||||
#define MAX_SOCK_NUM 4
|
||||
#else
|
||||
#define MAX_SOCK_NUM 8
|
||||
#endif
|
||||
|
||||
// By default, each socket uses 2K buffers inside the WIZnet chip. If
|
||||
// MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting
|
||||
// this will use larger buffers within the WIZnet chip. Large buffers
|
||||
// can really help with UDP protocols like Artnet. In theory larger
|
||||
// buffers should allow faster TCP over high-latency links, but this
|
||||
// does not always seem to work in practice (maybe WIZnet bugs?)
|
||||
//#define ETHERNET_LARGE_BUFFERS
|
||||
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Client.h"
|
||||
#include "Server.h"
|
||||
#include "Udp.h"
|
||||
|
||||
enum EthernetLinkStatus {
|
||||
Unknown,
|
||||
LinkON,
|
||||
LinkOFF
|
||||
};
|
||||
|
||||
enum EthernetHardwareStatus {
|
||||
EthernetNoHardware,
|
||||
EthernetW5100,
|
||||
EthernetW5200,
|
||||
EthernetW5500
|
||||
};
|
||||
|
||||
class EthernetUDP;
|
||||
class EthernetClient;
|
||||
class EthernetServer;
|
||||
class DhcpClass;
|
||||
|
||||
class EthernetClass {
|
||||
private:
|
||||
static IPAddress _dnsServerAddress;
|
||||
static DhcpClass* _dhcp;
|
||||
public:
|
||||
// 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
|
||||
static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
|
||||
static int maintain();
|
||||
static EthernetLinkStatus linkStatus();
|
||||
static EthernetHardwareStatus hardwareStatus();
|
||||
|
||||
// Manual configuration
|
||||
static void begin(uint8_t *mac, IPAddress ip);
|
||||
static void begin(uint8_t *mac, IPAddress ip, IPAddress dns);
|
||||
static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway);
|
||||
static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet);
|
||||
static void init(uint8_t sspin = 10);
|
||||
|
||||
static void MACAddress(uint8_t *mac_address);
|
||||
static IPAddress localIP();
|
||||
static IPAddress subnetMask();
|
||||
static IPAddress gatewayIP();
|
||||
static IPAddress dnsServerIP() { return _dnsServerAddress; }
|
||||
|
||||
void setMACAddress(const uint8_t *mac_address);
|
||||
void setLocalIP(const IPAddress local_ip);
|
||||
void setSubnetMask(const IPAddress subnet);
|
||||
void setGatewayIP(const IPAddress gateway);
|
||||
void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; }
|
||||
void setRetransmissionTimeout(uint16_t milliseconds);
|
||||
void setRetransmissionCount(uint8_t num);
|
||||
|
||||
friend class EthernetClient;
|
||||
friend class EthernetServer;
|
||||
friend class EthernetUDP;
|
||||
private:
|
||||
// Opens a socket(TCP or UDP or IP_RAW mode)
|
||||
static uint8_t socketBegin(uint8_t protocol, uint16_t port);
|
||||
static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port);
|
||||
static uint8_t socketStatus(uint8_t s);
|
||||
// Close socket
|
||||
static void socketClose(uint8_t s);
|
||||
// Establish TCP connection (Active connection)
|
||||
static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port);
|
||||
// disconnect the connection
|
||||
static void socketDisconnect(uint8_t s);
|
||||
// Establish TCP connection (Passive connection)
|
||||
static uint8_t socketListen(uint8_t s);
|
||||
// Send data (TCP)
|
||||
static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len);
|
||||
static uint16_t socketSendAvailable(uint8_t s);
|
||||
// Receive data (TCP)
|
||||
static int socketRecv(uint8_t s, uint8_t * buf, int16_t len);
|
||||
static uint16_t socketRecvAvailable(uint8_t s);
|
||||
static uint8_t socketPeek(uint8_t s);
|
||||
// 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 true if the datagram was successfully set up, or false if there was an error
|
||||
static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port);
|
||||
// copy 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
|
||||
static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len);
|
||||
// Send a UDP datagram built up from a sequence of startUDP followed by one or more
|
||||
// calls to bufferData.
|
||||
// return true if the datagram was successfully sent, or false if there was an error
|
||||
static bool socketSendUDP(uint8_t s);
|
||||
// Initialize the "random" source port number
|
||||
static void socketPortRand(uint16_t n);
|
||||
};
|
||||
|
||||
extern EthernetClass Ethernet;
|
||||
|
||||
|
||||
#define UDP_TX_PACKET_MAX_SIZE 24
|
||||
|
||||
class EthernetUDP : public UDP {
|
||||
private:
|
||||
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
|
||||
|
||||
protected:
|
||||
uint8_t sockindex;
|
||||
uint16_t _remaining; // remaining bytes of incoming packet yet to be processed
|
||||
|
||||
public:
|
||||
EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // 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 uint8_t beginMulticast(IPAddress, 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; };
|
||||
virtual uint16_t localPort() { return _port; }
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
class EthernetClient : public Client {
|
||||
public:
|
||||
EthernetClient() : _sockindex(MAX_SOCK_NUM), _timeout(1000) { }
|
||||
EthernetClient(uint8_t s) : _sockindex(s), _timeout(1000) { }
|
||||
virtual ~EthernetClient() {};
|
||||
|
||||
uint8_t status();
|
||||
virtual int connect(IPAddress ip, uint16_t port);
|
||||
virtual int connect(const char *host, uint16_t port);
|
||||
virtual int availableForWrite(void);
|
||||
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() { return _sockindex < MAX_SOCK_NUM; }
|
||||
virtual bool operator==(const bool value) { return bool() == value; }
|
||||
virtual bool operator!=(const bool value) { return bool() != value; }
|
||||
virtual bool operator==(const EthernetClient&);
|
||||
virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); }
|
||||
uint8_t getSocketNumber() const { return _sockindex; }
|
||||
virtual uint16_t localPort();
|
||||
virtual IPAddress remoteIP();
|
||||
virtual uint16_t remotePort();
|
||||
virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; }
|
||||
|
||||
friend class EthernetServer;
|
||||
|
||||
using Print::write;
|
||||
|
||||
private:
|
||||
uint8_t _sockindex; // MAX_SOCK_NUM means client not in use
|
||||
uint16_t _timeout;
|
||||
};
|
||||
|
||||
|
||||
class EthernetServer : public Server {
|
||||
private:
|
||||
uint16_t _port;
|
||||
public:
|
||||
EthernetServer(uint16_t port) : _port(port) { }
|
||||
EthernetClient available();
|
||||
EthernetClient accept();
|
||||
virtual void begin();
|
||||
virtual size_t write(uint8_t);
|
||||
virtual size_t write(const uint8_t *buf, size_t size);
|
||||
virtual operator bool();
|
||||
using Print::write;
|
||||
//void statusreport();
|
||||
|
||||
// TODO: make private when socket allocation moves to EthernetClass
|
||||
static uint16_t server_port[MAX_SOCK_NUM];
|
||||
};
|
||||
|
||||
|
||||
class DhcpClass {
|
||||
private:
|
||||
uint32_t _dhcpInitialTransactionId;
|
||||
uint32_t _dhcpTransactionId;
|
||||
uint8_t _dhcpMacAddr[6];
|
||||
#ifdef __arm__
|
||||
uint8_t _dhcpLocalIp[4] __attribute__((aligned(4)));
|
||||
uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4)));
|
||||
uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4)));
|
||||
uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4)));
|
||||
uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4)));
|
||||
#else
|
||||
uint8_t _dhcpLocalIp[4];
|
||||
uint8_t _dhcpSubnetMask[4];
|
||||
uint8_t _dhcpGatewayIp[4];
|
||||
uint8_t _dhcpDhcpServerIp[4];
|
||||
uint8_t _dhcpDnsServerIp[4];
|
||||
#endif
|
||||
uint32_t _dhcpLeaseTime;
|
||||
uint32_t _dhcpT1, _dhcpT2;
|
||||
uint32_t _renewInSec;
|
||||
uint32_t _rebindInSec;
|
||||
unsigned long _timeout;
|
||||
unsigned long _responseTimeout;
|
||||
unsigned long _lastCheckLeaseMillis;
|
||||
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
|
213
Arduino/libraries/Ethernet/src/EthernetClient.cpp
Normal file
213
Arduino/libraries/Ethernet/src/EthernetClient.cpp
Normal file
@ -0,0 +1,213 @@
|
||||
/* Copyright 2018 Paul Stoffregen
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "Dns.h"
|
||||
#include "utility/w5100.h"
|
||||
|
||||
int EthernetClient::connect(const char * host, uint16_t port)
|
||||
{
|
||||
DNSClient dns; // Look up the host first
|
||||
IPAddress remote_addr;
|
||||
|
||||
if (_sockindex < MAX_SOCK_NUM) {
|
||||
if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) {
|
||||
Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()?
|
||||
}
|
||||
_sockindex = MAX_SOCK_NUM;
|
||||
}
|
||||
dns.begin(Ethernet.dnsServerIP());
|
||||
if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout
|
||||
return connect(remote_addr, port);
|
||||
}
|
||||
|
||||
int EthernetClient::connect(IPAddress ip, uint16_t port)
|
||||
{
|
||||
if (_sockindex < MAX_SOCK_NUM) {
|
||||
if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) {
|
||||
Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()?
|
||||
}
|
||||
_sockindex = MAX_SOCK_NUM;
|
||||
}
|
||||
#if defined(ESP8266) || defined(ESP32)
|
||||
if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0;
|
||||
#else
|
||||
if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0;
|
||||
#endif
|
||||
_sockindex = Ethernet.socketBegin(SnMR::TCP, 0);
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
Ethernet.socketConnect(_sockindex, rawIPAddress(ip), port);
|
||||
uint32_t start = millis();
|
||||
while (1) {
|
||||
uint8_t stat = Ethernet.socketStatus(_sockindex);
|
||||
if (stat == SnSR::ESTABLISHED) return 1;
|
||||
if (stat == SnSR::CLOSE_WAIT) return 1;
|
||||
if (stat == SnSR::CLOSED) return 0;
|
||||
if (millis() - start > _timeout) break;
|
||||
delay(1);
|
||||
}
|
||||
Ethernet.socketClose(_sockindex);
|
||||
_sockindex = MAX_SOCK_NUM;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int EthernetClient::availableForWrite(void)
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
return Ethernet.socketSendAvailable(_sockindex);
|
||||
}
|
||||
|
||||
size_t EthernetClient::write(uint8_t b)
|
||||
{
|
||||
return write(&b, 1);
|
||||
}
|
||||
|
||||
size_t EthernetClient::write(const uint8_t *buf, size_t size)
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
if (Ethernet.socketSend(_sockindex, buf, size)) return size;
|
||||
setWriteError();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int EthernetClient::available()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
return Ethernet.socketRecvAvailable(_sockindex);
|
||||
// TODO: do the WIZnet chips automatically retransmit TCP ACK
|
||||
// packets if they are lost by the network? Someday this should
|
||||
// be checked by a man-in-the-middle test which discards certain
|
||||
// packets. If ACKs aren't resent, we would need to check for
|
||||
// returning 0 here and after a timeout do another Sock_RECV
|
||||
// command to cause the WIZnet chip to resend the ACK packet.
|
||||
}
|
||||
|
||||
int EthernetClient::read(uint8_t *buf, size_t size)
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
return Ethernet.socketRecv(_sockindex, buf, size);
|
||||
}
|
||||
|
||||
int EthernetClient::peek()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return -1;
|
||||
if (!available()) return -1;
|
||||
return Ethernet.socketPeek(_sockindex);
|
||||
}
|
||||
|
||||
int EthernetClient::read()
|
||||
{
|
||||
uint8_t b;
|
||||
if (Ethernet.socketRecv(_sockindex, &b, 1) > 0) return b;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void EthernetClient::flush()
|
||||
{
|
||||
while (_sockindex < MAX_SOCK_NUM) {
|
||||
uint8_t stat = Ethernet.socketStatus(_sockindex);
|
||||
if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return;
|
||||
if (Ethernet.socketSendAvailable(_sockindex) >= W5100.SSIZE) return;
|
||||
}
|
||||
}
|
||||
|
||||
void EthernetClient::stop()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return;
|
||||
|
||||
// attempt to close the connection gracefully (send a FIN to other side)
|
||||
Ethernet.socketDisconnect(_sockindex);
|
||||
unsigned long start = millis();
|
||||
|
||||
// wait up to a second for the connection to close
|
||||
do {
|
||||
if (Ethernet.socketStatus(_sockindex) == SnSR::CLOSED) {
|
||||
_sockindex = MAX_SOCK_NUM;
|
||||
return; // exit the loop
|
||||
}
|
||||
delay(1);
|
||||
} while (millis() - start < _timeout);
|
||||
|
||||
// if it hasn't closed, close it forcefully
|
||||
Ethernet.socketClose(_sockindex);
|
||||
_sockindex = MAX_SOCK_NUM;
|
||||
}
|
||||
|
||||
uint8_t EthernetClient::connected()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
|
||||
uint8_t s = Ethernet.socketStatus(_sockindex);
|
||||
return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
|
||||
(s == SnSR::CLOSE_WAIT && !available()));
|
||||
}
|
||||
|
||||
uint8_t EthernetClient::status()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED;
|
||||
return Ethernet.socketStatus(_sockindex);
|
||||
}
|
||||
|
||||
// the next function allows us to use the client returned by
|
||||
// EthernetServer::available() as the condition in an if-statement.
|
||||
bool EthernetClient::operator==(const EthernetClient& rhs)
|
||||
{
|
||||
if (_sockindex != rhs._sockindex) return false;
|
||||
if (_sockindex >= MAX_SOCK_NUM) return false;
|
||||
if (rhs._sockindex >= MAX_SOCK_NUM) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// https://github.com/per1234/EthernetMod
|
||||
// from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd
|
||||
uint16_t EthernetClient::localPort()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
uint16_t port;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
port = W5100.readSnPORT(_sockindex);
|
||||
SPI.endTransaction();
|
||||
return port;
|
||||
}
|
||||
|
||||
// https://github.com/per1234/EthernetMod
|
||||
// returns the remote IP address: https://forum.arduino.cc/index.php?topic=82416.0
|
||||
IPAddress EthernetClient::remoteIP()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0);
|
||||
uint8_t remoteIParray[4];
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.readSnDIPR(_sockindex, remoteIParray);
|
||||
SPI.endTransaction();
|
||||
return IPAddress(remoteIParray);
|
||||
}
|
||||
|
||||
// https://github.com/per1234/EthernetMod
|
||||
// from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75
|
||||
uint16_t EthernetClient::remotePort()
|
||||
{
|
||||
if (_sockindex >= MAX_SOCK_NUM) return 0;
|
||||
uint16_t port;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
port = W5100.readSnDPORT(_sockindex);
|
||||
SPI.endTransaction();
|
||||
return port;
|
||||
}
|
3
Arduino/libraries/Ethernet/src/EthernetClient.h
Normal file
3
Arduino/libraries/Ethernet/src/EthernetClient.h
Normal file
@ -0,0 +1,3 @@
|
||||
// This file is in the public domain. No copyright is claimed.
|
||||
|
||||
#include "Ethernet.h"
|
179
Arduino/libraries/Ethernet/src/EthernetServer.cpp
Normal file
179
Arduino/libraries/Ethernet/src/EthernetServer.cpp
Normal file
@ -0,0 +1,179 @@
|
||||
/* Copyright 2018 Paul Stoffregen
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "utility/w5100.h"
|
||||
|
||||
uint16_t EthernetServer::server_port[MAX_SOCK_NUM];
|
||||
|
||||
|
||||
void EthernetServer::begin()
|
||||
{
|
||||
uint8_t sockindex = Ethernet.socketBegin(SnMR::TCP, _port);
|
||||
if (sockindex < MAX_SOCK_NUM) {
|
||||
if (Ethernet.socketListen(sockindex)) {
|
||||
server_port[sockindex] = _port;
|
||||
} else {
|
||||
Ethernet.socketDisconnect(sockindex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EthernetClient EthernetServer::available()
|
||||
{
|
||||
bool listening = false;
|
||||
uint8_t sockindex = MAX_SOCK_NUM;
|
||||
uint8_t chip, maxindex=MAX_SOCK_NUM;
|
||||
|
||||
chip = W5100.getChip();
|
||||
if (!chip) return EthernetClient(MAX_SOCK_NUM);
|
||||
#if MAX_SOCK_NUM > 4
|
||||
if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
|
||||
#endif
|
||||
for (uint8_t i=0; i < maxindex; i++) {
|
||||
if (server_port[i] == _port) {
|
||||
uint8_t stat = Ethernet.socketStatus(i);
|
||||
if (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT) {
|
||||
if (Ethernet.socketRecvAvailable(i) > 0) {
|
||||
sockindex = i;
|
||||
} else {
|
||||
// remote host closed connection, our end still open
|
||||
if (stat == SnSR::CLOSE_WAIT) {
|
||||
Ethernet.socketDisconnect(i);
|
||||
// status becomes LAST_ACK for short time
|
||||
}
|
||||
}
|
||||
} else if (stat == SnSR::LISTEN) {
|
||||
listening = true;
|
||||
} else if (stat == SnSR::CLOSED) {
|
||||
server_port[i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!listening) begin();
|
||||
return EthernetClient(sockindex);
|
||||
}
|
||||
|
||||
EthernetClient EthernetServer::accept()
|
||||
{
|
||||
bool listening = false;
|
||||
uint8_t sockindex = MAX_SOCK_NUM;
|
||||
uint8_t chip, maxindex=MAX_SOCK_NUM;
|
||||
|
||||
chip = W5100.getChip();
|
||||
if (!chip) return EthernetClient(MAX_SOCK_NUM);
|
||||
#if MAX_SOCK_NUM > 4
|
||||
if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
|
||||
#endif
|
||||
for (uint8_t i=0; i < maxindex; i++) {
|
||||
if (server_port[i] == _port) {
|
||||
uint8_t stat = Ethernet.socketStatus(i);
|
||||
if (sockindex == MAX_SOCK_NUM &&
|
||||
(stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT)) {
|
||||
// Return the connected client even if no data received.
|
||||
// Some protocols like FTP expect the server to send the
|
||||
// first data.
|
||||
sockindex = i;
|
||||
server_port[i] = 0; // only return the client once
|
||||
} else if (stat == SnSR::LISTEN) {
|
||||
listening = true;
|
||||
} else if (stat == SnSR::CLOSED) {
|
||||
server_port[i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!listening) begin();
|
||||
return EthernetClient(sockindex);
|
||||
}
|
||||
|
||||
EthernetServer::operator bool()
|
||||
{
|
||||
uint8_t maxindex=MAX_SOCK_NUM;
|
||||
#if MAX_SOCK_NUM > 4
|
||||
if (W5100.getChip() == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
|
||||
#endif
|
||||
for (uint8_t i=0; i < maxindex; i++) {
|
||||
if (server_port[i] == _port) {
|
||||
if (Ethernet.socketStatus(i) == SnSR::LISTEN) {
|
||||
return true; // server is listening for incoming clients
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#if 0
|
||||
void EthernetServer::statusreport()
|
||||
{
|
||||
Serial.printf("EthernetServer, port=%d\n", _port);
|
||||
for (uint8_t i=0; i < MAX_SOCK_NUM; i++) {
|
||||
uint16_t port = server_port[i];
|
||||
uint8_t stat = Ethernet.socketStatus(i);
|
||||
const char *name;
|
||||
switch (stat) {
|
||||
case 0x00: name = "CLOSED"; break;
|
||||
case 0x13: name = "INIT"; break;
|
||||
case 0x14: name = "LISTEN"; break;
|
||||
case 0x15: name = "SYNSENT"; break;
|
||||
case 0x16: name = "SYNRECV"; break;
|
||||
case 0x17: name = "ESTABLISHED"; break;
|
||||
case 0x18: name = "FIN_WAIT"; break;
|
||||
case 0x1A: name = "CLOSING"; break;
|
||||
case 0x1B: name = "TIME_WAIT"; break;
|
||||
case 0x1C: name = "CLOSE_WAIT"; break;
|
||||
case 0x1D: name = "LAST_ACK"; break;
|
||||
case 0x22: name = "UDP"; break;
|
||||
case 0x32: name = "IPRAW"; break;
|
||||
case 0x42: name = "MACRAW"; break;
|
||||
case 0x5F: name = "PPPOE"; break;
|
||||
default: name = "???";
|
||||
}
|
||||
int avail = Ethernet.socketRecvAvailable(i);
|
||||
Serial.printf(" %d: port=%d, status=%s (0x%02X), avail=%d\n",
|
||||
i, port, name, stat, avail);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
size_t EthernetServer::write(uint8_t b)
|
||||
{
|
||||
return write(&b, 1);
|
||||
}
|
||||
|
||||
size_t EthernetServer::write(const uint8_t *buffer, size_t size)
|
||||
{
|
||||
uint8_t chip, maxindex=MAX_SOCK_NUM;
|
||||
|
||||
chip = W5100.getChip();
|
||||
if (!chip) return 0;
|
||||
#if MAX_SOCK_NUM > 4
|
||||
if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
|
||||
#endif
|
||||
available();
|
||||
for (uint8_t i=0; i < maxindex; i++) {
|
||||
if (server_port[i] == _port) {
|
||||
if (Ethernet.socketStatus(i) == SnSR::ESTABLISHED) {
|
||||
Ethernet.socketSend(i, buffer, size);
|
||||
}
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
3
Arduino/libraries/Ethernet/src/EthernetServer.h
Normal file
3
Arduino/libraries/Ethernet/src/EthernetServer.h
Normal file
@ -0,0 +1,3 @@
|
||||
// This file is in the public domain. No copyright is claimed.
|
||||
|
||||
#include "Ethernet.h"
|
190
Arduino/libraries/Ethernet/src/EthernetUdp.cpp
Normal file
190
Arduino/libraries/Ethernet/src/EthernetUdp.cpp
Normal file
@ -0,0 +1,190 @@
|
||||
/*
|
||||
* Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield.
|
||||
* This version only offers minimal wrapping of socket.cpp
|
||||
* 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 <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "Dns.h"
|
||||
#include "utility/w5100.h"
|
||||
|
||||
/* Start EthernetUDP socket, listening at local port PORT */
|
||||
uint8_t EthernetUDP::begin(uint16_t port)
|
||||
{
|
||||
if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex);
|
||||
sockindex = Ethernet.socketBegin(SnMR::UDP, port);
|
||||
if (sockindex >= MAX_SOCK_NUM) return 0;
|
||||
_port = port;
|
||||
_remaining = 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 (sockindex < MAX_SOCK_NUM) {
|
||||
Ethernet.socketClose(sockindex);
|
||||
sockindex = 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 ret;
|
||||
return beginPacket(remote_addr, port);
|
||||
}
|
||||
|
||||
int EthernetUDP::beginPacket(IPAddress ip, uint16_t port)
|
||||
{
|
||||
_offset = 0;
|
||||
//Serial.printf("UDP beginPacket\n");
|
||||
return Ethernet.socketStartUDP(sockindex, rawIPAddress(ip), port);
|
||||
}
|
||||
|
||||
int EthernetUDP::endPacket()
|
||||
{
|
||||
return Ethernet.socketSendUDP(sockindex);
|
||||
}
|
||||
|
||||
size_t EthernetUDP::write(uint8_t byte)
|
||||
{
|
||||
return write(&byte, 1);
|
||||
}
|
||||
|
||||
size_t EthernetUDP::write(const uint8_t *buffer, size_t size)
|
||||
{
|
||||
//Serial.printf("UDP write %d\n", size);
|
||||
uint16_t bytes_written = Ethernet.socketBufferData(sockindex, _offset, buffer, size);
|
||||
_offset += bytes_written;
|
||||
return bytes_written;
|
||||
}
|
||||
|
||||
int EthernetUDP::parsePacket()
|
||||
{
|
||||
// discard any remaining bytes in the last packet
|
||||
while (_remaining) {
|
||||
// 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 :)
|
||||
read((uint8_t *)NULL, _remaining);
|
||||
}
|
||||
|
||||
if (Ethernet.socketRecvAvailable(sockindex) > 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 = Ethernet.socketRecv(sockindex, 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) && (Ethernet.socketRecv(sockindex, &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 = Ethernet.socketRecv(sockindex, buffer, _remaining);
|
||||
} else {
|
||||
// too much data for the buffer,
|
||||
// grab as much as will fit
|
||||
got = Ethernet.socketRecv(sockindex, buffer, len);
|
||||
}
|
||||
if (got > 0) {
|
||||
_remaining -= got;
|
||||
//Serial.printf("UDP read %d\n", got);
|
||||
return got;
|
||||
}
|
||||
}
|
||||
// If we get here, there's no data available or recv failed
|
||||
return -1;
|
||||
}
|
||||
|
||||
int EthernetUDP::peek()
|
||||
{
|
||||
// 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 (sockindex >= MAX_SOCK_NUM || _remaining == 0) return -1;
|
||||
return Ethernet.socketPeek(sockindex);
|
||||
}
|
||||
|
||||
void EthernetUDP::flush()
|
||||
{
|
||||
// TODO: we should wait for TX buffer to be emptied
|
||||
}
|
||||
|
||||
/* Start EthernetUDP socket, listening at local port PORT */
|
||||
uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port)
|
||||
{
|
||||
if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex);
|
||||
sockindex = Ethernet.socketBeginMulticast(SnMR::UDP | SnMR::MULTI, ip, port);
|
||||
if (sockindex >= MAX_SOCK_NUM) return 0;
|
||||
_port = port;
|
||||
_remaining = 0;
|
||||
return 1;
|
||||
}
|
38
Arduino/libraries/Ethernet/src/EthernetUdp.h
Normal file
38
Arduino/libraries/Ethernet/src/EthernetUdp.h
Normal file
@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield.
|
||||
* This version only offers minimal wrapping of socket.cpp
|
||||
* 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
|
||||
*/
|
||||
|
||||
#include "Ethernet.h"
|
||||
|
538
Arduino/libraries/Ethernet/src/socket.cpp
Normal file
538
Arduino/libraries/Ethernet/src/socket.cpp
Normal file
@ -0,0 +1,538 @@
|
||||
/* Copyright 2018 Paul Stoffregen
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "utility/w5100.h"
|
||||
|
||||
#if ARDUINO >= 156 && !defined(ARDUINO_ARCH_PIC32)
|
||||
extern void yield(void);
|
||||
#else
|
||||
#define yield()
|
||||
#endif
|
||||
|
||||
// TODO: randomize this when not using DHCP, but how?
|
||||
static uint16_t local_port = 49152; // 49152 to 65535
|
||||
|
||||
typedef struct {
|
||||
uint16_t RX_RSR; // Number of bytes received
|
||||
uint16_t RX_RD; // Address to read
|
||||
uint16_t TX_FSR; // Free space ready for transmit
|
||||
uint8_t RX_inc; // how much have we advanced RX_RD
|
||||
} socketstate_t;
|
||||
|
||||
static socketstate_t state[MAX_SOCK_NUM];
|
||||
|
||||
|
||||
static uint16_t getSnTX_FSR(uint8_t s);
|
||||
static uint16_t getSnRX_RSR(uint8_t s);
|
||||
static void write_data(uint8_t s, uint16_t offset, const uint8_t *data, uint16_t len);
|
||||
static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len);
|
||||
|
||||
|
||||
|
||||
/*****************************************/
|
||||
/* Socket management */
|
||||
/*****************************************/
|
||||
|
||||
|
||||
void EthernetClass::socketPortRand(uint16_t n)
|
||||
{
|
||||
n &= 0x3FFF;
|
||||
local_port ^= n;
|
||||
//Serial.printf("socketPortRand %d, srcport=%d\n", n, local_port);
|
||||
}
|
||||
|
||||
uint8_t EthernetClass::socketBegin(uint8_t protocol, uint16_t port)
|
||||
{
|
||||
uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM;
|
||||
|
||||
// first check hardware compatibility
|
||||
chip = W5100.getChip();
|
||||
if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected
|
||||
#if MAX_SOCK_NUM > 4
|
||||
if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
|
||||
#endif
|
||||
//Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port);
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
// look at all the hardware sockets, use any that are closed (unused)
|
||||
for (s=0; s < maxindex; s++) {
|
||||
status[s] = W5100.readSnSR(s);
|
||||
if (status[s] == SnSR::CLOSED) goto makesocket;
|
||||
}
|
||||
//Serial.printf("W5000socket step2\n");
|
||||
// as a last resort, forcibly close any already closing
|
||||
for (s=0; s < maxindex; s++) {
|
||||
uint8_t stat = status[s];
|
||||
if (stat == SnSR::LAST_ACK) goto closemakesocket;
|
||||
if (stat == SnSR::TIME_WAIT) goto closemakesocket;
|
||||
if (stat == SnSR::FIN_WAIT) goto closemakesocket;
|
||||
if (stat == SnSR::CLOSING) goto closemakesocket;
|
||||
}
|
||||
#if 0
|
||||
Serial.printf("W5000socket step3\n");
|
||||
// next, use any that are effectively closed
|
||||
for (s=0; s < MAX_SOCK_NUM; s++) {
|
||||
uint8_t stat = status[s];
|
||||
// TODO: this also needs to check if no more data
|
||||
if (stat == SnSR::CLOSE_WAIT) goto closemakesocket;
|
||||
}
|
||||
#endif
|
||||
SPI.endTransaction();
|
||||
return MAX_SOCK_NUM; // all sockets are in use
|
||||
closemakesocket:
|
||||
//Serial.printf("W5000socket close\n");
|
||||
W5100.execCmdSn(s, Sock_CLOSE);
|
||||
makesocket:
|
||||
//Serial.printf("W5000socket %d\n", s);
|
||||
EthernetServer::server_port[s] = 0;
|
||||
delayMicroseconds(250); // TODO: is this needed??
|
||||
W5100.writeSnMR(s, protocol);
|
||||
W5100.writeSnIR(s, 0xFF);
|
||||
if (port > 0) {
|
||||
W5100.writeSnPORT(s, port);
|
||||
} else {
|
||||
// if don't set the source port, set local_port number.
|
||||
if (++local_port < 49152) local_port = 49152;
|
||||
W5100.writeSnPORT(s, local_port);
|
||||
}
|
||||
W5100.execCmdSn(s, Sock_OPEN);
|
||||
state[s].RX_RSR = 0;
|
||||
state[s].RX_RD = W5100.readSnRX_RD(s); // always zero?
|
||||
state[s].RX_inc = 0;
|
||||
state[s].TX_FSR = 0;
|
||||
//Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD);
|
||||
SPI.endTransaction();
|
||||
return s;
|
||||
}
|
||||
|
||||
// multicast version to set fields before open thd
|
||||
uint8_t EthernetClass::socketBeginMulticast(uint8_t protocol, IPAddress ip, uint16_t port)
|
||||
{
|
||||
uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM;
|
||||
|
||||
// first check hardware compatibility
|
||||
chip = W5100.getChip();
|
||||
if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected
|
||||
#if MAX_SOCK_NUM > 4
|
||||
if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets
|
||||
#endif
|
||||
//Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port);
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
// look at all the hardware sockets, use any that are closed (unused)
|
||||
for (s=0; s < maxindex; s++) {
|
||||
status[s] = W5100.readSnSR(s);
|
||||
if (status[s] == SnSR::CLOSED) goto makesocket;
|
||||
}
|
||||
//Serial.printf("W5000socket step2\n");
|
||||
// as a last resort, forcibly close any already closing
|
||||
for (s=0; s < maxindex; s++) {
|
||||
uint8_t stat = status[s];
|
||||
if (stat == SnSR::LAST_ACK) goto closemakesocket;
|
||||
if (stat == SnSR::TIME_WAIT) goto closemakesocket;
|
||||
if (stat == SnSR::FIN_WAIT) goto closemakesocket;
|
||||
if (stat == SnSR::CLOSING) goto closemakesocket;
|
||||
}
|
||||
#if 0
|
||||
Serial.printf("W5000socket step3\n");
|
||||
// next, use any that are effectively closed
|
||||
for (s=0; s < MAX_SOCK_NUM; s++) {
|
||||
uint8_t stat = status[s];
|
||||
// TODO: this also needs to check if no more data
|
||||
if (stat == SnSR::CLOSE_WAIT) goto closemakesocket;
|
||||
}
|
||||
#endif
|
||||
SPI.endTransaction();
|
||||
return MAX_SOCK_NUM; // all sockets are in use
|
||||
closemakesocket:
|
||||
//Serial.printf("W5000socket close\n");
|
||||
W5100.execCmdSn(s, Sock_CLOSE);
|
||||
makesocket:
|
||||
//Serial.printf("W5000socket %d\n", s);
|
||||
EthernetServer::server_port[s] = 0;
|
||||
delayMicroseconds(250); // TODO: is this needed??
|
||||
W5100.writeSnMR(s, protocol);
|
||||
W5100.writeSnIR(s, 0xFF);
|
||||
if (port > 0) {
|
||||
W5100.writeSnPORT(s, port);
|
||||
} else {
|
||||
// if don't set the source port, set local_port number.
|
||||
if (++local_port < 49152) local_port = 49152;
|
||||
W5100.writeSnPORT(s, local_port);
|
||||
}
|
||||
// Calculate MAC address from Multicast IP Address
|
||||
byte mac[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00 };
|
||||
mac[3] = ip[1] & 0x7F;
|
||||
mac[4] = ip[2];
|
||||
mac[5] = ip[3];
|
||||
W5100.writeSnDIPR(s, ip.raw_address()); //239.255.0.1
|
||||
W5100.writeSnDPORT(s, port);
|
||||
W5100.writeSnDHAR(s, mac);
|
||||
W5100.execCmdSn(s, Sock_OPEN);
|
||||
state[s].RX_RSR = 0;
|
||||
state[s].RX_RD = W5100.readSnRX_RD(s); // always zero?
|
||||
state[s].RX_inc = 0;
|
||||
state[s].TX_FSR = 0;
|
||||
//Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD);
|
||||
SPI.endTransaction();
|
||||
return s;
|
||||
}
|
||||
// Return the socket's status
|
||||
//
|
||||
uint8_t EthernetClass::socketStatus(uint8_t s)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
uint8_t status = W5100.readSnSR(s);
|
||||
SPI.endTransaction();
|
||||
return status;
|
||||
}
|
||||
|
||||
// Immediately close. If a TCP connection is established, the
|
||||
// remote host is left unaware we closed.
|
||||
//
|
||||
void EthernetClass::socketClose(uint8_t s)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.execCmdSn(s, Sock_CLOSE);
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
|
||||
// Place the socket in listening (server) mode
|
||||
//
|
||||
uint8_t EthernetClass::socketListen(uint8_t s)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
if (W5100.readSnSR(s) != SnSR::INIT) {
|
||||
SPI.endTransaction();
|
||||
return 0;
|
||||
}
|
||||
W5100.execCmdSn(s, Sock_LISTEN);
|
||||
SPI.endTransaction();
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
// establish a TCP connection in Active (client) mode.
|
||||
//
|
||||
void EthernetClass::socketConnect(uint8_t s, uint8_t * addr, uint16_t port)
|
||||
{
|
||||
// set destination IP
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.writeSnDIPR(s, addr);
|
||||
W5100.writeSnDPORT(s, port);
|
||||
W5100.execCmdSn(s, Sock_CONNECT);
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Gracefully disconnect a TCP connection.
|
||||
//
|
||||
void EthernetClass::socketDisconnect(uint8_t s)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.execCmdSn(s, Sock_DISCON);
|
||||
SPI.endTransaction();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*****************************************/
|
||||
/* Socket Data Receive Functions */
|
||||
/*****************************************/
|
||||
|
||||
|
||||
static uint16_t getSnRX_RSR(uint8_t s)
|
||||
{
|
||||
#if 1
|
||||
uint16_t val, prev;
|
||||
|
||||
prev = W5100.readSnRX_RSR(s);
|
||||
while (1) {
|
||||
val = W5100.readSnRX_RSR(s);
|
||||
if (val == prev) {
|
||||
return val;
|
||||
}
|
||||
prev = val;
|
||||
}
|
||||
#else
|
||||
uint16_t val = W5100.readSnRX_RSR(s);
|
||||
return val;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len)
|
||||
{
|
||||
uint16_t size;
|
||||
uint16_t src_mask;
|
||||
uint16_t src_ptr;
|
||||
|
||||
//Serial.printf("read_data, len=%d, at:%d\n", len, src);
|
||||
src_mask = (uint16_t)src & W5100.SMASK;
|
||||
src_ptr = W5100.RBASE(s) + src_mask;
|
||||
|
||||
if (W5100.hasOffsetAddressMapping() || src_mask + len <= W5100.SSIZE) {
|
||||
W5100.read(src_ptr, dst, len);
|
||||
} else {
|
||||
size = W5100.SSIZE - src_mask;
|
||||
W5100.read(src_ptr, dst, size);
|
||||
dst += size;
|
||||
W5100.read(W5100.RBASE(s), dst, len - size);
|
||||
}
|
||||
}
|
||||
|
||||
// Receive data. Returns size, or -1 for no data, or 0 if connection closed
|
||||
//
|
||||
int EthernetClass::socketRecv(uint8_t s, uint8_t *buf, int16_t len)
|
||||
{
|
||||
// Check how much data is available
|
||||
int ret = state[s].RX_RSR;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
if (ret < len) {
|
||||
uint16_t rsr = getSnRX_RSR(s);
|
||||
ret = rsr - state[s].RX_inc;
|
||||
state[s].RX_RSR = ret;
|
||||
//Serial.printf("Sock_RECV, RX_RSR=%d, RX_inc=%d\n", ret, state[s].RX_inc);
|
||||
}
|
||||
if (ret == 0) {
|
||||
// No data available.
|
||||
uint8_t status = W5100.readSnSR(s);
|
||||
if ( status == SnSR::LISTEN || status == SnSR::CLOSED ||
|
||||
status == SnSR::CLOSE_WAIT ) {
|
||||
// The remote end has closed its side of the connection,
|
||||
// so this is the eof state
|
||||
ret = 0;
|
||||
} else {
|
||||
// The connection is still up, but there's no data waiting to be read
|
||||
ret = -1;
|
||||
}
|
||||
} else {
|
||||
if (ret > len) ret = len; // more data available than buffer length
|
||||
uint16_t ptr = state[s].RX_RD;
|
||||
if (buf) read_data(s, ptr, buf, ret);
|
||||
ptr += ret;
|
||||
state[s].RX_RD = ptr;
|
||||
state[s].RX_RSR -= ret;
|
||||
uint16_t inc = state[s].RX_inc + ret;
|
||||
if (inc >= 250 || state[s].RX_RSR == 0) {
|
||||
state[s].RX_inc = 0;
|
||||
W5100.writeSnRX_RD(s, ptr);
|
||||
W5100.execCmdSn(s, Sock_RECV);
|
||||
//Serial.printf("Sock_RECV cmd, RX_RD=%d, RX_RSR=%d\n",
|
||||
// state[s].RX_RD, state[s].RX_RSR);
|
||||
} else {
|
||||
state[s].RX_inc = inc;
|
||||
}
|
||||
}
|
||||
SPI.endTransaction();
|
||||
//Serial.printf("socketRecv, ret=%d\n", ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
uint16_t EthernetClass::socketRecvAvailable(uint8_t s)
|
||||
{
|
||||
uint16_t ret = state[s].RX_RSR;
|
||||
if (ret == 0) {
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
uint16_t rsr = getSnRX_RSR(s);
|
||||
SPI.endTransaction();
|
||||
ret = rsr - state[s].RX_inc;
|
||||
state[s].RX_RSR = ret;
|
||||
//Serial.printf("sockRecvAvailable s=%d, RX_RSR=%d\n", s, ret);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
// get the first byte in the receive queue (no checking)
|
||||
//
|
||||
uint8_t EthernetClass::socketPeek(uint8_t s)
|
||||
{
|
||||
uint8_t b;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
uint16_t ptr = state[s].RX_RD;
|
||||
W5100.read((ptr & W5100.SMASK) + W5100.RBASE(s), &b, 1);
|
||||
SPI.endTransaction();
|
||||
return b;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*****************************************/
|
||||
/* Socket Data Transmit Functions */
|
||||
/*****************************************/
|
||||
|
||||
static uint16_t getSnTX_FSR(uint8_t s)
|
||||
{
|
||||
uint16_t val, prev;
|
||||
|
||||
prev = W5100.readSnTX_FSR(s);
|
||||
while (1) {
|
||||
val = W5100.readSnTX_FSR(s);
|
||||
if (val == prev) {
|
||||
state[s].TX_FSR = val;
|
||||
return val;
|
||||
}
|
||||
prev = val;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void write_data(uint8_t s, uint16_t data_offset, const uint8_t *data, uint16_t len)
|
||||
{
|
||||
uint16_t ptr = W5100.readSnTX_WR(s);
|
||||
ptr += data_offset;
|
||||
uint16_t offset = ptr & W5100.SMASK;
|
||||
uint16_t dstAddr = offset + W5100.SBASE(s);
|
||||
|
||||
if (W5100.hasOffsetAddressMapping() || offset + len <= W5100.SSIZE) {
|
||||
W5100.write(dstAddr, data, len);
|
||||
} else {
|
||||
// Wrap around circular buffer
|
||||
uint16_t size = W5100.SSIZE - offset;
|
||||
W5100.write(dstAddr, data, size);
|
||||
W5100.write(W5100.SBASE(s), data + size, len - size);
|
||||
}
|
||||
ptr += len;
|
||||
W5100.writeSnTX_WR(s, ptr);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief This function used to send the data in TCP mode
|
||||
* @return 1 for success else 0.
|
||||
*/
|
||||
uint16_t EthernetClass::socketSend(uint8_t s, const uint8_t * buf, uint16_t len)
|
||||
{
|
||||
uint8_t status=0;
|
||||
uint16_t ret=0;
|
||||
uint16_t freesize=0;
|
||||
|
||||
if (len > W5100.SSIZE) {
|
||||
ret = W5100.SSIZE; // check size not to exceed MAX size.
|
||||
} else {
|
||||
ret = len;
|
||||
}
|
||||
|
||||
// if freebuf is available, start.
|
||||
do {
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
freesize = getSnTX_FSR(s);
|
||||
status = W5100.readSnSR(s);
|
||||
SPI.endTransaction();
|
||||
if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) {
|
||||
ret = 0;
|
||||
break;
|
||||
}
|
||||
yield();
|
||||
} while (freesize < ret);
|
||||
|
||||
// copy data
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
write_data(s, 0, (uint8_t *)buf, ret);
|
||||
W5100.execCmdSn(s, Sock_SEND);
|
||||
|
||||
/* +2008.01 bj */
|
||||
while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) {
|
||||
/* m2008.01 [bj] : reduce code */
|
||||
if ( W5100.readSnSR(s) == SnSR::CLOSED ) {
|
||||
SPI.endTransaction();
|
||||
return 0;
|
||||
}
|
||||
SPI.endTransaction();
|
||||
yield();
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
}
|
||||
/* +2008.01 bj */
|
||||
W5100.writeSnIR(s, SnIR::SEND_OK);
|
||||
SPI.endTransaction();
|
||||
return ret;
|
||||
}
|
||||
|
||||
uint16_t EthernetClass::socketSendAvailable(uint8_t s)
|
||||
{
|
||||
uint8_t status=0;
|
||||
uint16_t freesize=0;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
freesize = getSnTX_FSR(s);
|
||||
status = W5100.readSnSR(s);
|
||||
SPI.endTransaction();
|
||||
if ((status == SnSR::ESTABLISHED) || (status == SnSR::CLOSE_WAIT)) {
|
||||
return freesize;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t EthernetClass::socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len)
|
||||
{
|
||||
//Serial.printf(" bufferData, offset=%d, len=%d\n", offset, len);
|
||||
uint16_t ret =0;
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
uint16_t txfree = getSnTX_FSR(s);
|
||||
if (len > txfree) {
|
||||
ret = txfree; // check size not to exceed MAX size.
|
||||
} else {
|
||||
ret = len;
|
||||
}
|
||||
write_data(s, offset, buf, ret);
|
||||
SPI.endTransaction();
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool EthernetClass::socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port)
|
||||
{
|
||||
if ( ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) ||
|
||||
((port == 0x00)) ) {
|
||||
return false;
|
||||
}
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.writeSnDIPR(s, addr);
|
||||
W5100.writeSnDPORT(s, port);
|
||||
SPI.endTransaction();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EthernetClass::socketSendUDP(uint8_t s)
|
||||
{
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
W5100.execCmdSn(s, Sock_SEND);
|
||||
|
||||
/* +2008.01 bj */
|
||||
while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) {
|
||||
if (W5100.readSnIR(s) & SnIR::TIMEOUT) {
|
||||
/* +2008.01 [bj]: clear interrupt */
|
||||
W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT));
|
||||
SPI.endTransaction();
|
||||
//Serial.printf("sendUDP timeout\n");
|
||||
return false;
|
||||
}
|
||||
SPI.endTransaction();
|
||||
yield();
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
}
|
||||
|
||||
/* +2008.01 bj */
|
||||
W5100.writeSnIR(s, SnIR::SEND_OK);
|
||||
SPI.endTransaction();
|
||||
|
||||
//Serial.printf("sendUDP ok\n");
|
||||
/* Sent ok */
|
||||
return true;
|
||||
}
|
474
Arduino/libraries/Ethernet/src/utility/w5100.cpp
Normal file
474
Arduino/libraries/Ethernet/src/utility/w5100.cpp
Normal file
@ -0,0 +1,474 @@
|
||||
/*
|
||||
* Copyright 2018 Paul Stoffregen
|
||||
* Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
|
||||
*
|
||||
* This file is free software; you can redistribute it and/or modify
|
||||
* it under the terms of either the GNU General Public License version 2
|
||||
* or the GNU Lesser General Public License version 2.1, both as
|
||||
* published by the Free Software Foundation.
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "Ethernet.h"
|
||||
#include "w5100.h"
|
||||
|
||||
|
||||
/***************************************************/
|
||||
/** Default SS pin setting **/
|
||||
/***************************************************/
|
||||
|
||||
// If variant.h or other headers specifically define the
|
||||
// default SS pin for Ethernet, use it.
|
||||
#if defined(PIN_SPI_SS_ETHERNET_LIB)
|
||||
#define SS_PIN_DEFAULT PIN_SPI_SS_ETHERNET_LIB
|
||||
|
||||
// MKR boards default to pin 5 for MKR ETH
|
||||
// Pins 8-10 are MOSI/SCK/MISO on MRK, so don't use pin 10
|
||||
#elif defined(USE_ARDUINO_MKR_PIN_LAYOUT) || defined(ARDUINO_SAMD_MKRZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRVIDOR4000)
|
||||
#define SS_PIN_DEFAULT 5
|
||||
|
||||
// For boards using AVR, assume shields with SS on pin 10
|
||||
// will be used. This allows for Arduino Mega (where
|
||||
// SS is pin 53) and Arduino Leonardo (where SS is pin 17)
|
||||
// to work by default with Arduino Ethernet Shield R2 & R3.
|
||||
#elif defined(__AVR__)
|
||||
#define SS_PIN_DEFAULT 10
|
||||
|
||||
// If variant.h or other headers define these names
|
||||
// use them if none of the other cases match
|
||||
#elif defined(PIN_SPI_SS)
|
||||
#define SS_PIN_DEFAULT PIN_SPI_SS
|
||||
#elif defined(CORE_SS0_PIN)
|
||||
#define SS_PIN_DEFAULT CORE_SS0_PIN
|
||||
|
||||
// As a final fallback, use pin 10
|
||||
#else
|
||||
#define SS_PIN_DEFAULT 10
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
// W5100 controller instance
|
||||
uint8_t W5100Class::chip = 0;
|
||||
uint8_t W5100Class::CH_BASE_MSB;
|
||||
uint8_t W5100Class::ss_pin = SS_PIN_DEFAULT;
|
||||
#ifdef ETHERNET_LARGE_BUFFERS
|
||||
uint16_t W5100Class::SSIZE = 2048;
|
||||
uint16_t W5100Class::SMASK = 0x07FF;
|
||||
#endif
|
||||
W5100Class W5100;
|
||||
|
||||
// pointers and bitmasks for optimized SS pin
|
||||
#if defined(__AVR__)
|
||||
volatile uint8_t * W5100Class::ss_pin_reg;
|
||||
uint8_t W5100Class::ss_pin_mask;
|
||||
#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__)
|
||||
volatile uint8_t * W5100Class::ss_pin_reg;
|
||||
#elif defined(__MKL26Z64__)
|
||||
volatile uint8_t * W5100Class::ss_pin_reg;
|
||||
uint8_t W5100Class::ss_pin_mask;
|
||||
#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__)
|
||||
volatile uint32_t * W5100Class::ss_pin_reg;
|
||||
uint32_t W5100Class::ss_pin_mask;
|
||||
#elif defined(__PIC32MX__)
|
||||
volatile uint32_t * W5100Class::ss_pin_reg;
|
||||
uint32_t W5100Class::ss_pin_mask;
|
||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
||||
volatile uint32_t * W5100Class::ss_pin_reg;
|
||||
uint32_t W5100Class::ss_pin_mask;
|
||||
#elif defined(__SAMD21G18A__)
|
||||
volatile uint32_t * W5100Class::ss_pin_reg;
|
||||
uint32_t W5100Class::ss_pin_mask;
|
||||
#endif
|
||||
|
||||
|
||||
uint8_t W5100Class::init(void)
|
||||
{
|
||||
static bool initialized = false;
|
||||
uint8_t i;
|
||||
|
||||
if (initialized) return 1;
|
||||
|
||||
// Many Ethernet shields have a CAT811 or similar reset chip
|
||||
// connected to W5100 or W5200 chips. The W5200 will not work at
|
||||
// all, and may even drive its MISO pin, until given an active low
|
||||
// reset pulse! The CAT811 has a 240 ms typical pulse length, and
|
||||
// a 400 ms worst case maximum pulse length. MAX811 has a worst
|
||||
// case maximum 560 ms pulse length. This delay is meant to wait
|
||||
// until the reset pulse is ended. If your hardware has a shorter
|
||||
// reset time, this can be edited or removed.
|
||||
delay(560);
|
||||
//Serial.println("w5100 init");
|
||||
|
||||
SPI.begin();
|
||||
initSS();
|
||||
resetSS();
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
|
||||
// Attempt W5200 detection first, because W5200 does not properly
|
||||
// reset its SPI state when CS goes high (inactive). Communication
|
||||
// from detecting the other chips can leave the W5200 in a state
|
||||
// where it won't recover, unless given a reset pulse.
|
||||
if (isW5200()) {
|
||||
CH_BASE_MSB = 0x40;
|
||||
#ifdef ETHERNET_LARGE_BUFFERS
|
||||
#if MAX_SOCK_NUM <= 1
|
||||
SSIZE = 16384;
|
||||
#elif MAX_SOCK_NUM <= 2
|
||||
SSIZE = 8192;
|
||||
#elif MAX_SOCK_NUM <= 4
|
||||
SSIZE = 4096;
|
||||
#else
|
||||
SSIZE = 2048;
|
||||
#endif
|
||||
SMASK = SSIZE - 1;
|
||||
#endif
|
||||
for (i=0; i<MAX_SOCK_NUM; i++) {
|
||||
writeSnRX_SIZE(i, SSIZE >> 10);
|
||||
writeSnTX_SIZE(i, SSIZE >> 10);
|
||||
}
|
||||
for (; i<8; i++) {
|
||||
writeSnRX_SIZE(i, 0);
|
||||
writeSnTX_SIZE(i, 0);
|
||||
}
|
||||
// Try W5500 next. WIZnet finally seems to have implemented
|
||||
// SPI well with this chip. It appears to be very resilient,
|
||||
// so try it after the fragile W5200
|
||||
} else if (isW5500()) {
|
||||
CH_BASE_MSB = 0x10;
|
||||
#ifdef ETHERNET_LARGE_BUFFERS
|
||||
#if MAX_SOCK_NUM <= 1
|
||||
SSIZE = 16384;
|
||||
#elif MAX_SOCK_NUM <= 2
|
||||
SSIZE = 8192;
|
||||
#elif MAX_SOCK_NUM <= 4
|
||||
SSIZE = 4096;
|
||||
#else
|
||||
SSIZE = 2048;
|
||||
#endif
|
||||
SMASK = SSIZE - 1;
|
||||
for (i=0; i<MAX_SOCK_NUM; i++) {
|
||||
writeSnRX_SIZE(i, SSIZE >> 10);
|
||||
writeSnTX_SIZE(i, SSIZE >> 10);
|
||||
}
|
||||
for (; i<8; i++) {
|
||||
writeSnRX_SIZE(i, 0);
|
||||
writeSnTX_SIZE(i, 0);
|
||||
}
|
||||
#endif
|
||||
// Try W5100 last. This simple chip uses fixed 4 byte frames
|
||||
// for every 8 bit access. Terribly inefficient, but so simple
|
||||
// it recovers from "hearing" unsuccessful W5100 or W5200
|
||||
// communication. W5100 is also the only chip without a VERSIONR
|
||||
// register for identification, so we check this last.
|
||||
} else if (isW5100()) {
|
||||
CH_BASE_MSB = 0x04;
|
||||
#ifdef ETHERNET_LARGE_BUFFERS
|
||||
#if MAX_SOCK_NUM <= 1
|
||||
SSIZE = 8192;
|
||||
writeTMSR(0x03);
|
||||
writeRMSR(0x03);
|
||||
#elif MAX_SOCK_NUM <= 2
|
||||
SSIZE = 4096;
|
||||
writeTMSR(0x0A);
|
||||
writeRMSR(0x0A);
|
||||
#else
|
||||
SSIZE = 2048;
|
||||
writeTMSR(0x55);
|
||||
writeRMSR(0x55);
|
||||
#endif
|
||||
SMASK = SSIZE - 1;
|
||||
#else
|
||||
writeTMSR(0x55);
|
||||
writeRMSR(0x55);
|
||||
#endif
|
||||
// No hardware seems to be present. Or it could be a W5200
|
||||
// that's heard other SPI communication if its chip select
|
||||
// pin wasn't high when a SD card or other SPI chip was used.
|
||||
} else {
|
||||
//Serial.println("no chip :-(");
|
||||
chip = 0;
|
||||
SPI.endTransaction();
|
||||
return 0; // no known chip is responding :-(
|
||||
}
|
||||
SPI.endTransaction();
|
||||
initialized = true;
|
||||
return 1; // successful init
|
||||
}
|
||||
|
||||
// Soft reset the WIZnet chip, by writing to its MR register reset bit
|
||||
uint8_t W5100Class::softReset(void)
|
||||
{
|
||||
uint16_t count=0;
|
||||
|
||||
//Serial.println("WIZnet soft reset");
|
||||
// write to reset bit
|
||||
writeMR(0x80);
|
||||
// then wait for soft reset to complete
|
||||
do {
|
||||
uint8_t mr = readMR();
|
||||
//Serial.print("mr=");
|
||||
//Serial.println(mr, HEX);
|
||||
if (mr == 0) return 1;
|
||||
delay(1);
|
||||
} while (++count < 20);
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t W5100Class::isW5100(void)
|
||||
{
|
||||
chip = 51;
|
||||
//Serial.println("w5100.cpp: detect W5100 chip");
|
||||
if (!softReset()) return 0;
|
||||
writeMR(0x10);
|
||||
if (readMR() != 0x10) return 0;
|
||||
writeMR(0x12);
|
||||
if (readMR() != 0x12) return 0;
|
||||
writeMR(0x00);
|
||||
if (readMR() != 0x00) return 0;
|
||||
//Serial.println("chip is W5100");
|
||||
return 1;
|
||||
}
|
||||
|
||||
uint8_t W5100Class::isW5200(void)
|
||||
{
|
||||
chip = 52;
|
||||
//Serial.println("w5100.cpp: detect W5200 chip");
|
||||
if (!softReset()) return 0;
|
||||
writeMR(0x08);
|
||||
if (readMR() != 0x08) return 0;
|
||||
writeMR(0x10);
|
||||
if (readMR() != 0x10) return 0;
|
||||
writeMR(0x00);
|
||||
if (readMR() != 0x00) return 0;
|
||||
int ver = readVERSIONR_W5200();
|
||||
//Serial.print("version=");
|
||||
//Serial.println(ver);
|
||||
if (ver != 3) return 0;
|
||||
//Serial.println("chip is W5200");
|
||||
return 1;
|
||||
}
|
||||
|
||||
uint8_t W5100Class::isW5500(void)
|
||||
{
|
||||
chip = 55;
|
||||
//Serial.println("w5100.cpp: detect W5500 chip");
|
||||
if (!softReset()) return 0;
|
||||
writeMR(0x08);
|
||||
if (readMR() != 0x08) return 0;
|
||||
writeMR(0x10);
|
||||
if (readMR() != 0x10) return 0;
|
||||
writeMR(0x00);
|
||||
if (readMR() != 0x00) return 0;
|
||||
int ver = readVERSIONR_W5500();
|
||||
//Serial.print("version=");
|
||||
//Serial.println(ver);
|
||||
if (ver != 4) return 0;
|
||||
//Serial.println("chip is W5500");
|
||||
return 1;
|
||||
}
|
||||
|
||||
W5100Linkstatus W5100Class::getLinkStatus()
|
||||
{
|
||||
uint8_t phystatus;
|
||||
|
||||
if (!init()) return UNKNOWN;
|
||||
switch (chip) {
|
||||
case 52:
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
phystatus = readPSTATUS_W5200();
|
||||
SPI.endTransaction();
|
||||
if (phystatus & 0x20) return LINK_ON;
|
||||
return LINK_OFF;
|
||||
case 55:
|
||||
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
|
||||
phystatus = readPHYCFGR_W5500();
|
||||
SPI.endTransaction();
|
||||
if (phystatus & 0x01) return LINK_ON;
|
||||
return LINK_OFF;
|
||||
default:
|
||||
return UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t W5100Class::write(uint16_t addr, const uint8_t *buf, uint16_t len)
|
||||
{
|
||||
uint8_t cmd[8];
|
||||
|
||||
if (chip == 51) {
|
||||
for (uint16_t i=0; i<len; i++) {
|
||||
setSS();
|
||||
SPI.transfer(0xF0);
|
||||
SPI.transfer(addr >> 8);
|
||||
SPI.transfer(addr & 0xFF);
|
||||
addr++;
|
||||
SPI.transfer(buf[i]);
|
||||
resetSS();
|
||||
}
|
||||
} else if (chip == 52) {
|
||||
setSS();
|
||||
cmd[0] = addr >> 8;
|
||||
cmd[1] = addr & 0xFF;
|
||||
cmd[2] = ((len >> 8) & 0x7F) | 0x80;
|
||||
cmd[3] = len & 0xFF;
|
||||
SPI.transfer(cmd, 4);
|
||||
#ifdef SPI_HAS_TRANSFER_BUF
|
||||
SPI.transfer(buf, NULL, len);
|
||||
#else
|
||||
// TODO: copy 8 bytes at a time to cmd[] and block transfer
|
||||
for (uint16_t i=0; i < len; i++) {
|
||||
SPI.transfer(buf[i]);
|
||||
}
|
||||
#endif
|
||||
resetSS();
|
||||
} else { // chip == 55
|
||||
setSS();
|
||||
if (addr < 0x100) {
|
||||
// common registers 00nn
|
||||
cmd[0] = 0;
|
||||
cmd[1] = addr & 0xFF;
|
||||
cmd[2] = 0x04;
|
||||
} else if (addr < 0x8000) {
|
||||
// socket registers 10nn, 11nn, 12nn, 13nn, etc
|
||||
cmd[0] = 0;
|
||||
cmd[1] = addr & 0xFF;
|
||||
cmd[2] = ((addr >> 3) & 0xE0) | 0x0C;
|
||||
} else if (addr < 0xC000) {
|
||||
// transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc
|
||||
// 10## #nnn nnnn nnnn
|
||||
cmd[0] = addr >> 8;
|
||||
cmd[1] = addr & 0xFF;
|
||||
#if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
|
||||
cmd[2] = 0x14; // 16K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
|
||||
cmd[2] = ((addr >> 8) & 0x20) | 0x14; // 8K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
|
||||
cmd[2] = ((addr >> 7) & 0x60) | 0x14; // 4K buffers
|
||||
#else
|
||||
cmd[2] = ((addr >> 6) & 0xE0) | 0x14; // 2K buffers
|
||||
#endif
|
||||
} else {
|
||||
// receive buffers
|
||||
cmd[0] = addr >> 8;
|
||||
cmd[1] = addr & 0xFF;
|
||||
#if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
|
||||
cmd[2] = 0x1C; // 16K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
|
||||
cmd[2] = ((addr >> 8) & 0x20) | 0x1C; // 8K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
|
||||
cmd[2] = ((addr >> 7) & 0x60) | 0x1C; // 4K buffers
|
||||
#else
|
||||
cmd[2] = ((addr >> 6) & 0xE0) | 0x1C; // 2K buffers
|
||||
#endif
|
||||
}
|
||||
if (len <= 5) {
|
||||
for (uint8_t i=0; i < len; i++) {
|
||||
cmd[i + 3] = buf[i];
|
||||
}
|
||||
SPI.transfer(cmd, len + 3);
|
||||
} else {
|
||||
SPI.transfer(cmd, 3);
|
||||
#ifdef SPI_HAS_TRANSFER_BUF
|
||||
SPI.transfer(buf, NULL, len);
|
||||
#else
|
||||
// TODO: copy 8 bytes at a time to cmd[] and block transfer
|
||||
for (uint16_t i=0; i < len; i++) {
|
||||
SPI.transfer(buf[i]);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
resetSS();
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
uint16_t W5100Class::read(uint16_t addr, uint8_t *buf, uint16_t len)
|
||||
{
|
||||
uint8_t cmd[4];
|
||||
|
||||
if (chip == 51) {
|
||||
for (uint16_t i=0; i < len; i++) {
|
||||
setSS();
|
||||
#if 1
|
||||
SPI.transfer(0x0F);
|
||||
SPI.transfer(addr >> 8);
|
||||
SPI.transfer(addr & 0xFF);
|
||||
addr++;
|
||||
buf[i] = SPI.transfer(0);
|
||||
#else
|
||||
cmd[0] = 0x0F;
|
||||
cmd[1] = addr >> 8;
|
||||
cmd[2] = addr & 0xFF;
|
||||
cmd[3] = 0;
|
||||
SPI.transfer(cmd, 4); // TODO: why doesn't this work?
|
||||
buf[i] = cmd[3];
|
||||
addr++;
|
||||
#endif
|
||||
resetSS();
|
||||
}
|
||||
} else if (chip == 52) {
|
||||
setSS();
|
||||
cmd[0] = addr >> 8;
|
||||
cmd[1] = addr & 0xFF;
|
||||
cmd[2] = (len >> 8) & 0x7F;
|
||||
cmd[3] = len & 0xFF;
|
||||
SPI.transfer(cmd, 4);
|
||||
memset(buf, 0, len);
|
||||
SPI.transfer(buf, len);
|
||||
resetSS();
|
||||
} else { // chip == 55
|
||||
setSS();
|
||||
if (addr < 0x100) {
|
||||
// common registers 00nn
|
||||
cmd[0] = 0;
|
||||
cmd[1] = addr & 0xFF;
|
||||
cmd[2] = 0x00;
|
||||
} else if (addr < 0x8000) {
|
||||
// socket registers 10nn, 11nn, 12nn, 13nn, etc
|
||||
cmd[0] = 0;
|
||||
cmd[1] = addr & 0xFF;
|
||||
cmd[2] = ((addr >> 3) & 0xE0) | 0x08;
|
||||
} else if (addr < 0xC000) {
|
||||
// transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc
|
||||
// 10## #nnn nnnn nnnn
|
||||
cmd[0] = addr >> 8;
|
||||
cmd[1] = addr & 0xFF;
|
||||
#if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
|
||||
cmd[2] = 0x10; // 16K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
|
||||
cmd[2] = ((addr >> 8) & 0x20) | 0x10; // 8K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
|
||||
cmd[2] = ((addr >> 7) & 0x60) | 0x10; // 4K buffers
|
||||
#else
|
||||
cmd[2] = ((addr >> 6) & 0xE0) | 0x10; // 2K buffers
|
||||
#endif
|
||||
} else {
|
||||
// receive buffers
|
||||
cmd[0] = addr >> 8;
|
||||
cmd[1] = addr & 0xFF;
|
||||
#if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
|
||||
cmd[2] = 0x18; // 16K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
|
||||
cmd[2] = ((addr >> 8) & 0x20) | 0x18; // 8K buffers
|
||||
#elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
|
||||
cmd[2] = ((addr >> 7) & 0x60) | 0x18; // 4K buffers
|
||||
#else
|
||||
cmd[2] = ((addr >> 6) & 0xE0) | 0x18; // 2K buffers
|
||||
#endif
|
||||
}
|
||||
SPI.transfer(cmd, 3);
|
||||
memset(buf, 0, len);
|
||||
SPI.transfer(buf, len);
|
||||
resetSS();
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd)
|
||||
{
|
||||
// Send command to socket
|
||||
writeSnCR(s, _cmd);
|
||||
// Wait for command to complete
|
||||
while (readSnCR(s)) ;
|
||||
}
|
479
Arduino/libraries/Ethernet/src/utility/w5100.h
Normal file
479
Arduino/libraries/Ethernet/src/utility/w5100.h
Normal file
@ -0,0 +1,479 @@
|
||||
/*
|
||||
* Copyright 2018 Paul Stoffregen
|
||||
* Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
|
||||
*
|
||||
* This file is free software; you can redistribute it and/or modify
|
||||
* it under the terms of either the GNU General Public License version 2
|
||||
* or the GNU Lesser General Public License version 2.1, both as
|
||||
* published by the Free Software Foundation.
|
||||
*/
|
||||
|
||||
// w5100.h contains private W5x00 hardware "driver" level definitions
|
||||
// which are not meant to be exposed to other libraries or Arduino users
|
||||
|
||||
#ifndef W5100_H_INCLUDED
|
||||
#define W5100_H_INCLUDED
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <SPI.h>
|
||||
|
||||
// Safe for all chips
|
||||
#define SPI_ETHERNET_SETTINGS SPISettings(14000000, MSBFIRST, SPI_MODE0)
|
||||
|
||||
// Safe for W5200 and W5500, but too fast for W5100
|
||||
// Uncomment this if you know you'll never need W5100 support.
|
||||
// Higher SPI clock only results in faster transfer to hosts on a LAN
|
||||
// or with very low packet latency. With ordinary internet latency,
|
||||
// the TCP window size & packet loss determine your overall speed.
|
||||
//#define SPI_ETHERNET_SETTINGS SPISettings(30000000, MSBFIRST, SPI_MODE0)
|
||||
|
||||
|
||||
// Require Ethernet.h, because we need MAX_SOCK_NUM
|
||||
#ifndef ethernet_h_
|
||||
#error "Ethernet.h must be included before w5100.h"
|
||||
#endif
|
||||
|
||||
|
||||
// Arduino 101's SPI can not run faster than 8 MHz.
|
||||
#if defined(ARDUINO_ARCH_ARC32)
|
||||
#undef SPI_ETHERNET_SETTINGS
|
||||
#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0)
|
||||
#endif
|
||||
|
||||
// Arduino Zero can't use W5100-based shields faster than 8 MHz
|
||||
// https://github.com/arduino-libraries/Ethernet/issues/37#issuecomment-408036848
|
||||
// W5500 does seem to work at 12 MHz. Delete this if only using W5500
|
||||
#if defined(__SAMD21G18A__)
|
||||
#undef SPI_ETHERNET_SETTINGS
|
||||
#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0)
|
||||
#endif
|
||||
|
||||
|
||||
typedef uint8_t SOCKET;
|
||||
|
||||
class SnMR {
|
||||
public:
|
||||
static const uint8_t CLOSE = 0x00;
|
||||
static const uint8_t TCP = 0x21;
|
||||
static const uint8_t UDP = 0x02;
|
||||
static const uint8_t IPRAW = 0x03;
|
||||
static const uint8_t MACRAW = 0x04;
|
||||
static const uint8_t PPPOE = 0x05;
|
||||
static const uint8_t ND = 0x20;
|
||||
static const uint8_t MULTI = 0x80;
|
||||
};
|
||||
|
||||
enum SockCMD {
|
||||
Sock_OPEN = 0x01,
|
||||
Sock_LISTEN = 0x02,
|
||||
Sock_CONNECT = 0x04,
|
||||
Sock_DISCON = 0x08,
|
||||
Sock_CLOSE = 0x10,
|
||||
Sock_SEND = 0x20,
|
||||
Sock_SEND_MAC = 0x21,
|
||||
Sock_SEND_KEEP = 0x22,
|
||||
Sock_RECV = 0x40
|
||||
};
|
||||
|
||||
class SnIR {
|
||||
public:
|
||||
static const uint8_t SEND_OK = 0x10;
|
||||
static const uint8_t TIMEOUT = 0x08;
|
||||
static const uint8_t RECV = 0x04;
|
||||
static const uint8_t DISCON = 0x02;
|
||||
static const uint8_t CON = 0x01;
|
||||
};
|
||||
|
||||
class SnSR {
|
||||
public:
|
||||
static const uint8_t CLOSED = 0x00;
|
||||
static const uint8_t INIT = 0x13;
|
||||
static const uint8_t LISTEN = 0x14;
|
||||
static const uint8_t SYNSENT = 0x15;
|
||||
static const uint8_t SYNRECV = 0x16;
|
||||
static const uint8_t ESTABLISHED = 0x17;
|
||||
static const uint8_t FIN_WAIT = 0x18;
|
||||
static const uint8_t CLOSING = 0x1A;
|
||||
static const uint8_t TIME_WAIT = 0x1B;
|
||||
static const uint8_t CLOSE_WAIT = 0x1C;
|
||||
static const uint8_t LAST_ACK = 0x1D;
|
||||
static const uint8_t UDP = 0x22;
|
||||
static const uint8_t IPRAW = 0x32;
|
||||
static const uint8_t MACRAW = 0x42;
|
||||
static const uint8_t PPPOE = 0x5F;
|
||||
};
|
||||
|
||||
class IPPROTO {
|
||||
public:
|
||||
static const uint8_t IP = 0;
|
||||
static const uint8_t ICMP = 1;
|
||||
static const uint8_t IGMP = 2;
|
||||
static const uint8_t GGP = 3;
|
||||
static const uint8_t TCP = 6;
|
||||
static const uint8_t PUP = 12;
|
||||
static const uint8_t UDP = 17;
|
||||
static const uint8_t IDP = 22;
|
||||
static const uint8_t ND = 77;
|
||||
static const uint8_t RAW = 255;
|
||||
};
|
||||
|
||||
enum W5100Linkstatus {
|
||||
UNKNOWN,
|
||||
LINK_ON,
|
||||
LINK_OFF
|
||||
};
|
||||
|
||||
class W5100Class {
|
||||
|
||||
public:
|
||||
static uint8_t init(void);
|
||||
|
||||
inline void setGatewayIp(const uint8_t * addr) { writeGAR(addr); }
|
||||
inline void getGatewayIp(uint8_t * addr) { readGAR(addr); }
|
||||
|
||||
inline void setSubnetMask(const uint8_t * addr) { writeSUBR(addr); }
|
||||
inline void getSubnetMask(uint8_t * addr) { readSUBR(addr); }
|
||||
|
||||
inline void setMACAddress(const uint8_t * addr) { writeSHAR(addr); }
|
||||
inline void getMACAddress(uint8_t * addr) { readSHAR(addr); }
|
||||
|
||||
inline void setIPAddress(const uint8_t * addr) { writeSIPR(addr); }
|
||||
inline void getIPAddress(uint8_t * addr) { readSIPR(addr); }
|
||||
|
||||
inline void setRetransmissionTime(uint16_t timeout) { writeRTR(timeout); }
|
||||
inline void setRetransmissionCount(uint8_t retry) { writeRCR(retry); }
|
||||
|
||||
static void execCmdSn(SOCKET s, SockCMD _cmd);
|
||||
|
||||
|
||||
// W5100 Registers
|
||||
// ---------------
|
||||
//private:
|
||||
public:
|
||||
static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len);
|
||||
static uint8_t write(uint16_t addr, uint8_t data) {
|
||||
return write(addr, &data, 1);
|
||||
}
|
||||
static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len);
|
||||
static uint8_t read(uint16_t addr) {
|
||||
uint8_t data;
|
||||
read(addr, &data, 1);
|
||||
return data;
|
||||
}
|
||||
|
||||
#define __GP_REGISTER8(name, address) \
|
||||
static inline void write##name(uint8_t _data) { \
|
||||
write(address, _data); \
|
||||
} \
|
||||
static inline uint8_t read##name() { \
|
||||
return read(address); \
|
||||
}
|
||||
#define __GP_REGISTER16(name, address) \
|
||||
static void write##name(uint16_t _data) { \
|
||||
uint8_t buf[2]; \
|
||||
buf[0] = _data >> 8; \
|
||||
buf[1] = _data & 0xFF; \
|
||||
write(address, buf, 2); \
|
||||
} \
|
||||
static uint16_t read##name() { \
|
||||
uint8_t buf[2]; \
|
||||
read(address, buf, 2); \
|
||||
return (buf[0] << 8) | buf[1]; \
|
||||
}
|
||||
#define __GP_REGISTER_N(name, address, size) \
|
||||
static uint16_t write##name(const uint8_t *_buff) { \
|
||||
return write(address, _buff, size); \
|
||||
} \
|
||||
static uint16_t read##name(uint8_t *_buff) { \
|
||||
return read(address, _buff, size); \
|
||||
}
|
||||
static W5100Linkstatus getLinkStatus();
|
||||
|
||||
public:
|
||||
__GP_REGISTER8 (MR, 0x0000); // Mode
|
||||
__GP_REGISTER_N(GAR, 0x0001, 4); // Gateway IP address
|
||||
__GP_REGISTER_N(SUBR, 0x0005, 4); // Subnet mask address
|
||||
__GP_REGISTER_N(SHAR, 0x0009, 6); // Source MAC address
|
||||
__GP_REGISTER_N(SIPR, 0x000F, 4); // Source IP address
|
||||
__GP_REGISTER8 (IR, 0x0015); // Interrupt
|
||||
__GP_REGISTER8 (IMR, 0x0016); // Interrupt Mask
|
||||
__GP_REGISTER16(RTR, 0x0017); // Timeout address
|
||||
__GP_REGISTER8 (RCR, 0x0019); // Retry count
|
||||
__GP_REGISTER8 (RMSR, 0x001A); // Receive memory size (W5100 only)
|
||||
__GP_REGISTER8 (TMSR, 0x001B); // Transmit memory size (W5100 only)
|
||||
__GP_REGISTER8 (PATR, 0x001C); // Authentication type address in PPPoE mode
|
||||
__GP_REGISTER8 (PTIMER, 0x0028); // PPP LCP Request Timer
|
||||
__GP_REGISTER8 (PMAGIC, 0x0029); // PPP LCP Magic Number
|
||||
__GP_REGISTER_N(UIPR, 0x002A, 4); // Unreachable IP address in UDP mode (W5100 only)
|
||||
__GP_REGISTER16(UPORT, 0x002E); // Unreachable Port address in UDP mode (W5100 only)
|
||||
__GP_REGISTER8 (VERSIONR_W5200,0x001F); // Chip Version Register (W5200 only)
|
||||
__GP_REGISTER8 (VERSIONR_W5500,0x0039); // Chip Version Register (W5500 only)
|
||||
__GP_REGISTER8 (PSTATUS_W5200, 0x0035); // PHY Status
|
||||
__GP_REGISTER8 (PHYCFGR_W5500, 0x002E); // PHY Configuration register, default: 10111xxx
|
||||
|
||||
|
||||
#undef __GP_REGISTER8
|
||||
#undef __GP_REGISTER16
|
||||
#undef __GP_REGISTER_N
|
||||
|
||||
// W5100 Socket registers
|
||||
// ----------------------
|
||||
private:
|
||||
static uint16_t CH_BASE(void) {
|
||||
//if (chip == 55) return 0x1000;
|
||||
//if (chip == 52) return 0x4000;
|
||||
//return 0x0400;
|
||||
return CH_BASE_MSB << 8;
|
||||
}
|
||||
static uint8_t CH_BASE_MSB; // 1 redundant byte, saves ~80 bytes code on AVR
|
||||
static const uint16_t CH_SIZE = 0x0100;
|
||||
|
||||
static inline uint8_t readSn(SOCKET s, uint16_t addr) {
|
||||
return read(CH_BASE() + s * CH_SIZE + addr);
|
||||
}
|
||||
static inline uint8_t writeSn(SOCKET s, uint16_t addr, uint8_t data) {
|
||||
return write(CH_BASE() + s * CH_SIZE + addr, data);
|
||||
}
|
||||
static inline uint16_t readSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) {
|
||||
return read(CH_BASE() + s * CH_SIZE + addr, buf, len);
|
||||
}
|
||||
static inline uint16_t writeSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) {
|
||||
return write(CH_BASE() + s * CH_SIZE + addr, buf, len);
|
||||
}
|
||||
|
||||
#define __SOCKET_REGISTER8(name, address) \
|
||||
static inline void write##name(SOCKET _s, uint8_t _data) { \
|
||||
writeSn(_s, address, _data); \
|
||||
} \
|
||||
static inline uint8_t read##name(SOCKET _s) { \
|
||||
return readSn(_s, address); \
|
||||
}
|
||||
#define __SOCKET_REGISTER16(name, address) \
|
||||
static void write##name(SOCKET _s, uint16_t _data) { \
|
||||
uint8_t buf[2]; \
|
||||
buf[0] = _data >> 8; \
|
||||
buf[1] = _data & 0xFF; \
|
||||
writeSn(_s, address, buf, 2); \
|
||||
} \
|
||||
static uint16_t read##name(SOCKET _s) { \
|
||||
uint8_t buf[2]; \
|
||||
readSn(_s, address, buf, 2); \
|
||||
return (buf[0] << 8) | buf[1]; \
|
||||
}
|
||||
#define __SOCKET_REGISTER_N(name, address, size) \
|
||||
static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \
|
||||
return writeSn(_s, address, _buff, size); \
|
||||
} \
|
||||
static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \
|
||||
return readSn(_s, address, _buff, size); \
|
||||
}
|
||||
|
||||
public:
|
||||
__SOCKET_REGISTER8(SnMR, 0x0000) // Mode
|
||||
__SOCKET_REGISTER8(SnCR, 0x0001) // Command
|
||||
__SOCKET_REGISTER8(SnIR, 0x0002) // Interrupt
|
||||
__SOCKET_REGISTER8(SnSR, 0x0003) // Status
|
||||
__SOCKET_REGISTER16(SnPORT, 0x0004) // Source Port
|
||||
__SOCKET_REGISTER_N(SnDHAR, 0x0006, 6) // Destination Hardw Addr
|
||||
__SOCKET_REGISTER_N(SnDIPR, 0x000C, 4) // Destination IP Addr
|
||||
__SOCKET_REGISTER16(SnDPORT, 0x0010) // Destination Port
|
||||
__SOCKET_REGISTER16(SnMSSR, 0x0012) // Max Segment Size
|
||||
__SOCKET_REGISTER8(SnPROTO, 0x0014) // Protocol in IP RAW Mode
|
||||
__SOCKET_REGISTER8(SnTOS, 0x0015) // IP TOS
|
||||
__SOCKET_REGISTER8(SnTTL, 0x0016) // IP TTL
|
||||
__SOCKET_REGISTER8(SnRX_SIZE, 0x001E) // RX Memory Size (W5200 only)
|
||||
__SOCKET_REGISTER8(SnTX_SIZE, 0x001F) // RX Memory Size (W5200 only)
|
||||
__SOCKET_REGISTER16(SnTX_FSR, 0x0020) // TX Free Size
|
||||
__SOCKET_REGISTER16(SnTX_RD, 0x0022) // TX Read Pointer
|
||||
__SOCKET_REGISTER16(SnTX_WR, 0x0024) // TX Write Pointer
|
||||
__SOCKET_REGISTER16(SnRX_RSR, 0x0026) // RX Free Size
|
||||
__SOCKET_REGISTER16(SnRX_RD, 0x0028) // RX Read Pointer
|
||||
__SOCKET_REGISTER16(SnRX_WR, 0x002A) // RX Write Pointer (supported?)
|
||||
|
||||
#undef __SOCKET_REGISTER8
|
||||
#undef __SOCKET_REGISTER16
|
||||
#undef __SOCKET_REGISTER_N
|
||||
|
||||
|
||||
private:
|
||||
static uint8_t chip;
|
||||
static uint8_t ss_pin;
|
||||
static uint8_t softReset(void);
|
||||
static uint8_t isW5100(void);
|
||||
static uint8_t isW5200(void);
|
||||
static uint8_t isW5500(void);
|
||||
|
||||
public:
|
||||
static uint8_t getChip(void) { return chip; }
|
||||
#ifdef ETHERNET_LARGE_BUFFERS
|
||||
static uint16_t SSIZE;
|
||||
static uint16_t SMASK;
|
||||
#else
|
||||
static const uint16_t SSIZE = 2048;
|
||||
static const uint16_t SMASK = 0x07FF;
|
||||
#endif
|
||||
static uint16_t SBASE(uint8_t socknum) {
|
||||
if (chip == 51) {
|
||||
return socknum * SSIZE + 0x4000;
|
||||
} else {
|
||||
return socknum * SSIZE + 0x8000;
|
||||
}
|
||||
}
|
||||
static uint16_t RBASE(uint8_t socknum) {
|
||||
if (chip == 51) {
|
||||
return socknum * SSIZE + 0x6000;
|
||||
} else {
|
||||
return socknum * SSIZE + 0xC000;
|
||||
}
|
||||
}
|
||||
|
||||
static bool hasOffsetAddressMapping(void) {
|
||||
if (chip == 55) return true;
|
||||
return false;
|
||||
}
|
||||
static void setSS(uint8_t pin) { ss_pin = pin; }
|
||||
|
||||
private:
|
||||
#if defined(__AVR__)
|
||||
static volatile uint8_t *ss_pin_reg;
|
||||
static uint8_t ss_pin_mask;
|
||||
inline static void initSS() {
|
||||
ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin));
|
||||
ss_pin_mask = digitalPinToBitMask(ss_pin);
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
*(ss_pin_reg) &= ~ss_pin_mask;
|
||||
}
|
||||
inline static void resetSS() {
|
||||
*(ss_pin_reg) |= ss_pin_mask;
|
||||
}
|
||||
#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__)
|
||||
static volatile uint8_t *ss_pin_reg;
|
||||
inline static void initSS() {
|
||||
ss_pin_reg = portOutputRegister(ss_pin);
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
*(ss_pin_reg+256) = 1;
|
||||
}
|
||||
inline static void resetSS() {
|
||||
*(ss_pin_reg+128) = 1;
|
||||
}
|
||||
#elif defined(__MKL26Z64__)
|
||||
static volatile uint8_t *ss_pin_reg;
|
||||
static uint8_t ss_pin_mask;
|
||||
inline static void initSS() {
|
||||
ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin));
|
||||
ss_pin_mask = digitalPinToBitMask(ss_pin);
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
*(ss_pin_reg+8) = ss_pin_mask;
|
||||
}
|
||||
inline static void resetSS() {
|
||||
*(ss_pin_reg+4) = ss_pin_mask;
|
||||
}
|
||||
#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__)
|
||||
static volatile uint32_t *ss_pin_reg;
|
||||
static uint32_t ss_pin_mask;
|
||||
inline static void initSS() {
|
||||
ss_pin_reg = &(digitalPinToPort(ss_pin)->PIO_PER);
|
||||
ss_pin_mask = digitalPinToBitMask(ss_pin);
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
*(ss_pin_reg+13) = ss_pin_mask;
|
||||
}
|
||||
inline static void resetSS() {
|
||||
*(ss_pin_reg+12) = ss_pin_mask;
|
||||
}
|
||||
#elif defined(__PIC32MX__)
|
||||
static volatile uint32_t *ss_pin_reg;
|
||||
static uint32_t ss_pin_mask;
|
||||
inline static void initSS() {
|
||||
ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin));
|
||||
ss_pin_mask = digitalPinToBitMask(ss_pin);
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
*(ss_pin_reg+8+1) = ss_pin_mask;
|
||||
}
|
||||
inline static void resetSS() {
|
||||
*(ss_pin_reg+8+2) = ss_pin_mask;
|
||||
}
|
||||
|
||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
||||
static volatile uint32_t *ss_pin_reg;
|
||||
static uint32_t ss_pin_mask;
|
||||
inline static void initSS() {
|
||||
ss_pin_reg = (volatile uint32_t*)GPO;
|
||||
ss_pin_mask = 1 << ss_pin;
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
GPOC = ss_pin_mask;
|
||||
}
|
||||
inline static void resetSS() {
|
||||
GPOS = ss_pin_mask;
|
||||
}
|
||||
|
||||
#elif defined(__SAMD21G18A__)
|
||||
static volatile uint32_t *ss_pin_reg;
|
||||
static uint32_t ss_pin_mask;
|
||||
inline static void initSS() {
|
||||
ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin));
|
||||
ss_pin_mask = digitalPinToBitMask(ss_pin);
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
*(ss_pin_reg+5) = ss_pin_mask;
|
||||
}
|
||||
inline static void resetSS() {
|
||||
*(ss_pin_reg+6) = ss_pin_mask;
|
||||
}
|
||||
#else
|
||||
inline static void initSS() {
|
||||
pinMode(ss_pin, OUTPUT);
|
||||
}
|
||||
inline static void setSS() {
|
||||
digitalWrite(ss_pin, LOW);
|
||||
}
|
||||
inline static void resetSS() {
|
||||
digitalWrite(ss_pin, HIGH);
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
extern W5100Class W5100;
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef UTIL_H
|
||||
#define UTIL_H
|
||||
|
||||
#ifndef htons
|
||||
// The host order of the Arduino platform is little endian.
|
||||
// Sometimes it is desired to convert to big endian (or
|
||||
// network order)
|
||||
|
||||
// Host to Network short
|
||||
#define htons(x) ( (((x)&0xFF)<<8) | (((x)>>8)&0xFF) )
|
||||
|
||||
// Network to Host short
|
||||
#define ntohs(x) htons(x)
|
||||
|
||||
// Host to Network long
|
||||
#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \
|
||||
((x)<< 8 & 0x00FF0000UL) | \
|
||||
((x)>> 8 & 0x0000FF00UL) | \
|
||||
((x)>>24 & 0x000000FFUL) )
|
||||
|
||||
// Network to Host long
|
||||
#define ntohl(x) htonl(x)
|
||||
|
||||
#endif // !defined(htons)
|
||||
|
||||
#endif
|
33
Arduino/libraries/Ethernet2/CONTRIBUTIONS.txt
Normal file
33
Arduino/libraries/Ethernet2/CONTRIBUTIONS.txt
Normal file
@ -0,0 +1,33 @@
|
||||
---------------
|
||||
DHCP.cpp
|
||||
|
||||
// DHCP Library v0.3 - April 25, 2009
|
||||
// Author: Jordan Terrell - blog.jordanterrell.com
|
||||
|
||||
---------------
|
||||
DNS.cpp
|
||||
|
||||
// Arduino DNS client for WizNet5100-based Ethernet shield
|
||||
// (c) Copyright 2009-2010 MCQN Ltd.
|
||||
// Released under Apache License, version 2.0
|
||||
|
||||
---------------
|
||||
Ethernet2:
|
||||
modified 12 Aug 2013
|
||||
by Soohwan Kim (suhwan@wiznet.co.kr)
|
||||
|
||||
---------------
|
||||
UDP.cpp: bjoern@cs.stanford.edu 12/30/2008
|
||||
|
||||
---------------
|
||||
|
||||
Twitter.cpp - Arduino library to Post messages to Twitter using OAuth.
|
||||
Copyright (c) NeoCat 2010-2011. All right reserved.
|
||||
|
||||
---------------
|
||||
Wiz5500.cpp
|
||||
|
||||
Copyright (c) 2010 by WIZnet <support@wiznet.co.kr>
|
||||
|
||||
--------------
|
||||
Various by Arduino.org team
|
42
Arduino/libraries/Ethernet2/README.md
Normal file
42
Arduino/libraries/Ethernet2/README.md
Normal file
@ -0,0 +1,42 @@
|
||||
Ethernet "2" Library for Arduino
|
||||
================================
|
||||
|
||||
This Arduino library is for shields that use the **Wiznet [W5500]** chipset only.
|
||||
It does **not** work with other chipsets, such as the original Arduino Ethernet shield which
|
||||
uses the Wiznet [W5100] chipset.
|
||||
|
||||
For more information about this library please visit us at:
|
||||
http://www.arduino.cc/en/Reference/Ethernet
|
||||
|
||||
|
||||
W5500 Shields
|
||||
-------------
|
||||
|
||||
* [Adafruit W5500 Ethernet Shield](https://www.adafruit.com/products/2971)
|
||||
* [Arduino Ethernet Shield v2](https://www.arduino.cc/en/Main/ArduinoEthernetShieldV2)
|
||||
* [Industruino Ethernet module](https://industruino.com/shop/product/ethernet-expansion-module-10)
|
||||
* [Wiznet W5500 Ethernet Shield](http://www.wiznet.co.kr/product-item/w5500-ethernet-shield/)
|
||||
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
Copyright (c) 2009-2016 Arduino LLC. 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
|
||||
|
||||
|
||||
[W5100]: http://www.wiznet.co.kr/product-item/w5100/
|
||||
[W5500]: http://www.wiznet.co.kr/product-item/w5500/
|
@ -0,0 +1,108 @@
|
||||
/*
|
||||
Advanced Chat Server
|
||||
|
||||
A more advanced server that distributes any incoming messages
|
||||
to all connected clients but the client the message comes from.
|
||||
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
|
||||
redesigned to make use of operator== 25 Nov 2013
|
||||
by Norbert Truchsess
|
||||
|
||||
*/
|
||||
|
||||
#include <SPI.h>
|
||||
#include <Ethernet2.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);
|
||||
|
||||
EthernetClient clients[4];
|
||||
|
||||
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) {
|
||||
|
||||
boolean newClient = true;
|
||||
for (byte i=0;i<4;i++) {
|
||||
//check whether this client refers to the same socket as one of the existing instances:
|
||||
if (clients[i]==client) {
|
||||
newClient = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (newClient) {
|
||||
//check which of the existing clients can be overridden:
|
||||
for (byte i=0;i<4;i++) {
|
||||
if (!clients[i] && clients[i]!=client) {
|
||||
clients[i] = client;
|
||||
// clead out the input buffer:
|
||||
client.flush();
|
||||
Serial.println("We have a new client");
|
||||
client.print("Hello, client number: ");
|
||||
client.print(i);
|
||||
client.println();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (client.available() > 0) {
|
||||
// read the bytes incoming from the client:
|
||||
char thisChar = client.read();
|
||||
// echo the bytes back to all other connected clients:
|
||||
for (byte i=0;i<4;i++) {
|
||||
if (clients[i] && (clients[i]!=client)) {
|
||||
clients[i].write(thisChar);
|
||||
}
|
||||
}
|
||||
// echo the bytes to the server as well:
|
||||
Serial.write(thisChar);
|
||||
}
|
||||
}
|
||||
for (byte i=0;i<4;i++) {
|
||||
if (!(clients[i].connected())) {
|
||||
// client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false;
|
||||
clients[i].stop();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,223 @@
|
||||
/*
|
||||
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 <Ethernet2.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);
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
/*
|
||||
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 <Ethernet2.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
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 <Ethernet2.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() {
|
||||
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,88 @@
|
||||
/*
|
||||
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 <Ethernet2.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);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,94 @@
|
||||
/*
|
||||
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 <Ethernet2.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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
@ -0,0 +1,119 @@
|
||||
/*
|
||||
UDPSendReceive.pde:
|
||||
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 <Ethernet2.h>
|
||||
#include <EthernetUdp2.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();
|
||||
}
|
||||
*/
|
||||
|
||||
|
@ -0,0 +1,142 @@
|
||||
/*
|
||||
|
||||
Udp NTP Client
|
||||
|
||||
Get the time from a Network Time Protocol (NTP) time server
|
||||
Demonstrates use of UDP sendPacket and ReceivePacket
|
||||
For more on NTP time servers and the messages needed to communicate with them,
|
||||
see http://en.wikipedia.org/wiki/Network_Time_Protocol
|
||||
|
||||
created 4 Sep 2010
|
||||
by Michael Margolis
|
||||
modified 9 Apr 2012
|
||||
by Tom Igoe
|
||||
|
||||
This code is in the public domain.
|
||||
|
||||
*/
|
||||
|
||||
#include <SPI.h>
|
||||
#include <Ethernet2.h>
|
||||
#include <EthernetUdp2.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
|
||||
|
||||
char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server
|
||||
|
||||
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
|
||||
|
||||
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(char* 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();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
88
Arduino/libraries/Ethernet2/examples/WebClient/WebClient.ino
Normal file
88
Arduino/libraries/Ethernet2/examples/WebClient/WebClient.ino
Normal file
@ -0,0 +1,88 @@
|
||||
/*
|
||||
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 <Ethernet2.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 };
|
||||
// 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(74,125,232,128); // numeric IP for Google (no DNS)
|
||||
char server[] = "www.google.com"; // name address for Google (using DNS)
|
||||
|
||||
// Set the static IP address to use if the DHCP fails to assign
|
||||
IPAddress ip(192, 168, 0, 177);
|
||||
|
||||
// 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:
|
||||
// try to congifure using IP address instead of DHCP:
|
||||
Ethernet.begin(mac, ip);
|
||||
}
|
||||
// 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.1");
|
||||
client.println("Host: www.google.com");
|
||||
client.println("Connection: close");
|
||||
client.println();
|
||||
}
|
||||
else {
|
||||
// kf you didn't get a connection to the server:
|
||||
Serial.println("connection failed");
|
||||
}
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// if there are incoming bytes available
|
||||
// from the server, read them and print them:
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,108 @@
|
||||
/*
|
||||
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
|
||||
modified 21 Jan 2014
|
||||
by Federico Vanzati
|
||||
|
||||
http://arduino.cc/en/Tutorial/WebClientRepeating
|
||||
This code is in the public domain.
|
||||
|
||||
*/
|
||||
|
||||
#include <SPI.h>
|
||||
#include <Ethernet2.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(192, 168, 1, 177);
|
||||
|
||||
// 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";
|
||||
//IPAddress server(64,131,82,241);
|
||||
|
||||
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
|
||||
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
|
||||
// the "L" is needed to use long type numbers
|
||||
|
||||
void setup() {
|
||||
// start serial port:
|
||||
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 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.write(c);
|
||||
}
|
||||
|
||||
// if ten seconds have passed since your last connection,
|
||||
// then connect again and send data:
|
||||
if (millis() - lastConnectionTime > postingInterval) {
|
||||
httpRequest();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// this method makes a HTTP connection to the server:
|
||||
void httpRequest() {
|
||||
// close any connection before send a new request.
|
||||
// This will free the socket on the WiFi shield
|
||||
client.stop();
|
||||
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
|
||||
|
101
Arduino/libraries/Ethernet2/examples/WebServer/WebServer.ino
Normal file
101
Arduino/libraries/Ethernet2/examples/WebServer/WebServer.ino
Normal file
@ -0,0 +1,101 @@
|
||||
/*
|
||||
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 <Ethernet2.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"); // the connection will be closed after completion of the response
|
||||
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
|
||||
client.println();
|
||||
client.println("<!DOCTYPE HTML>");
|
||||
client.println("<html>");
|
||||
// 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 disconnected");
|
||||
}
|
||||
}
|
||||
|
38
Arduino/libraries/Ethernet2/keywords.txt
Normal file
38
Arduino/libraries/Ethernet2/keywords.txt
Normal file
@ -0,0 +1,38 @@
|
||||
#######################################
|
||||
# Syntax Coloring Map For Ethernet
|
||||
#######################################
|
||||
|
||||
#######################################
|
||||
# Datatypes (KEYWORD1)
|
||||
#######################################
|
||||
|
||||
Ethernet2 KEYWORD1
|
||||
EthernetClient KEYWORD1
|
||||
EthernetServer KEYWORD1
|
||||
IPAddress KEYWORD1
|
||||
EthernetUdp2 KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
status KEYWORD2
|
||||
connect KEYWORD2
|
||||
write KEYWORD2
|
||||
available KEYWORD2
|
||||
read KEYWORD2
|
||||
peek KEYWORD2
|
||||
flush KEYWORD2
|
||||
stop KEYWORD2
|
||||
connected KEYWORD2
|
||||
begin KEYWORD2
|
||||
beginPacket KEYWORD2
|
||||
endPacket KEYWORD2
|
||||
parsePacket KEYWORD2
|
||||
remoteIP KEYWORD2
|
||||
remotePort KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
#######################################
|
||||
|
9
Arduino/libraries/Ethernet2/library.properties
Normal file
9
Arduino/libraries/Ethernet2/library.properties
Normal file
@ -0,0 +1,9 @@
|
||||
name=Ethernet2
|
||||
version=1.0.4
|
||||
author=Various
|
||||
maintainer=Adafruit <info@adafruit.com>
|
||||
sentence=Enables network connection (local and Internet) using W5500 based Ethernet shields.
|
||||
paragraph=With this library you can use W5500 based Ethernet shields, such as the 'Arduino Ethernet Shield v2' to connect to Internet, but not older W5100 based shields. The library provides both Client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS.
|
||||
category=Communication
|
||||
url=https://github.com/adafruit/Ethernet2
|
||||
architectures=*
|
753
Arduino/libraries/Ethernet2/license.txt
Normal file
753
Arduino/libraries/Ethernet2/license.txt
Normal file
@ -0,0 +1,753 @@
|
||||
this file includes licensing information for parts of arduino.
|
||||
|
||||
first, the gnu general public license, which covers the main body
|
||||
of the processing/arduino code (in general, all the stuff inside the 'app'
|
||||
and 'core' subfolders).
|
||||
|
||||
next, the gnu lesser general public license that covers the arduino core
|
||||
and libraries.
|
||||
|
||||
|
||||
.....................................................................
|
||||
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Library General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
|
||||
|
||||
.....................................................................
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
518
Arduino/libraries/Ethernet2/src/Dhcp.cpp
Normal file
518
Arduino/libraries/Ethernet2/src/Dhcp.cpp
Normal file
@ -0,0 +1,518 @@
|
||||
// DHCP Library v0.3 - April 25, 2009
|
||||
// Author: Jordan Terrell - blog.jordanterrell.com
|
||||
|
||||
#include "utility/w5500.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include "Dhcp.h"
|
||||
#include "Arduino.h"
|
||||
#include "utility/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)
|
||||
{
|
||||
//Serial.println("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 w5500 transmit buffer
|
||||
_dhcpUdpSocket.write(buffer, 28);
|
||||
|
||||
memset(buffer, 0, 32); // clear local buffer
|
||||
|
||||
memcpy(buffer, _dhcpMacAddr, 6); // chaddr
|
||||
|
||||
//put data in w5500 transmit buffer
|
||||
_dhcpUdpSocket.write(buffer, 16);
|
||||
|
||||
memset(buffer, 0, 32); // clear local buffer
|
||||
|
||||
// leave zeroed out for sname && file
|
||||
// put in w5500 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 w5500 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 w5500 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 w5500 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 domainName:
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpDnsdomainName = (char*)malloc(sizeof(char)*opt_len+1);
|
||||
_dhcpUdpSocket.read(_dhcpDnsdomainName, opt_len);
|
||||
_dhcpDnsdomainName[opt_len] = '\0';
|
||||
break;
|
||||
case hostName:
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
_dhcpHostName = (char*)malloc(sizeof(char)*opt_len+1);
|
||||
_dhcpUdpSocket.read(_dhcpHostName, opt_len);
|
||||
_dhcpHostName[opt_len] = '\0';
|
||||
break;
|
||||
case dhcpServerIdentifier :
|
||||
|
||||
opt_len = _dhcpUdpSocket.read();
|
||||
if(((_dhcpDhcpServerIp[0] == 0) && (_dhcpDhcpServerIp[1] == 0) && (_dhcpDhcpServerIp[2] == 0) && (_dhcpDhcpServerIp[3] == 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);
|
||||
}
|
||||
|
||||
char* DhcpClass::getDnsDomainName()
|
||||
{
|
||||
return _dhcpDnsdomainName;
|
||||
}
|
||||
|
||||
char* DhcpClass::getHostName()
|
||||
{
|
||||
return _dhcpHostName;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
182
Arduino/libraries/Ethernet2/src/Dhcp.h
Normal file
182
Arduino/libraries/Ethernet2/src/Dhcp.h
Normal file
@ -0,0 +1,182 @@
|
||||
// DHCP Library v0.3 - April 25, 2009
|
||||
// Author: Jordan Terrell - blog.jordanterrell.com
|
||||
|
||||
#ifndef Dhcp_h
|
||||
#define Dhcp_h
|
||||
|
||||
#include "EthernetUdp2.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];
|
||||
char* _dhcpDnsdomainName;
|
||||
char* _dhcpHostName;
|
||||
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();
|
||||
char* getDnsDomainName();
|
||||
char* getHostName();
|
||||
|
||||
int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 5000);
|
||||
int checkLease();
|
||||
};
|
||||
|
||||
#endif
|
423
Arduino/libraries/Ethernet2/src/Dns.cpp
Normal file
423
Arduino/libraries/Ethernet2/src/Dns.cpp
Normal file
@ -0,0 +1,423 @@
|
||||
// Arduino DNS client for WizNet5100-based Ethernet shield
|
||||
// (c) Copyright 2009-2010 MCQN Ltd.
|
||||
// Released under Apache License, version 2.0
|
||||
|
||||
#include "utility/w5500.h"
|
||||
#include "EthernetUdp2.h"
|
||||
#include "utility/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;
|
||||
}
|
||||
|
41
Arduino/libraries/Ethernet2/src/Dns.h
Normal file
41
Arduino/libraries/Ethernet2/src/Dns.h
Normal file
@ -0,0 +1,41 @@
|
||||
// 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 <EthernetUdp2.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
|
209
Arduino/libraries/Ethernet2/src/Ethernet2.cpp
Normal file
209
Arduino/libraries/Ethernet2/src/Ethernet2.cpp
Normal file
@ -0,0 +1,209 @@
|
||||
/*
|
||||
modified 12 Aug 2013
|
||||
by Soohwan Kim (suhwan@wiznet.co.kr)
|
||||
|
||||
- 10 Apr. 2015
|
||||
Added support for Arduino Ethernet Shield 2
|
||||
by Arduino.org team
|
||||
|
||||
*/
|
||||
|
||||
#include "Ethernet2.h"
|
||||
#include "Dhcp.h"
|
||||
|
||||
// XXX: don't make assumptions about the value of MAX_SOCK_NUM.
|
||||
uint8_t EthernetClass::_state[MAX_SOCK_NUM] = { 0, };
|
||||
uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = { 0, };
|
||||
|
||||
|
||||
|
||||
#if defined(WIZ550io_WITH_MACADDRESS)
|
||||
int EthernetClass::begin(void)
|
||||
{
|
||||
byte mac_address[6] ={0,};
|
||||
if (_dhcp != NULL) {
|
||||
delete _dhcp;
|
||||
}
|
||||
_dhcp = new DhcpClass();
|
||||
|
||||
// Initialise the basic info
|
||||
w5500.init(w5500_cspin);
|
||||
w5500.setIPAddress(IPAddress(0,0,0,0).raw_address());
|
||||
w5500.getMACAddress(mac_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
|
||||
w5500.setIPAddress(_dhcp->getLocalIp().raw_address());
|
||||
w5500.setGatewayIp(_dhcp->getGatewayIp().raw_address());
|
||||
w5500.setSubnetMask(_dhcp->getSubnetMask().raw_address());
|
||||
_dnsServerAddress = _dhcp->getDnsServerIp();
|
||||
_dnsDomainName = _dhcp->getDnsDomainName();
|
||||
_hostName = _dhcp->getHostName();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void EthernetClass::begin(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(local_ip, dns_server);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(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(local_ip, dns_server, gateway);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
|
||||
{
|
||||
IPAddress subnet(255, 255, 255, 0);
|
||||
begin(local_ip, dns_server, gateway, subnet);
|
||||
}
|
||||
|
||||
void EthernetClass::begin(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet)
|
||||
{
|
||||
w5500.init(w5500_cspin);
|
||||
w5500.setIPAddress(local_ip.raw_address());
|
||||
w5500.setGatewayIp(gateway.raw_address());
|
||||
w5500.setSubnetMask(subnet.raw_address());
|
||||
_dnsServerAddress = dns_server;
|
||||
}
|
||||
#else
|
||||
int EthernetClass::begin(uint8_t *mac_address)
|
||||
{
|
||||
if (_dhcp != NULL) {
|
||||
delete _dhcp;
|
||||
}
|
||||
_dhcp = new DhcpClass();
|
||||
// Initialise the basic info
|
||||
w5500.init(w5500_cspin);
|
||||
w5500.setMACAddress(mac_address);
|
||||
w5500.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
|
||||
w5500.setIPAddress(_dhcp->getLocalIp().raw_address());
|
||||
w5500.setGatewayIp(_dhcp->getGatewayIp().raw_address());
|
||||
w5500.setSubnetMask(_dhcp->getSubnetMask().raw_address());
|
||||
_dnsServerAddress = _dhcp->getDnsServerIp();
|
||||
_dnsDomainName = _dhcp->getDnsDomainName();
|
||||
_hostName = _dhcp->getHostName();
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
w5500.init(w5500_cspin);
|
||||
w5500.setMACAddress(mac);
|
||||
w5500.setIPAddress(local_ip.raw_address());
|
||||
w5500.setGatewayIp(gateway.raw_address());
|
||||
w5500.setSubnetMask(subnet.raw_address());
|
||||
_dnsServerAddress = dns_server;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
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.
|
||||
w5500.setIPAddress(_dhcp->getLocalIp().raw_address());
|
||||
w5500.setGatewayIp(_dhcp->getGatewayIp().raw_address());
|
||||
w5500.setSubnetMask(_dhcp->getSubnetMask().raw_address());
|
||||
_dnsServerAddress = _dhcp->getDnsServerIp();
|
||||
_dnsDomainName = _dhcp->getDnsDomainName();
|
||||
_hostName = _dhcp->getHostName();
|
||||
break;
|
||||
default:
|
||||
//this is actually a error, it will retry though
|
||||
break;
|
||||
}
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::localIP()
|
||||
{
|
||||
IPAddress ret;
|
||||
w5500.getIPAddress(ret.raw_address());
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::subnetMask()
|
||||
{
|
||||
IPAddress ret;
|
||||
w5500.getSubnetMask(ret.raw_address());
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::gatewayIP()
|
||||
{
|
||||
IPAddress ret;
|
||||
w5500.getGatewayIp(ret.raw_address());
|
||||
return ret;
|
||||
}
|
||||
|
||||
IPAddress EthernetClass::dnsServerIP()
|
||||
{
|
||||
return _dnsServerAddress;
|
||||
}
|
||||
|
||||
char* EthernetClass::dnsDomainName(){
|
||||
return _dnsDomainName;
|
||||
}
|
||||
|
||||
char* EthernetClass::hostName(){
|
||||
return _hostName;
|
||||
}
|
||||
|
||||
EthernetClass Ethernet;
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user