├── README.md ├── Ethernet-master ├── src │ ├── EthernetClient.h │ ├── EthernetServer.h │ ├── Dns.h │ ├── EthernetUdp.h │ ├── Dhcp.h │ ├── EthernetServer.cpp │ ├── EthernetUdp.cpp │ ├── EthernetClient.cpp │ ├── Ethernet.cpp │ ├── Dns.cpp │ ├── Dhcp.cpp │ ├── Ethernet.h │ └── utility │ │ └── w5100.cpp ├── library.json ├── library.properties ├── examples │ ├── LinkStatus │ │ └── LinkStatus.ino │ ├── DhcpAddressPrinter │ │ └── DhcpAddressPrinter.ino │ ├── ChatServer │ │ └── ChatServer.ino │ ├── DhcpChatServer │ │ └── DhcpChatServer.ino │ ├── TelnetClient │ │ └── TelnetClient.ino │ ├── AdvancedChatServer │ │ └── AdvancedChatServer.ino │ ├── WebServer │ │ └── WebServer.ino │ ├── UDPSendReceiveString │ │ └── UDPSendReceiveString.ino │ ├── WebClientRepeating │ │ └── WebClientRepeating.ino │ ├── WebClient │ │ └── WebClient.ino │ ├── TwitterClient │ │ └── TwitterClient.ino │ ├── UdpNtpClient │ │ └── UdpNtpClient.ino │ ├── PachubeClientString │ │ └── PachubeClientString.ino │ ├── XivelyClientString │ │ └── XivelyClientString.ino │ ├── XivelyClient │ │ └── XivelyClient.ino │ ├── PachubeClient │ │ └── PachubeClient.ino │ └── BarometricPressureWebServer │ │ └── BarometricPressureWebServer.ino ├── AUTHORS ├── keywords.txt └── README.md ├── ESP32Encoder-master ├── library.properties ├── README.md ├── src │ ├── ESP32Encoder.h │ └── ESP32Encoder.cpp ├── examples │ └── Encoder │ │ └── Encoder.ino └── licence.txt ├── udp.comp └── linuxcncinterface └── linuxcncinterface.ino /README.md: -------------------------------------------------------------------------------- 1 | # linuxcnc-esp32 2 | External pulse generator 3 | -------------------------------------------------------------------------------- /Ethernet-master/src/EthernetClient.h: -------------------------------------------------------------------------------- 1 | // This file is in the public domain. No copyright is claimed. 2 | 3 | #include "Ethernet.h" 4 | -------------------------------------------------------------------------------- /Ethernet-master/src/EthernetServer.h: -------------------------------------------------------------------------------- 1 | // This file is in the public domain. No copyright is claimed. 2 | 3 | #include "Ethernet.h" 4 | -------------------------------------------------------------------------------- /Ethernet-master/library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Ethernet", 3 | "keywords": "http, web, server, ethernet", 4 | "description": "Ethernet Library for Teensy", 5 | "repository": 6 | { 7 | "type": "git", 8 | "url": "https://github.com/PaulStoffregen/Ethernet.git" 9 | }, 10 | "frameworks": "arduino", 11 | "platforms": "teensy" 12 | } 13 | -------------------------------------------------------------------------------- /ESP32Encoder-master/library.properties: -------------------------------------------------------------------------------- 1 | name=ESP32Encoder 2 | version=0.3.8 3 | author=Kevin Harrington 4 | maintainer=Kevin Harrington 5 | sentence=Encoder library for the ESP32 using interrupts. 6 | paragraph=Encoder library for the ESP32 using interrupts. This library supports quadrature and half quadrature. 7 | category=Device Control 8 | url=https://github.com/madhephaestus/ESP32Encoder/ 9 | architectures=esp32 10 | includes=ESP32Encoder.h 11 | 12 | -------------------------------------------------------------------------------- /Ethernet-master/library.properties: -------------------------------------------------------------------------------- 1 | name=Ethernet 2 | version=2.0.0 3 | author=Various (see AUTHORS file for details) 4 | maintainer=Paul Stoffregen , Arduino 5 | sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield. 6 | 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. 7 | category=Communication 8 | url=http://www.arduino.cc/en/Reference/Ethernet 9 | architectures=* 10 | includes=Ethernet.h 11 | -------------------------------------------------------------------------------- /ESP32Encoder-master/README.md: -------------------------------------------------------------------------------- 1 | # ESP32Encoder 2 | 3 | ESP32Encoder library uses the ESP32 pulse counter hardware peripheral: 4 | 5 | https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/pcnt.html 6 | 7 | There is only one interrupt for the peripheral, and that is managed by the library. the user has no interrupt interface, and no interrupts are generated on each pulse. interrupts come when the 16 bit counter buffer overflows, so this library has a tiny interrupt footprint while providing 10 simultaneous quadrature encoders. 8 | 9 | ## Pull Downs 10 | 11 | The 2 encoder pins have an internal weak pull down. This is to prevent erronious ticking when disconnected. 12 | -------------------------------------------------------------------------------- /Ethernet-master/examples/LinkStatus/LinkStatus.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Link Status 3 | This sketch prints the ethernet link status. When the 4 | ethernet cable is connected the link status should go to "ON". 5 | NOTE: Only WizNet W5200 and W5500 are capable of reporting 6 | the link status. W5100 will report "Unknown". 7 | Hardware: 8 | - Ethernet shield or equivalent board/shield with WizNet 5200/5500 9 | Written by Cristian Maglie 10 | This example is public domain. 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | void setup() { 17 | // You can use Ethernet.init(pin) to configure the CS pin 18 | //Ethernet.init(10); // Most Arduino shields 19 | //Ethernet.init(5); // MKR ETH shield 20 | //Ethernet.init(0); // Teensy 2.0 21 | //Ethernet.init(20); // Teensy++ 2.0 22 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 23 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 24 | 25 | Serial.begin(9600); 26 | } 27 | 28 | void loop() { 29 | auto link = Ethernet.linkStatus(); 30 | Serial.print("Link status: "); 31 | switch (link) { 32 | case Unknown: 33 | Serial.println("Unknown"); 34 | break; 35 | case LinkON: 36 | Serial.println("ON"); 37 | break; 38 | case LinkOFF: 39 | Serial.println("OFF"); 40 | break; 41 | } 42 | delay(1000); 43 | } 44 | -------------------------------------------------------------------------------- /Ethernet-master/src/Dns.h: -------------------------------------------------------------------------------- 1 | // Arduino DNS client for WizNet5100-based Ethernet shield 2 | // (c) Copyright 2009-2010 MCQN Ltd. 3 | // Released under Apache License, version 2.0 4 | 5 | #ifndef DNSClient_h 6 | #define DNSClient_h 7 | 8 | #include "Ethernet.h" 9 | 10 | class DNSClient 11 | { 12 | public: 13 | void begin(const IPAddress& aDNSServer); 14 | 15 | /** Convert a numeric IP address string into a four-byte IP address. 16 | @param aIPAddrString IP address to convert 17 | @param aResult IPAddress structure to store the returned IP address 18 | @result 1 if aIPAddrString was successfully converted to an IP address, 19 | else error code 20 | */ 21 | int inet_aton(const char *aIPAddrString, IPAddress& aResult); 22 | 23 | /** Resolve the given hostname to an IP address. 24 | @param aHostname Name to be resolved 25 | @param aResult IPAddress structure to store the returned IP address 26 | @result 1 if aIPAddrString was successfully converted to an IP address, 27 | else error code 28 | */ 29 | int getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout=5000); 30 | 31 | protected: 32 | uint16_t BuildRequest(const char* aName); 33 | uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress); 34 | 35 | IPAddress iDNSServer; 36 | uint16_t iRequestId; 37 | EthernetUDP iUdp; 38 | }; 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /ESP32Encoder-master/src/ESP32Encoder.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include "driver/pcnt.h" 5 | #define MAX_ESP32_ENCODERS PCNT_UNIT_MAX 6 | #define _INT16_MAX 32766 7 | #define _INT16_MIN -32766 8 | 9 | enum encType { 10 | single, 11 | half, 12 | full 13 | }; 14 | enum puType { 15 | UP, 16 | DOWN, 17 | NONE 18 | }; 19 | class ESP32Encoder { 20 | private: 21 | void attach(int aPintNumber, int bPinNumber, enum encType et); 22 | boolean attached=false; 23 | 24 | 25 | static pcnt_isr_handle_t user_isr_handle; //user's ISR service handle 26 | bool direction; 27 | bool working; 28 | 29 | static bool attachedInterrupt; 30 | int64_t getCountRaw(); 31 | public: 32 | ESP32Encoder(); 33 | ~ESP32Encoder(); 34 | void attachHalfQuad(int aPintNumber, int bPinNumber); 35 | void attachFullQuad(int aPintNumber, int bPinNumber); 36 | void attachSingleEdge(int aPintNumber, int bPinNumber); 37 | //void attachHalfQuad(int aPintNumber, int bPinNumber); 38 | int64_t getCount(); 39 | int64_t clearCount(); 40 | int64_t pauseCount(); 41 | int64_t resumeCount(); 42 | 43 | boolean isAttached(){return attached;} 44 | void setCount(int64_t value); 45 | static ESP32Encoder *encoders[MAX_ESP32_ENCODERS]; 46 | gpio_num_t aPinNumber; 47 | gpio_num_t bPinNumber; 48 | pcnt_unit_t unit; 49 | bool fullQuad=false; 50 | int countsMode = 2; 51 | volatile int64_t count=0; 52 | pcnt_config_t r_enc_config; 53 | static enum puType useInternalWeakPullResistors; 54 | }; 55 | 56 | //Added by Sloeber 57 | #pragma once 58 | 59 | -------------------------------------------------------------------------------- /ESP32Encoder-master/examples/Encoder/Encoder.ino: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | ESP32Encoder encoder; 5 | ESP32Encoder encoder2; 6 | 7 | // timer and flag for example, not needed for encoders 8 | unsigned long encoder2lastToggled; 9 | bool encoder2Paused = false; 10 | 11 | void setup(){ 12 | 13 | Serial.begin(115200); 14 | // Enable the weak pull down resistors 15 | 16 | //ESP32Encoder::useInternalWeakPullResistors=DOWN; 17 | // Enable the weak pull up resistors 18 | ESP32Encoder::useInternalWeakPullResistors=UP; 19 | 20 | // Attache pins for use as encoder pins 21 | encoder.attachHalfQuad(19, 18); 22 | // Attache pins for use as encoder pins 23 | encoder2.attachHalfQuad(17, 16); 24 | 25 | // set starting count value after attaching 26 | encoder.setCount(37); 27 | 28 | // clear the encoder's raw count and set the tracked count to zero 29 | encoder2.clearCount(); 30 | Serial.println("Encoder Start = "+String((int32_t)encoder.getCount())); 31 | // set the lastToggle 32 | encoder2lastToggled = millis(); 33 | } 34 | 35 | void loop(){ 36 | // Loop and read the count 37 | Serial.println("Encoder count = "+String((int32_t)encoder.getCount())+" "+String((int32_t)encoder2.getCount())); 38 | delay(100); 39 | 40 | // every 5 seconds toggle encoder 2 41 | if (millis() - encoder2lastToggled >= 5000) { 42 | if(encoder2Paused) { 43 | Serial.println("Resuming Encoder 2"); 44 | encoder2.resumeCount(); 45 | } else { 46 | Serial.println("Paused Encoder 2"); 47 | encoder2.pauseCount(); 48 | } 49 | 50 | encoder2Paused = !encoder2Paused; 51 | encoder2lastToggled = millis(); 52 | } 53 | } 54 | 55 | -------------------------------------------------------------------------------- /ESP32Encoder-master/licence.txt: -------------------------------------------------------------------------------- 1 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 2 | 3 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 4 | 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. 5 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 6 | 4. Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Universidad de Palermo, Argentina" (http://www.palermo.edu/).' 7 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 OR CONTRIBUTORS 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. 8 | 9 | Standard License Header 10 | There is no standard license header for the license 11 | -------------------------------------------------------------------------------- /Ethernet-master/AUTHORS: -------------------------------------------------------------------------------- 1 | 2 | Alberto Panu https://github.com/bigjohnson 3 | Alasdair Allan https://github.com/aallan 4 | Alice Pintus https://github.com/00alis 5 | Adrian McEwen https://github.com/amcewen 6 | Arduino LLC http://arduino.cc/ 7 | Arnie97 https://github.com/Arnie97 8 | Arturo Guadalupi https://github.com/agdl 9 | Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/ 10 | chaveiro https://github.com/chaveiro 11 | Cristian Maglie https://github.com/cmaglie 12 | David A. Mellis https://github.com/damellis 13 | Dino Tinitigan https://github.com/bigdinotech 14 | Eddy https://github.com/eddyst 15 | Federico Vanzati https://github.com/Fede85 16 | Federico Fissore https://github.com/ffissore 17 | Jack Christensen https://github.com/JChristensen 18 | Johann Richard https://github.com/johannrichard 19 | Jordan Terrell https://github.com/iSynaptic 20 | Justin Paulin https://github.com/interwho 21 | lathoub https://github.com/lathoub 22 | Martino Facchin https://github.com/facchinm 23 | Matthias Hertel https://github.com/mathertel 24 | Matthijs Kooijman https://github.com/matthijskooijman 25 | Matt Robinson https://github.com/ribbons 26 | MCQN Ltd. http://mcqn.com/ 27 | Michael Amie https://github.com/michaelamie 28 | Michael Margolis https://github.com/michaelmargolis 29 | Norbert Truchsess https://github.com/ntruchsess 30 | Paul Stoffregen https://github.com/PaulStoffregen 31 | per1234 https://github.com/per1234 32 | Richard Sim 33 | Scott Fitzgerald https://github.com/shfitz 34 | Thibaut Viard https://github.com/aethaniel 35 | Tom Igoe https://github.com/tigoe 36 | WizNet http://www.wiznet.co.kr 37 | Zach Eveland https://github.com/zeveland 38 | 39 | -------------------------------------------------------------------------------- /Ethernet-master/keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For Ethernet 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | 9 | Ethernet KEYWORD1 Ethernet 10 | EthernetClient KEYWORD1 EthernetClient 11 | EthernetServer KEYWORD1 EthernetServer 12 | IPAddress KEYWORD1 EthernetIPAddress 13 | 14 | ####################################### 15 | # Methods and Functions (KEYWORD2) 16 | ####################################### 17 | 18 | status KEYWORD2 19 | connect KEYWORD2 20 | write KEYWORD2 21 | available KEYWORD2 22 | availableForWrite KEYWORD2 23 | read KEYWORD2 24 | peek KEYWORD2 25 | flush KEYWORD2 26 | stop KEYWORD2 27 | connected KEYWORD2 28 | accept KEYWORD2 29 | begin KEYWORD2 30 | beginMulticast KEYWORD2 31 | beginPacket KEYWORD2 32 | endPacket KEYWORD2 33 | parsePacket KEYWORD2 34 | remoteIP KEYWORD2 35 | remotePort KEYWORD2 36 | getSocketNumber KEYWORD2 37 | localIP KEYWORD2 38 | localPort KEYWORD2 39 | maintain KEYWORD2 40 | linkStatus KEYWORD2 41 | hardwareStatus KEYWORD2 42 | MACAddress KEYWORD2 43 | subnetMask KEYWORD2 44 | gatewayIP KEYWORD2 45 | dnsServerIP KEYWORD2 46 | setMACAddress KEYWORD2 47 | setLocalIP KEYWORD2 48 | setSubnetMask KEYWORD2 49 | setGatewayIP KEYWORD2 50 | setDnsServerIP KEYWORD2 51 | setRetransmissionTimeout KEYWORD2 52 | setRetransmissionCount KEYWORD2 53 | setConnectionTimeout KEYWORD2 54 | 55 | ####################################### 56 | # Constants (LITERAL1) 57 | ####################################### 58 | 59 | EthernetLinkStatus LITERAL1 60 | Unknown LITERAL1 61 | LinkON LITERAL1 62 | LinkOFF LITERAL1 63 | EthernetHardwareStatus LITERAL1 64 | EthernetNoHardware LITERAL1 65 | EthernetW5100 LITERAL1 66 | EthernetW5200 LITERAL1 67 | EthernetW5500 LITERAL1 68 | -------------------------------------------------------------------------------- /Ethernet-master/src/EthernetUdp.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. 3 | * This version only offers minimal wrapping of socket.cpp 4 | * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ 5 | * 6 | * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) 7 | * 1) UDP does not guarantee the order in which assembled UDP packets are received. This 8 | * might not happen often in practice, but in larger network topologies, a UDP 9 | * packet can be received out of sequence. 10 | * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being 11 | * aware of it. Again, this may not be a concern in practice on small local networks. 12 | * For more information, see http://www.cafeaulait.org/course/week12/35.html 13 | * 14 | * MIT License: 15 | * Copyright (c) 2008 Bjoern Hartmann 16 | * Permission is hereby granted, free of charge, to any person obtaining a copy 17 | * of this software and associated documentation files (the "Software"), to deal 18 | * in the Software without restriction, including without limitation the rights 19 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 20 | * copies of the Software, and to permit persons to whom the Software is 21 | * furnished to do so, subject to the following conditions: 22 | * 23 | * The above copyright notice and this permission notice shall be included in 24 | * all copies or substantial portions of the Software. 25 | * 26 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 27 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 28 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 29 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 30 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 31 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 32 | * THE SOFTWARE. 33 | * 34 | * bjoern@cs.stanford.edu 12/30/2008 35 | */ 36 | 37 | #include "Ethernet.h" 38 | 39 | -------------------------------------------------------------------------------- /Ethernet-master/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino: -------------------------------------------------------------------------------- 1 | /* 2 | DHCP-based IP printer 3 | 4 | This sketch uses the DHCP extensions to the Ethernet library 5 | to get an IP address via DHCP and print the address obtained. 6 | using an Arduino Wiznet Ethernet shield. 7 | 8 | Circuit: 9 | Ethernet shield attached to pins 10, 11, 12, 13 10 | 11 | created 12 April 2011 12 | modified 9 Apr 2012 13 | by Tom Igoe 14 | modified 02 Sept 2015 15 | by Arturo Guadalupi 16 | 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | // Enter a MAC address for your controller below. 23 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 24 | byte mac[] = { 25 | 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 26 | }; 27 | 28 | void setup() { 29 | // You can use Ethernet.init(pin) to configure the CS pin 30 | //Ethernet.init(10); // Most Arduino shields 31 | //Ethernet.init(5); // MKR ETH shield 32 | //Ethernet.init(0); // Teensy 2.0 33 | //Ethernet.init(20); // Teensy++ 2.0 34 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 35 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 36 | 37 | // Open serial communications and wait for port to open: 38 | Serial.begin(9600); 39 | while (!Serial) { 40 | ; // wait for serial port to connect. Needed for native USB port only 41 | } 42 | 43 | // start the Ethernet connection: 44 | Serial.println("Initialize Ethernet with DHCP:"); 45 | if (Ethernet.begin(mac) == 0) { 46 | Serial.println("Failed to configure Ethernet using DHCP"); 47 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 48 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 49 | } else if (Ethernet.linkStatus() == LinkOFF) { 50 | Serial.println("Ethernet cable is not connected."); 51 | } 52 | // no point in carrying on, so do nothing forevermore: 53 | while (true) { 54 | delay(1); 55 | } 56 | } 57 | // print your local IP address: 58 | Serial.print("My IP address: "); 59 | Serial.println(Ethernet.localIP()); 60 | } 61 | 62 | void loop() { 63 | switch (Ethernet.maintain()) { 64 | case 1: 65 | //renewed fail 66 | Serial.println("Error: renewed fail"); 67 | break; 68 | 69 | case 2: 70 | //renewed success 71 | Serial.println("Renewed success"); 72 | //print your local IP address: 73 | Serial.print("My IP address: "); 74 | Serial.println(Ethernet.localIP()); 75 | break; 76 | 77 | case 3: 78 | //rebind fail 79 | Serial.println("Error: rebind fail"); 80 | break; 81 | 82 | case 4: 83 | //rebind success 84 | Serial.println("Rebind success"); 85 | //print your local IP address: 86 | Serial.print("My IP address: "); 87 | Serial.println(Ethernet.localIP()); 88 | break; 89 | 90 | default: 91 | //nothing happened 92 | break; 93 | } 94 | } 95 | 96 | -------------------------------------------------------------------------------- /Ethernet-master/examples/ChatServer/ChatServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Chat Server 3 | 4 | A simple server that distributes any incoming messages to all 5 | connected clients. To use, telnet to your device's IP address and type. 6 | You can see the client's input in the serial monitor as well. 7 | Using an Arduino Wiznet Ethernet shield. 8 | 9 | Circuit: 10 | * Ethernet shield attached to pins 10, 11, 12, 13 11 | 12 | created 18 Dec 2009 13 | by David A. Mellis 14 | modified 9 Apr 2012 15 | by Tom Igoe 16 | 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | // Enter a MAC address and IP address for your controller below. 23 | // The IP address will be dependent on your local network. 24 | // gateway and subnet are optional: 25 | byte mac[] = { 26 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 27 | IPAddress ip(192, 168, 1, 177); 28 | IPAddress myDns(192, 168, 1, 1); 29 | IPAddress gateway(192, 168, 1, 1); 30 | IPAddress subnet(255, 255, 0, 0); 31 | 32 | 33 | // telnet defaults to port 23 34 | EthernetServer server(23); 35 | boolean alreadyConnected = false; // whether or not the client was connected previously 36 | 37 | void setup() { 38 | // You can use Ethernet.init(pin) to configure the CS pin 39 | //Ethernet.init(10); // Most Arduino shields 40 | //Ethernet.init(5); // MKR ETH shield 41 | //Ethernet.init(0); // Teensy 2.0 42 | //Ethernet.init(20); // Teensy++ 2.0 43 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 44 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 45 | 46 | // initialize the ethernet device 47 | Ethernet.begin(mac, ip, myDns, gateway, subnet); 48 | 49 | // Open serial communications and wait for port to open: 50 | Serial.begin(9600); 51 | while (!Serial) { 52 | ; // wait for serial port to connect. Needed for native USB port only 53 | } 54 | 55 | // Check for Ethernet hardware present 56 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 57 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 58 | while (true) { 59 | delay(1); // do nothing, no point running without Ethernet hardware 60 | } 61 | } 62 | if (Ethernet.linkStatus() == LinkOFF) { 63 | Serial.println("Ethernet cable is not connected."); 64 | } 65 | 66 | // start listening for clients 67 | server.begin(); 68 | 69 | Serial.print("Chat server address:"); 70 | Serial.println(Ethernet.localIP()); 71 | } 72 | 73 | void loop() { 74 | // wait for a new client: 75 | EthernetClient client = server.available(); 76 | 77 | // when the client sends the first byte, say hello: 78 | if (client) { 79 | if (!alreadyConnected) { 80 | // clear out the input buffer: 81 | client.flush(); 82 | Serial.println("We have a new client"); 83 | client.println("Hello, client!"); 84 | alreadyConnected = true; 85 | } 86 | 87 | if (client.available() > 0) { 88 | // read the bytes incoming from the client: 89 | char thisChar = client.read(); 90 | // echo the bytes back to the client: 91 | server.write(thisChar); 92 | // echo the bytes to the server as well: 93 | Serial.write(thisChar); 94 | } 95 | } 96 | } 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /Ethernet-master/examples/DhcpChatServer/DhcpChatServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | DHCP Chat Server 3 | 4 | A simple server that distributes any incoming messages to all 5 | connected clients. To use, telnet to your device's IP address and type. 6 | You can see the client's input in the serial monitor as well. 7 | Using an Arduino Wiznet Ethernet shield. 8 | 9 | THis version attempts to get an IP address using DHCP 10 | 11 | Circuit: 12 | * Ethernet shield attached to pins 10, 11, 12, 13 13 | 14 | created 21 May 2011 15 | modified 9 Apr 2012 16 | by Tom Igoe 17 | modified 02 Sept 2015 18 | by Arturo Guadalupi 19 | Based on ChatServer example by David A. Mellis 20 | 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | // Enter a MAC address and IP address for your controller below. 27 | // The IP address will be dependent on your local network. 28 | // gateway and subnet are optional: 29 | byte mac[] = { 30 | 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 31 | }; 32 | IPAddress ip(192, 168, 1, 177); 33 | IPAddress myDns(192, 168, 1, 1); 34 | IPAddress gateway(192, 168, 1, 1); 35 | IPAddress subnet(255, 255, 0, 0); 36 | 37 | // telnet defaults to port 23 38 | EthernetServer server(23); 39 | boolean gotAMessage = false; // whether or not you got a message from the client yet 40 | 41 | void setup() { 42 | // You can use Ethernet.init(pin) to configure the CS pin 43 | //Ethernet.init(10); // Most Arduino shields 44 | //Ethernet.init(5); // MKR ETH shield 45 | //Ethernet.init(0); // Teensy 2.0 46 | //Ethernet.init(20); // Teensy++ 2.0 47 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 48 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 49 | 50 | // Open serial communications and wait for port to open: 51 | Serial.begin(9600); 52 | while (!Serial) { 53 | ; // wait for serial port to connect. Needed for native USB port only 54 | } 55 | 56 | // start the Ethernet connection: 57 | Serial.println("Trying to get an IP address using DHCP"); 58 | if (Ethernet.begin(mac) == 0) { 59 | Serial.println("Failed to configure Ethernet using DHCP"); 60 | // Check for Ethernet hardware present 61 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 62 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 63 | while (true) { 64 | delay(1); // do nothing, no point running without Ethernet hardware 65 | } 66 | } 67 | if (Ethernet.linkStatus() == LinkOFF) { 68 | Serial.println("Ethernet cable is not connected."); 69 | } 70 | // initialize the Ethernet device not using DHCP: 71 | Ethernet.begin(mac, ip, myDns, gateway, subnet); 72 | } 73 | // print your local IP address: 74 | Serial.print("My IP address: "); 75 | Serial.println(Ethernet.localIP()); 76 | 77 | // start listening for clients 78 | server.begin(); 79 | } 80 | 81 | void loop() { 82 | // wait for a new client: 83 | EthernetClient client = server.available(); 84 | 85 | // when the client sends the first byte, say hello: 86 | if (client) { 87 | if (!gotAMessage) { 88 | Serial.println("We have a new client"); 89 | client.println("Hello, client!"); 90 | gotAMessage = true; 91 | } 92 | 93 | // read the bytes incoming from the client: 94 | char thisChar = client.read(); 95 | // echo the bytes back to the client: 96 | server.write(thisChar); 97 | // echo the bytes to the server as well: 98 | Serial.print(thisChar); 99 | Ethernet.maintain(); 100 | } 101 | } 102 | 103 | -------------------------------------------------------------------------------- /Ethernet-master/src/Dhcp.h: -------------------------------------------------------------------------------- 1 | // DHCP Library v0.3 - April 25, 2009 2 | // Author: Jordan Terrell - blog.jordanterrell.com 3 | 4 | #ifndef Dhcp_h 5 | #define Dhcp_h 6 | 7 | /* DHCP state machine. */ 8 | #define STATE_DHCP_START 0 9 | #define STATE_DHCP_DISCOVER 1 10 | #define STATE_DHCP_REQUEST 2 11 | #define STATE_DHCP_LEASED 3 12 | #define STATE_DHCP_REREQUEST 4 13 | #define STATE_DHCP_RELEASE 5 14 | 15 | #define DHCP_FLAGSBROADCAST 0x8000 16 | 17 | /* UDP port numbers for DHCP */ 18 | #define DHCP_SERVER_PORT 67 /* from server to client */ 19 | #define DHCP_CLIENT_PORT 68 /* from client to server */ 20 | 21 | /* DHCP message OP code */ 22 | #define DHCP_BOOTREQUEST 1 23 | #define DHCP_BOOTREPLY 2 24 | 25 | /* DHCP message type */ 26 | #define DHCP_DISCOVER 1 27 | #define DHCP_OFFER 2 28 | #define DHCP_REQUEST 3 29 | #define DHCP_DECLINE 4 30 | #define DHCP_ACK 5 31 | #define DHCP_NAK 6 32 | #define DHCP_RELEASE 7 33 | #define DHCP_INFORM 8 34 | 35 | #define DHCP_HTYPE10MB 1 36 | #define DHCP_HTYPE100MB 2 37 | 38 | #define DHCP_HLENETHERNET 6 39 | #define DHCP_HOPS 0 40 | #define DHCP_SECS 0 41 | 42 | #define MAGIC_COOKIE 0x63825363 43 | #define MAX_DHCP_OPT 16 44 | 45 | #define HOST_NAME "WIZnet" 46 | #define DEFAULT_LEASE (900) //default lease time in seconds 47 | 48 | #define DHCP_CHECK_NONE (0) 49 | #define DHCP_CHECK_RENEW_FAIL (1) 50 | #define DHCP_CHECK_RENEW_OK (2) 51 | #define DHCP_CHECK_REBIND_FAIL (3) 52 | #define DHCP_CHECK_REBIND_OK (4) 53 | 54 | enum 55 | { 56 | padOption = 0, 57 | subnetMask = 1, 58 | timerOffset = 2, 59 | routersOnSubnet = 3, 60 | /* timeServer = 4, 61 | nameServer = 5,*/ 62 | dns = 6, 63 | /*logServer = 7, 64 | cookieServer = 8, 65 | lprServer = 9, 66 | impressServer = 10, 67 | resourceLocationServer = 11,*/ 68 | hostName = 12, 69 | /*bootFileSize = 13, 70 | meritDumpFile = 14,*/ 71 | domainName = 15, 72 | /*swapServer = 16, 73 | rootPath = 17, 74 | extentionsPath = 18, 75 | IPforwarding = 19, 76 | nonLocalSourceRouting = 20, 77 | policyFilter = 21, 78 | maxDgramReasmSize = 22, 79 | defaultIPTTL = 23, 80 | pathMTUagingTimeout = 24, 81 | pathMTUplateauTable = 25, 82 | ifMTU = 26, 83 | allSubnetsLocal = 27, 84 | broadcastAddr = 28, 85 | performMaskDiscovery = 29, 86 | maskSupplier = 30, 87 | performRouterDiscovery = 31, 88 | routerSolicitationAddr = 32, 89 | staticRoute = 33, 90 | trailerEncapsulation = 34, 91 | arpCacheTimeout = 35, 92 | ethernetEncapsulation = 36, 93 | tcpDefaultTTL = 37, 94 | tcpKeepaliveInterval = 38, 95 | tcpKeepaliveGarbage = 39, 96 | nisDomainName = 40, 97 | nisServers = 41, 98 | ntpServers = 42, 99 | vendorSpecificInfo = 43, 100 | netBIOSnameServer = 44, 101 | netBIOSdgramDistServer = 45, 102 | netBIOSnodeType = 46, 103 | netBIOSscope = 47, 104 | xFontServer = 48, 105 | xDisplayManager = 49,*/ 106 | dhcpRequestedIPaddr = 50, 107 | dhcpIPaddrLeaseTime = 51, 108 | /*dhcpOptionOverload = 52,*/ 109 | dhcpMessageType = 53, 110 | dhcpServerIdentifier = 54, 111 | dhcpParamRequest = 55, 112 | /*dhcpMsg = 56, 113 | dhcpMaxMsgSize = 57,*/ 114 | dhcpT1value = 58, 115 | dhcpT2value = 59, 116 | /*dhcpClassIdentifier = 60,*/ 117 | dhcpClientIdentifier = 61, 118 | endOption = 255 119 | }; 120 | 121 | typedef struct _RIP_MSG_FIXED 122 | { 123 | uint8_t op; 124 | uint8_t htype; 125 | uint8_t hlen; 126 | uint8_t hops; 127 | uint32_t xid; 128 | uint16_t secs; 129 | uint16_t flags; 130 | uint8_t ciaddr[4]; 131 | uint8_t yiaddr[4]; 132 | uint8_t siaddr[4]; 133 | uint8_t giaddr[4]; 134 | uint8_t chaddr[6]; 135 | } RIP_MSG_FIXED; 136 | 137 | #endif 138 | -------------------------------------------------------------------------------- /Ethernet-master/examples/TelnetClient/TelnetClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Telnet client 3 | 4 | This sketch connects to a a telnet server (http://www.google.com) 5 | using an Arduino Wiznet Ethernet shield. You'll need a telnet server 6 | to test this with. 7 | Processing's ChatServer example (part of the network library) works well, 8 | running on port 10002. It can be found as part of the examples 9 | in the Processing application, available at 10 | http://processing.org/ 11 | 12 | Circuit: 13 | * Ethernet shield attached to pins 10, 11, 12, 13 14 | 15 | created 14 Sep 2010 16 | modified 9 Apr 2012 17 | by Tom Igoe 18 | */ 19 | 20 | #include 21 | #include 22 | 23 | // Enter a MAC address and IP address for your controller below. 24 | // The IP address will be dependent on your local network: 25 | byte mac[] = { 26 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 27 | }; 28 | IPAddress ip(192, 168, 1, 177); 29 | 30 | // Enter the IP address of the server you're connecting to: 31 | IPAddress server(1, 1, 1, 1); 32 | 33 | // Initialize the Ethernet client library 34 | // with the IP address and port of the server 35 | // that you want to connect to (port 23 is default for telnet; 36 | // if you're using Processing's ChatServer, use port 10002): 37 | EthernetClient client; 38 | 39 | void setup() { 40 | // You can use Ethernet.init(pin) to configure the CS pin 41 | //Ethernet.init(10); // Most Arduino shields 42 | //Ethernet.init(5); // MKR ETH shield 43 | //Ethernet.init(0); // Teensy 2.0 44 | //Ethernet.init(20); // Teensy++ 2.0 45 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 46 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 47 | 48 | // start the Ethernet connection: 49 | Ethernet.begin(mac, ip); 50 | 51 | // Open serial communications and wait for port to open: 52 | Serial.begin(9600); 53 | while (!Serial) { 54 | ; // wait for serial port to connect. Needed for native USB port only 55 | } 56 | 57 | // Check for Ethernet hardware present 58 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 59 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 60 | while (true) { 61 | delay(1); // do nothing, no point running without Ethernet hardware 62 | } 63 | } 64 | while (Ethernet.linkStatus() == LinkOFF) { 65 | Serial.println("Ethernet cable is not connected."); 66 | delay(500); 67 | } 68 | 69 | // give the Ethernet shield a second to initialize: 70 | delay(1000); 71 | Serial.println("connecting..."); 72 | 73 | // if you get a connection, report back via serial: 74 | if (client.connect(server, 10002)) { 75 | Serial.println("connected"); 76 | } else { 77 | // if you didn't get a connection to the server: 78 | Serial.println("connection failed"); 79 | } 80 | } 81 | 82 | void loop() { 83 | // if there are incoming bytes available 84 | // from the server, read them and print them: 85 | if (client.available()) { 86 | char c = client.read(); 87 | Serial.print(c); 88 | } 89 | 90 | // as long as there are bytes in the serial queue, 91 | // read them and send them out the socket if it's open: 92 | while (Serial.available() > 0) { 93 | char inChar = Serial.read(); 94 | if (client.connected()) { 95 | client.print(inChar); 96 | } 97 | } 98 | 99 | // if the server's disconnected, stop the client: 100 | if (!client.connected()) { 101 | Serial.println(); 102 | Serial.println("disconnecting."); 103 | client.stop(); 104 | // do nothing: 105 | while (true) { 106 | delay(1); 107 | } 108 | } 109 | } 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /Ethernet-master/examples/AdvancedChatServer/AdvancedChatServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Advanced Chat Server 3 | 4 | A more advanced server that distributes any incoming messages 5 | to all connected clients but the client the message comes from. 6 | To use, telnet to your device's IP address and type. 7 | You can see the client's input in the serial monitor as well. 8 | Using an Arduino Wiznet Ethernet shield. 9 | 10 | Circuit: 11 | * Ethernet shield attached to pins 10, 11, 12, 13 12 | 13 | created 18 Dec 2009 14 | by David A. Mellis 15 | modified 9 Apr 2012 16 | by Tom Igoe 17 | redesigned to make use of operator== 25 Nov 2013 18 | by Norbert Truchsess 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | 25 | // Enter a MAC address and IP address for your controller below. 26 | // The IP address will be dependent on your local network. 27 | // gateway and subnet are optional: 28 | byte mac[] = { 29 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 30 | }; 31 | IPAddress ip(192, 168, 1, 177); 32 | IPAddress myDns(192, 168, 1, 1); 33 | IPAddress gateway(192, 168, 1, 1); 34 | IPAddress subnet(255, 255, 0, 0); 35 | 36 | 37 | // telnet defaults to port 23 38 | EthernetServer server(23); 39 | 40 | EthernetClient clients[8]; 41 | 42 | void setup() { 43 | // You can use Ethernet.init(pin) to configure the CS pin 44 | //Ethernet.init(10); // Most Arduino shields 45 | //Ethernet.init(5); // MKR ETH shield 46 | //Ethernet.init(0); // Teensy 2.0 47 | //Ethernet.init(20); // Teensy++ 2.0 48 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 49 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 50 | 51 | // initialize the Ethernet device 52 | Ethernet.begin(mac, ip, myDns, gateway, subnet); 53 | 54 | // Open serial communications and wait for port to open: 55 | Serial.begin(9600); 56 | while (!Serial) { 57 | ; // wait for serial port to connect. Needed for native USB port only 58 | } 59 | 60 | // Check for Ethernet hardware present 61 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 62 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 63 | while (true) { 64 | delay(1); // do nothing, no point running without Ethernet hardware 65 | } 66 | } 67 | if (Ethernet.linkStatus() == LinkOFF) { 68 | Serial.println("Ethernet cable is not connected."); 69 | } 70 | 71 | // start listening for clients 72 | server.begin(); 73 | 74 | Serial.print("Chat server address:"); 75 | Serial.println(Ethernet.localIP()); 76 | } 77 | 78 | void loop() { 79 | // check for any new client connecting, and say hello (before any incoming data) 80 | EthernetClient newClient = server.accept(); 81 | if (newClient) { 82 | for (byte i=0; i < 8; i++) { 83 | if (!clients[i]) { 84 | Serial.print("We have a new client #"); 85 | Serial.println(i); 86 | newClient.print("Hello, client number: "); 87 | newClient.println(i); 88 | // Once we "accept", the client is no longer tracked by EthernetServer 89 | // so we must store it into our list of clients 90 | clients[i] = newClient; 91 | break; 92 | } 93 | } 94 | } 95 | 96 | // check for incoming data from all clients 97 | for (byte i=0; i < 8; i++) { 98 | if (clients[i] && clients[i].available() > 0) { 99 | // read bytes from a client 100 | byte buffer[80]; 101 | int count = clients[i].read(buffer, 80); 102 | // write the bytes to all other connected clients 103 | for (byte j=0; j < 8; j++) { 104 | if (j != i && clients[j].connected()) { 105 | clients[j].write(buffer, count); 106 | } 107 | } 108 | } 109 | } 110 | 111 | // stop any clients which disconnect 112 | for (byte i=0; i < 8; i++) { 113 | if (clients[i] && !clients[i].connected()) { 114 | Serial.print("disconnect client #"); 115 | Serial.println(i); 116 | clients[i].stop(); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /Ethernet-master/README.md: -------------------------------------------------------------------------------- 1 | # Improved Performance Ethernet Library 2 | 3 | Wiznet chips W5100, W5200 and W5500 are automatically detected. 4 | 5 | Efficient block mode of W5200 & W5500 are used for data and multi-byte register access. 6 | 7 | Wiznet socket registers are cached, which greatly reduces SPI communication overhead, at the cost of a small increase in RAM usage. TCP connections and UDP packets accessed in small chunks typically see a substantial performance boost. 8 | 9 | Adafruit's Ethernet.init(CSPIN) extension is supported, to allow use of different pins for the chip select signal. Optimized direct register I/O is used for most Arduino compatible boards. 10 | 11 | http://www.pjrc.com/teensy/td_libs_Ethernet.html 12 | 13 | ![](http://www.pjrc.com/store/wiz820_assem5.jpg) 14 | 15 | ### Tested Hardware 16 | 17 | 18 | | Board | Chip | Shield / Module | Internet | Local (LAN) | 19 | | --------------------- | :---: | :-------------------: | ------------: | ------------: | 20 | | Teensy 3.6 | W5500 | WIZ850io | 212.59 | 1143.58 | 21 | | Teensy 3.6 | W5200 | WIZ820io | 202.44 | 1102.71 | 22 | | Teensy 3.6 | W5100 | WIZ812MJ | 180.76 | 274.14 | 23 | | ESP32 Feather | W5500 | Featherwing Ethernet | 211.06 | 965.76 | 24 | | Teensy 3.2 | W5500 | WIZ850io | 205.37 | 958.06 | 25 | | Teensy 3.2 | W5200 | WIZ820io | 215.44 | 914.78 | 26 | | Teensy 3.2 | W5100 | WIZ812MJ | 170.07 | 234.55 | 27 | | ChipKit Uno32 | W5500 | Seeed Ethernet W5500 | 177.19 | 858.81 | 28 | | ChipKit Uno32 | W5200 | WIZ820io | 188.31 | 837.56 | 29 | | ChipKit Uno32 | W5100 | Ethernet R2 (clone) | 159.72 | 272.18 | 30 | | Arduino Due | W5500 | Seeed Ethernet | 214.44 | 689.69 | 31 | | Arduino Due | W5200 | WIZ820io | 206.51 | 670.88 | 32 | | Arduino Due | W5100 | Arduino Ethernet R3 | 105.98 | 109.73 | 33 | | ESP8266 Feather | W5500 | Featherwing Ethernet | fail (dns) | 583.31 | 34 | | Teensy LC | W5500 | WIZ850io | 200.51 | 479.73 | 35 | | Teensy LC | W5200 | WIZ820io | 199.62 | 471.95 | 36 | | Teensy LC | W5100 | WIZ812MJ | 126.40 | 137.77 | 37 | | Arduino 101 (Intel) | W5500 | Seeed Ethernet W5500 | 168.96 | 359.32 | 38 | | Arduino 101 (Intel) | W5200 | WIZ820io | 169.37 | 349.35 | 39 | | Arduino 101 (Intel) | W5100 | Arduino Ethernet R3 | 42.39 | 43.60 | 40 | | Teensy 2.0 | W5100 | WIZ812MJ | 81.07 | 84.85 | 41 | | Arduino Uno R3 | W5500 | Seeed Ethernet W5500 | 185.44 | 329.00 | 42 | | Arduino Uno R3 | W5500 | Arduino.org Ethernet2 | 195.32 | 329.60 | 43 | | Arduino Uno R3 | W5200 | WIZ820io | 191.85 | 331.27 | 44 | | Arduino Uno R3 | W5100 | Arduino Ethernet R3 | 79.11 | 82.66 | 45 | | Arduino Uno R3 | W5100 | Ethernet R2 (clone) | 79.27 | 82.66 | 46 | | Arduino Leonardo | W5500 | Seeed Ethernet W5500 | 179.98 | 328.14 | 47 | | Arduino Leonardo | W5200 | WIZ820io | 183.69 | 330.30 | 48 | | Arduino Leonardo | W5100 | Ethernet R2 (clone) | 78.75 | 82.28 | 49 | | Mega 2560 (clone) | W5500 | Seeed Ethernet W5500 | 179.58 | 323.36 | 50 | | Mega 2560 (clone) | W5200 | WIZ820io | 172.73 | 325.44 | 51 | | Mega 2560 (clone) | W5100 | Ethernet R2 (clone) | 74.31 | 77.44 | 52 | | Arduino Zero | W5500 | Seeed Ethernet W5500 | 183.13 | 305.26 | 53 | | Arduino Zero | W5500 | Arduino.org Ethernet2 | 181.60 | 305.28 | 54 | | Arduino Zero | W5200 | WIZ820io | 177.53 | 298.53 | 55 | | Arduino Zero | W5100 | Arduino Ethernet R3 | 91.33 | 96.64 | 56 | | Arduino Zero | W5100 | Ethernet R2 (clone) | 91.42 | 96.64 | 57 | | Arduino MKR1000 | W5500 | MKR ETH | 181.27 | 298.93 | 58 | | Arduino MKR1000 | W5200 | WIZ820io | 125.20 | 291.98 | 59 | | Arduino Uno Wifi Rev2 | W5500 | Seeed Ethernet W5500 | 163.86 | 213.36 | 60 | | Arduino Uno Wifi Rev2 | W5500 | Arduino.org Ethernet2 | 169.72 | 212.88 | 61 | | Arduino Uno Wifi Rev2 | W5200 | WIZ820io | 161.94 | 212.19 | 62 | | Arduino Uno Wifi Rev2 | W5100 | Arduino.org Ethernet2 | 69.50 | 72.23 | 63 | | Arduino Uno Wifi Rev2 | W5100 | Ethernet R2 (clone) | 69.55 | 72.30 | 64 | 65 | For more information about these benchmarks: 66 | https://www.pjrc.com/arduino-ethernet-library-2-0-0/ 67 | 68 | ESP32 may require edit to SPI.h to add SPI.transfer(data, size) 69 | https://github.com/espressif/arduino-esp32/issues/1623 70 | -------------------------------------------------------------------------------- /Ethernet-master/examples/WebServer/WebServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Web Server 3 | 4 | A simple web server that shows the value of the analog input pins. 5 | using an Arduino Wiznet Ethernet shield. 6 | 7 | Circuit: 8 | * Ethernet shield attached to pins 10, 11, 12, 13 9 | * Analog inputs attached to pins A0 through A5 (optional) 10 | 11 | created 18 Dec 2009 12 | by David A. Mellis 13 | modified 9 Apr 2012 14 | by Tom Igoe 15 | modified 02 Sept 2015 16 | by Arturo Guadalupi 17 | 18 | */ 19 | 20 | #include 21 | #include 22 | 23 | // Enter a MAC address and IP address for your controller below. 24 | // The IP address will be dependent on your local network: 25 | byte mac[] = { 26 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 27 | }; 28 | IPAddress ip(192, 168, 1, 177); 29 | 30 | // Initialize the Ethernet server library 31 | // with the IP address and port you want to use 32 | // (port 80 is default for HTTP): 33 | EthernetServer server(80); 34 | 35 | void setup() { 36 | // You can use Ethernet.init(pin) to configure the CS pin 37 | //Ethernet.init(10); // Most Arduino shields 38 | //Ethernet.init(5); // MKR ETH shield 39 | //Ethernet.init(0); // Teensy 2.0 40 | //Ethernet.init(20); // Teensy++ 2.0 41 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 42 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 43 | 44 | // Open serial communications and wait for port to open: 45 | Serial.begin(9600); 46 | while (!Serial) { 47 | ; // wait for serial port to connect. Needed for native USB port only 48 | } 49 | Serial.println("Ethernet WebServer Example"); 50 | 51 | // start the Ethernet connection and the server: 52 | Ethernet.begin(mac, ip); 53 | 54 | // Check for Ethernet hardware present 55 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 56 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 57 | while (true) { 58 | delay(1); // do nothing, no point running without Ethernet hardware 59 | } 60 | } 61 | if (Ethernet.linkStatus() == LinkOFF) { 62 | Serial.println("Ethernet cable is not connected."); 63 | } 64 | 65 | // start the server 66 | server.begin(); 67 | Serial.print("server is at "); 68 | Serial.println(Ethernet.localIP()); 69 | } 70 | 71 | 72 | void loop() { 73 | // listen for incoming clients 74 | EthernetClient client = server.available(); 75 | if (client) { 76 | Serial.println("new client"); 77 | // an http request ends with a blank line 78 | boolean currentLineIsBlank = true; 79 | while (client.connected()) { 80 | if (client.available()) { 81 | char c = client.read(); 82 | Serial.write(c); 83 | // if you've gotten to the end of the line (received a newline 84 | // character) and the line is blank, the http request has ended, 85 | // so you can send a reply 86 | if (c == '\n' && currentLineIsBlank) { 87 | // send a standard http response header 88 | client.println("HTTP/1.1 200 OK"); 89 | client.println("Content-Type: text/html"); 90 | client.println("Connection: close"); // the connection will be closed after completion of the response 91 | client.println("Refresh: 5"); // refresh the page automatically every 5 sec 92 | client.println(); 93 | client.println(""); 94 | client.println(""); 95 | // output the value of each analog input pin 96 | for (int analogChannel = 0; analogChannel < 6; analogChannel++) { 97 | int sensorReading = analogRead(analogChannel); 98 | client.print("analog input "); 99 | client.print(analogChannel); 100 | client.print(" is "); 101 | client.print(sensorReading); 102 | client.println("
"); 103 | } 104 | client.println(""); 105 | break; 106 | } 107 | if (c == '\n') { 108 | // you're starting a new line 109 | currentLineIsBlank = true; 110 | } else if (c != '\r') { 111 | // you've gotten a character on the current line 112 | currentLineIsBlank = false; 113 | } 114 | } 115 | } 116 | // give the web browser time to receive the data 117 | delay(1); 118 | // close the connection: 119 | client.stop(); 120 | Serial.println("client disconnected"); 121 | } 122 | } 123 | 124 | -------------------------------------------------------------------------------- /Ethernet-master/examples/UDPSendReceiveString/UDPSendReceiveString.ino: -------------------------------------------------------------------------------- 1 | /* 2 | UDPSendReceiveString: 3 | This sketch receives UDP message strings, prints them to the serial port 4 | and sends an "acknowledge" string back to the sender 5 | 6 | A Processing sketch is included at the end of file that can be used to send 7 | and received messages for testing with a computer. 8 | 9 | created 21 Aug 2010 10 | by Michael Margolis 11 | 12 | This code is in the public domain. 13 | */ 14 | 15 | 16 | #include 17 | #include 18 | 19 | // Enter a MAC address and IP address for your controller below. 20 | // The IP address will be dependent on your local network: 21 | byte mac[] = { 22 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 23 | }; 24 | IPAddress ip(192, 168, 1, 177); 25 | 26 | unsigned int localPort = 8888; // local port to listen on 27 | 28 | // buffers for receiving and sending data 29 | char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet, 30 | char ReplyBuffer[] = "acknowledged"; // a string to send back 31 | 32 | // An EthernetUDP instance to let us send and receive packets over UDP 33 | EthernetUDP Udp; 34 | 35 | void setup() { 36 | // You can use Ethernet.init(pin) to configure the CS pin 37 | //Ethernet.init(10); // Most Arduino shields 38 | //Ethernet.init(5); // MKR ETH shield 39 | //Ethernet.init(0); // Teensy 2.0 40 | //Ethernet.init(20); // Teensy++ 2.0 41 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 42 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 43 | 44 | // start the Ethernet 45 | Ethernet.begin(mac, ip); 46 | 47 | // Open serial communications and wait for port to open: 48 | Serial.begin(9600); 49 | while (!Serial) { 50 | ; // wait for serial port to connect. Needed for native USB port only 51 | } 52 | 53 | // Check for Ethernet hardware present 54 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 55 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 56 | while (true) { 57 | delay(1); // do nothing, no point running without Ethernet hardware 58 | } 59 | } 60 | if (Ethernet.linkStatus() == LinkOFF) { 61 | Serial.println("Ethernet cable is not connected."); 62 | } 63 | 64 | // start UDP 65 | Udp.begin(localPort); 66 | } 67 | 68 | void loop() { 69 | // if there's data available, read a packet 70 | int packetSize = Udp.parsePacket(); 71 | if (packetSize) { 72 | Serial.print("Received packet of size "); 73 | Serial.println(packetSize); 74 | Serial.print("From "); 75 | IPAddress remote = Udp.remoteIP(); 76 | for (int i=0; i < 4; i++) { 77 | Serial.print(remote[i], DEC); 78 | if (i < 3) { 79 | Serial.print("."); 80 | } 81 | } 82 | Serial.print(", port "); 83 | Serial.println(Udp.remotePort()); 84 | 85 | // read the packet into packetBufffer 86 | Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); 87 | Serial.println("Contents:"); 88 | Serial.println(packetBuffer); 89 | 90 | // send a reply to the IP address and port that sent us the packet we received 91 | Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); 92 | Udp.write(ReplyBuffer); 93 | Udp.endPacket(); 94 | } 95 | delay(10); 96 | } 97 | 98 | 99 | /* 100 | Processing sketch to run with this example 101 | ===================================================== 102 | 103 | // Processing UDP example to send and receive string data from Arduino 104 | // press any key to send the "Hello Arduino" message 105 | 106 | 107 | import hypermedia.net.*; 108 | 109 | UDP udp; // define the UDP object 110 | 111 | 112 | void setup() { 113 | udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000 114 | //udp.log( true ); // <-- printout the connection activity 115 | udp.listen( true ); // and wait for incoming message 116 | } 117 | 118 | void draw() 119 | { 120 | } 121 | 122 | void keyPressed() { 123 | String ip = "192.168.1.177"; // the remote IP address 124 | int port = 8888; // the destination port 125 | 126 | udp.send("Hello World", ip, port ); // the message to send 127 | 128 | } 129 | 130 | void receive( byte[] data ) { // <-- default handler 131 | //void receive( byte[] data, String ip, int port ) { // <-- extended handler 132 | 133 | for(int i=0; i < data.length; i++) 134 | print(char(data[i])); 135 | println(); 136 | } 137 | */ 138 | 139 | 140 | -------------------------------------------------------------------------------- /Ethernet-master/examples/WebClientRepeating/WebClientRepeating.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Repeating Web client 3 | 4 | This sketch connects to a a web server and makes a request 5 | using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or 6 | the Adafruit Ethernet shield, either one will work, as long as it's got 7 | a Wiznet Ethernet module on board. 8 | 9 | This example uses DNS, by assigning the Ethernet client with a MAC address, 10 | IP address, and DNS address. 11 | 12 | Circuit: 13 | * Ethernet shield attached to pins 10, 11, 12, 13 14 | 15 | created 19 Apr 2012 16 | by Tom Igoe 17 | modified 21 Jan 2014 18 | by Federico Vanzati 19 | 20 | http://www.arduino.cc/en/Tutorial/WebClientRepeating 21 | This code is in the public domain. 22 | 23 | */ 24 | 25 | #include 26 | #include 27 | 28 | // assign a MAC address for the ethernet controller. 29 | // fill in your address here: 30 | byte mac[] = { 31 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 32 | }; 33 | // Set the static IP address to use if the DHCP fails to assign 34 | IPAddress ip(192, 168, 0, 177); 35 | IPAddress myDns(192, 168, 0, 1); 36 | 37 | // initialize the library instance: 38 | EthernetClient client; 39 | 40 | char server[] = "www.arduino.cc"; // also change the Host line in httpRequest() 41 | //IPAddress server(64,131,82,241); 42 | 43 | unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds 44 | const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds 45 | 46 | void setup() { 47 | // You can use Ethernet.init(pin) to configure the CS pin 48 | //Ethernet.init(10); // Most Arduino shields 49 | //Ethernet.init(5); // MKR ETH shield 50 | //Ethernet.init(0); // Teensy 2.0 51 | //Ethernet.init(20); // Teensy++ 2.0 52 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 53 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 54 | 55 | // start serial port: 56 | Serial.begin(9600); 57 | while (!Serial) { 58 | ; // wait for serial port to connect. Needed for native USB port only 59 | } 60 | 61 | // start the Ethernet connection: 62 | Serial.println("Initialize Ethernet with DHCP:"); 63 | if (Ethernet.begin(mac) == 0) { 64 | Serial.println("Failed to configure Ethernet using DHCP"); 65 | // Check for Ethernet hardware present 66 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 67 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 68 | while (true) { 69 | delay(1); // do nothing, no point running without Ethernet hardware 70 | } 71 | } 72 | if (Ethernet.linkStatus() == LinkOFF) { 73 | Serial.println("Ethernet cable is not connected."); 74 | } 75 | // try to congifure using IP address instead of DHCP: 76 | Ethernet.begin(mac, ip, myDns); 77 | Serial.print("My IP address: "); 78 | Serial.println(Ethernet.localIP()); 79 | } else { 80 | Serial.print(" DHCP assigned IP "); 81 | Serial.println(Ethernet.localIP()); 82 | } 83 | // give the Ethernet shield a second to initialize: 84 | delay(1000); 85 | } 86 | 87 | void loop() { 88 | // if there's incoming data from the net connection. 89 | // send it out the serial port. This is for debugging 90 | // purposes only: 91 | if (client.available()) { 92 | char c = client.read(); 93 | Serial.write(c); 94 | } 95 | 96 | // if ten seconds have passed since your last connection, 97 | // then connect again and send data: 98 | if (millis() - lastConnectionTime > postingInterval) { 99 | httpRequest(); 100 | } 101 | 102 | } 103 | 104 | // this method makes a HTTP connection to the server: 105 | void httpRequest() { 106 | // close any connection before send a new request. 107 | // This will free the socket on the WiFi shield 108 | client.stop(); 109 | 110 | // if there's a successful connection: 111 | if (client.connect(server, 80)) { 112 | Serial.println("connecting..."); 113 | // send the HTTP GET request: 114 | client.println("GET /latest.txt HTTP/1.1"); 115 | client.println("Host: www.arduino.cc"); 116 | client.println("User-Agent: arduino-ethernet"); 117 | client.println("Connection: close"); 118 | client.println(); 119 | 120 | // note the time that the connection was made: 121 | lastConnectionTime = millis(); 122 | } else { 123 | // if you couldn't make a connection: 124 | Serial.println("connection failed"); 125 | } 126 | } 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /Ethernet-master/examples/WebClient/WebClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Web client 3 | 4 | This sketch connects to a website (http://www.google.com) 5 | using an Arduino Wiznet Ethernet shield. 6 | 7 | Circuit: 8 | * Ethernet shield attached to pins 10, 11, 12, 13 9 | 10 | created 18 Dec 2009 11 | by David A. Mellis 12 | modified 9 Apr 2012 13 | by Tom Igoe, based on work by Adrian McEwen 14 | 15 | */ 16 | 17 | #include 18 | #include 19 | 20 | // Enter a MAC address for your controller below. 21 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 22 | byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 23 | 24 | // if you don't want to use DNS (and reduce your sketch size) 25 | // use the numeric IP instead of the name for the server: 26 | //IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) 27 | char server[] = "www.google.com"; // name address for Google (using DNS) 28 | 29 | // Set the static IP address to use if the DHCP fails to assign 30 | IPAddress ip(192, 168, 0, 177); 31 | IPAddress myDns(192, 168, 0, 1); 32 | 33 | // Initialize the Ethernet client library 34 | // with the IP address and port of the server 35 | // that you want to connect to (port 80 is default for HTTP): 36 | EthernetClient client; 37 | 38 | // Variables to measure the speed 39 | unsigned long beginMicros, endMicros; 40 | unsigned long byteCount = 0; 41 | bool printWebData = true; // set to false for better speed measurement 42 | 43 | void setup() { 44 | // You can use Ethernet.init(pin) to configure the CS pin 45 | //Ethernet.init(10); // Most Arduino shields 46 | //Ethernet.init(5); // MKR ETH shield 47 | //Ethernet.init(0); // Teensy 2.0 48 | //Ethernet.init(20); // Teensy++ 2.0 49 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 50 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 51 | 52 | // Open serial communications and wait for port to open: 53 | Serial.begin(9600); 54 | while (!Serial) { 55 | ; // wait for serial port to connect. Needed for native USB port only 56 | } 57 | 58 | // start the Ethernet connection: 59 | Serial.println("Initialize Ethernet with DHCP:"); 60 | if (Ethernet.begin(mac) == 0) { 61 | Serial.println("Failed to configure Ethernet using DHCP"); 62 | // Check for Ethernet hardware present 63 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 64 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 65 | while (true) { 66 | delay(1); // do nothing, no point running without Ethernet hardware 67 | } 68 | } 69 | if (Ethernet.linkStatus() == LinkOFF) { 70 | Serial.println("Ethernet cable is not connected."); 71 | } 72 | // try to congifure using IP address instead of DHCP: 73 | Ethernet.begin(mac, ip, myDns); 74 | } else { 75 | Serial.print(" DHCP assigned IP "); 76 | Serial.println(Ethernet.localIP()); 77 | } 78 | // give the Ethernet shield a second to initialize: 79 | delay(1000); 80 | Serial.print("connecting to "); 81 | Serial.print(server); 82 | Serial.println("..."); 83 | 84 | // if you get a connection, report back via serial: 85 | if (client.connect(server, 80)) { 86 | Serial.print("connected to "); 87 | Serial.println(client.remoteIP()); 88 | // Make a HTTP request: 89 | client.println("GET /search?q=arduino HTTP/1.1"); 90 | client.println("Host: www.google.com"); 91 | client.println("Connection: close"); 92 | client.println(); 93 | } else { 94 | // if you didn't get a connection to the server: 95 | Serial.println("connection failed"); 96 | } 97 | beginMicros = micros(); 98 | } 99 | 100 | void loop() { 101 | // if there are incoming bytes available 102 | // from the server, read them and print them: 103 | int len = client.available(); 104 | if (len > 0) { 105 | byte buffer[80]; 106 | if (len > 80) len = 80; 107 | client.read(buffer, len); 108 | if (printWebData) { 109 | Serial.write(buffer, len); // show in the serial monitor (slows some boards) 110 | } 111 | byteCount = byteCount + len; 112 | } 113 | 114 | // if the server's disconnected, stop the client: 115 | if (!client.connected()) { 116 | endMicros = micros(); 117 | Serial.println(); 118 | Serial.println("disconnecting."); 119 | client.stop(); 120 | Serial.print("Received "); 121 | Serial.print(byteCount); 122 | Serial.print(" bytes in "); 123 | float seconds = (float)(endMicros - beginMicros) / 1000000.0; 124 | Serial.print(seconds, 4); 125 | float rate = (float)byteCount / seconds / 1000.0; 126 | Serial.print(", rate = "); 127 | Serial.print(rate); 128 | Serial.print(" kbytes/second"); 129 | Serial.println(); 130 | 131 | // do nothing forevermore: 132 | while (true) { 133 | delay(1); 134 | } 135 | } 136 | } 137 | 138 | -------------------------------------------------------------------------------- /Ethernet-master/examples/TwitterClient/TwitterClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Twitter Client with Strings 3 | 4 | This sketch connects to Twitter using an Ethernet shield. It parses the XML 5 | returned, and looks for this is a tweet 6 | 7 | You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield, 8 | either one will work, as long as it's got a Wiznet Ethernet module on board. 9 | 10 | This example uses the DHCP routines in the Ethernet library which is part of the 11 | Arduino core from version 1.0 beta 1 12 | 13 | This example uses the String library, which is part of the Arduino core from 14 | version 0019. 15 | 16 | Circuit: 17 | * Ethernet shield attached to pins 10, 11, 12, 13 18 | 19 | created 21 May 2011 20 | modified 9 Apr 2012 21 | by Tom Igoe 22 | 23 | This code is in the public domain. 24 | 25 | */ 26 | #include 27 | #include 28 | 29 | 30 | // Enter a MAC address and IP address for your controller below. 31 | // The IP address will be dependent on your local network: 32 | byte mac[] = { 33 | 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 34 | }; 35 | IPAddress ip(192, 168, 1, 20); 36 | 37 | // initialize the library instance: 38 | EthernetClient client; 39 | 40 | const unsigned long requestInterval = 60000; // delay between requests 41 | 42 | char serverName[] = "api.twitter.com"; // twitter URL 43 | 44 | boolean requested; // whether you've made a request since connecting 45 | unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds 46 | 47 | String currentLine = ""; // string to hold the text from server 48 | String tweet = ""; // string to hold the tweet 49 | boolean readingTweet = false; // if you're currently reading the tweet 50 | 51 | void setup() { 52 | // You can use Ethernet.init(pin) to configure the CS pin 53 | //Ethernet.init(10); // Most Arduino shields 54 | //Ethernet.init(5); // MKR ETH shield 55 | //Ethernet.init(0); // Teensy 2.0 56 | //Ethernet.init(20); // Teensy++ 2.0 57 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 58 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 59 | 60 | // reserve space for the strings: 61 | currentLine.reserve(256); 62 | tweet.reserve(150); 63 | 64 | // Open serial communications and wait for port to open: 65 | Serial.begin(9600); 66 | while (!Serial) { 67 | ; // wait for serial port to connect. Needed for Leonardo only 68 | } 69 | 70 | 71 | // attempt a DHCP connection: 72 | Serial.println("Attempting to get an IP address using DHCP:"); 73 | if (!Ethernet.begin(mac)) { 74 | // if DHCP fails, start with a hard-coded address: 75 | Serial.println("failed to get an IP address using DHCP, trying manually"); 76 | Ethernet.begin(mac, ip); 77 | } 78 | Serial.print("My address:"); 79 | Serial.println(Ethernet.localIP()); 80 | // connect to Twitter: 81 | connectToServer(); 82 | } 83 | 84 | 85 | 86 | void loop() 87 | { 88 | if (client.connected()) { 89 | if (client.available()) { 90 | // read incoming bytes: 91 | char inChar = client.read(); 92 | 93 | // add incoming byte to end of line: 94 | currentLine += inChar; 95 | 96 | // if you get a newline, clear the line: 97 | if (inChar == '\n') { 98 | currentLine = ""; 99 | } 100 | // if the current line ends with , it will 101 | // be followed by the tweet: 102 | if ( currentLine.endsWith("")) { 103 | // tweet is beginning. Clear the tweet string: 104 | readingTweet = true; 105 | tweet = ""; 106 | } 107 | // if you're currently reading the bytes of a tweet, 108 | // add them to the tweet String: 109 | if (readingTweet) { 110 | if (inChar != '<') { 111 | tweet += inChar; 112 | } else { 113 | // if you got a "<" character, 114 | // you've reached the end of the tweet: 115 | readingTweet = false; 116 | Serial.println(tweet); 117 | // close the connection to the server: 118 | client.stop(); 119 | } 120 | } 121 | } 122 | } 123 | else if (millis() - lastAttemptTime > requestInterval) { 124 | // if you're not connected, and two minutes have passed since 125 | // your last connection, then attempt to connect again: 126 | connectToServer(); 127 | } 128 | } 129 | 130 | void connectToServer() { 131 | // attempt to connect, and wait a millisecond: 132 | Serial.println("connecting to server..."); 133 | if (client.connect(serverName, 80)) { 134 | Serial.println("making HTTP request..."); 135 | // make HTTP GET request to twitter: 136 | client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1"); 137 | client.println("HOST: api.twitter.com"); 138 | client.println("Connection: close"); 139 | client.println(); 140 | } 141 | // note the time of this connect attempt: 142 | lastAttemptTime = millis(); 143 | } 144 | 145 | -------------------------------------------------------------------------------- /Ethernet-master/examples/UdpNtpClient/UdpNtpClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Udp NTP Client 4 | 5 | Get the time from a Network Time Protocol (NTP) time server 6 | Demonstrates use of UDP sendPacket and ReceivePacket 7 | For more on NTP time servers and the messages needed to communicate with them, 8 | see http://en.wikipedia.org/wiki/Network_Time_Protocol 9 | 10 | created 4 Sep 2010 11 | by Michael Margolis 12 | modified 9 Apr 2012 13 | by Tom Igoe 14 | modified 02 Sept 2015 15 | by Arturo Guadalupi 16 | 17 | This code is in the public domain. 18 | 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | // Enter a MAC address for your controller below. 26 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 27 | byte mac[] = { 28 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 29 | }; 30 | 31 | unsigned int localPort = 8888; // local port to listen for UDP packets 32 | 33 | const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server 34 | 35 | const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message 36 | 37 | byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 38 | 39 | // A UDP instance to let us send and receive packets over UDP 40 | EthernetUDP Udp; 41 | 42 | void setup() { 43 | // You can use Ethernet.init(pin) to configure the CS pin 44 | //Ethernet.init(10); // Most Arduino shields 45 | //Ethernet.init(5); // MKR ETH shield 46 | //Ethernet.init(0); // Teensy 2.0 47 | //Ethernet.init(20); // Teensy++ 2.0 48 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 49 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 50 | 51 | // Open serial communications and wait for port to open: 52 | Serial.begin(9600); 53 | while (!Serial) { 54 | ; // wait for serial port to connect. Needed for native USB port only 55 | } 56 | 57 | // start Ethernet and UDP 58 | if (Ethernet.begin(mac) == 0) { 59 | Serial.println("Failed to configure Ethernet using DHCP"); 60 | // Check for Ethernet hardware present 61 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 62 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 63 | } else if (Ethernet.linkStatus() == LinkOFF) { 64 | Serial.println("Ethernet cable is not connected."); 65 | } 66 | // no point in carrying on, so do nothing forevermore: 67 | while (true) { 68 | delay(1); 69 | } 70 | } 71 | Udp.begin(localPort); 72 | } 73 | 74 | void loop() { 75 | sendNTPpacket(timeServer); // send an NTP packet to a time server 76 | 77 | // wait to see if a reply is available 78 | delay(1000); 79 | if (Udp.parsePacket()) { 80 | // We've received a packet, read the data from it 81 | Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer 82 | 83 | // the timestamp starts at byte 40 of the received packet and is four bytes, 84 | // or two words, long. First, extract the two words: 85 | 86 | unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); 87 | unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); 88 | // combine the four bytes (two words) into a long integer 89 | // this is NTP time (seconds since Jan 1 1900): 90 | unsigned long secsSince1900 = highWord << 16 | lowWord; 91 | Serial.print("Seconds since Jan 1 1900 = "); 92 | Serial.println(secsSince1900); 93 | 94 | // now convert NTP time into everyday time: 95 | Serial.print("Unix time = "); 96 | // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: 97 | const unsigned long seventyYears = 2208988800UL; 98 | // subtract seventy years: 99 | unsigned long epoch = secsSince1900 - seventyYears; 100 | // print Unix time: 101 | Serial.println(epoch); 102 | 103 | 104 | // print the hour, minute and second: 105 | Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) 106 | Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) 107 | Serial.print(':'); 108 | if (((epoch % 3600) / 60) < 10) { 109 | // In the first 10 minutes of each hour, we'll want a leading '0' 110 | Serial.print('0'); 111 | } 112 | Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) 113 | Serial.print(':'); 114 | if ((epoch % 60) < 10) { 115 | // In the first 10 seconds of each minute, we'll want a leading '0' 116 | Serial.print('0'); 117 | } 118 | Serial.println(epoch % 60); // print the second 119 | } 120 | // wait ten seconds before asking for the time again 121 | delay(10000); 122 | Ethernet.maintain(); 123 | } 124 | 125 | // send an NTP request to the time server at the given address 126 | void sendNTPpacket(const char * address) { 127 | // set all bytes in the buffer to 0 128 | memset(packetBuffer, 0, NTP_PACKET_SIZE); 129 | // Initialize values needed to form NTP request 130 | // (see URL above for details on the packets) 131 | packetBuffer[0] = 0b11100011; // LI, Version, Mode 132 | packetBuffer[1] = 0; // Stratum, or type of clock 133 | packetBuffer[2] = 6; // Polling Interval 134 | packetBuffer[3] = 0xEC; // Peer Clock Precision 135 | // 8 bytes of zero for Root Delay & Root Dispersion 136 | packetBuffer[12] = 49; 137 | packetBuffer[13] = 0x4E; 138 | packetBuffer[14] = 49; 139 | packetBuffer[15] = 52; 140 | 141 | // all NTP fields have been given values, now 142 | // you can send a packet requesting a timestamp: 143 | Udp.beginPacket(address, 123); // NTP requests are to port 123 144 | Udp.write(packetBuffer, NTP_PACKET_SIZE); 145 | Udp.endPacket(); 146 | } 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | -------------------------------------------------------------------------------- /Ethernet-master/examples/PachubeClientString/PachubeClientString.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Pachube sensor client with Strings 3 | 4 | This sketch connects an analog sensor to Pachube (http://www.pachube.com) 5 | using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or 6 | the Adafruit Ethernet shield, either one will work, as long as it's got 7 | a Wiznet Ethernet module on board. 8 | 9 | This example has been updated to use version 2.0 of the pachube.com API. 10 | To make it work, create a feed with two datastreams, and give them the IDs 11 | sensor1 and sensor2. Or change the code below to match your feed. 12 | 13 | This example uses the String library, which is part of the Arduino core from 14 | version 0019. 15 | 16 | Circuit: 17 | * Analog sensor attached to analog in A0 18 | * Ethernet shield attached to pins 10, 11, 12, 13 19 | 20 | created 15 March 2010 21 | modified 9 Apr 2012 22 | by Tom Igoe with input from Usman Haque and Joe Saavedra 23 | modified 8 September 2012 24 | by Scott Fitzgerald 25 | 26 | http://arduino.cc/en/Tutorial/PachubeClientString 27 | This code is in the public domain. 28 | 29 | */ 30 | 31 | #include 32 | #include 33 | 34 | 35 | #define APIKEY "YOUR API KEY GOES HERE" // replace your Pachube api key here 36 | #define FEEDID 00000 // replace your feed ID 37 | #define USERAGENT "My Project" // user agent is the project name 38 | 39 | 40 | // assign a MAC address for the ethernet controller. 41 | // fill in your address here: 42 | byte mac[] = { 43 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 44 | }; 45 | 46 | // fill in an available IP address on your network here, 47 | // for manual configuration: 48 | IPAddress ip(10,0,1,20); 49 | 50 | // initialize the library instance: 51 | EthernetClient client; 52 | 53 | // if you don't want to use DNS (and reduce your sketch size) 54 | // use the numeric IP instead of the name for the server: 55 | IPAddress server(216,52,233,121); // numeric IP for api.pachube.com 56 | //char server[] = "api.pachube.com"; // name address for pachube API 57 | 58 | unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds 59 | boolean lastConnected = false; // state of the connection last time through the main loop 60 | const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com 61 | 62 | void setup() { 63 | // You can use Ethernet.init(pin) to configure the CS pin 64 | //Ethernet.init(10); // Most Arduino shields 65 | //Ethernet.init(5); // MKR ETH shield 66 | //Ethernet.init(0); // Teensy 2.0 67 | //Ethernet.init(20); // Teensy++ 2.0 68 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 69 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 70 | 71 | // Open serial communications and wait for port to open: 72 | Serial.begin(9600); 73 | while (!Serial) { 74 | ; // wait for serial port to connect. Needed for Leonardo only 75 | } 76 | 77 | 78 | // give the ethernet module time to boot up: 79 | delay(1000); 80 | // start the Ethernet connection: 81 | if (Ethernet.begin(mac) == 0) { 82 | Serial.println("Failed to configure Ethernet using DHCP"); 83 | // DHCP failed, so use a fixed IP address: 84 | Ethernet.begin(mac, ip); 85 | } 86 | } 87 | 88 | void loop() { 89 | // read the analog sensor: 90 | int sensorReading = analogRead(A0); 91 | // convert the data to a String to send it: 92 | 93 | String dataString = "sensor1,"; 94 | dataString += sensorReading; 95 | 96 | // you can append multiple readings to this String if your 97 | // pachube feed is set up to handle multiple values: 98 | int otherSensorReading = analogRead(A1); 99 | dataString += "\nsensor2,"; 100 | dataString += otherSensorReading; 101 | 102 | // if there's incoming data from the net connection. 103 | // send it out the serial port. This is for debugging 104 | // purposes only: 105 | if (client.available()) { 106 | char c = client.read(); 107 | Serial.print(c); 108 | } 109 | 110 | // if there's no net connection, but there was one last time 111 | // through the loop, then stop the client: 112 | if (!client.connected() && lastConnected) { 113 | Serial.println(); 114 | Serial.println("disconnecting."); 115 | client.stop(); 116 | } 117 | 118 | // if you're not connected, and ten seconds have passed since 119 | // your last connection, then connect again and send data: 120 | if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { 121 | sendData(dataString); 122 | } 123 | // store the state of the connection for next time through 124 | // the loop: 125 | lastConnected = client.connected(); 126 | } 127 | 128 | // this method makes a HTTP connection to the server: 129 | void sendData(String thisData) { 130 | // if there's a successful connection: 131 | if (client.connect(server, 80)) { 132 | Serial.println("connecting..."); 133 | // send the HTTP PUT request: 134 | client.print("PUT /v2/feeds/"); 135 | client.print(FEEDID); 136 | client.println(".csv HTTP/1.1"); 137 | client.println("Host: api.pachube.com"); 138 | client.print("X-pachubeApiKey: "); 139 | client.println(APIKEY); 140 | client.print("User-Agent: "); 141 | client.println(USERAGENT); 142 | client.print("Content-Length: "); 143 | client.println(thisData.length()); 144 | 145 | // last pieces of the HTTP PUT request: 146 | client.println("Content-Type: text/csv"); 147 | client.println("Connection: close"); 148 | client.println(); 149 | 150 | // here's the actual content of the PUT request: 151 | client.println(thisData); 152 | } else { 153 | // if you couldn't make a connection: 154 | Serial.println("connection failed"); 155 | Serial.println(); 156 | Serial.println("disconnecting."); 157 | client.stop(); 158 | } 159 | // note the time that the connection was made or attempted: 160 | lastConnectionTime = millis(); 161 | } 162 | 163 | -------------------------------------------------------------------------------- /Ethernet-master/examples/XivelyClientString/XivelyClientString.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Xively sensor client with Strings 3 | 4 | This sketch connects an analog sensor to Xively (http://www.xively.com) 5 | using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or 6 | the Adafruit Ethernet shield, either one will work, as long as it's got 7 | a Wiznet Ethernet module on board. 8 | 9 | This example has been updated to use version 2.0 of the xively.com API. 10 | To make it work, create a feed with two datastreams, and give them the IDs 11 | sensor1 and sensor2. Or change the code below to match your feed. 12 | 13 | This example uses the String library, which is part of the Arduino core from 14 | version 0019. 15 | 16 | Circuit: 17 | * Analog sensor attached to analog in 0 18 | * Ethernet shield attached to pins 10, 11, 12, 13 19 | 20 | created 15 March 2010 21 | modified 9 Apr 2012 22 | by Tom Igoe with input from Usman Haque and Joe Saavedra 23 | modified 8 September 2012 24 | by Scott Fitzgerald 25 | 26 | http://arduino.cc/en/Tutorial/XivelyClientString 27 | This code is in the public domain. 28 | 29 | */ 30 | 31 | #include 32 | #include 33 | 34 | 35 | #define APIKEY "YOUR API KEY GOES HERE" // replace your Xively api key here 36 | #define FEEDID 00000 // replace your feed ID 37 | #define USERAGENT "My Project" // user agent is the project name 38 | 39 | 40 | // assign a MAC address for the ethernet controller. 41 | // fill in your address here: 42 | byte mac[] = { 43 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 44 | }; 45 | 46 | // fill in an available IP address on your network here, 47 | // for manual configuration: 48 | IPAddress ip(10, 0, 1, 20); 49 | 50 | // initialize the library instance: 51 | EthernetClient client; 52 | 53 | // if you don't want to use DNS (and reduce your sketch size) 54 | // use the numeric IP instead of the name for the server: 55 | IPAddress server(216, 52, 233, 121); // numeric IP for api.xively.com 56 | //char server[] = "api.xively.com"; // name address for xively API 57 | 58 | unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds 59 | boolean lastConnected = false; // state of the connection last time through the main loop 60 | const unsigned long postingInterval = 10*1000; //delay between updates to xively.com 61 | 62 | void setup() { 63 | // You can use Ethernet.init(pin) to configure the CS pin 64 | //Ethernet.init(10); // Most Arduino shields 65 | //Ethernet.init(5); // MKR ETH shield 66 | //Ethernet.init(0); // Teensy 2.0 67 | //Ethernet.init(20); // Teensy++ 2.0 68 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 69 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 70 | 71 | // Open serial communications and wait for port to open: 72 | Serial.begin(9600); 73 | while (!Serial) { 74 | ; // wait for serial port to connect. Needed for native USB port only 75 | } 76 | 77 | 78 | // give the ethernet module time to boot up: 79 | delay(1000); 80 | // start the Ethernet connection: 81 | if (Ethernet.begin(mac) == 0) { 82 | Serial.println("Failed to configure Ethernet using DHCP"); 83 | // DHCP failed, so use a fixed IP address: 84 | Ethernet.begin(mac, ip); 85 | } 86 | } 87 | 88 | void loop() { 89 | // read the analog sensor: 90 | int sensorReading = analogRead(A0); 91 | // convert the data to a String to send it: 92 | 93 | String dataString = "sensor1,"; 94 | dataString += sensorReading; 95 | 96 | // you can append multiple readings to this String if your 97 | // xively feed is set up to handle multiple values: 98 | int otherSensorReading = analogRead(A1); 99 | dataString += "\nsensor2,"; 100 | dataString += otherSensorReading; 101 | 102 | // if there's incoming data from the net connection. 103 | // send it out the serial port. This is for debugging 104 | // purposes only: 105 | if (client.available()) { 106 | char c = client.read(); 107 | Serial.print(c); 108 | } 109 | 110 | // if there's no net connection, but there was one last time 111 | // through the loop, then stop the client: 112 | if (!client.connected() && lastConnected) { 113 | Serial.println(); 114 | Serial.println("disconnecting."); 115 | client.stop(); 116 | } 117 | 118 | // if you're not connected, and ten seconds have passed since 119 | // your last connection, then connect again and send data: 120 | if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { 121 | sendData(dataString); 122 | } 123 | // store the state of the connection for next time through 124 | // the loop: 125 | lastConnected = client.connected(); 126 | } 127 | 128 | // this method makes a HTTP connection to the server: 129 | void sendData(String thisData) { 130 | // if there's a successful connection: 131 | if (client.connect(server, 80)) { 132 | Serial.println("connecting..."); 133 | // send the HTTP PUT request: 134 | client.print("PUT /v2/feeds/"); 135 | client.print(FEEDID); 136 | client.println(".csv HTTP/1.1"); 137 | client.println("Host: api.xively.com"); 138 | client.print("X-xivelyApiKey: "); 139 | client.println(APIKEY); 140 | client.print("User-Agent: "); 141 | client.println(USERAGENT); 142 | client.print("Content-Length: "); 143 | client.println(thisData.length()); 144 | 145 | // last pieces of the HTTP PUT request: 146 | client.println("Content-Type: text/csv"); 147 | client.println("Connection: close"); 148 | client.println(); 149 | 150 | // here's the actual content of the PUT request: 151 | client.println(thisData); 152 | } 153 | else { 154 | // if you couldn't make a connection: 155 | Serial.println("connection failed"); 156 | Serial.println(); 157 | Serial.println("disconnecting."); 158 | client.stop(); 159 | } 160 | // note the time that the connection was made or attempted: 161 | lastConnectionTime = millis(); 162 | } 163 | 164 | -------------------------------------------------------------------------------- /Ethernet-master/src/EthernetServer.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | 25 | uint16_t EthernetServer::server_port[MAX_SOCK_NUM]; 26 | 27 | 28 | void EthernetServer::begin() 29 | { 30 | uint8_t sockindex = Ethernet.socketBegin(SnMR::TCP, _port); 31 | if (sockindex < MAX_SOCK_NUM) { 32 | if (Ethernet.socketListen(sockindex)) { 33 | server_port[sockindex] = _port; 34 | } else { 35 | Ethernet.socketDisconnect(sockindex); 36 | } 37 | } 38 | } 39 | 40 | EthernetClient EthernetServer::available() 41 | { 42 | bool listening = false; 43 | uint8_t sockindex = MAX_SOCK_NUM; 44 | uint8_t chip, maxindex=MAX_SOCK_NUM; 45 | 46 | chip = W5100.getChip(); 47 | if (!chip) return EthernetClient(MAX_SOCK_NUM); 48 | #if MAX_SOCK_NUM > 4 49 | if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets 50 | #endif 51 | for (uint8_t i=0; i < maxindex; i++) { 52 | if (server_port[i] == _port) { 53 | uint8_t stat = Ethernet.socketStatus(i); 54 | if (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT) { 55 | if (Ethernet.socketRecvAvailable(i) > 0) { 56 | sockindex = i; 57 | } else { 58 | // remote host closed connection, our end still open 59 | if (stat == SnSR::CLOSE_WAIT) { 60 | Ethernet.socketDisconnect(i); 61 | // status becomes LAST_ACK for short time 62 | } 63 | } 64 | } else if (stat == SnSR::LISTEN) { 65 | listening = true; 66 | } else if (stat == SnSR::CLOSED) { 67 | server_port[i] = 0; 68 | } 69 | } 70 | } 71 | if (!listening) begin(); 72 | return EthernetClient(sockindex); 73 | } 74 | 75 | EthernetClient EthernetServer::accept() 76 | { 77 | bool listening = false; 78 | uint8_t sockindex = MAX_SOCK_NUM; 79 | uint8_t chip, maxindex=MAX_SOCK_NUM; 80 | 81 | chip = W5100.getChip(); 82 | if (!chip) return EthernetClient(MAX_SOCK_NUM); 83 | #if MAX_SOCK_NUM > 4 84 | if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets 85 | #endif 86 | for (uint8_t i=0; i < maxindex; i++) { 87 | if (server_port[i] == _port) { 88 | uint8_t stat = Ethernet.socketStatus(i); 89 | if (sockindex == MAX_SOCK_NUM && 90 | (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT)) { 91 | // Return the connected client even if no data received. 92 | // Some protocols like FTP expect the server to send the 93 | // first data. 94 | sockindex = i; 95 | server_port[i] = 0; // only return the client once 96 | } else if (stat == SnSR::LISTEN) { 97 | listening = true; 98 | } else if (stat == SnSR::CLOSED) { 99 | server_port[i] = 0; 100 | } 101 | } 102 | } 103 | if (!listening) begin(); 104 | return EthernetClient(sockindex); 105 | } 106 | 107 | EthernetServer::operator bool() 108 | { 109 | uint8_t maxindex=MAX_SOCK_NUM; 110 | #if MAX_SOCK_NUM > 4 111 | if (W5100.getChip() == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets 112 | #endif 113 | for (uint8_t i=0; i < maxindex; i++) { 114 | if (server_port[i] == _port) { 115 | if (Ethernet.socketStatus(i) == SnSR::LISTEN) { 116 | return true; // server is listening for incoming clients 117 | } 118 | } 119 | } 120 | return false; 121 | } 122 | 123 | #if 0 124 | void EthernetServer::statusreport() 125 | { 126 | Serial.printf("EthernetServer, port=%d\n", _port); 127 | for (uint8_t i=0; i < MAX_SOCK_NUM; i++) { 128 | uint16_t port = server_port[i]; 129 | uint8_t stat = Ethernet.socketStatus(i); 130 | const char *name; 131 | switch (stat) { 132 | case 0x00: name = "CLOSED"; break; 133 | case 0x13: name = "INIT"; break; 134 | case 0x14: name = "LISTEN"; break; 135 | case 0x15: name = "SYNSENT"; break; 136 | case 0x16: name = "SYNRECV"; break; 137 | case 0x17: name = "ESTABLISHED"; break; 138 | case 0x18: name = "FIN_WAIT"; break; 139 | case 0x1A: name = "CLOSING"; break; 140 | case 0x1B: name = "TIME_WAIT"; break; 141 | case 0x1C: name = "CLOSE_WAIT"; break; 142 | case 0x1D: name = "LAST_ACK"; break; 143 | case 0x22: name = "UDP"; break; 144 | case 0x32: name = "IPRAW"; break; 145 | case 0x42: name = "MACRAW"; break; 146 | case 0x5F: name = "PPPOE"; break; 147 | default: name = "???"; 148 | } 149 | int avail = Ethernet.socketRecvAvailable(i); 150 | Serial.printf(" %d: port=%d, status=%s (0x%02X), avail=%d\n", 151 | i, port, name, stat, avail); 152 | } 153 | } 154 | #endif 155 | 156 | size_t EthernetServer::write(uint8_t b) 157 | { 158 | return write(&b, 1); 159 | } 160 | 161 | size_t EthernetServer::write(const uint8_t *buffer, size_t size) 162 | { 163 | uint8_t chip, maxindex=MAX_SOCK_NUM; 164 | 165 | chip = W5100.getChip(); 166 | if (!chip) return 0; 167 | #if MAX_SOCK_NUM > 4 168 | if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets 169 | #endif 170 | available(); 171 | for (uint8_t i=0; i < maxindex; i++) { 172 | if (server_port[i] == _port) { 173 | if (Ethernet.socketStatus(i) == SnSR::ESTABLISHED) { 174 | Ethernet.socketSend(i, buffer, size); 175 | } 176 | } 177 | } 178 | return size; 179 | } 180 | -------------------------------------------------------------------------------- /Ethernet-master/examples/XivelyClient/XivelyClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Xively sensor client 3 | 4 | This sketch connects an analog sensor to Xively (http://www.xively.com) 5 | using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or 6 | the Adafruit Ethernet shield, either one will work, as long as it's got 7 | a Wiznet Ethernet module on board. 8 | 9 | This example has been updated to use version 2.0 of the Xively.com API. 10 | To make it work, create a feed with a datastream, and give it the ID 11 | sensor1. Or change the code below to match your feed. 12 | 13 | 14 | Circuit: 15 | * Analog sensor attached to analog in 0 16 | * Ethernet shield attached to pins 10, 11, 12, 13 17 | 18 | created 15 March 2010 19 | modified 9 Apr 2012 20 | by Tom Igoe with input from Usman Haque and Joe Saavedra 21 | 22 | http://arduino.cc/en/Tutorial/XivelyClient 23 | This code is in the public domain. 24 | 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | #define APIKEY "YOUR API KEY GOES HERE" // replace your xively api key here 31 | #define FEEDID 00000 // replace your feed ID 32 | #define USERAGENT "My Project" // user agent is the project name 33 | 34 | // assign a MAC address for the ethernet controller. 35 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 36 | // fill in your address here: 37 | byte mac[] = { 38 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 39 | }; 40 | 41 | // fill in an available IP address on your network here, 42 | // for manual configuration: 43 | IPAddress ip(10, 0, 1, 20); 44 | // initialize the library instance: 45 | EthernetClient client; 46 | 47 | // if you don't want to use DNS (and reduce your sketch size) 48 | // use the numeric IP instead of the name for the server: 49 | IPAddress server(216, 52, 233, 122); // numeric IP for api.xively.com 50 | //char server[] = "api.xively.com"; // name address for xively API 51 | 52 | unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds 53 | boolean lastConnected = false; // state of the connection last time through the main loop 54 | const unsigned long postingInterval = 10*1000; //delay between updates to Xively.com 55 | 56 | void setup() { 57 | // You can use Ethernet.init(pin) to configure the CS pin 58 | //Ethernet.init(10); // Most Arduino shields 59 | //Ethernet.init(5); // MKR ETH shield 60 | //Ethernet.init(0); // Teensy 2.0 61 | //Ethernet.init(20); // Teensy++ 2.0 62 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 63 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 64 | 65 | // Open serial communications and wait for port to open: 66 | Serial.begin(9600); 67 | while (!Serial) { 68 | ; // wait for serial port to connect. Needed for native USB port only 69 | } 70 | 71 | 72 | // start the Ethernet connection: 73 | if (Ethernet.begin(mac) == 0) { 74 | Serial.println("Failed to configure Ethernet using DHCP"); 75 | // DHCP failed, so use a fixed IP address: 76 | Ethernet.begin(mac, ip); 77 | } 78 | } 79 | 80 | void loop() { 81 | // read the analog sensor: 82 | int sensorReading = analogRead(A0); 83 | 84 | // if there's incoming data from the net connection. 85 | // send it out the serial port. This is for debugging 86 | // purposes only: 87 | if (client.available()) { 88 | char c = client.read(); 89 | Serial.print(c); 90 | } 91 | 92 | // if there's no net connection, but there was one last time 93 | // through the loop, then stop the client: 94 | if (!client.connected() && lastConnected) { 95 | Serial.println(); 96 | Serial.println("disconnecting."); 97 | client.stop(); 98 | } 99 | 100 | // if you're not connected, and ten seconds have passed since 101 | // your last connection, then connect again and send data: 102 | if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { 103 | sendData(sensorReading); 104 | } 105 | // store the state of the connection for next time through 106 | // the loop: 107 | lastConnected = client.connected(); 108 | } 109 | 110 | // this method makes a HTTP connection to the server: 111 | void sendData(int thisData) { 112 | // if there's a successful connection: 113 | if (client.connect(server, 80)) { 114 | Serial.println("connecting..."); 115 | // send the HTTP PUT request: 116 | client.print("PUT /v2/feeds/"); 117 | client.print(FEEDID); 118 | client.println(".csv HTTP/1.1"); 119 | client.println("Host: api.xively.com"); 120 | client.print("X-XivelyApiKey: "); 121 | client.println(APIKEY); 122 | client.print("User-Agent: "); 123 | client.println(USERAGENT); 124 | client.print("Content-Length: "); 125 | 126 | // calculate the length of the sensor reading in bytes: 127 | // 8 bytes for "sensor1," + number of digits of the data: 128 | int thisLength = 8 + getLength(thisData); 129 | client.println(thisLength); 130 | 131 | // last pieces of the HTTP PUT request: 132 | client.println("Content-Type: text/csv"); 133 | client.println("Connection: close"); 134 | client.println(); 135 | 136 | // here's the actual content of the PUT request: 137 | client.print("sensor1,"); 138 | client.println(thisData); 139 | 140 | } else { 141 | // if you couldn't make a connection: 142 | Serial.println("connection failed"); 143 | Serial.println(); 144 | Serial.println("disconnecting."); 145 | client.stop(); 146 | } 147 | // note the time that the connection was made or attempted: 148 | lastConnectionTime = millis(); 149 | } 150 | 151 | 152 | // This method calculates the number of digits in the 153 | // sensor reading. Since each digit of the ASCII decimal 154 | // representation is a byte, the number of digits equals 155 | // the number of bytes: 156 | 157 | int getLength(int someValue) { 158 | // there's at least one byte: 159 | int digits = 1; 160 | // continually divide the value by ten, 161 | // adding one to the digit count for each 162 | // time you divide, until you're at 0: 163 | int dividend = someValue /10; 164 | while (dividend > 0) { 165 | dividend = dividend /10; 166 | digits++; 167 | } 168 | // return the number of digits: 169 | return digits; 170 | } 171 | 172 | -------------------------------------------------------------------------------- /Ethernet-master/examples/PachubeClient/PachubeClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Pachube sensor client 3 | 4 | This sketch connects an analog sensor to Pachube (http://www.pachube.com) 5 | using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or 6 | the Adafruit Ethernet shield, either one will work, as long as it's got 7 | a Wiznet Ethernet module on board. 8 | 9 | This example has been updated to use version 2.0 of the Pachube.com API. 10 | To make it work, create a feed with a datastream, and give it the ID 11 | sensor1. Or change the code below to match your feed. 12 | 13 | 14 | Circuit: 15 | * Analog sensor attached to analog in A0 16 | * Ethernet shield attached to pins 10, 11, 12, 13 17 | 18 | created 15 March 2010 19 | modified 9 Apr 2012 20 | by Tom Igoe with input from Usman Haque and Joe Saavedra 21 | 22 | http://arduino.cc/en/Tutorial/PachubeClient 23 | This code is in the public domain. 24 | 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | #define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here 31 | #define FEEDID 00000 // replace your feed ID 32 | #define USERAGENT "My Project" // user agent is the project name 33 | 34 | // assign a MAC address for the ethernet controller. 35 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 36 | // fill in your address here: 37 | byte mac[] = { 38 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; 39 | 40 | // fill in an available IP address on your network here, 41 | // for manual configuration: 42 | IPAddress ip(10,0,1,20); 43 | // initialize the library instance: 44 | EthernetClient client; 45 | 46 | // if you don't want to use DNS (and reduce your sketch size) 47 | // use the numeric IP instead of the name for the server: 48 | IPAddress server(216,52,233,122); // numeric IP for api.pachube.com 49 | //char server[] = "api.pachube.com"; // name address for pachube API 50 | 51 | unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds 52 | boolean lastConnected = false; // state of the connection last time through the main loop 53 | const unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com 54 | 55 | void setup() { 56 | // You can use Ethernet.init(pin) to configure the CS pin 57 | //Ethernet.init(10); // Most Arduino shields 58 | //Ethernet.init(5); // MKR ETH shield 59 | //Ethernet.init(0); // Teensy 2.0 60 | //Ethernet.init(20); // Teensy++ 2.0 61 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 62 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 63 | 64 | // Open serial communications and wait for port to open: 65 | Serial.begin(9600); 66 | while (!Serial) { 67 | ; // wait for serial port to connect. Needed for Leonardo only 68 | } 69 | 70 | 71 | // start the Ethernet connection: 72 | if (Ethernet.begin(mac) == 0) { 73 | Serial.println("Failed to configure Ethernet using DHCP"); 74 | // DHCP failed, so use a fixed IP address: 75 | Ethernet.begin(mac, ip); 76 | } 77 | } 78 | 79 | void loop() { 80 | // read the analog sensor: 81 | int sensorReading = analogRead(A0); 82 | 83 | // if there's incoming data from the net connection. 84 | // send it out the serial port. This is for debugging 85 | // purposes only: 86 | if (client.available()) { 87 | char c = client.read(); 88 | Serial.print(c); 89 | } 90 | 91 | // if there's no net connection, but there was one last time 92 | // through the loop, then stop the client: 93 | if (!client.connected() && lastConnected) { 94 | Serial.println(); 95 | Serial.println("disconnecting."); 96 | client.stop(); 97 | } 98 | 99 | // if you're not connected, and ten seconds have passed since 100 | // your last connection, then connect again and send data: 101 | if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { 102 | sendData(sensorReading); 103 | } 104 | // store the state of the connection for next time through 105 | // the loop: 106 | lastConnected = client.connected(); 107 | } 108 | 109 | // this method makes a HTTP connection to the server: 110 | void sendData(int thisData) { 111 | // if there's a successful connection: 112 | if (client.connect(server, 80)) { 113 | Serial.println("connecting..."); 114 | // send the HTTP PUT request: 115 | client.print("PUT /v2/feeds/"); 116 | client.print(FEEDID); 117 | client.println(".csv HTTP/1.1"); 118 | client.println("Host: api.pachube.com"); 119 | client.print("X-PachubeApiKey: "); 120 | client.println(APIKEY); 121 | client.print("User-Agent: "); 122 | client.println(USERAGENT); 123 | client.print("Content-Length: "); 124 | 125 | // calculate the length of the sensor reading in bytes: 126 | // 8 bytes for "sensor1," + number of digits of the data: 127 | int thisLength = 8 + getLength(thisData); 128 | client.println(thisLength); 129 | 130 | // last pieces of the HTTP PUT request: 131 | client.println("Content-Type: text/csv"); 132 | client.println("Connection: close"); 133 | client.println(); 134 | 135 | // here's the actual content of the PUT request: 136 | client.print("sensor1,"); 137 | client.println(thisData); 138 | 139 | } 140 | else { 141 | // if you couldn't make a connection: 142 | Serial.println("connection failed"); 143 | Serial.println(); 144 | Serial.println("disconnecting."); 145 | client.stop(); 146 | } 147 | // note the time that the connection was made or attempted: 148 | lastConnectionTime = millis(); 149 | } 150 | 151 | 152 | // This method calculates the number of digits in the 153 | // sensor reading. Since each digit of the ASCII decimal 154 | // representation is a byte, the number of digits equals 155 | // the number of bytes: 156 | 157 | int getLength(int someValue) { 158 | // there's at least one byte: 159 | int digits = 1; 160 | // continually divide the value by ten, 161 | // adding one to the digit count for each 162 | // time you divide, until you're at 0: 163 | int dividend = someValue /10; 164 | while (dividend > 0) { 165 | dividend = dividend /10; 166 | digits++; 167 | } 168 | // return the number of digits: 169 | return digits; 170 | } 171 | 172 | -------------------------------------------------------------------------------- /Ethernet-master/src/EthernetUdp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. 3 | * This version only offers minimal wrapping of socket.cpp 4 | * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ 5 | * 6 | * MIT License: 7 | * Copyright (c) 2008 Bjoern Hartmann 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | * 26 | * bjoern@cs.stanford.edu 12/30/2008 27 | */ 28 | 29 | #include 30 | #include "Ethernet.h" 31 | #include "Dns.h" 32 | #include "utility/w5100.h" 33 | 34 | /* Start EthernetUDP socket, listening at local port PORT */ 35 | uint8_t EthernetUDP::begin(uint16_t port) 36 | { 37 | if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); 38 | sockindex = Ethernet.socketBegin(SnMR::UDP, port); 39 | if (sockindex >= MAX_SOCK_NUM) return 0; 40 | _port = port; 41 | _remaining = 0; 42 | return 1; 43 | } 44 | 45 | /* return number of bytes available in the current packet, 46 | will return zero if parsePacket hasn't been called yet */ 47 | int EthernetUDP::available() 48 | { 49 | return _remaining; 50 | } 51 | 52 | /* Release any resources being used by this EthernetUDP instance */ 53 | void EthernetUDP::stop() 54 | { 55 | if (sockindex < MAX_SOCK_NUM) { 56 | Ethernet.socketClose(sockindex); 57 | sockindex = MAX_SOCK_NUM; 58 | } 59 | } 60 | 61 | int EthernetUDP::beginPacket(const char *host, uint16_t port) 62 | { 63 | // Look up the host first 64 | int ret = 0; 65 | DNSClient dns; 66 | IPAddress remote_addr; 67 | 68 | dns.begin(Ethernet.dnsServerIP()); 69 | ret = dns.getHostByName(host, remote_addr); 70 | if (ret != 1) return ret; 71 | return beginPacket(remote_addr, port); 72 | } 73 | 74 | int EthernetUDP::beginPacket(IPAddress ip, uint16_t port) 75 | { 76 | _offset = 0; 77 | //Serial.printf("UDP beginPacket\n"); 78 | return Ethernet.socketStartUDP(sockindex, rawIPAddress(ip), port); 79 | } 80 | 81 | int EthernetUDP::endPacket() 82 | { 83 | return Ethernet.socketSendUDP(sockindex); 84 | } 85 | 86 | size_t EthernetUDP::write(uint8_t byte) 87 | { 88 | return write(&byte, 1); 89 | } 90 | 91 | size_t EthernetUDP::write(const uint8_t *buffer, size_t size) 92 | { 93 | //Serial.printf("UDP write %d\n", size); 94 | uint16_t bytes_written = Ethernet.socketBufferData(sockindex, _offset, buffer, size); 95 | _offset += bytes_written; 96 | return bytes_written; 97 | } 98 | 99 | int EthernetUDP::parsePacket() 100 | { 101 | // discard any remaining bytes in the last packet 102 | while (_remaining) { 103 | // could this fail (loop endlessly) if _remaining > 0 and recv in read fails? 104 | // should only occur if recv fails after telling us the data is there, lets 105 | // hope the w5100 always behaves :) 106 | read((uint8_t *)NULL, _remaining); 107 | } 108 | 109 | if (Ethernet.socketRecvAvailable(sockindex) > 0) { 110 | //HACK - hand-parse the UDP packet using TCP recv method 111 | uint8_t tmpBuf[8]; 112 | int ret=0; 113 | //read 8 header bytes and get IP and port from it 114 | ret = Ethernet.socketRecv(sockindex, tmpBuf, 8); 115 | if (ret > 0) { 116 | _remoteIP = tmpBuf; 117 | _remotePort = tmpBuf[4]; 118 | _remotePort = (_remotePort << 8) + tmpBuf[5]; 119 | _remaining = tmpBuf[6]; 120 | _remaining = (_remaining << 8) + tmpBuf[7]; 121 | 122 | // When we get here, any remaining bytes are the data 123 | ret = _remaining; 124 | } 125 | return ret; 126 | } 127 | // There aren't any packets available 128 | return 0; 129 | } 130 | 131 | int EthernetUDP::read() 132 | { 133 | uint8_t byte; 134 | 135 | if ((_remaining > 0) && (Ethernet.socketRecv(sockindex, &byte, 1) > 0)) { 136 | // We read things without any problems 137 | _remaining--; 138 | return byte; 139 | } 140 | 141 | // If we get here, there's no data available 142 | return -1; 143 | } 144 | 145 | int EthernetUDP::read(unsigned char *buffer, size_t len) 146 | { 147 | if (_remaining > 0) { 148 | int got; 149 | if (_remaining <= len) { 150 | // data should fit in the buffer 151 | got = Ethernet.socketRecv(sockindex, buffer, _remaining); 152 | } else { 153 | // too much data for the buffer, 154 | // grab as much as will fit 155 | got = Ethernet.socketRecv(sockindex, buffer, len); 156 | } 157 | if (got > 0) { 158 | _remaining -= got; 159 | //Serial.printf("UDP read %d\n", got); 160 | return got; 161 | } 162 | } 163 | // If we get here, there's no data available or recv failed 164 | return -1; 165 | } 166 | 167 | int EthernetUDP::peek() 168 | { 169 | // Unlike recv, peek doesn't check to see if there's any data available, so we must. 170 | // If the user hasn't called parsePacket yet then return nothing otherwise they 171 | // may get the UDP header 172 | if (sockindex >= MAX_SOCK_NUM || _remaining == 0) return -1; 173 | return Ethernet.socketPeek(sockindex); 174 | } 175 | 176 | void EthernetUDP::flush() 177 | { 178 | // TODO: we should wait for TX buffer to be emptied 179 | } 180 | 181 | /* Start EthernetUDP socket, listening at local port PORT */ 182 | uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port) 183 | { 184 | if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); 185 | sockindex = Ethernet.socketBeginMulticast(SnMR::UDP | SnMR::MULTI, ip, port); 186 | if (sockindex >= MAX_SOCK_NUM) return 0; 187 | _port = port; 188 | _remaining = 0; 189 | return 1; 190 | } 191 | 192 | -------------------------------------------------------------------------------- /ESP32Encoder-master/src/ESP32Encoder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * ESP32Encoder.cpp 3 | * 4 | * Created on: Oct 15, 2018 5 | * Author: hephaestus 6 | */ 7 | 8 | #include 9 | 10 | //static ESP32Encoder *gpio2enc[48]; 11 | // 12 | // 13 | enum puType ESP32Encoder::useInternalWeakPullResistors=DOWN; 14 | ESP32Encoder *ESP32Encoder::encoders[MAX_ESP32_ENCODERS] = { NULL, NULL, NULL, 15 | NULL, 16 | NULL, NULL, NULL, NULL }; 17 | 18 | bool ESP32Encoder::attachedInterrupt=false; 19 | pcnt_isr_handle_t ESP32Encoder::user_isr_handle = NULL; 20 | 21 | ESP32Encoder::ESP32Encoder() { 22 | attached = false; 23 | aPinNumber = (gpio_num_t) 0; 24 | bPinNumber = (gpio_num_t) 0; 25 | working = false; 26 | direction = false; 27 | unit = (pcnt_unit_t) -1; 28 | } 29 | 30 | ESP32Encoder::~ESP32Encoder() { 31 | // TODO Auto-generated destructor stub 32 | } 33 | 34 | /* Decode what PCNT's unit originated an interrupt 35 | * and pass this information together with the event type 36 | * the main program using a queue. 37 | */ 38 | static void IRAM_ATTR pcnt_example_intr_handler(void *arg) { 39 | ESP32Encoder * ptr; 40 | 41 | uint32_t intr_status = PCNT.int_st.val; 42 | int i; 43 | 44 | for (i = 0; i < PCNT_UNIT_MAX; i++) { 45 | if (intr_status & (BIT(i))) { 46 | ptr = ESP32Encoder::encoders[i]; 47 | /* Save the PCNT event type that caused an interrupt 48 | to pass it to the main program */ 49 | 50 | int64_t status=0; 51 | if(PCNT.status_unit[i].h_lim_lat){ 52 | status=ptr->r_enc_config.counter_h_lim; 53 | } 54 | if(PCNT.status_unit[i].l_lim_lat){ 55 | status=ptr->r_enc_config.counter_l_lim; 56 | } 57 | //pcnt_counter_clear(ptr->unit); 58 | PCNT.int_clr.val = BIT(i); // clear the interrupt 59 | ptr->count = status + ptr->count; 60 | } 61 | } 62 | } 63 | 64 | void ESP32Encoder::attach(int a, int b, enum encType et) { 65 | if (attached) { 66 | Serial.println("All ready attached, FAIL!"); 67 | return; 68 | } 69 | int index = 0; 70 | for (; index < MAX_ESP32_ENCODERS; index++) { 71 | if (ESP32Encoder::encoders[index] == NULL) { 72 | encoders[index] = this; 73 | break; 74 | } 75 | } 76 | if (index == MAX_ESP32_ENCODERS) { 77 | Serial.println("Too many encoders, FAIL!"); 78 | return; 79 | } 80 | 81 | // Set data now that pin attach checks are done 82 | fullQuad = et != single; 83 | unit = (pcnt_unit_t) index; 84 | this->aPinNumber = (gpio_num_t) a; 85 | this->bPinNumber = (gpio_num_t) b; 86 | 87 | //Set up the IO state of hte pin 88 | gpio_pad_select_gpio(aPinNumber); 89 | gpio_pad_select_gpio(bPinNumber); 90 | gpio_set_direction(aPinNumber, GPIO_MODE_INPUT); 91 | gpio_set_direction(bPinNumber, GPIO_MODE_INPUT); 92 | if(useInternalWeakPullResistors==DOWN){ 93 | gpio_pulldown_en(aPinNumber); 94 | gpio_pulldown_en(bPinNumber); 95 | } 96 | if(useInternalWeakPullResistors==UP){ 97 | gpio_pullup_en(aPinNumber); 98 | gpio_pullup_en(bPinNumber); 99 | } 100 | // Set up encoder PCNT configuration 101 | r_enc_config.pulse_gpio_num = aPinNumber; //Rotary Encoder Chan A 102 | r_enc_config.ctrl_gpio_num = bPinNumber; //Rotary Encoder Chan B 103 | 104 | r_enc_config.unit = unit; 105 | r_enc_config.channel = PCNT_CHANNEL_0; 106 | 107 | r_enc_config.pos_mode = fullQuad ? PCNT_COUNT_DEC : PCNT_COUNT_DIS; //Count Only On Rising-Edges 108 | r_enc_config.neg_mode = PCNT_COUNT_INC; // Discard Falling-Edge 109 | 110 | r_enc_config.lctrl_mode = PCNT_MODE_KEEP; // Rising A on HIGH B = CW Step 111 | r_enc_config.hctrl_mode = PCNT_MODE_REVERSE; // Rising A on LOW B = CCW Step 112 | 113 | r_enc_config .counter_h_lim = _INT16_MAX; 114 | r_enc_config .counter_l_lim = _INT16_MIN ; 115 | 116 | pcnt_unit_config(&r_enc_config); 117 | 118 | if (et == full) { 119 | // set up second channel for full quad 120 | r_enc_config.pulse_gpio_num = bPinNumber; //make prior control into signal 121 | r_enc_config.ctrl_gpio_num = aPinNumber; //and prior signal into control 122 | 123 | r_enc_config.unit = unit; 124 | r_enc_config.channel = PCNT_CHANNEL_1; // channel 1 125 | 126 | r_enc_config.pos_mode = PCNT_COUNT_DEC; //Count Only On Rising-Edges 127 | r_enc_config.neg_mode = PCNT_COUNT_INC; // Discard Falling-Edge 128 | 129 | r_enc_config.lctrl_mode = PCNT_MODE_REVERSE; // prior high mode is now low 130 | r_enc_config.hctrl_mode = PCNT_MODE_KEEP; // prior low mode is now high 131 | 132 | r_enc_config .counter_h_lim = _INT16_MAX; 133 | r_enc_config .counter_l_lim = _INT16_MIN ; 134 | 135 | pcnt_unit_config(&r_enc_config); 136 | } else { // make sure channel 1 is not set when not full quad 137 | r_enc_config.pulse_gpio_num = bPinNumber; //make prior control into signal 138 | r_enc_config.ctrl_gpio_num = aPinNumber; //and prior signal into control 139 | 140 | r_enc_config.unit = unit; 141 | r_enc_config.channel = PCNT_CHANNEL_1; // channel 1 142 | 143 | r_enc_config.pos_mode = PCNT_COUNT_DIS; //disabling channel 1 144 | r_enc_config.neg_mode = PCNT_COUNT_DIS; // disabling channel 1 145 | 146 | r_enc_config.lctrl_mode = PCNT_MODE_DISABLE; // disabling channel 1 147 | r_enc_config.hctrl_mode = PCNT_MODE_DISABLE; // disabling channel 1 148 | 149 | r_enc_config .counter_h_lim = _INT16_MAX; 150 | r_enc_config .counter_l_lim = _INT16_MIN ; 151 | 152 | pcnt_unit_config(&r_enc_config); 153 | } 154 | 155 | 156 | // Filter out bounces and noise 157 | pcnt_set_filter_value(unit, 250); // Filter Runt Pulses 158 | pcnt_filter_enable(unit); 159 | 160 | 161 | /* Enable events on maximum and minimum limit values */ 162 | pcnt_event_enable(unit, PCNT_EVT_H_LIM); 163 | pcnt_event_enable(unit, PCNT_EVT_L_LIM); 164 | 165 | pcnt_counter_pause(unit); // Initial PCNT init 166 | pcnt_counter_clear(unit); 167 | /* Register ISR handler and enable interrupts for PCNT unit */ 168 | if(attachedInterrupt==false){ 169 | attachedInterrupt=true; 170 | esp_err_t er = pcnt_isr_register(pcnt_example_intr_handler,(void *) NULL, (int)0, 171 | (pcnt_isr_handle_t *)&ESP32Encoder::user_isr_handle); 172 | if (er != ESP_OK){ 173 | Serial.println("Encoder wrap interupt failed"); 174 | } 175 | } 176 | pcnt_intr_enable(unit); 177 | pcnt_counter_resume(unit); 178 | 179 | } 180 | 181 | void ESP32Encoder::attachHalfQuad(int aPintNumber, int bPinNumber) { 182 | attach(aPintNumber, bPinNumber, half); 183 | 184 | } 185 | void ESP32Encoder::attachSingleEdge(int aPintNumber, int bPinNumber) { 186 | attach(aPintNumber, bPinNumber, single); 187 | } 188 | void ESP32Encoder::attachFullQuad(int aPintNumber, int bPinNumber) { 189 | attach(aPintNumber, bPinNumber, full); 190 | } 191 | 192 | void ESP32Encoder::setCount(int64_t value) { 193 | count = value - getCountRaw(); 194 | } 195 | int64_t ESP32Encoder::getCountRaw() { 196 | int16_t c; 197 | pcnt_get_counter_value(unit, &c); 198 | return c; 199 | } 200 | int64_t ESP32Encoder::getCount() { 201 | return getCountRaw() + count; 202 | } 203 | 204 | int64_t ESP32Encoder::clearCount() { 205 | count = 0; 206 | return pcnt_counter_clear(unit); 207 | } 208 | 209 | int64_t ESP32Encoder::pauseCount() { 210 | return pcnt_counter_pause(unit); 211 | } 212 | 213 | int64_t ESP32Encoder::resumeCount() { 214 | return pcnt_counter_resume(unit); 215 | } 216 | 217 | -------------------------------------------------------------------------------- /udp.comp: -------------------------------------------------------------------------------- 1 | 2 | component udp "Compute the derivative of the input function"; 3 | pin in float posx; 4 | pin in float posy; 5 | pin in float posz; 6 | pin in float posa; 7 | 8 | pin out float test; 9 | 10 | pin out float fdbx; 11 | pin out float fdby; 12 | pin out float fdbz; 13 | pin out float fdba; 14 | pin out float fdbb; 15 | pin out float fdbc; 16 | pin out float fdbu; 17 | pin out float fdbv; 18 | pin out float fdbw; 19 | pin out float enc0; 20 | 21 | ///variable double old; 22 | 23 | pin out bit in_00; 24 | pin out bit in_01; 25 | pin out bit in_02; 26 | pin out bit in_03; 27 | pin out bit in_04; 28 | pin out bit in_05; 29 | pin out bit in_06; 30 | pin out bit in_07; 31 | pin out bit in_08; 32 | pin out bit in_09; 33 | pin out bit in_10; 34 | pin out bit in_11; 35 | pin out bit in_12; 36 | pin out bit in_13; 37 | pin out bit in_14; 38 | pin out bit in_15; 39 | pin out bit in_16; 40 | pin out bit in_17; 41 | pin out bit in_18; 42 | pin out bit in_19; 43 | pin out bit in_20; 44 | pin out bit in_21; 45 | pin out bit in_22; 46 | pin out bit in_23; 47 | pin out bit in_24; 48 | pin out bit in_25; 49 | pin out bit in_26; 50 | pin out bit in_27; 51 | pin out bit in_28; 52 | pin out bit in_29; 53 | pin out bit in_30; 54 | pin out bit in_31; 55 | pin out bit in_32; 56 | pin out bit in_33; 57 | pin out bit in_34; 58 | pin out bit in_35; 59 | pin out bit in_36; 60 | pin out bit in_37; 61 | pin out bit in_38; 62 | pin out bit in_39; 63 | 64 | pin in bit out_00; 65 | pin in bit out_01; 66 | pin in bit out_02; 67 | pin in bit out_03; 68 | pin in bit out_04; 69 | pin in bit out_05; 70 | pin in bit out_06; 71 | pin in bit out_07; 72 | pin in bit out_08; 73 | pin in bit out_09; 74 | pin in bit out_10; 75 | pin in bit out_11; 76 | pin in bit out_12; 77 | pin in bit out_13; 78 | pin in bit out_14; 79 | pin in bit out_15; 80 | pin in bit out_16; 81 | pin in bit out_17; 82 | pin in bit out_18; 83 | pin in bit out_19; 84 | pin in bit out_20; 85 | pin in bit out_21; 86 | pin in bit out_22; 87 | pin in bit out_23; 88 | pin in bit out_24; 89 | pin in bit out_25; 90 | pin in bit out_26; 91 | pin in bit out_27; 92 | pin in bit out_28; 93 | pin in bit out_29; 94 | pin in bit out_30; 95 | pin in bit out_31; 96 | pin in bit out_32; 97 | pin in bit out_33; 98 | pin in bit out_34; 99 | pin in bit out_35; 100 | pin in bit out_36; 101 | pin in bit out_37; 102 | pin in bit out_38; 103 | pin in bit out_39; 104 | 105 | 106 | option extra_setup yes; 107 | function update; 108 | license "GPL"; // indicates GPL v2 or later 109 | ;; 110 | 111 | // Server side implementation of UDP client-server model 112 | #include 113 | #include 114 | #include 115 | #include 116 | #include 117 | #include 118 | #include 119 | #include 120 | #include 121 | #include 122 | #include 123 | struct axes { 124 | int32_t fb0; 125 | int32_t fb1; 126 | int32_t fb2; 127 | int32_t fb3; 128 | int32_t fb4; 129 | uint32_t io; 130 | uint32_t io2; 131 | int64_t enc0v; 132 | }fb; 133 | 134 | struct pos { 135 | int32_t pos0; 136 | int32_t pos1; 137 | int32_t pos2; 138 | int32_t pos3; 139 | int32_t pos4; 140 | uint32_t io; 141 | uint32_t io2; 142 | int64_t analog; 143 | }motor_pos; 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | #define BUFSIZE 512 152 | //#define UDP_PORT 27181 153 | #define SEND_TIMEOUT_US 100 154 | #define RECV_TIMEOUT_US 100 155 | #define READ_PCK_DELAY_NS 10000 156 | 157 | 158 | int sockfd, portno, n; 159 | int serverlen; 160 | struct sockaddr_in serveraddr; 161 | struct hostent *server; 162 | char *hostname; 163 | char buf[BUFSIZE]; 164 | char buf1[BUFSIZE]; 165 | float axes[9]; 166 | char buffer[512] ; 167 | int32_t scale=100; 168 | 169 | EXTRA_SETUP() 170 | { 171 | ; 172 | } 173 | 174 | // Driver code 175 | FUNCTION(update) 176 | { 177 | 178 | 179 | 180 | 181 | motor_pos.pos0=posx*scale; 182 | motor_pos.pos1=posy*scale; 183 | motor_pos.pos2=posz*scale; 184 | motor_pos.pos3=posa*scale; 185 | motor_pos.pos4=posa*scale; 186 | 187 | 188 | // hostname = "192.168.1.177"; 189 | // portno = 5000; 190 | 191 | /* socket: create the socket */ 192 | sockfd = socket(AF_INET, SOCK_DGRAM, 0); 193 | 194 | 195 | /* gethostbyname: get the server's DNS entry */ 196 | server = gethostbyname("192.168.1.177"); 197 | /* build the server's Internet address */ 198 | bzero((char *) &serveraddr, sizeof(serveraddr)); 199 | serveraddr.sin_family = AF_INET; 200 | bcopy((char *)server->h_addr, 201 | (char *)&serveraddr.sin_addr.s_addr, server->h_length); 202 | serveraddr.sin_port = htons(27181); 203 | 204 | 205 | 206 | 207 | memcpy(&buf,&motor_pos,sizeof(motor_pos)); 208 | 209 | /* send the message to the server */ 210 | serverlen = sizeof(serveraddr); 211 | int ret; 212 | struct timeval timeout; 213 | timeout.tv_sec = 0; 214 | timeout.tv_usec = RECV_TIMEOUT_US; 215 | 216 | ret = setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); 217 | timeout.tv_usec = SEND_TIMEOUT_US; 218 | setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)); 219 | sendto(sockfd, buf,sizeof(motor_pos), 0, &serveraddr, serverlen); 220 | //if (n < 0) {writes=writes+1;} 221 | //recv(sockfd, buf1 ,sizeof(motor_pos), 0); 222 | ; 223 | //if(n < 0) { 224 | //reads=reads+1; 225 | if (recvfrom(sockfd,buf,sizeof(motor_pos),0,NULL,NULL)){ 226 | close(sockfd); 227 | //rtapi_delay(READ_PCK_DELAY_NS); 228 | //} 229 | 230 | //*****************************************************************// 231 | 232 | 233 | 234 | //memcpy(buffer, buf, 1024); 235 | memcpy(&fb, buf, sizeof(fb)); 236 | if(fb.fb0 <= -10000 | fb.fb1 <= -10000){ 237 | ; 238 | } 239 | else{ 240 | fdbx=(float)fb.fb0/scale; 241 | fdby=(float)fb.fb1/scale; 242 | fdbz=(float)fb.fb2/scale; 243 | fdba=(float)fb.fb3/scale; 244 | fdbb=(float)fb.fb4/scale; 245 | 246 | enc0=(float)fb.enc0v; 247 | in_00=(fb.io >> 0) & 1; 248 | in_01=(fb.io >> 1) & 1; 249 | in_02=(fb.io >> 2) & 1; 250 | in_03=(fb.io >> 3) & 1; 251 | in_04=(fb.io >> 4) & 1; 252 | in_05=(fb.io >> 5) & 1; 253 | in_06=(fb.io >> 6) & 1; 254 | in_07=(fb.io >> 7) & 1; 255 | in_08=(fb.io >> 8) & 1; 256 | in_09=(fb.io >> 9) & 1; 257 | in_10=(fb.io >> 10) & 1; 258 | in_11=(fb.io >> 11) & 1; 259 | in_12=(fb.io >> 12) & 1; 260 | in_13=(fb.io >> 13) & 1; 261 | in_14=(fb.io >> 14) & 1; 262 | in_15=(fb.io >> 15) & 1; 263 | in_16=(fb.io >> 16) & 1; 264 | in_17=(fb.io >> 17) & 1; 265 | in_18=(fb.io >> 18) & 1; 266 | in_19=(fb.io >> 19) & 1; 267 | in_20=(fb.io >> 20) & 1; 268 | in_21=(fb.io >> 21) & 1; 269 | in_22=(fb.io >> 22) & 1; 270 | in_23=(fb.io >> 23) & 1; 271 | in_24=(fb.io >> 24) & 1; 272 | in_25=(fb.io >> 25) & 1; 273 | in_26=(fb.io >> 26) & 1; 274 | in_27=(fb.io >> 27) & 1; 275 | in_28=(fb.io >> 28) & 1; 276 | in_29=(fb.io >> 29) & 1; 277 | in_30=(fb.io >> 30) & 1; 278 | in_31=(fb.io >> 31) & 1; 279 | in_32=(fb.io2 >> 0) & 1; 280 | in_33=(fb.io2 >> 1) & 1; 281 | in_34=(fb.io2 >> 2) & 1; 282 | in_35=(fb.io2 >> 3) & 1; 283 | in_36=(fb.io2 >> 4) & 1; 284 | in_37=(fb.io2 >> 5) & 1; 285 | in_38=(fb.io2 >> 6) & 1; 286 | in_39=(fb.io2 >> 7) & 1; 287 | 288 | 289 | 290 | 291 | } 292 | } 293 | 294 | } 295 | 296 | 297 | 298 | -------------------------------------------------------------------------------- /Ethernet-master/src/EthernetClient.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "Dns.h" 24 | #include "utility/w5100.h" 25 | 26 | int EthernetClient::connect(const char * host, uint16_t port) 27 | { 28 | DNSClient dns; // Look up the host first 29 | IPAddress remote_addr; 30 | 31 | if (sockindex < MAX_SOCK_NUM) { 32 | if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { 33 | Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? 34 | } 35 | sockindex = MAX_SOCK_NUM; 36 | } 37 | dns.begin(Ethernet.dnsServerIP()); 38 | if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout 39 | return connect(remote_addr, port); 40 | } 41 | 42 | int EthernetClient::connect(IPAddress ip, uint16_t port) 43 | { 44 | if (sockindex < MAX_SOCK_NUM) { 45 | if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { 46 | Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? 47 | } 48 | sockindex = MAX_SOCK_NUM; 49 | } 50 | #if defined(ESP8266) || defined(ESP32) 51 | if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0; 52 | #else 53 | if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0; 54 | #endif 55 | sockindex = Ethernet.socketBegin(SnMR::TCP, 0); 56 | if (sockindex >= MAX_SOCK_NUM) return 0; 57 | Ethernet.socketConnect(sockindex, rawIPAddress(ip), port); 58 | uint32_t start = millis(); 59 | while (1) { 60 | uint8_t stat = Ethernet.socketStatus(sockindex); 61 | if (stat == SnSR::ESTABLISHED) return 1; 62 | if (stat == SnSR::CLOSE_WAIT) return 1; 63 | if (stat == SnSR::CLOSED) return 0; 64 | if (millis() - start > _timeout) break; 65 | delay(1); 66 | } 67 | Ethernet.socketClose(sockindex); 68 | sockindex = MAX_SOCK_NUM; 69 | return 0; 70 | } 71 | 72 | int EthernetClient::availableForWrite(void) 73 | { 74 | if (sockindex >= MAX_SOCK_NUM) return 0; 75 | return Ethernet.socketSendAvailable(sockindex); 76 | } 77 | 78 | size_t EthernetClient::write(uint8_t b) 79 | { 80 | return write(&b, 1); 81 | } 82 | 83 | size_t EthernetClient::write(const uint8_t *buf, size_t size) 84 | { 85 | if (sockindex >= MAX_SOCK_NUM) return 0; 86 | if (Ethernet.socketSend(sockindex, buf, size)) return size; 87 | setWriteError(); 88 | return 0; 89 | } 90 | 91 | int EthernetClient::available() 92 | { 93 | if (sockindex >= MAX_SOCK_NUM) return 0; 94 | return Ethernet.socketRecvAvailable(sockindex); 95 | // TODO: do the Wiznet chips automatically retransmit TCP ACK 96 | // packets if they are lost by the network? Someday this should 97 | // be checked by a man-in-the-middle test which discards certain 98 | // packets. If ACKs aren't resent, we would need to check for 99 | // returning 0 here and after a timeout do another Sock_RECV 100 | // command to cause the Wiznet chip to resend the ACK packet. 101 | } 102 | 103 | int EthernetClient::read(uint8_t *buf, size_t size) 104 | { 105 | if (sockindex >= MAX_SOCK_NUM) return 0; 106 | return Ethernet.socketRecv(sockindex, buf, size); 107 | } 108 | 109 | int EthernetClient::peek() 110 | { 111 | if (sockindex >= MAX_SOCK_NUM) return -1; 112 | if (!available()) return -1; 113 | return Ethernet.socketPeek(sockindex); 114 | } 115 | 116 | int EthernetClient::read() 117 | { 118 | uint8_t b; 119 | if (Ethernet.socketRecv(sockindex, &b, 1) > 0) return b; 120 | return -1; 121 | } 122 | 123 | void EthernetClient::flush() 124 | { 125 | while (sockindex < MAX_SOCK_NUM) { 126 | uint8_t stat = Ethernet.socketStatus(sockindex); 127 | if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return; 128 | if (Ethernet.socketSendAvailable(sockindex) >= W5100.SSIZE) return; 129 | } 130 | } 131 | 132 | void EthernetClient::stop() 133 | { 134 | if (sockindex >= MAX_SOCK_NUM) return; 135 | 136 | // attempt to close the connection gracefully (send a FIN to other side) 137 | Ethernet.socketDisconnect(sockindex); 138 | unsigned long start = millis(); 139 | 140 | // wait up to a second for the connection to close 141 | do { 142 | if (Ethernet.socketStatus(sockindex) == SnSR::CLOSED) { 143 | sockindex = MAX_SOCK_NUM; 144 | return; // exit the loop 145 | } 146 | delay(1); 147 | } while (millis() - start < _timeout); 148 | 149 | // if it hasn't closed, close it forcefully 150 | Ethernet.socketClose(sockindex); 151 | sockindex = MAX_SOCK_NUM; 152 | } 153 | 154 | uint8_t EthernetClient::connected() 155 | { 156 | if (sockindex >= MAX_SOCK_NUM) return 0; 157 | 158 | uint8_t s = Ethernet.socketStatus(sockindex); 159 | return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT || 160 | (s == SnSR::CLOSE_WAIT && !available())); 161 | } 162 | 163 | uint8_t EthernetClient::status() 164 | { 165 | if (sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED; 166 | return Ethernet.socketStatus(sockindex); 167 | } 168 | 169 | // the next function allows us to use the client returned by 170 | // EthernetServer::available() as the condition in an if-statement. 171 | bool EthernetClient::operator==(const EthernetClient& rhs) 172 | { 173 | if (sockindex != rhs.sockindex) return false; 174 | if (sockindex >= MAX_SOCK_NUM) return false; 175 | if (rhs.sockindex >= MAX_SOCK_NUM) return false; 176 | return true; 177 | } 178 | 179 | // https://github.com/per1234/EthernetMod 180 | // from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd 181 | uint16_t EthernetClient::localPort() 182 | { 183 | if (sockindex >= MAX_SOCK_NUM) return 0; 184 | uint16_t port; 185 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 186 | port = W5100.readSnPORT(sockindex); 187 | SPI.endTransaction(); 188 | return port; 189 | } 190 | 191 | // https://github.com/per1234/EthernetMod 192 | // returns the remote IP address: http://forum.arduino.cc/index.php?topic=82416.0 193 | IPAddress EthernetClient::remoteIP() 194 | { 195 | if (sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0); 196 | uint8_t remoteIParray[4]; 197 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 198 | W5100.readSnDIPR(sockindex, remoteIParray); 199 | SPI.endTransaction(); 200 | return IPAddress(remoteIParray); 201 | } 202 | 203 | // https://github.com/per1234/EthernetMod 204 | // from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75 205 | uint16_t EthernetClient::remotePort() 206 | { 207 | if (sockindex >= MAX_SOCK_NUM) return 0; 208 | uint16_t port; 209 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 210 | port = W5100.readSnDPORT(sockindex); 211 | SPI.endTransaction(); 212 | return port; 213 | } 214 | 215 | 216 | -------------------------------------------------------------------------------- /Ethernet-master/src/Ethernet.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | #include "Dhcp.h" 25 | 26 | IPAddress EthernetClass::_dnsServerAddress; 27 | DhcpClass* EthernetClass::_dhcp = NULL; 28 | 29 | int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) 30 | { 31 | static DhcpClass s_dhcp; 32 | _dhcp = &s_dhcp; 33 | 34 | // Initialise the basic info 35 | if (W5100.init() == 0) return 0; 36 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 37 | W5100.setMACAddress(mac); 38 | W5100.setIPAddress(IPAddress(0,0,0,0).raw_address()); 39 | SPI.endTransaction(); 40 | 41 | // Now try to get our config info from a DHCP server 42 | int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout); 43 | if (ret == 1) { 44 | // We've successfully found a DHCP server and got our configuration 45 | // info, so set things accordingly 46 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 47 | W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); 48 | W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); 49 | W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); 50 | SPI.endTransaction(); 51 | _dnsServerAddress = _dhcp->getDnsServerIp(); 52 | socketPortRand(micros()); 53 | } 54 | return ret; 55 | } 56 | 57 | void EthernetClass::begin(uint8_t *mac, IPAddress ip) 58 | { 59 | // Assume the DNS server will be the machine on the same network as the local IP 60 | // but with last octet being '1' 61 | IPAddress dns = ip; 62 | dns[3] = 1; 63 | begin(mac, ip, dns); 64 | } 65 | 66 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns) 67 | { 68 | // Assume the gateway will be the machine on the same network as the local IP 69 | // but with last octet being '1' 70 | IPAddress gateway = ip; 71 | gateway[3] = 1; 72 | begin(mac, ip, dns, gateway); 73 | } 74 | 75 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway) 76 | { 77 | IPAddress subnet(255, 255, 255, 0); 78 | begin(mac, ip, dns, gateway, subnet); 79 | } 80 | 81 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet) 82 | { 83 | if (W5100.init() == 0) return; 84 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 85 | W5100.setMACAddress(mac); 86 | #if ARDUINO > 106 || TEENSYDUINO > 121 87 | W5100.setIPAddress(ip._address.bytes); 88 | W5100.setGatewayIp(gateway._address.bytes); 89 | W5100.setSubnetMask(subnet._address.bytes); 90 | #else 91 | W5100.setIPAddress(ip._address); 92 | W5100.setGatewayIp(gateway._address); 93 | W5100.setSubnetMask(subnet._address); 94 | #endif 95 | SPI.endTransaction(); 96 | _dnsServerAddress = dns; 97 | } 98 | 99 | void EthernetClass::init(uint8_t sspin) 100 | { 101 | W5100.setSS(sspin); 102 | } 103 | 104 | EthernetLinkStatus EthernetClass::linkStatus() 105 | { 106 | switch (W5100.getLinkStatus()) { 107 | case UNKNOWN: return Unknown; 108 | case LINK_ON: return LinkON; 109 | case LINK_OFF: return LinkOFF; 110 | default: return Unknown; 111 | } 112 | } 113 | 114 | EthernetHardwareStatus EthernetClass::hardwareStatus() 115 | { 116 | switch (W5100.getChip()) { 117 | case 51: return EthernetW5100; 118 | case 52: return EthernetW5200; 119 | case 55: return EthernetW5500; 120 | default: return EthernetNoHardware; 121 | } 122 | } 123 | 124 | int EthernetClass::maintain() 125 | { 126 | int rc = DHCP_CHECK_NONE; 127 | if (_dhcp != NULL) { 128 | // we have a pointer to dhcp, use it 129 | rc = _dhcp->checkLease(); 130 | switch (rc) { 131 | case DHCP_CHECK_NONE: 132 | //nothing done 133 | break; 134 | case DHCP_CHECK_RENEW_OK: 135 | case DHCP_CHECK_REBIND_OK: 136 | //we might have got a new IP. 137 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 138 | W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); 139 | W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); 140 | W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); 141 | SPI.endTransaction(); 142 | _dnsServerAddress = _dhcp->getDnsServerIp(); 143 | break; 144 | default: 145 | //this is actually an error, it will retry though 146 | break; 147 | } 148 | } 149 | return rc; 150 | } 151 | 152 | 153 | void EthernetClass::MACAddress(uint8_t *mac_address) 154 | { 155 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 156 | W5100.getMACAddress(mac_address); 157 | SPI.endTransaction(); 158 | } 159 | 160 | IPAddress EthernetClass::localIP() 161 | { 162 | IPAddress ret; 163 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 164 | W5100.getIPAddress(ret.raw_address()); 165 | SPI.endTransaction(); 166 | return ret; 167 | } 168 | 169 | IPAddress EthernetClass::subnetMask() 170 | { 171 | IPAddress ret; 172 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 173 | W5100.getSubnetMask(ret.raw_address()); 174 | SPI.endTransaction(); 175 | return ret; 176 | } 177 | 178 | IPAddress EthernetClass::gatewayIP() 179 | { 180 | IPAddress ret; 181 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 182 | W5100.getGatewayIp(ret.raw_address()); 183 | SPI.endTransaction(); 184 | return ret; 185 | } 186 | 187 | void EthernetClass::setMACAddress(const uint8_t *mac_address) 188 | { 189 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 190 | W5100.setMACAddress(mac_address); 191 | SPI.endTransaction(); 192 | } 193 | 194 | void EthernetClass::setLocalIP(const IPAddress local_ip) 195 | { 196 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 197 | IPAddress ip = local_ip; 198 | W5100.setIPAddress(ip.raw_address()); 199 | SPI.endTransaction(); 200 | } 201 | 202 | void EthernetClass::setSubnetMask(const IPAddress subnet) 203 | { 204 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 205 | IPAddress ip = subnet; 206 | W5100.setSubnetMask(ip.raw_address()); 207 | SPI.endTransaction(); 208 | } 209 | 210 | void EthernetClass::setGatewayIP(const IPAddress gateway) 211 | { 212 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 213 | IPAddress ip = gateway; 214 | W5100.setGatewayIp(ip.raw_address()); 215 | SPI.endTransaction(); 216 | } 217 | 218 | void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds) 219 | { 220 | if (milliseconds > 6553) milliseconds = 6553; 221 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 222 | W5100.setRetransmissionTime(milliseconds * 10); 223 | SPI.endTransaction(); 224 | } 225 | 226 | void EthernetClass::setRetransmissionCount(uint8_t num) 227 | { 228 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 229 | W5100.setRetransmissionCount(num); 230 | SPI.endTransaction(); 231 | } 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | EthernetClass Ethernet; 243 | -------------------------------------------------------------------------------- /Ethernet-master/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | SCP1000 Barometric Pressure Sensor Display 3 | 4 | Serves the output of a Barometric Pressure Sensor as a web page. 5 | Uses the SPI library. For details on the sensor, see: 6 | http://www.sparkfun.com/commerce/product_info.php?products_id=8161 7 | 8 | This sketch adapted from Nathan Seidle's SCP1000 example for PIC: 9 | http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip 10 | 11 | TODO: this hardware is long obsolete. This example program should 12 | be rewritten to use https://www.sparkfun.com/products/9721 13 | 14 | Circuit: 15 | SCP1000 sensor attached to pins 6,7, and 11 - 13: 16 | DRDY: pin 6 17 | CSB: pin 7 18 | MOSI: pin 11 19 | MISO: pin 12 20 | SCK: pin 13 21 | 22 | created 31 July 2010 23 | by Tom Igoe 24 | */ 25 | 26 | #include 27 | // the sensor communicates using SPI, so include the library: 28 | #include 29 | 30 | 31 | // assign a MAC address for the Ethernet controller. 32 | // fill in your address here: 33 | byte mac[] = { 34 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 35 | }; 36 | // assign an IP address for the controller: 37 | IPAddress ip(192, 168, 1, 20); 38 | 39 | 40 | // Initialize the Ethernet server library 41 | // with the IP address and port you want to use 42 | // (port 80 is default for HTTP): 43 | EthernetServer server(80); 44 | 45 | 46 | //Sensor's memory register addresses: 47 | const int PRESSURE = 0x1F; //3 most significant bits of pressure 48 | const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure 49 | const int TEMPERATURE = 0x21; //16 bit temperature reading 50 | 51 | // pins used for the connection with the sensor 52 | // the others you need are controlled by the SPI library): 53 | const int dataReadyPin = 6; 54 | const int chipSelectPin = 7; 55 | 56 | float temperature = 0.0; 57 | long pressure = 0; 58 | long lastReadingTime = 0; 59 | 60 | void setup() { 61 | // You can use Ethernet.init(pin) to configure the CS pin 62 | //Ethernet.init(10); // Most Arduino shields 63 | //Ethernet.init(5); // MKR ETH shield 64 | //Ethernet.init(0); // Teensy 2.0 65 | //Ethernet.init(20); // Teensy++ 2.0 66 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 67 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 68 | 69 | // start the SPI library: 70 | SPI.begin(); 71 | 72 | // start the Ethernet connection 73 | Ethernet.begin(mac, ip); 74 | 75 | // Open serial communications and wait for port to open: 76 | Serial.begin(9600); 77 | while (!Serial) { 78 | ; // wait for serial port to connect. Needed for native USB port only 79 | } 80 | 81 | // Check for Ethernet hardware present 82 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 83 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 84 | while (true) { 85 | delay(1); // do nothing, no point running without Ethernet hardware 86 | } 87 | } 88 | if (Ethernet.linkStatus() == LinkOFF) { 89 | Serial.println("Ethernet cable is not connected."); 90 | } 91 | 92 | // start listening for clients 93 | server.begin(); 94 | 95 | // initalize the data ready and chip select pins: 96 | pinMode(dataReadyPin, INPUT); 97 | pinMode(chipSelectPin, OUTPUT); 98 | 99 | //Configure SCP1000 for low noise configuration: 100 | writeRegister(0x02, 0x2D); 101 | writeRegister(0x01, 0x03); 102 | writeRegister(0x03, 0x02); 103 | 104 | // give the sensor and Ethernet shield time to set up: 105 | delay(1000); 106 | 107 | //Set the sensor to high resolution mode tp start readings: 108 | writeRegister(0x03, 0x0A); 109 | 110 | } 111 | 112 | void loop() { 113 | // check for a reading no more than once a second. 114 | if (millis() - lastReadingTime > 1000) { 115 | // if there's a reading ready, read it: 116 | // don't do anything until the data ready pin is high: 117 | if (digitalRead(dataReadyPin) == HIGH) { 118 | getData(); 119 | // timestamp the last time you got a reading: 120 | lastReadingTime = millis(); 121 | } 122 | } 123 | 124 | // listen for incoming Ethernet connections: 125 | listenForEthernetClients(); 126 | } 127 | 128 | 129 | void getData() { 130 | Serial.println("Getting reading"); 131 | //Read the temperature data 132 | int tempData = readRegister(0x21, 2); 133 | 134 | // convert the temperature to celsius and display it: 135 | temperature = (float)tempData / 20.0; 136 | 137 | //Read the pressure data highest 3 bits: 138 | byte pressureDataHigh = readRegister(0x1F, 1); 139 | pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0 140 | 141 | //Read the pressure data lower 16 bits: 142 | unsigned int pressureDataLow = readRegister(0x20, 2); 143 | //combine the two parts into one 19-bit number: 144 | pressure = ((pressureDataHigh << 16) | pressureDataLow) / 4; 145 | 146 | Serial.print("Temperature: "); 147 | Serial.print(temperature); 148 | Serial.println(" degrees C"); 149 | Serial.print("Pressure: " + String(pressure)); 150 | Serial.println(" Pa"); 151 | } 152 | 153 | void listenForEthernetClients() { 154 | // listen for incoming clients 155 | EthernetClient client = server.available(); 156 | if (client) { 157 | Serial.println("Got a client"); 158 | // an http request ends with a blank line 159 | boolean currentLineIsBlank = true; 160 | while (client.connected()) { 161 | if (client.available()) { 162 | char c = client.read(); 163 | // if you've gotten to the end of the line (received a newline 164 | // character) and the line is blank, the http request has ended, 165 | // so you can send a reply 166 | if (c == '\n' && currentLineIsBlank) { 167 | // send a standard http response header 168 | client.println("HTTP/1.1 200 OK"); 169 | client.println("Content-Type: text/html"); 170 | client.println(); 171 | // print the current readings, in HTML format: 172 | client.print("Temperature: "); 173 | client.print(temperature); 174 | client.print(" degrees C"); 175 | client.println("
"); 176 | client.print("Pressure: " + String(pressure)); 177 | client.print(" Pa"); 178 | client.println("
"); 179 | break; 180 | } 181 | if (c == '\n') { 182 | // you're starting a new line 183 | currentLineIsBlank = true; 184 | } else if (c != '\r') { 185 | // you've gotten a character on the current line 186 | currentLineIsBlank = false; 187 | } 188 | } 189 | } 190 | // give the web browser time to receive the data 191 | delay(1); 192 | // close the connection: 193 | client.stop(); 194 | } 195 | } 196 | 197 | 198 | //Send a write command to SCP1000 199 | void writeRegister(byte registerName, byte registerValue) { 200 | // SCP1000 expects the register name in the upper 6 bits 201 | // of the byte: 202 | registerName <<= 2; 203 | // command (read or write) goes in the lower two bits: 204 | registerName |= 0b00000010; //Write command 205 | 206 | // take the chip select low to select the device: 207 | digitalWrite(chipSelectPin, LOW); 208 | 209 | SPI.transfer(registerName); //Send register location 210 | SPI.transfer(registerValue); //Send value to record into register 211 | 212 | // take the chip select high to de-select: 213 | digitalWrite(chipSelectPin, HIGH); 214 | } 215 | 216 | 217 | //Read register from the SCP1000: 218 | unsigned int readRegister(byte registerName, int numBytes) { 219 | byte inByte = 0; // incoming from the SPI read 220 | unsigned int result = 0; // result to return 221 | 222 | // SCP1000 expects the register name in the upper 6 bits 223 | // of the byte: 224 | registerName <<= 2; 225 | // command (read or write) goes in the lower two bits: 226 | registerName &= 0b11111100; //Read command 227 | 228 | // take the chip select low to select the device: 229 | digitalWrite(chipSelectPin, LOW); 230 | // send the device the register you want to read: 231 | SPI.transfer(registerName); 232 | // send a value of 0 to read the first byte returned: 233 | inByte = SPI.transfer(0x00); 234 | 235 | result = inByte; 236 | // if there's more than one byte returned, 237 | // shift the first byte then get the second byte: 238 | if (numBytes > 1) { 239 | result = inByte << 8; 240 | inByte = SPI.transfer(0x00); 241 | result = result | inByte; 242 | } 243 | // take the chip select high to de-select: 244 | digitalWrite(chipSelectPin, HIGH); 245 | // return the result: 246 | return (result); 247 | } 248 | -------------------------------------------------------------------------------- /Ethernet-master/src/Dns.cpp: -------------------------------------------------------------------------------- 1 | // Arduino DNS client for WizNet5100-based Ethernet shield 2 | // (c) Copyright 2009-2010 MCQN Ltd. 3 | // Released under Apache License, version 2.0 4 | 5 | #include 6 | #include "Ethernet.h" 7 | #include "Dns.h" 8 | #include "utility/w5100.h" 9 | 10 | 11 | #define SOCKET_NONE 255 12 | // Various flags and header field values for a DNS message 13 | #define UDP_HEADER_SIZE 8 14 | #define DNS_HEADER_SIZE 12 15 | #define TTL_SIZE 4 16 | #define QUERY_FLAG (0) 17 | #define RESPONSE_FLAG (1<<15) 18 | #define QUERY_RESPONSE_MASK (1<<15) 19 | #define OPCODE_STANDARD_QUERY (0) 20 | #define OPCODE_INVERSE_QUERY (1<<11) 21 | #define OPCODE_STATUS_REQUEST (2<<11) 22 | #define OPCODE_MASK (15<<11) 23 | #define AUTHORITATIVE_FLAG (1<<10) 24 | #define TRUNCATION_FLAG (1<<9) 25 | #define RECURSION_DESIRED_FLAG (1<<8) 26 | #define RECURSION_AVAILABLE_FLAG (1<<7) 27 | #define RESP_NO_ERROR (0) 28 | #define RESP_FORMAT_ERROR (1) 29 | #define RESP_SERVER_FAILURE (2) 30 | #define RESP_NAME_ERROR (3) 31 | #define RESP_NOT_IMPLEMENTED (4) 32 | #define RESP_REFUSED (5) 33 | #define RESP_MASK (15) 34 | #define TYPE_A (0x0001) 35 | #define CLASS_IN (0x0001) 36 | #define LABEL_COMPRESSION_MASK (0xC0) 37 | // Port number that DNS servers listen on 38 | #define DNS_PORT 53 39 | 40 | // Possible return codes from ProcessResponse 41 | #define SUCCESS 1 42 | #define TIMED_OUT -1 43 | #define INVALID_SERVER -2 44 | #define TRUNCATED -3 45 | #define INVALID_RESPONSE -4 46 | 47 | void DNSClient::begin(const IPAddress& aDNSServer) 48 | { 49 | iDNSServer = aDNSServer; 50 | iRequestId = 0; 51 | } 52 | 53 | 54 | int DNSClient::inet_aton(const char* address, IPAddress& result) 55 | { 56 | uint16_t acc = 0; // Accumulator 57 | uint8_t dots = 0; 58 | 59 | while (*address) { 60 | char c = *address++; 61 | if (c >= '0' && c <= '9') { 62 | acc = acc * 10 + (c - '0'); 63 | if (acc > 255) { 64 | // Value out of [0..255] range 65 | return 0; 66 | } 67 | } else if (c == '.') { 68 | if (dots == 3) { 69 | // Too much dots (there must be 3 dots) 70 | return 0; 71 | } 72 | result[dots++] = acc; 73 | acc = 0; 74 | } else { 75 | // Invalid char 76 | return 0; 77 | } 78 | } 79 | 80 | if (dots != 3) { 81 | // Too few dots (there must be 3 dots) 82 | return 0; 83 | } 84 | result[3] = acc; 85 | return 1; 86 | } 87 | 88 | int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout) 89 | { 90 | int ret = 0; 91 | 92 | // See if it's a numeric IP address 93 | if (inet_aton(aHostname, aResult)) { 94 | // It is, our work here is done 95 | return 1; 96 | } 97 | 98 | // Check we've got a valid DNS server to use 99 | if (iDNSServer == INADDR_NONE) { 100 | return INVALID_SERVER; 101 | } 102 | 103 | // Find a socket to use 104 | if (iUdp.begin(1024+(millis() & 0xF)) == 1) { 105 | // Try up to three times 106 | int retries = 0; 107 | // while ((retries < 3) && (ret <= 0)) { 108 | // Send DNS request 109 | ret = iUdp.beginPacket(iDNSServer, DNS_PORT); 110 | if (ret != 0) { 111 | // Now output the request data 112 | ret = BuildRequest(aHostname); 113 | if (ret != 0) { 114 | // And finally send the request 115 | ret = iUdp.endPacket(); 116 | if (ret != 0) { 117 | // Now wait for a response 118 | int wait_retries = 0; 119 | ret = TIMED_OUT; 120 | while ((wait_retries < 3) && (ret == TIMED_OUT)) { 121 | ret = ProcessResponse(timeout, aResult); 122 | wait_retries++; 123 | } 124 | } 125 | } 126 | } 127 | retries++; 128 | //} 129 | 130 | // We're done with the socket now 131 | iUdp.stop(); 132 | } 133 | 134 | return ret; 135 | } 136 | 137 | uint16_t DNSClient::BuildRequest(const char* aName) 138 | { 139 | // Build header 140 | // 1 1 1 1 1 1 141 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 142 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 143 | // | ID | 144 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 145 | // |QR| Opcode |AA|TC|RD|RA| Z | RCODE | 146 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 147 | // | QDCOUNT | 148 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 149 | // | ANCOUNT | 150 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 151 | // | NSCOUNT | 152 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 153 | // | ARCOUNT | 154 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 155 | // As we only support one request at a time at present, we can simplify 156 | // some of this header 157 | iRequestId = millis(); // generate a random ID 158 | uint16_t twoByteBuffer; 159 | 160 | // FIXME We should also check that there's enough space available to write to, rather 161 | // FIXME than assume there's enough space (as the code does at present) 162 | iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId)); 163 | 164 | twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG); 165 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 166 | 167 | twoByteBuffer = htons(1); // One question record 168 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 169 | 170 | twoByteBuffer = 0; // Zero answer records 171 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 172 | 173 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 174 | // and zero additional records 175 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 176 | 177 | // Build question 178 | const char* start =aName; 179 | const char* end =start; 180 | uint8_t len; 181 | // Run through the name being requested 182 | while (*end) { 183 | // Find out how long this section of the name is 184 | end = start; 185 | while (*end && (*end != '.') ) { 186 | end++; 187 | } 188 | 189 | if (end-start > 0) { 190 | // Write out the size of this section 191 | len = end-start; 192 | iUdp.write(&len, sizeof(len)); 193 | // And then write out the section 194 | iUdp.write((uint8_t*)start, end-start); 195 | } 196 | start = end+1; 197 | } 198 | 199 | // We've got to the end of the question name, so 200 | // terminate it with a zero-length section 201 | len = 0; 202 | iUdp.write(&len, sizeof(len)); 203 | // Finally the type and class of question 204 | twoByteBuffer = htons(TYPE_A); 205 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 206 | 207 | twoByteBuffer = htons(CLASS_IN); // Internet class of question 208 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 209 | // Success! Everything buffered okay 210 | return 1; 211 | } 212 | 213 | 214 | uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) 215 | { 216 | uint32_t startTime = millis(); 217 | 218 | // Wait for a response packet 219 | while (iUdp.parsePacket() <= 0) { 220 | if ((millis() - startTime) > aTimeout) { 221 | return TIMED_OUT; 222 | } 223 | delay(50); 224 | } 225 | 226 | // We've had a reply! 227 | // Read the UDP header 228 | //uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header 229 | union { 230 | uint8_t byte[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header 231 | uint16_t word[DNS_HEADER_SIZE/2]; 232 | } header; 233 | 234 | // Check that it's a response from the right server and the right port 235 | if ( (iDNSServer != iUdp.remoteIP()) || (iUdp.remotePort() != DNS_PORT) ) { 236 | // It's not from who we expected 237 | return INVALID_SERVER; 238 | } 239 | 240 | // Read through the rest of the response 241 | if (iUdp.available() < DNS_HEADER_SIZE) { 242 | return TRUNCATED; 243 | } 244 | iUdp.read(header.byte, DNS_HEADER_SIZE); 245 | 246 | uint16_t header_flags = htons(header.word[1]); 247 | // Check that it's a response to this request 248 | if ((iRequestId != (header.word[0])) || 249 | ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) { 250 | // Mark the entire packet as read 251 | iUdp.flush(); // FIXME 252 | return INVALID_RESPONSE; 253 | } 254 | // Check for any errors in the response (or in our request) 255 | // although we don't do anything to get round these 256 | if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) ) { 257 | // Mark the entire packet as read 258 | iUdp.flush(); // FIXME 259 | return -5; //INVALID_RESPONSE; 260 | } 261 | 262 | // And make sure we've got (at least) one answer 263 | uint16_t answerCount = htons(header.word[3]); 264 | if (answerCount == 0) { 265 | // Mark the entire packet as read 266 | iUdp.flush(); // FIXME 267 | return -6; //INVALID_RESPONSE; 268 | } 269 | 270 | // Skip over any questions 271 | for (uint16_t i=0; i < htons(header.word[2]); i++) { 272 | // Skip over the name 273 | uint8_t len; 274 | do { 275 | iUdp.read(&len, sizeof(len)); 276 | if (len > 0) { 277 | // Don't need to actually read the data out for the string, just 278 | // advance ptr to beyond it 279 | iUdp.read((uint8_t *)NULL, (size_t)len); 280 | } 281 | } while (len != 0); 282 | 283 | // Now jump over the type and class 284 | iUdp.read((uint8_t *)NULL, 4); 285 | } 286 | 287 | // Now we're up to the bit we're interested in, the answer 288 | // There might be more than one answer (although we'll just use the first 289 | // type A answer) and some authority and additional resource records but 290 | // we're going to ignore all of them. 291 | 292 | for (uint16_t i=0; i < answerCount; i++) { 293 | // Skip the name 294 | uint8_t len; 295 | do { 296 | iUdp.read(&len, sizeof(len)); 297 | if ((len & LABEL_COMPRESSION_MASK) == 0) { 298 | // It's just a normal label 299 | if (len > 0) { 300 | // And it's got a length 301 | // Don't need to actually read the data out for the string, 302 | // just advance ptr to beyond it 303 | iUdp.read((uint8_t *)NULL, len); 304 | } 305 | } else { 306 | // This is a pointer to a somewhere else in the message for the 307 | // rest of the name. We don't care about the name, and RFC1035 308 | // says that a name is either a sequence of labels ended with a 309 | // 0 length octet or a pointer or a sequence of labels ending in 310 | // a pointer. Either way, when we get here we're at the end of 311 | // the name 312 | // Skip over the pointer 313 | iUdp.read((uint8_t *)NULL, 1); // we don't care about the byte 314 | // And set len so that we drop out of the name loop 315 | len = 0; 316 | } 317 | } while (len != 0); 318 | 319 | // Check the type and class 320 | uint16_t answerType; 321 | uint16_t answerClass; 322 | iUdp.read((uint8_t*)&answerType, sizeof(answerType)); 323 | iUdp.read((uint8_t*)&answerClass, sizeof(answerClass)); 324 | 325 | // Ignore the Time-To-Live as we don't do any caching 326 | iUdp.read((uint8_t *)NULL, TTL_SIZE); // don't care about the returned bytes 327 | 328 | // And read out the length of this answer 329 | // Don't need header_flags anymore, so we can reuse it here 330 | iUdp.read((uint8_t*)&header_flags, sizeof(header_flags)); 331 | 332 | if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) ) { 333 | if (htons(header_flags) != 4) { 334 | // It's a weird size 335 | // Mark the entire packet as read 336 | iUdp.flush(); // FIXME 337 | return -9;//INVALID_RESPONSE; 338 | } 339 | // FIXME: seeems to lock up here on ESP8266, but why?? 340 | iUdp.read(aAddress.raw_address(), 4); 341 | return SUCCESS; 342 | } else { 343 | // This isn't an answer type we're after, move onto the next one 344 | iUdp.read((uint8_t *)NULL, htons(header_flags)); 345 | } 346 | } 347 | 348 | // Mark the entire packet as read 349 | iUdp.flush(); // FIXME 350 | 351 | // If we get here then we haven't found an answer 352 | return -10; //INVALID_RESPONSE; 353 | } 354 | 355 | -------------------------------------------------------------------------------- /Ethernet-master/src/Dhcp.cpp: -------------------------------------------------------------------------------- 1 | // DHCP Library v0.3 - April 25, 2009 2 | // Author: Jordan Terrell - blog.jordanterrell.com 3 | 4 | #include 5 | #include "Ethernet.h" 6 | #include "Dhcp.h" 7 | #include "utility/w5100.h" 8 | 9 | int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) 10 | { 11 | _dhcpLeaseTime=0; 12 | _dhcpT1=0; 13 | _dhcpT2=0; 14 | _timeout = timeout; 15 | _responseTimeout = responseTimeout; 16 | 17 | // zero out _dhcpMacAddr 18 | memset(_dhcpMacAddr, 0, 6); 19 | reset_DHCP_lease(); 20 | 21 | memcpy((void*)_dhcpMacAddr, (void*)mac, 6); 22 | _dhcp_state = STATE_DHCP_START; 23 | return request_DHCP_lease(); 24 | } 25 | 26 | void DhcpClass::reset_DHCP_lease() 27 | { 28 | // zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp 29 | memset(_dhcpLocalIp, 0, 20); 30 | } 31 | 32 | //return:0 on error, 1 if request is sent and response is received 33 | int DhcpClass::request_DHCP_lease() 34 | { 35 | uint8_t messageType = 0; 36 | 37 | // Pick an initial transaction ID 38 | _dhcpTransactionId = random(1UL, 2000UL); 39 | _dhcpInitialTransactionId = _dhcpTransactionId; 40 | 41 | _dhcpUdpSocket.stop(); 42 | if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0) { 43 | // Couldn't get a socket 44 | return 0; 45 | } 46 | 47 | presend_DHCP(); 48 | 49 | int result = 0; 50 | 51 | unsigned long startTime = millis(); 52 | 53 | while (_dhcp_state != STATE_DHCP_LEASED) { 54 | if (_dhcp_state == STATE_DHCP_START) { 55 | _dhcpTransactionId++; 56 | send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000)); 57 | _dhcp_state = STATE_DHCP_DISCOVER; 58 | } else if (_dhcp_state == STATE_DHCP_REREQUEST) { 59 | _dhcpTransactionId++; 60 | send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000)); 61 | _dhcp_state = STATE_DHCP_REQUEST; 62 | } else if (_dhcp_state == STATE_DHCP_DISCOVER) { 63 | uint32_t respId; 64 | messageType = parseDHCPResponse(_responseTimeout, respId); 65 | if (messageType == DHCP_OFFER) { 66 | // We'll use the transaction ID that the offer came with, 67 | // rather than the one we were up to 68 | _dhcpTransactionId = respId; 69 | send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000)); 70 | _dhcp_state = STATE_DHCP_REQUEST; 71 | } 72 | } else if (_dhcp_state == STATE_DHCP_REQUEST) { 73 | uint32_t respId; 74 | messageType = parseDHCPResponse(_responseTimeout, respId); 75 | if (messageType == DHCP_ACK) { 76 | _dhcp_state = STATE_DHCP_LEASED; 77 | result = 1; 78 | //use default lease time if we didn't get it 79 | if (_dhcpLeaseTime == 0) { 80 | _dhcpLeaseTime = DEFAULT_LEASE; 81 | } 82 | // Calculate T1 & T2 if we didn't get it 83 | if (_dhcpT1 == 0) { 84 | // T1 should be 50% of _dhcpLeaseTime 85 | _dhcpT1 = _dhcpLeaseTime >> 1; 86 | } 87 | if (_dhcpT2 == 0) { 88 | // T2 should be 87.5% (7/8ths) of _dhcpLeaseTime 89 | _dhcpT2 = _dhcpLeaseTime - (_dhcpLeaseTime >> 3); 90 | } 91 | _renewInSec = _dhcpT1; 92 | _rebindInSec = _dhcpT2; 93 | } else if (messageType == DHCP_NAK) { 94 | _dhcp_state = STATE_DHCP_START; 95 | } 96 | } 97 | 98 | if (messageType == 255) { 99 | messageType = 0; 100 | _dhcp_state = STATE_DHCP_START; 101 | } 102 | 103 | if (result != 1 && ((millis() - startTime) > _timeout)) 104 | break; 105 | } 106 | 107 | // We're done with the socket now 108 | _dhcpUdpSocket.stop(); 109 | _dhcpTransactionId++; 110 | 111 | _lastCheckLeaseMillis = millis(); 112 | return result; 113 | } 114 | 115 | void DhcpClass::presend_DHCP() 116 | { 117 | } 118 | 119 | void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed) 120 | { 121 | uint8_t buffer[32]; 122 | memset(buffer, 0, 32); 123 | IPAddress dest_addr(255, 255, 255, 255); // Broadcast address 124 | 125 | if (_dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT) == -1) { 126 | //Serial.printf("DHCP transmit error\n"); 127 | // FIXME Need to return errors 128 | return; 129 | } 130 | 131 | buffer[0] = DHCP_BOOTREQUEST; // op 132 | buffer[1] = DHCP_HTYPE10MB; // htype 133 | buffer[2] = DHCP_HLENETHERNET; // hlen 134 | buffer[3] = DHCP_HOPS; // hops 135 | 136 | // xid 137 | unsigned long xid = htonl(_dhcpTransactionId); 138 | memcpy(buffer + 4, &(xid), 4); 139 | 140 | // 8, 9 - seconds elapsed 141 | buffer[8] = ((secondsElapsed & 0xff00) >> 8); 142 | buffer[9] = (secondsElapsed & 0x00ff); 143 | 144 | // flags 145 | unsigned short flags = htons(DHCP_FLAGSBROADCAST); 146 | memcpy(buffer + 10, &(flags), 2); 147 | 148 | // ciaddr: already zeroed 149 | // yiaddr: already zeroed 150 | // siaddr: already zeroed 151 | // giaddr: already zeroed 152 | 153 | //put data in W5100 transmit buffer 154 | _dhcpUdpSocket.write(buffer, 28); 155 | 156 | memset(buffer, 0, 32); // clear local buffer 157 | 158 | memcpy(buffer, _dhcpMacAddr, 6); // chaddr 159 | 160 | //put data in W5100 transmit buffer 161 | _dhcpUdpSocket.write(buffer, 16); 162 | 163 | memset(buffer, 0, 32); // clear local buffer 164 | 165 | // leave zeroed out for sname && file 166 | // put in W5100 transmit buffer x 6 (192 bytes) 167 | 168 | for(int i = 0; i < 6; i++) { 169 | _dhcpUdpSocket.write(buffer, 32); 170 | } 171 | 172 | // OPT - Magic Cookie 173 | buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF); 174 | buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF); 175 | buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF); 176 | buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF); 177 | 178 | // OPT - message type 179 | buffer[4] = dhcpMessageType; 180 | buffer[5] = 0x01; 181 | buffer[6] = messageType; //DHCP_REQUEST; 182 | 183 | // OPT - client identifier 184 | buffer[7] = dhcpClientIdentifier; 185 | buffer[8] = 0x07; 186 | buffer[9] = 0x01; 187 | memcpy(buffer + 10, _dhcpMacAddr, 6); 188 | 189 | // OPT - host name 190 | buffer[16] = hostName; 191 | buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address 192 | strcpy((char*)&(buffer[18]), HOST_NAME); 193 | 194 | printByte((char*)&(buffer[24]), _dhcpMacAddr[3]); 195 | printByte((char*)&(buffer[26]), _dhcpMacAddr[4]); 196 | printByte((char*)&(buffer[28]), _dhcpMacAddr[5]); 197 | 198 | //put data in W5100 transmit buffer 199 | _dhcpUdpSocket.write(buffer, 30); 200 | 201 | if (messageType == DHCP_REQUEST) { 202 | buffer[0] = dhcpRequestedIPaddr; 203 | buffer[1] = 0x04; 204 | buffer[2] = _dhcpLocalIp[0]; 205 | buffer[3] = _dhcpLocalIp[1]; 206 | buffer[4] = _dhcpLocalIp[2]; 207 | buffer[5] = _dhcpLocalIp[3]; 208 | 209 | buffer[6] = dhcpServerIdentifier; 210 | buffer[7] = 0x04; 211 | buffer[8] = _dhcpDhcpServerIp[0]; 212 | buffer[9] = _dhcpDhcpServerIp[1]; 213 | buffer[10] = _dhcpDhcpServerIp[2]; 214 | buffer[11] = _dhcpDhcpServerIp[3]; 215 | 216 | //put data in W5100 transmit buffer 217 | _dhcpUdpSocket.write(buffer, 12); 218 | } 219 | 220 | buffer[0] = dhcpParamRequest; 221 | buffer[1] = 0x06; 222 | buffer[2] = subnetMask; 223 | buffer[3] = routersOnSubnet; 224 | buffer[4] = dns; 225 | buffer[5] = domainName; 226 | buffer[6] = dhcpT1value; 227 | buffer[7] = dhcpT2value; 228 | buffer[8] = endOption; 229 | 230 | //put data in W5100 transmit buffer 231 | _dhcpUdpSocket.write(buffer, 9); 232 | 233 | _dhcpUdpSocket.endPacket(); 234 | } 235 | 236 | uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId) 237 | { 238 | uint8_t type = 0; 239 | uint8_t opt_len = 0; 240 | 241 | unsigned long startTime = millis(); 242 | 243 | while (_dhcpUdpSocket.parsePacket() <= 0) { 244 | if ((millis() - startTime) > responseTimeout) { 245 | return 255; 246 | } 247 | delay(50); 248 | } 249 | // start reading in the packet 250 | RIP_MSG_FIXED fixedMsg; 251 | _dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED)); 252 | 253 | if (fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT) { 254 | transactionId = ntohl(fixedMsg.xid); 255 | if (memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || 256 | (transactionId < _dhcpInitialTransactionId) || 257 | (transactionId > _dhcpTransactionId)) { 258 | // Need to read the rest of the packet here regardless 259 | _dhcpUdpSocket.flush(); // FIXME 260 | return 0; 261 | } 262 | 263 | memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4); 264 | 265 | // Skip to the option part 266 | _dhcpUdpSocket.read((uint8_t *)NULL, 240 - (int)sizeof(RIP_MSG_FIXED)); 267 | 268 | while (_dhcpUdpSocket.available() > 0) { 269 | switch (_dhcpUdpSocket.read()) { 270 | case endOption : 271 | break; 272 | 273 | case padOption : 274 | break; 275 | 276 | case dhcpMessageType : 277 | opt_len = _dhcpUdpSocket.read(); 278 | type = _dhcpUdpSocket.read(); 279 | break; 280 | 281 | case subnetMask : 282 | opt_len = _dhcpUdpSocket.read(); 283 | _dhcpUdpSocket.read(_dhcpSubnetMask, 4); 284 | break; 285 | 286 | case routersOnSubnet : 287 | opt_len = _dhcpUdpSocket.read(); 288 | _dhcpUdpSocket.read(_dhcpGatewayIp, 4); 289 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); 290 | break; 291 | 292 | case dns : 293 | opt_len = _dhcpUdpSocket.read(); 294 | _dhcpUdpSocket.read(_dhcpDnsServerIp, 4); 295 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); 296 | break; 297 | 298 | case dhcpServerIdentifier : 299 | opt_len = _dhcpUdpSocket.read(); 300 | if ( IPAddress(_dhcpDhcpServerIp) == IPAddress((uint32_t)0) || 301 | IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) { 302 | _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp)); 303 | } else { 304 | // Skip over the rest of this option 305 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); 306 | } 307 | break; 308 | 309 | case dhcpT1value : 310 | opt_len = _dhcpUdpSocket.read(); 311 | _dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1)); 312 | _dhcpT1 = ntohl(_dhcpT1); 313 | break; 314 | 315 | case dhcpT2value : 316 | opt_len = _dhcpUdpSocket.read(); 317 | _dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2)); 318 | _dhcpT2 = ntohl(_dhcpT2); 319 | break; 320 | 321 | case dhcpIPaddrLeaseTime : 322 | opt_len = _dhcpUdpSocket.read(); 323 | _dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime)); 324 | _dhcpLeaseTime = ntohl(_dhcpLeaseTime); 325 | _renewInSec = _dhcpLeaseTime; 326 | break; 327 | 328 | default : 329 | opt_len = _dhcpUdpSocket.read(); 330 | // Skip over the rest of this option 331 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); 332 | break; 333 | } 334 | } 335 | } 336 | 337 | // Need to skip to end of the packet regardless here 338 | _dhcpUdpSocket.flush(); // FIXME 339 | 340 | return type; 341 | } 342 | 343 | 344 | /* 345 | returns: 346 | 0/DHCP_CHECK_NONE: nothing happened 347 | 1/DHCP_CHECK_RENEW_FAIL: renew failed 348 | 2/DHCP_CHECK_RENEW_OK: renew success 349 | 3/DHCP_CHECK_REBIND_FAIL: rebind fail 350 | 4/DHCP_CHECK_REBIND_OK: rebind success 351 | */ 352 | int DhcpClass::checkLease() 353 | { 354 | int rc = DHCP_CHECK_NONE; 355 | 356 | unsigned long now = millis(); 357 | unsigned long elapsed = now - _lastCheckLeaseMillis; 358 | 359 | // if more then one sec passed, reduce the counters accordingly 360 | if (elapsed >= 1000) { 361 | // set the new timestamps 362 | _lastCheckLeaseMillis = now - (elapsed % 1000); 363 | elapsed = elapsed / 1000; 364 | 365 | // decrease the counters by elapsed seconds 366 | // we assume that the cycle time (elapsed) is fairly constant 367 | // if the remainder is less than cycle time * 2 368 | // do it early instead of late 369 | if (_renewInSec < elapsed * 2) { 370 | _renewInSec = 0; 371 | } else { 372 | _renewInSec -= elapsed; 373 | } 374 | if (_rebindInSec < elapsed * 2) { 375 | _rebindInSec = 0; 376 | } else { 377 | _rebindInSec -= elapsed; 378 | } 379 | } 380 | 381 | // if we have a lease but should renew, do it 382 | if (_renewInSec == 0 &&_dhcp_state == STATE_DHCP_LEASED) { 383 | _dhcp_state = STATE_DHCP_REREQUEST; 384 | rc = 1 + request_DHCP_lease(); 385 | } 386 | 387 | // if we have a lease or is renewing but should bind, do it 388 | if (_rebindInSec == 0 && (_dhcp_state == STATE_DHCP_LEASED || 389 | _dhcp_state == STATE_DHCP_START)) { 390 | // this should basically restart completely 391 | _dhcp_state = STATE_DHCP_START; 392 | reset_DHCP_lease(); 393 | rc = 3 + request_DHCP_lease(); 394 | } 395 | return rc; 396 | } 397 | 398 | IPAddress DhcpClass::getLocalIp() 399 | { 400 | return IPAddress(_dhcpLocalIp); 401 | } 402 | 403 | IPAddress DhcpClass::getSubnetMask() 404 | { 405 | return IPAddress(_dhcpSubnetMask); 406 | } 407 | 408 | IPAddress DhcpClass::getGatewayIp() 409 | { 410 | return IPAddress(_dhcpGatewayIp); 411 | } 412 | 413 | IPAddress DhcpClass::getDhcpServerIp() 414 | { 415 | return IPAddress(_dhcpDhcpServerIp); 416 | } 417 | 418 | IPAddress DhcpClass::getDnsServerIp() 419 | { 420 | return IPAddress(_dhcpDnsServerIp); 421 | } 422 | 423 | void DhcpClass::printByte(char * buf, uint8_t n ) 424 | { 425 | char *str = &buf[1]; 426 | buf[0]='0'; 427 | do { 428 | unsigned long m = n; 429 | n /= 16; 430 | char c = m - 16 * n; 431 | *str-- = c < 10 ? c + '0' : c + 'A' - 10; 432 | } while(n); 433 | } 434 | -------------------------------------------------------------------------------- /Ethernet-master/src/Ethernet.h: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #ifndef ethernet_h_ 22 | #define ethernet_h_ 23 | 24 | // All symbols exposed to Arduino sketches are contained in this header file 25 | // 26 | // Older versions had much of this stuff in EthernetClient.h, EthernetServer.h, 27 | // and socket.h. Including headers in different order could cause trouble, so 28 | // these "friend" classes are now defined in the same header file. socket.h 29 | // was removed to avoid possible conflict with the C library header files. 30 | 31 | 32 | // Configure the maximum number of sockets to support. W5100 chips can have 33 | // up to 4 sockets. W5200 & W5500 can have up to 8 sockets. Several bytes 34 | // of RAM are used for each socket. Reducing the maximum can save RAM, but 35 | // you are limited to fewer simultaneous connections. 36 | #if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048) 37 | #define MAX_SOCK_NUM 4 38 | #else 39 | #define MAX_SOCK_NUM 8 40 | #endif 41 | 42 | // By default, each socket uses 2K buffers inside the Wiznet chip. If 43 | // MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting 44 | // this will use larger buffers within the Wiznet chip. Large buffers 45 | // can really help with UDP protocols like Artnet. In theory larger 46 | // buffers should allow faster TCP over high-latency links, but this 47 | // does not always seem to work in practice (maybe Wiznet bugs?) 48 | //#define ETHERNET_LARGE_BUFFERS 49 | 50 | 51 | #include 52 | #include "Client.h" 53 | #include "Server.h" 54 | #include "Udp.h" 55 | 56 | enum EthernetLinkStatus { 57 | Unknown, 58 | LinkON, 59 | LinkOFF 60 | }; 61 | 62 | enum EthernetHardwareStatus { 63 | EthernetNoHardware, 64 | EthernetW5100, 65 | EthernetW5200, 66 | EthernetW5500 67 | }; 68 | 69 | class EthernetUDP; 70 | class EthernetClient; 71 | class EthernetServer; 72 | class DhcpClass; 73 | 74 | class EthernetClass { 75 | private: 76 | static IPAddress _dnsServerAddress; 77 | static DhcpClass* _dhcp; 78 | public: 79 | // Initialise the Ethernet shield to use the provided MAC address and 80 | // gain the rest of the configuration through DHCP. 81 | // Returns 0 if the DHCP configuration failed, and 1 if it succeeded 82 | static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); 83 | static int maintain(); 84 | static EthernetLinkStatus linkStatus(); 85 | static EthernetHardwareStatus hardwareStatus(); 86 | 87 | // Manaul configuration 88 | static void begin(uint8_t *mac, IPAddress ip); 89 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns); 90 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway); 91 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet); 92 | static void init(uint8_t sspin = 10); 93 | 94 | static void MACAddress(uint8_t *mac_address); 95 | static IPAddress localIP(); 96 | static IPAddress subnetMask(); 97 | static IPAddress gatewayIP(); 98 | static IPAddress dnsServerIP() { return _dnsServerAddress; } 99 | 100 | void setMACAddress(const uint8_t *mac_address); 101 | void setLocalIP(const IPAddress local_ip); 102 | void setSubnetMask(const IPAddress subnet); 103 | void setGatewayIP(const IPAddress gateway); 104 | void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; } 105 | void setRetransmissionTimeout(uint16_t milliseconds); 106 | void setRetransmissionCount(uint8_t num); 107 | 108 | friend class EthernetClient; 109 | friend class EthernetServer; 110 | friend class EthernetUDP; 111 | private: 112 | // Opens a socket(TCP or UDP or IP_RAW mode) 113 | static uint8_t socketBegin(uint8_t protocol, uint16_t port); 114 | static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port); 115 | static uint8_t socketStatus(uint8_t s); 116 | // Close socket 117 | static void socketClose(uint8_t s); 118 | // Establish TCP connection (Active connection) 119 | static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port); 120 | // disconnect the connection 121 | static void socketDisconnect(uint8_t s); 122 | // Establish TCP connection (Passive connection) 123 | static uint8_t socketListen(uint8_t s); 124 | // Send data (TCP) 125 | static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len); 126 | static uint16_t socketSendAvailable(uint8_t s); 127 | // Receive data (TCP) 128 | static int socketRecv(uint8_t s, uint8_t * buf, int16_t len); 129 | static uint16_t socketRecvAvailable(uint8_t s); 130 | static uint8_t socketPeek(uint8_t s); 131 | // sets up a UDP datagram, the data for which will be provided by one 132 | // or more calls to bufferData and then finally sent with sendUDP. 133 | // return true if the datagram was successfully set up, or false if there was an error 134 | static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port); 135 | // copy up to len bytes of data from buf into a UDP datagram to be 136 | // sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls. 137 | // return Number of bytes successfully buffered 138 | static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len); 139 | // Send a UDP datagram built up from a sequence of startUDP followed by one or more 140 | // calls to bufferData. 141 | // return true if the datagram was successfully sent, or false if there was an error 142 | static bool socketSendUDP(uint8_t s); 143 | // Initialize the "random" source port number 144 | static void socketPortRand(uint16_t n); 145 | }; 146 | 147 | extern EthernetClass Ethernet; 148 | 149 | 150 | #define UDP_TX_PACKET_MAX_SIZE 24 151 | 152 | class EthernetUDP : public UDP { 153 | private: 154 | uint16_t _port; // local port to listen on 155 | IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed 156 | uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed 157 | uint16_t _offset; // offset into the packet being sent 158 | 159 | protected: 160 | uint8_t sockindex; 161 | uint16_t _remaining; // remaining bytes of incoming packet yet to be processed 162 | 163 | public: 164 | EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // Constructor 165 | 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 166 | 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 167 | virtual void stop(); // Finish with the UDP socket 168 | 169 | // Sending UDP packets 170 | 171 | // Start building up a packet to send to the remote host specific in ip and port 172 | // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port 173 | virtual int beginPacket(IPAddress ip, uint16_t port); 174 | // Start building up a packet to send to the remote host specific in host and port 175 | // Returns 1 if successful, 0 if there was a problem resolving the hostname or port 176 | virtual int beginPacket(const char *host, uint16_t port); 177 | // Finish off this packet and send it 178 | // Returns 1 if the packet was sent successfully, 0 if there was an error 179 | virtual int endPacket(); 180 | // Write a single byte into the packet 181 | virtual size_t write(uint8_t); 182 | // Write size bytes from buffer into the packet 183 | virtual size_t write(const uint8_t *buffer, size_t size); 184 | 185 | using Print::write; 186 | 187 | // Start processing the next available incoming packet 188 | // Returns the size of the packet in bytes, or 0 if no packets are available 189 | virtual int parsePacket(); 190 | // Number of bytes remaining in the current packet 191 | virtual int available(); 192 | // Read a single byte from the current packet 193 | virtual int read(); 194 | // Read up to len bytes from the current packet and place them into buffer 195 | // Returns the number of bytes read, or 0 if none are available 196 | virtual int read(unsigned char* buffer, size_t len); 197 | // Read up to len characters from the current packet and place them into buffer 198 | // Returns the number of characters read, or 0 if none are available 199 | virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; 200 | // Return the next byte from the current packet without moving on to the next byte 201 | virtual int peek(); 202 | virtual void flush(); // Finish reading the current packet 203 | 204 | // Return the IP address of the host who sent the current incoming packet 205 | virtual IPAddress remoteIP() { return _remoteIP; }; 206 | // Return the port of the host who sent the current incoming packet 207 | virtual uint16_t remotePort() { return _remotePort; }; 208 | virtual uint16_t localPort() { return _port; } 209 | }; 210 | 211 | 212 | 213 | 214 | class EthernetClient : public Client { 215 | public: 216 | EthernetClient() : sockindex(MAX_SOCK_NUM), _timeout(1000) { } 217 | EthernetClient(uint8_t s) : sockindex(s), _timeout(1000) { } 218 | 219 | uint8_t status(); 220 | virtual int connect(IPAddress ip, uint16_t port); 221 | virtual int connect(const char *host, uint16_t port); 222 | virtual int availableForWrite(void); 223 | virtual size_t write(uint8_t); 224 | virtual size_t write(const uint8_t *buf, size_t size); 225 | virtual int available(); 226 | virtual int read(); 227 | virtual int read(uint8_t *buf, size_t size); 228 | virtual int peek(); 229 | virtual void flush(); 230 | virtual void stop(); 231 | virtual uint8_t connected(); 232 | virtual operator bool() { return sockindex < MAX_SOCK_NUM; } 233 | virtual bool operator==(const bool value) { return bool() == value; } 234 | virtual bool operator!=(const bool value) { return bool() != value; } 235 | virtual bool operator==(const EthernetClient&); 236 | virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); } 237 | uint8_t getSocketNumber() const { return sockindex; } 238 | virtual uint16_t localPort(); 239 | virtual IPAddress remoteIP(); 240 | virtual uint16_t remotePort(); 241 | virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; } 242 | 243 | friend class EthernetServer; 244 | 245 | using Print::write; 246 | 247 | private: 248 | uint8_t sockindex; // MAX_SOCK_NUM means client not in use 249 | uint16_t _timeout; 250 | }; 251 | 252 | 253 | class EthernetServer : public Server { 254 | private: 255 | uint16_t _port; 256 | public: 257 | EthernetServer(uint16_t port) : _port(port) { } 258 | EthernetClient available(); 259 | EthernetClient accept(); 260 | virtual void begin(); 261 | virtual size_t write(uint8_t); 262 | virtual size_t write(const uint8_t *buf, size_t size); 263 | virtual operator bool(); 264 | using Print::write; 265 | //void statusreport(); 266 | 267 | // TODO: make private when socket allocation moves to EthernetClass 268 | static uint16_t server_port[MAX_SOCK_NUM]; 269 | }; 270 | 271 | 272 | class DhcpClass { 273 | private: 274 | uint32_t _dhcpInitialTransactionId; 275 | uint32_t _dhcpTransactionId; 276 | uint8_t _dhcpMacAddr[6]; 277 | #ifdef __arm__ 278 | uint8_t _dhcpLocalIp[4] __attribute__((aligned(4))); 279 | uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4))); 280 | uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4))); 281 | uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4))); 282 | uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4))); 283 | #else 284 | uint8_t _dhcpLocalIp[4]; 285 | uint8_t _dhcpSubnetMask[4]; 286 | uint8_t _dhcpGatewayIp[4]; 287 | uint8_t _dhcpDhcpServerIp[4]; 288 | uint8_t _dhcpDnsServerIp[4]; 289 | #endif 290 | uint32_t _dhcpLeaseTime; 291 | uint32_t _dhcpT1, _dhcpT2; 292 | uint32_t _renewInSec; 293 | uint32_t _rebindInSec; 294 | unsigned long _timeout; 295 | unsigned long _responseTimeout; 296 | unsigned long _lastCheckLeaseMillis; 297 | uint8_t _dhcp_state; 298 | EthernetUDP _dhcpUdpSocket; 299 | 300 | int request_DHCP_lease(); 301 | void reset_DHCP_lease(); 302 | void presend_DHCP(); 303 | void send_DHCP_MESSAGE(uint8_t, uint16_t); 304 | void printByte(char *, uint8_t); 305 | 306 | uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId); 307 | public: 308 | IPAddress getLocalIp(); 309 | IPAddress getSubnetMask(); 310 | IPAddress getGatewayIp(); 311 | IPAddress getDhcpServerIp(); 312 | IPAddress getDnsServerIp(); 313 | 314 | int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); 315 | int checkLease(); 316 | }; 317 | 318 | 319 | 320 | 321 | 322 | #endif 323 | -------------------------------------------------------------------------------- /linuxcncinterface/linuxcncinterface.ino: -------------------------------------------------------------------------------- 1 | /* 2 | UDPSendReceiveString: 3 | This sketch receives UDP message strings, prints them to the serial port 4 | and sends an "acknowledge" string back to the sender 5 | 6 | A Processing sketch is included at the end of file that can be used to send 7 | and received messages for testing with a computer. 8 | 9 | created 21 Aug 2010 10 | by Michael Margolis 11 | 12 | This code is in the public domain. 13 | */ 14 | 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | ///#include 25 | //#include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | 32 | ESP32Encoder encoder; 33 | 34 | // Enter a MAC address and IP address for your controller below. 35 | // The IP address will be dependent on your local network: 36 | 37 | /*###########################Ethernet definitions ######################################*/ 38 | byte mac[] = { 39 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 40 | }; 41 | IPAddress ip(192, 168, 1, 177); 42 | IPAddress sub(255, 255, 255, 0); 43 | unsigned int localPort = 27181; // local port to listen on 44 | // buffers for receiving and sending data 45 | char packetBuffer[512]; // buffer to hold incoming packet, 46 | EthernetUDP Udp; 47 | //WiFiUDP Udp; 48 | 49 | 50 | 51 | /*##################################i nterupt function ################################*/ 52 | unsigned long timeus; 53 | volatile int interrupts; 54 | int totalInterrupts; 55 | hw_timer_t * timer = NULL; 56 | 57 | portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; 58 | 59 | /*######################### STEPPER variables ################################*/ 60 | 61 | int16_t steps_0_dir; 62 | int16_t steps_0; 63 | int16_t steps_1_dir; 64 | int16_t steps_1; 65 | int16_t steps_2_dir; 66 | int16_t steps_2; 67 | int16_t steps_3_dir; 68 | int16_t steps_3; 69 | int16_t steps_4_dir; 70 | int16_t steps_4; 71 | 72 | 73 | int16_t steps_0_executed; 74 | int16_t steps_1_executed; 75 | int16_t steps_2_executed; 76 | int16_t steps_3_executed; 77 | int16_t steps_4_executed; 78 | 79 | 80 | 81 | 82 | 83 | struct old { 84 | 85 | int32_t old_pos_0; 86 | int32_t old_pos_1; 87 | int32_t old_pos_2; 88 | int32_t old_pos_3; 89 | int32_t old_pos_4; 90 | 91 | }olds; 92 | 93 | 94 | 95 | 96 | 97 | 98 | int8_t dir0=1; 99 | int8_t dir1=1; 100 | int8_t dir2=1; 101 | int8_t dir3=1; 102 | int8_t dir4=1; 103 | 104 | 105 | 106 | struct axes { 107 | int32_t fb0; 108 | int32_t fb1; 109 | int32_t fb2; 110 | int32_t fb3; 111 | int32_t fb4; 112 | uint32_t io; 113 | uint32_t io2; 114 | int64_t enc0; 115 | 116 | }; 117 | 118 | //axes fdbrt; 119 | //struct axes mayaxes ; 120 | 121 | struct pos { 122 | int32_t pos0; 123 | int32_t pos1; 124 | int32_t pos2; 125 | int32_t pos3; 126 | int32_t pos4; 127 | uint32_t io; 128 | uint32_t io2; 129 | int64_t analog; 130 | 131 | }cmd; 132 | 133 | axes fdb={0, 0, 0, 0, 0, 0, 0, 0}; 134 | 135 | int packetSize; 136 | long enc0; 137 | long enc1; 138 | long enc2; 139 | long enc3; 140 | char bufferin[sizeof(fdb)] ; 141 | 142 | //////////////////////////////////task nucleo 2 //////////////////////// 143 | 144 | void LoopOnProCpu(void *arg) { 145 | (void)arg; 146 | int packetSize = Udp.parsePacket(); 147 | if (packetSize) { 148 | 149 | //portENTER_CRITICAL_ISR(&timerMux); 150 | 151 | Udp.write(bufferin,sizeof(fdb)); 152 | Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); 153 | Udp.endPacket(); 154 | memcpy(&bufferin, &fdb, sizeof(fdb)); 155 | Udp.read(packetBuffer,sizeof(cmd)); 156 | memcpy(&cmd,packetBuffer,sizeof(cmd)); 157 | 158 | fdb.io = (REG_READ(GPIO_IN_REG)) ; 159 | fdb.io2 = (REG_READ(GPIO_IN1_REG)) ; 160 | 161 | // if (fdb.enc0 < 0){ 162 | // Serial.println (fdb.fb0); 163 | // } 164 | 165 | // if there's data available, read a packet 166 | 167 | //Serial.println (cmd.pos5); 168 | //fdb={fdbrt.fb0,fdbrt.fb1,fdbrt.fb2,fdbrt.fb3,fdbrt.fb4,fdbrt.io,fdbrt.io2,enc0}; 169 | //fdb={cmd.pos0,cmd.pos1,cmd.pos2,cmd.pos3,3}; 170 | 171 | 172 | 173 | 174 | //Serial.println (testch1); 175 | 176 | //////////////////////////////////////////////////////// 177 | steps_0_executed=0; 178 | steps_0_dir=cmd.pos0 - fdb.fb0; 179 | if(steps_0_dir > 0 && dir0 == -1 ){ 180 | REG_WRITE(GPIO_OUT_W1TC_REG, BIT12);//GPIO4 LOW (clear); 181 | dir0=1; 182 | steps_0_dir=0; 183 | 184 | } 185 | if(steps_0_dir < 0 && dir0 == 1 ){ 186 | 187 | REG_WRITE(GPIO_OUT_W1TS_REG, BIT12);//GPIO4 HIGH (clear); 188 | dir0=-1; 189 | steps_0_dir=0; 190 | 191 | } 192 | steps_0=abs(steps_0_dir); 193 | ///////////////////////////////////////////////////// 194 | steps_1_executed=0; 195 | steps_1_dir=cmd.pos1 - fdb.fb1; 196 | if(steps_1_dir > 0 && dir1 != 1 ){ 197 | REG_WRITE(GPIO_OUT_W1TC_REG, BIT13);//GPIO4 LOW (clear); 198 | steps_1_dir=0; 199 | dir1=1; 200 | } 201 | if(steps_1_dir < 0 && dir1 != -1 ){ 202 | 203 | REG_WRITE(GPIO_OUT_W1TS_REG, BIT13);//GPIO4 HIGH (clear); 204 | steps_1_dir=0; 205 | dir1=-1; 206 | } 207 | steps_1=abs(steps_1_dir); 208 | ///////////////////////////////////////////////////// 209 | steps_2_executed=0; 210 | steps_2_dir=cmd.pos2 - fdb.fb2; 211 | if(steps_2_dir > 0 && dir2 != 1 ){ 212 | steps_2_dir=0; 213 | REG_WRITE(GPIO_OUT_W1TC_REG, BIT14);//GPIO2 LOW (clear); 214 | dir2=1; 215 | } 216 | if(steps_2_dir < 0 && dir2 != -1 ){ 217 | steps_2_dir=0; 218 | REG_WRITE(GPIO_OUT_W1TS_REG, BIT14);//GPIO2 LOW (clear); 219 | dir2=-1; 220 | } 221 | steps_2=abs(steps_2_dir); 222 | //////////////////////////////////////////////////// 223 | steps_3_executed=0; 224 | steps_3_dir=cmd.pos3 - fdb.fb3; 225 | if(steps_3_dir > 0 && dir3 != 1 ){ 226 | REG_WRITE(GPIO_OUT_W1TC_REG, BIT14);//GPIO4 LOW (clear); 227 | steps_3_dir=0; 228 | dir3=1; 229 | } 230 | if(steps_3_dir < 0 && dir3 != -1 ){ 231 | 232 | REG_WRITE(GPIO_OUT_W1TS_REG, BIT14);//GPIO4 HIGH (clear); 233 | steps_3_dir=0; 234 | dir3=-1; 235 | } 236 | steps_3=abs(steps_3_dir); 237 | 238 | //portEXIT_CRITICAL_ISR(&timerMux); 239 | } 240 | } 241 | 242 | 243 | 244 | //////////////////////////////////////////////////////// 245 | /*######################### RMT configuration function ################################*/ 246 | void initRMT() { 247 | rmt_item32_t rmtItem[2]; 248 | rmt_config_t rmtConfig; 249 | rmtConfig.rmt_mode = RMT_MODE_TX; 250 | rmtConfig.clk_div = 20; 251 | rmtConfig.mem_block_num = 2; 252 | rmtConfig.tx_config.loop_en = false; 253 | rmtConfig.tx_config.carrier_en = 0; 254 | rmtConfig.tx_config.carrier_freq_hz = 0; 255 | rmtConfig.tx_config.carrier_duty_percent = 50; 256 | rmtConfig.tx_config.carrier_level = RMT_CARRIER_LEVEL_LOW; 257 | rmtConfig.tx_config.idle_output_en = true; 258 | 259 | 260 | rmtConfig.mem_block_num = 2; 261 | rmtConfig.tx_config.loop_en = false; 262 | rmtConfig.tx_config.carrier_en = 0; 263 | rmtConfig.tx_config.carrier_freq_hz = 0; 264 | 265 | //#ifdef STEP_PULSE_DELAY 266 | // rmtItem[0].duration0 = 4 * 2; 267 | //#else 268 | rmtItem[0].duration0 = 2; 269 | //#endif 270 | rmtItem[0].duration1 = 4 * 2; 271 | rmtItem[1].duration0 = 0; 272 | rmtItem[1].duration1 = 0; 273 | //AXIS 0 Config 274 | 275 | rmt_set_source_clk(RMT_CHANNEL_0, RMT_BASECLK_APB); 276 | rmtConfig.channel = RMT_CHANNEL_0; 277 | rmtConfig.tx_config.idle_level = RMT_IDLE_LEVEL_LOW; 278 | rmtConfig.gpio_num = GPIO_NUM_2; 279 | rmtItem[0].level0 = rmtConfig.tx_config.idle_level; 280 | rmtItem[0].level1 = !rmtConfig.tx_config.idle_level; 281 | rmt_config(&rmtConfig); 282 | rmt_fill_tx_items(rmtConfig.channel, &rmtItem[0], rmtConfig.mem_block_num, 0); 283 | 284 | 285 | //AXIS 1 Config 286 | 287 | rmt_set_source_clk(RMT_CHANNEL_1, RMT_BASECLK_APB); 288 | rmtConfig.channel = RMT_CHANNEL_1; 289 | rmtConfig.tx_config.idle_level = RMT_IDLE_LEVEL_LOW; 290 | rmtConfig.gpio_num = GPIO_NUM_4; 291 | rmtItem[0].level0 = rmtConfig.tx_config.idle_level; 292 | rmtItem[0].level1 = !rmtConfig.tx_config.idle_level; 293 | rmt_config(&rmtConfig); 294 | rmt_fill_tx_items(rmtConfig.channel, &rmtItem[0], rmtConfig.mem_block_num, 0); 295 | 296 | 297 | //AXIS 2 Config 298 | 299 | rmt_set_source_clk(RMT_CHANNEL_2, RMT_BASECLK_APB); 300 | rmtConfig.channel = RMT_CHANNEL_2; 301 | rmtConfig.tx_config.idle_level = RMT_IDLE_LEVEL_LOW; 302 | rmtConfig.gpio_num = GPIO_NUM_16; 303 | rmtItem[0].level0 = rmtConfig.tx_config.idle_level; 304 | rmtItem[0].level1 = !rmtConfig.tx_config.idle_level; 305 | rmt_config(&rmtConfig); 306 | rmt_fill_tx_items(rmtConfig.channel, &rmtItem[0], rmtConfig.mem_block_num, 0); 307 | 308 | //AXIS 3 Config 309 | 310 | rmt_set_source_clk(RMT_CHANNEL_3, RMT_BASECLK_APB); 311 | rmtConfig.channel = RMT_CHANNEL_3; 312 | rmtConfig.tx_config.idle_level = RMT_IDLE_LEVEL_LOW; 313 | rmtConfig.gpio_num = GPIO_NUM_16; 314 | rmtItem[0].level0 = rmtConfig.tx_config.idle_level; 315 | rmtItem[0].level1 = !rmtConfig.tx_config.idle_level; 316 | rmt_config(&rmtConfig); 317 | rmt_fill_tx_items(rmtConfig.channel, &rmtItem[0], rmtConfig.mem_block_num, 0); 318 | 319 | //AXIS 4 Config 320 | 321 | rmt_set_source_clk(RMT_CHANNEL_4, RMT_BASECLK_APB); 322 | rmtConfig.channel = RMT_CHANNEL_4; 323 | rmtConfig.tx_config.idle_level = RMT_IDLE_LEVEL_LOW; 324 | rmtConfig.gpio_num = GPIO_NUM_16; 325 | rmtItem[0].level0 = rmtConfig.tx_config.idle_level; 326 | rmtItem[0].level1 = !rmtConfig.tx_config.idle_level; 327 | rmt_config(&rmtConfig); 328 | rmt_fill_tx_items(rmtConfig.channel, &rmtItem[0], rmtConfig.mem_block_num, 0); 329 | 330 | //AXIS 5 Config 331 | 332 | rmt_set_source_clk(RMT_CHANNEL_5, RMT_BASECLK_APB); 333 | rmtConfig.channel = RMT_CHANNEL_5; 334 | rmtConfig.tx_config.idle_level = RMT_IDLE_LEVEL_LOW; 335 | rmtConfig.gpio_num = GPIO_NUM_16; 336 | rmtItem[0].level0 = rmtConfig.tx_config.idle_level; 337 | rmtItem[0].level1 = !rmtConfig.tx_config.idle_level; 338 | rmt_config(&rmtConfig); 339 | rmt_fill_tx_items(rmtConfig.channel, &rmtItem[0], rmtConfig.mem_block_num, 0); 340 | 341 | } 342 | 343 | 344 | 345 | 346 | //IRAM_ATTR static void onTime()(){ 347 | static void IRAM_ATTR onTime() { 348 | 349 | 350 | //portENTER_CRITICAL_ISR(&timerMux); 351 | if (steps_0_executed < steps_0) { 352 | RMT.conf_ch[RMT_CHANNEL_0].conf1.mem_rd_rst = 1; 353 | RMT.conf_ch[RMT_CHANNEL_0].conf1.tx_start = 1; 354 | steps_0_executed++; 355 | fdb.fb0=fdb.fb0+dir0; 356 | } 357 | 358 | 359 | if (steps_1_executed < steps_1) { 360 | RMT.conf_ch[RMT_CHANNEL_1].conf1.mem_rd_rst = 1; 361 | RMT.conf_ch[RMT_CHANNEL_1].conf1.tx_start = 1; 362 | steps_1_executed++; 363 | fdb.fb1=fdb.fb1+dir1; 364 | 365 | } 366 | if (steps_2_executed < steps_2) { 367 | RMT.conf_ch[RMT_CHANNEL_2].conf1.mem_rd_rst = 1; 368 | RMT.conf_ch[RMT_CHANNEL_2].conf1.tx_start = 1; 369 | steps_2_executed++; 370 | fdb.fb2=fdb.fb2+dir2; 371 | 372 | } 373 | /* 374 | if (steps_3_executed < steps_3) { 375 | RMT.conf_ch[RMT_CHANNEL_3].conf1.mem_rd_rst = 1; 376 | RMT.conf_ch[RMT_CHANNEL_3].conf1.tx_start = 1; 377 | steps_3_executed++; 378 | fdbrt.fb3=fdbrt.fb3+dir3; 379 | } 380 | 381 | 382 | 383 | 384 | if (steps_0_executed==steps_0 && steps_1_executed==steps_1 385 | && steps_2_executed==steps_2 && steps_3_executed==steps_3) 386 | { 387 | //fdbrt.fb0=fdbrt.fb0+steps_0_dir; 388 | 389 | // timerAlarmDisable(timer); 390 | //timerEnd(timer); 391 | //timer = NULL; 392 | } 393 | //*/ 394 | //portEXIT_CRITICAL_ISR(&timerMux); 395 | } 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | void setup() { 406 | 407 | 408 | 409 | //pinMode(4,OUTPUT); 410 | pinMode(12,OUTPUT); 411 | pinMode(13,OUTPUT); 412 | pinMode(26,INPUT); 413 | pinMode(25,INPUT); 414 | pinMode(33,INPUT); 415 | pinMode(32,INPUT); 416 | pinMode(35,INPUT); 417 | pinMode(34,INPUT); 418 | pinMode(39,INPUT); 419 | pinMode(36,INPUT); 420 | //REG_WRITE(GPIO_ENABLE_REG, BIT4);//Define o GPIO2 como saída 421 | //REG_WRITE(GPIO_ENABLE_REG, BIT15);//Define o GPIO2 como saída 422 | //REG_WRITE(GPIO_ENABLE_REG, BIT17);//Define o GPIO2 como saída 423 | 424 | /////////////////////// encoder /////////////////////////////// 425 | 426 | // Enable the weak pull up resistors 427 | ESP32Encoder::useInternalWeakPullResistors=UP; 428 | 429 | // Attache pins for use as encoder pins 430 | encoder.attachHalfQuad(15, 17); 431 | 432 | 433 | /////////////////////////////////////////////////////////////// 434 | 435 | 436 | 437 | initRMT(); 438 | 439 | /***************************************** Main timer stepper *****************/ 440 | 441 | //hw_timer_t * timer = NULL; 442 | portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; 443 | 444 | 445 | // Configure Prescaler to 80, as our timer runs @ 80Mhz 446 | // Giving an output of 80,000,000 / 80 = 1,000,000 ticks / second 447 | timer = timerBegin(0, 8, true); 448 | timerAttachInterrupt(timer, &onTime, true); 449 | // Fire Interrupt every 1m ticks, so 1s 450 | timerAlarmWrite(timer,35, true); 451 | timerAlarmEnable(timer); 452 | 453 | 454 | 455 | // You can use Ethernet.init(pin) to configure the CS pin 456 | 457 | Ethernet.init(5); // MKR ETH shield 458 | 459 | //*********************************// 460 | //Ethernet.setCsPin(5); // set Pin 3 for CS 461 | //Ethernet.setRstPin(27); // set Pin 4 for RST 462 | //*********************************// 463 | 464 | 465 | 466 | //pinMode(15, OUTPUT); 467 | //pinMode(2, OUTPUT); 468 | // start the Ethernet 469 | Ethernet.begin(mac, ip, sub); 470 | 471 | // Open serial communications and wait for port to open: 472 | Serial.begin(115200); 473 | while (!Serial) { 474 | ; // wait for serial port to connect. Needed for native USB port only 475 | } 476 | 477 | // Check for Ethernet hardware present 478 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 479 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 480 | while (true) { 481 | delay(1); // do nothing, no point running without Ethernet hardware 482 | } 483 | } 484 | if (Ethernet.linkStatus() == LinkOFF) { 485 | Serial.println("Ethernet cable is not connected."); 486 | } 487 | 488 | // start UDP 489 | Udp.begin(localPort); 490 | } 491 | 492 | IPAddress remote = Udp.remoteIP(); 493 | //////////////// LOOP//////////////////////////////////////////// 494 | void loop() { 495 | 496 | 497 | //fdbrt.fb0=cmd.pos0; 498 | //fdbrt.fb1=cmd.pos1; 499 | //fdbrt.fb2=cmd.pos2; 500 | 501 | 502 | //Serial.println(enc0); 503 | //Serial.println(steps_0); 504 | //timerAlarmWrite(timer, 1000, true); 505 | // timerAlarmEnable(timer); 506 | // 507 | 508 | 509 | 510 | //delayMicroseconds(20); 511 | enc0=encoder.getCount(); 512 | enc1=encoder.getCount(); 513 | enc2=encoder.getCount(); 514 | enc3=encoder.getCount(); 515 | 516 | //fdb.io = 517 | 518 | 519 | 520 | esp_ipc_call(PRO_CPU_NUM, LoopOnProCpu, NULL); 521 | } 522 | -------------------------------------------------------------------------------- /Ethernet-master/src/utility/w5100.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Paul Stoffregen 3 | * Copyright (c) 2010 by Cristian Maglie 4 | * 5 | * This file is free software; you can redistribute it and/or modify 6 | * it under the terms of either the GNU General Public License version 2 7 | * or the GNU Lesser General Public License version 2.1, both as 8 | * published by the Free Software Foundation. 9 | */ 10 | 11 | #include 12 | #include "Ethernet.h" 13 | #include "w5100.h" 14 | 15 | 16 | /***************************************************/ 17 | /** Default SS pin setting **/ 18 | /***************************************************/ 19 | 20 | // If variant.h or other headers specifically define the 21 | // default SS pin for ethernet, use it. 22 | #if defined(PIN_SPI_SS_ETHERNET_LIB) 23 | #define SS_PIN_DEFAULT PIN_SPI_SS_ETHERNET_LIB 24 | 25 | // MKR boards default to pin 5 for MKR ETH 26 | // Pins 8-10 are MOSI/SCK/MISO on MRK, so don't use pin 10 27 | #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) 28 | #define SS_PIN_DEFAULT 5 29 | 30 | // For boards using AVR, assume shields with SS on pin 10 31 | // will be used. This allows for Arduino Mega (where 32 | // SS is pin 53) and Arduino Leonardo (where SS is pin 17) 33 | // to work by default with Arduino Ethernet Shield R2 & R3. 34 | #elif defined(__AVR__) 35 | #define SS_PIN_DEFAULT 10 36 | 37 | // If variant.h or other headers define these names 38 | // use them if none of the other cases match 39 | #elif defined(PIN_SPI_SS) 40 | #define SS_PIN_DEFAULT PIN_SPI_SS 41 | #elif defined(CORE_SS0_PIN) 42 | #define SS_PIN_DEFAULT CORE_SS0_PIN 43 | 44 | // As a final fallback, use pin 10 45 | #else 46 | #define SS_PIN_DEFAULT 10 47 | #endif 48 | 49 | 50 | 51 | 52 | // W5100 controller instance 53 | uint8_t W5100Class::chip = 0; 54 | uint8_t W5100Class::CH_BASE_MSB; 55 | uint8_t W5100Class::ss_pin = SS_PIN_DEFAULT; 56 | #ifdef ETHERNET_LARGE_BUFFERS 57 | uint16_t W5100Class::SSIZE = 2048; 58 | uint16_t W5100Class::SMASK = 0x07FF; 59 | #endif 60 | W5100Class W5100; 61 | 62 | // pointers and bitmasks for optimized SS pin 63 | #if defined(__AVR__) 64 | volatile uint8_t * W5100Class::ss_pin_reg; 65 | uint8_t W5100Class::ss_pin_mask; 66 | #elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) 67 | volatile uint8_t * W5100Class::ss_pin_reg; 68 | #elif defined(__IMXRT1062__) 69 | volatile uint32_t * W5100Class::ss_pin_reg; 70 | uint32_t W5100Class::ss_pin_mask; 71 | #elif defined(__MKL26Z64__) 72 | volatile uint8_t * W5100Class::ss_pin_reg; 73 | uint8_t W5100Class::ss_pin_mask; 74 | #elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) 75 | volatile uint32_t * W5100Class::ss_pin_reg; 76 | uint32_t W5100Class::ss_pin_mask; 77 | #elif defined(__PIC32MX__) 78 | volatile uint32_t * W5100Class::ss_pin_reg; 79 | uint32_t W5100Class::ss_pin_mask; 80 | #elif defined(ARDUINO_ARCH_ESP8266) 81 | volatile uint32_t * W5100Class::ss_pin_reg; 82 | uint32_t W5100Class::ss_pin_mask; 83 | #elif defined(__SAMD21G18A__) 84 | volatile uint32_t * W5100Class::ss_pin_reg; 85 | uint32_t W5100Class::ss_pin_mask; 86 | #endif 87 | 88 | 89 | uint8_t W5100Class::init(void) 90 | { 91 | static bool initialized = false; 92 | uint8_t i; 93 | 94 | if (initialized) return 1; 95 | 96 | // Many Ethernet shields have a CAT811 or similar reset chip 97 | // connected to W5100 or W5200 chips. The W5200 will not work at 98 | // all, and may even drive its MISO pin, until given an active low 99 | // reset pulse! The CAT811 has a 240 ms typical pulse length, and 100 | // a 400 ms worst case maximum pulse length. MAX811 has a worst 101 | // case maximum 560 ms pulse length. This delay is meant to wait 102 | // until the reset pulse is ended. If your hardware has a shorter 103 | // reset time, this can be edited or removed. 104 | delay(560); 105 | //Serial.println("w5100 init"); 106 | 107 | SPI.begin(); 108 | initSS(); 109 | resetSS(); 110 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 111 | 112 | // Attempt W5200 detection first, because W5200 does not properly 113 | // reset its SPI state when CS goes high (inactive). Communication 114 | // from detecting the other chips can leave the W5200 in a state 115 | // where it won't recover, unless given a reset pulse. 116 | if (isW5200()) { 117 | CH_BASE_MSB = 0x40; 118 | #ifdef ETHERNET_LARGE_BUFFERS 119 | #if MAX_SOCK_NUM <= 1 120 | SSIZE = 16384; 121 | #elif MAX_SOCK_NUM <= 2 122 | SSIZE = 8192; 123 | #elif MAX_SOCK_NUM <= 4 124 | SSIZE = 4096; 125 | #else 126 | SSIZE = 2048; 127 | #endif 128 | SMASK = SSIZE - 1; 129 | #endif 130 | for (i=0; i> 10); 132 | writeSnTX_SIZE(i, SSIZE >> 10); 133 | } 134 | for (; i<8; i++) { 135 | writeSnRX_SIZE(i, 0); 136 | writeSnTX_SIZE(i, 0); 137 | } 138 | // Try W5500 next. Wiznet finally seems to have implemented 139 | // SPI well with this chip. It appears to be very resilient, 140 | // so try it after the fragile W5200 141 | } else if (isW5500()) { 142 | CH_BASE_MSB = 0x10; 143 | #ifdef ETHERNET_LARGE_BUFFERS 144 | #if MAX_SOCK_NUM <= 1 145 | SSIZE = 16384; 146 | #elif MAX_SOCK_NUM <= 2 147 | SSIZE = 8192; 148 | #elif MAX_SOCK_NUM <= 4 149 | SSIZE = 4096; 150 | #else 151 | SSIZE = 2048; 152 | #endif 153 | SMASK = SSIZE - 1; 154 | for (i=0; i> 10); 156 | writeSnTX_SIZE(i, SSIZE >> 10); 157 | } 158 | for (; i<8; i++) { 159 | writeSnRX_SIZE(i, 0); 160 | writeSnTX_SIZE(i, 0); 161 | } 162 | #endif 163 | // Try W5100 last. This simple chip uses fixed 4 byte frames 164 | // for every 8 bit access. Terribly inefficient, but so simple 165 | // it recovers from "hearing" unsuccessful W5100 or W5200 166 | // communication. W5100 is also the only chip without a VERSIONR 167 | // register for identification, so we check this last. 168 | } else if (isW5100()) { 169 | CH_BASE_MSB = 0x04; 170 | #ifdef ETHERNET_LARGE_BUFFERS 171 | #if MAX_SOCK_NUM <= 1 172 | SSIZE = 8192; 173 | writeTMSR(0x03); 174 | writeRMSR(0x03); 175 | #elif MAX_SOCK_NUM <= 2 176 | SSIZE = 4096; 177 | writeTMSR(0x0A); 178 | writeRMSR(0x0A); 179 | #else 180 | SSIZE = 2048; 181 | writeTMSR(0x55); 182 | writeRMSR(0x55); 183 | #endif 184 | SMASK = SSIZE - 1; 185 | #else 186 | writeTMSR(0x55); 187 | writeRMSR(0x55); 188 | #endif 189 | // No hardware seems to be present. Or it could be a W5200 190 | // that's heard other SPI communication if its chip select 191 | // pin wasn't high when a SD card or other SPI chip was used. 192 | } else { 193 | //Serial.println("no chip :-("); 194 | chip = 0; 195 | SPI.endTransaction(); 196 | return 0; // no known chip is responding :-( 197 | } 198 | SPI.endTransaction(); 199 | initialized = true; 200 | return 1; // successful init 201 | } 202 | 203 | // Soft reset the Wiznet chip, by writing to its MR register reset bit 204 | uint8_t W5100Class::softReset(void) 205 | { 206 | uint16_t count=0; 207 | 208 | //Serial.println("Wiznet soft reset"); 209 | // write to reset bit 210 | writeMR(0x80); 211 | // then wait for soft reset to complete 212 | do { 213 | uint8_t mr = readMR(); 214 | //Serial.print("mr="); 215 | //Serial.println(mr, HEX); 216 | if (mr == 0) return 1; 217 | delay(1); 218 | } while (++count < 20); 219 | return 0; 220 | } 221 | 222 | uint8_t W5100Class::isW5100(void) 223 | { 224 | chip = 51; 225 | //Serial.println("w5100.cpp: detect W5100 chip"); 226 | if (!softReset()) return 0; 227 | writeMR(0x10); 228 | if (readMR() != 0x10) return 0; 229 | writeMR(0x12); 230 | if (readMR() != 0x12) return 0; 231 | writeMR(0x00); 232 | if (readMR() != 0x00) return 0; 233 | //Serial.println("chip is W5100"); 234 | return 1; 235 | } 236 | 237 | uint8_t W5100Class::isW5200(void) 238 | { 239 | chip = 52; 240 | //Serial.println("w5100.cpp: detect W5200 chip"); 241 | if (!softReset()) return 0; 242 | writeMR(0x08); 243 | if (readMR() != 0x08) return 0; 244 | writeMR(0x10); 245 | if (readMR() != 0x10) return 0; 246 | writeMR(0x00); 247 | if (readMR() != 0x00) return 0; 248 | int ver = readVERSIONR_W5200(); 249 | //Serial.print("version="); 250 | //Serial.println(ver); 251 | if (ver != 3) return 0; 252 | //Serial.println("chip is W5200"); 253 | return 1; 254 | } 255 | 256 | uint8_t W5100Class::isW5500(void) 257 | { 258 | chip = 55; 259 | //Serial.println("w5100.cpp: detect W5500 chip"); 260 | if (!softReset()) return 0; 261 | writeMR(0x08); 262 | if (readMR() != 0x08) return 0; 263 | writeMR(0x10); 264 | if (readMR() != 0x10) return 0; 265 | writeMR(0x00); 266 | if (readMR() != 0x00) return 0; 267 | int ver = readVERSIONR_W5500(); 268 | //Serial.print("version="); 269 | //Serial.println(ver); 270 | if (ver != 4) return 0; 271 | //Serial.println("chip is W5500"); 272 | return 1; 273 | } 274 | 275 | W5100Linkstatus W5100Class::getLinkStatus() 276 | { 277 | uint8_t phystatus; 278 | 279 | if (!init()) return UNKNOWN; 280 | switch (chip) { 281 | case 52: 282 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 283 | phystatus = readPSTATUS_W5200(); 284 | SPI.endTransaction(); 285 | if (phystatus & 0x20) return LINK_ON; 286 | return LINK_OFF; 287 | case 55: 288 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 289 | phystatus = readPHYCFGR_W5500(); 290 | SPI.endTransaction(); 291 | if (phystatus & 0x01) return LINK_ON; 292 | return LINK_OFF; 293 | default: 294 | return UNKNOWN; 295 | } 296 | } 297 | 298 | uint16_t W5100Class::write(uint16_t addr, const uint8_t *buf, uint16_t len) 299 | { 300 | uint8_t cmd[8]; 301 | 302 | if (chip == 51) { 303 | for (uint16_t i=0; i> 8); 307 | SPI.transfer(addr & 0xFF); 308 | addr++; 309 | SPI.transfer(buf[i]); 310 | resetSS(); 311 | } 312 | } else if (chip == 52) { 313 | setSS(); 314 | cmd[0] = addr >> 8; 315 | cmd[1] = addr & 0xFF; 316 | cmd[2] = ((len >> 8) & 0x7F) | 0x80; 317 | cmd[3] = len & 0xFF; 318 | SPI.transfer(cmd, 4); 319 | #ifdef SPI_HAS_TRANSFER_BUF 320 | SPI.transfer(buf, NULL, len); 321 | #else 322 | // TODO: copy 8 bytes at a time to cmd[] and block transfer 323 | for (uint16_t i=0; i < len; i++) { 324 | SPI.transfer(buf[i]); 325 | } 326 | #endif 327 | resetSS(); 328 | } else { // chip == 55 329 | setSS(); 330 | if (addr < 0x100) { 331 | // common registers 00nn 332 | cmd[0] = 0; 333 | cmd[1] = addr & 0xFF; 334 | cmd[2] = 0x04; 335 | } else if (addr < 0x8000) { 336 | // socket registers 10nn, 11nn, 12nn, 13nn, etc 337 | cmd[0] = 0; 338 | cmd[1] = addr & 0xFF; 339 | cmd[2] = ((addr >> 3) & 0xE0) | 0x0C; 340 | } else if (addr < 0xC000) { 341 | // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc 342 | // 10## #nnn nnnn nnnn 343 | cmd[0] = addr >> 8; 344 | cmd[1] = addr & 0xFF; 345 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 346 | cmd[2] = 0x14; // 16K buffers 347 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 348 | cmd[2] = ((addr >> 8) & 0x20) | 0x14; // 8K buffers 349 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 350 | cmd[2] = ((addr >> 7) & 0x60) | 0x14; // 4K buffers 351 | #else 352 | cmd[2] = ((addr >> 6) & 0xE0) | 0x14; // 2K buffers 353 | #endif 354 | } else { 355 | // receive buffers 356 | cmd[0] = addr >> 8; 357 | cmd[1] = addr & 0xFF; 358 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 359 | cmd[2] = 0x1C; // 16K buffers 360 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 361 | cmd[2] = ((addr >> 8) & 0x20) | 0x1C; // 8K buffers 362 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 363 | cmd[2] = ((addr >> 7) & 0x60) | 0x1C; // 4K buffers 364 | #else 365 | cmd[2] = ((addr >> 6) & 0xE0) | 0x1C; // 2K buffers 366 | #endif 367 | } 368 | if (len <= 5) { 369 | for (uint8_t i=0; i < len; i++) { 370 | cmd[i + 3] = buf[i]; 371 | } 372 | SPI.transfer(cmd, len + 3); 373 | } else { 374 | SPI.transfer(cmd, 3); 375 | #ifdef SPI_HAS_TRANSFER_BUF 376 | SPI.transfer(buf, NULL, len); 377 | #else 378 | // TODO: copy 8 bytes at a time to cmd[] and block transfer 379 | for (uint16_t i=0; i < len; i++) { 380 | SPI.transfer(buf[i]); 381 | } 382 | #endif 383 | } 384 | resetSS(); 385 | } 386 | return len; 387 | } 388 | 389 | uint16_t W5100Class::read(uint16_t addr, uint8_t *buf, uint16_t len) 390 | { 391 | uint8_t cmd[4]; 392 | 393 | if (chip == 51) { 394 | for (uint16_t i=0; i < len; i++) { 395 | setSS(); 396 | #if 1 397 | SPI.transfer(0x0F); 398 | SPI.transfer(addr >> 8); 399 | SPI.transfer(addr & 0xFF); 400 | addr++; 401 | buf[i] = SPI.transfer(0); 402 | #else 403 | cmd[0] = 0x0F; 404 | cmd[1] = addr >> 8; 405 | cmd[2] = addr & 0xFF; 406 | cmd[3] = 0; 407 | SPI.transfer(cmd, 4); // TODO: why doesn't this work? 408 | buf[i] = cmd[3]; 409 | addr++; 410 | #endif 411 | resetSS(); 412 | } 413 | } else if (chip == 52) { 414 | setSS(); 415 | cmd[0] = addr >> 8; 416 | cmd[1] = addr & 0xFF; 417 | cmd[2] = (len >> 8) & 0x7F; 418 | cmd[3] = len & 0xFF; 419 | SPI.transfer(cmd, 4); 420 | memset(buf, 0, len); 421 | SPI.transfer(buf, len); 422 | resetSS(); 423 | } else { // chip == 55 424 | setSS(); 425 | if (addr < 0x100) { 426 | // common registers 00nn 427 | cmd[0] = 0; 428 | cmd[1] = addr & 0xFF; 429 | cmd[2] = 0x00; 430 | } else if (addr < 0x8000) { 431 | // socket registers 10nn, 11nn, 12nn, 13nn, etc 432 | cmd[0] = 0; 433 | cmd[1] = addr & 0xFF; 434 | cmd[2] = ((addr >> 3) & 0xE0) | 0x08; 435 | } else if (addr < 0xC000) { 436 | // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc 437 | // 10## #nnn nnnn nnnn 438 | cmd[0] = addr >> 8; 439 | cmd[1] = addr & 0xFF; 440 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 441 | cmd[2] = 0x10; // 16K buffers 442 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 443 | cmd[2] = ((addr >> 8) & 0x20) | 0x10; // 8K buffers 444 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 445 | cmd[2] = ((addr >> 7) & 0x60) | 0x10; // 4K buffers 446 | #else 447 | cmd[2] = ((addr >> 6) & 0xE0) | 0x10; // 2K buffers 448 | #endif 449 | } else { 450 | // receive buffers 451 | cmd[0] = addr >> 8; 452 | cmd[1] = addr & 0xFF; 453 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 454 | cmd[2] = 0x18; // 16K buffers 455 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 456 | cmd[2] = ((addr >> 8) & 0x20) | 0x18; // 8K buffers 457 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 458 | cmd[2] = ((addr >> 7) & 0x60) | 0x18; // 4K buffers 459 | #else 460 | cmd[2] = ((addr >> 6) & 0xE0) | 0x18; // 2K buffers 461 | #endif 462 | } 463 | SPI.transfer(cmd, 3); 464 | memset(buf, 0, len); 465 | SPI.transfer(buf, len); 466 | resetSS(); 467 | } 468 | return len; 469 | } 470 | 471 | void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) 472 | { 473 | // Send command to socket 474 | writeSnCR(s, _cmd); 475 | // Wait for command to complete 476 | while (readSnCR(s)) ; 477 | } 478 | --------------------------------------------------------------------------------