From 4bfbbb3484cbc8ffccb90609e59a04796f618470 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Wed, 26 Jun 2013 19:13:04 +0200 Subject: Ethernet, SD and LiquidCrystal to the new library format --- libraries/Ethernet/Dhcp.cpp | 480 --------------------- libraries/Ethernet/Dhcp.h | 178 -------- libraries/Ethernet/Dns.cpp | 423 ------------------ libraries/Ethernet/Dns.h | 41 -- libraries/Ethernet/Ethernet.cpp | 122 ------ libraries/Ethernet/Ethernet.h | 41 -- libraries/Ethernet/EthernetClient.cpp | 165 ------- libraries/Ethernet/EthernetClient.h | 37 -- libraries/Ethernet/EthernetServer.cpp | 91 ---- libraries/Ethernet/EthernetServer.h | 22 - libraries/Ethernet/EthernetUdp.cpp | 218 ---------- libraries/Ethernet/EthernetUdp.h | 99 ----- .../BarometricPressureWebServer.ino | 222 ---------- .../Ethernet/examples/ChatServer/ChatServer.ino | 79 ---- .../Ethernet/examples/CosmClient/CosmClient.ino | 161 ------- .../examples/CosmClientString/CosmClientString.ino | 146 ------- .../DhcpAddressPrinter/DhcpAddressPrinter.ino | 59 --- .../examples/DhcpChatServer/DhcpChatServer.ino | 87 ---- .../examples/PachubeClient/PachubeClient.ino | 163 ------- .../PachubeClientString/PachubeClientString.ino | 152 ------- .../examples/TelnetClient/TelnetClient.ino | 93 ---- .../examples/TwitterClient/TwitterClient.ino | 136 ------ .../UDPSendReceiveString/UDPSendReceiveString.ino | 118 ----- .../examples/UdpNtpClient/UdpNtpClient.ino | 141 ------ .../Ethernet/examples/WebClient/WebClient.ino | 88 ---- .../WebClientRepeating/WebClientRepeating.ino | 111 ----- .../Ethernet/examples/WebServer/WebServer.ino | 100 ----- libraries/Ethernet/keywords.txt | 37 -- libraries/Ethernet/util.h | 13 - libraries/Ethernet/utility/socket.cpp | 400 ----------------- libraries/Ethernet/utility/socket.h | 41 -- libraries/Ethernet/utility/w5100.cpp | 188 -------- libraries/Ethernet/utility/w5100.h | 404 ----------------- 33 files changed, 4856 deletions(-) delete mode 100644 libraries/Ethernet/Dhcp.cpp delete mode 100644 libraries/Ethernet/Dhcp.h delete mode 100644 libraries/Ethernet/Dns.cpp delete mode 100644 libraries/Ethernet/Dns.h delete mode 100644 libraries/Ethernet/Ethernet.cpp delete mode 100644 libraries/Ethernet/Ethernet.h delete mode 100644 libraries/Ethernet/EthernetClient.cpp delete mode 100644 libraries/Ethernet/EthernetClient.h delete mode 100644 libraries/Ethernet/EthernetServer.cpp delete mode 100644 libraries/Ethernet/EthernetServer.h delete mode 100644 libraries/Ethernet/EthernetUdp.cpp delete mode 100644 libraries/Ethernet/EthernetUdp.h delete mode 100644 libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino delete mode 100644 libraries/Ethernet/examples/ChatServer/ChatServer.ino delete mode 100644 libraries/Ethernet/examples/CosmClient/CosmClient.ino delete mode 100644 libraries/Ethernet/examples/CosmClientString/CosmClientString.ino delete mode 100644 libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino delete mode 100644 libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino delete mode 100644 libraries/Ethernet/examples/PachubeClient/PachubeClient.ino delete mode 100644 libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino delete mode 100644 libraries/Ethernet/examples/TelnetClient/TelnetClient.ino delete mode 100644 libraries/Ethernet/examples/TwitterClient/TwitterClient.ino delete mode 100644 libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino delete mode 100644 libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino delete mode 100644 libraries/Ethernet/examples/WebClient/WebClient.ino delete mode 100644 libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino delete mode 100644 libraries/Ethernet/examples/WebServer/WebServer.ino delete mode 100644 libraries/Ethernet/keywords.txt delete mode 100644 libraries/Ethernet/util.h delete mode 100644 libraries/Ethernet/utility/socket.cpp delete mode 100644 libraries/Ethernet/utility/socket.h delete mode 100644 libraries/Ethernet/utility/w5100.cpp delete mode 100644 libraries/Ethernet/utility/w5100.h diff --git a/libraries/Ethernet/Dhcp.cpp b/libraries/Ethernet/Dhcp.cpp deleted file mode 100644 index 56d5b69..0000000 --- a/libraries/Ethernet/Dhcp.cpp +++ /dev/null @@ -1,480 +0,0 @@ -// DHCP Library v0.3 - April 25, 2009 -// Author: Jordan Terrell - blog.jordanterrell.com - -#include "w5100.h" - -#include -#include -#include "Dhcp.h" -#include "Arduino.h" -#include "util.h" - -int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) -{ - _dhcpLeaseTime=0; - _dhcpT1=0; - _dhcpT2=0; - _lastCheck=0; - _timeout = timeout; - _responseTimeout = responseTimeout; - - // zero out _dhcpMacAddr - memset(_dhcpMacAddr, 0, 6); - reset_DHCP_lease(); - - memcpy((void*)_dhcpMacAddr, (void*)mac, 6); - _dhcp_state = STATE_DHCP_START; - return request_DHCP_lease(); -} - -void DhcpClass::reset_DHCP_lease(){ - // zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp - memset(_dhcpLocalIp, 0, 20); -} - -//return:0 on error, 1 if request is sent and response is received -int DhcpClass::request_DHCP_lease(){ - - uint8_t messageType = 0; - - - - // Pick an initial transaction ID - _dhcpTransactionId = random(1UL, 2000UL); - _dhcpInitialTransactionId = _dhcpTransactionId; - - _dhcpUdpSocket.stop(); - if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0) - { - // Couldn't get a socket - return 0; - } - - presend_DHCP(); - - int result = 0; - - unsigned long startTime = millis(); - - while(_dhcp_state != STATE_DHCP_LEASED) - { - if(_dhcp_state == STATE_DHCP_START) - { - _dhcpTransactionId++; - - send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000)); - _dhcp_state = STATE_DHCP_DISCOVER; - } - else if(_dhcp_state == STATE_DHCP_REREQUEST){ - _dhcpTransactionId++; - send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000)); - _dhcp_state = STATE_DHCP_REQUEST; - } - else if(_dhcp_state == STATE_DHCP_DISCOVER) - { - uint32_t respId; - messageType = parseDHCPResponse(_responseTimeout, respId); - if(messageType == DHCP_OFFER) - { - // We'll use the transaction ID that the offer came with, - // rather than the one we were up to - _dhcpTransactionId = respId; - send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000)); - _dhcp_state = STATE_DHCP_REQUEST; - } - } - else if(_dhcp_state == STATE_DHCP_REQUEST) - { - uint32_t respId; - messageType = parseDHCPResponse(_responseTimeout, respId); - if(messageType == DHCP_ACK) - { - _dhcp_state = STATE_DHCP_LEASED; - result = 1; - //use default lease time if we didn't get it - if(_dhcpLeaseTime == 0){ - _dhcpLeaseTime = DEFAULT_LEASE; - } - //calculate T1 & T2 if we didn't get it - if(_dhcpT1 == 0){ - //T1 should be 50% of _dhcpLeaseTime - _dhcpT1 = _dhcpLeaseTime >> 1; - } - if(_dhcpT2 == 0){ - //T2 should be 87.5% (7/8ths) of _dhcpLeaseTime - _dhcpT2 = _dhcpT1 << 1; - } - _renewInSec = _dhcpT1; - _rebindInSec = _dhcpT2; - } - else if(messageType == DHCP_NAK) - _dhcp_state = STATE_DHCP_START; - } - - if(messageType == 255) - { - messageType = 0; - _dhcp_state = STATE_DHCP_START; - } - - if(result != 1 && ((millis() - startTime) > _timeout)) - break; - } - - // We're done with the socket now - _dhcpUdpSocket.stop(); - _dhcpTransactionId++; - - return result; -} - -void DhcpClass::presend_DHCP() -{ -} - -void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed) -{ - uint8_t buffer[32]; - memset(buffer, 0, 32); - IPAddress dest_addr( 255, 255, 255, 255 ); // Broadcast address - - if (-1 == _dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT)) - { - // FIXME Need to return errors - return; - } - - buffer[0] = DHCP_BOOTREQUEST; // op - buffer[1] = DHCP_HTYPE10MB; // htype - buffer[2] = DHCP_HLENETHERNET; // hlen - buffer[3] = DHCP_HOPS; // hops - - // xid - unsigned long xid = htonl(_dhcpTransactionId); - memcpy(buffer + 4, &(xid), 4); - - // 8, 9 - seconds elapsed - buffer[8] = ((secondsElapsed & 0xff00) >> 8); - buffer[9] = (secondsElapsed & 0x00ff); - - // flags - unsigned short flags = htons(DHCP_FLAGSBROADCAST); - memcpy(buffer + 10, &(flags), 2); - - // ciaddr: already zeroed - // yiaddr: already zeroed - // siaddr: already zeroed - // giaddr: already zeroed - - //put data in W5100 transmit buffer - _dhcpUdpSocket.write(buffer, 28); - - memset(buffer, 0, 32); // clear local buffer - - memcpy(buffer, _dhcpMacAddr, 6); // chaddr - - //put data in W5100 transmit buffer - _dhcpUdpSocket.write(buffer, 16); - - memset(buffer, 0, 32); // clear local buffer - - // leave zeroed out for sname && file - // put in W5100 transmit buffer x 6 (192 bytes) - - for(int i = 0; i < 6; i++) { - _dhcpUdpSocket.write(buffer, 32); - } - - // OPT - Magic Cookie - buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF); - buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF); - buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF); - buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF); - - // OPT - message type - buffer[4] = dhcpMessageType; - buffer[5] = 0x01; - buffer[6] = messageType; //DHCP_REQUEST; - - // OPT - client identifier - buffer[7] = dhcpClientIdentifier; - buffer[8] = 0x07; - buffer[9] = 0x01; - memcpy(buffer + 10, _dhcpMacAddr, 6); - - // OPT - host name - buffer[16] = hostName; - buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address - strcpy((char*)&(buffer[18]), HOST_NAME); - - printByte((char*)&(buffer[24]), _dhcpMacAddr[3]); - printByte((char*)&(buffer[26]), _dhcpMacAddr[4]); - printByte((char*)&(buffer[28]), _dhcpMacAddr[5]); - - //put data in W5100 transmit buffer - _dhcpUdpSocket.write(buffer, 30); - - if(messageType == DHCP_REQUEST) - { - buffer[0] = dhcpRequestedIPaddr; - buffer[1] = 0x04; - buffer[2] = _dhcpLocalIp[0]; - buffer[3] = _dhcpLocalIp[1]; - buffer[4] = _dhcpLocalIp[2]; - buffer[5] = _dhcpLocalIp[3]; - - buffer[6] = dhcpServerIdentifier; - buffer[7] = 0x04; - buffer[8] = _dhcpDhcpServerIp[0]; - buffer[9] = _dhcpDhcpServerIp[1]; - buffer[10] = _dhcpDhcpServerIp[2]; - buffer[11] = _dhcpDhcpServerIp[3]; - - //put data in W5100 transmit buffer - _dhcpUdpSocket.write(buffer, 12); - } - - buffer[0] = dhcpParamRequest; - buffer[1] = 0x06; - buffer[2] = subnetMask; - buffer[3] = routersOnSubnet; - buffer[4] = dns; - buffer[5] = domainName; - buffer[6] = dhcpT1value; - buffer[7] = dhcpT2value; - buffer[8] = endOption; - - //put data in W5100 transmit buffer - _dhcpUdpSocket.write(buffer, 9); - - _dhcpUdpSocket.endPacket(); -} - -uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId) -{ - uint8_t type = 0; - uint8_t opt_len = 0; - - unsigned long startTime = millis(); - - while(_dhcpUdpSocket.parsePacket() <= 0) - { - if((millis() - startTime) > responseTimeout) - { - return 255; - } - delay(50); - } - // start reading in the packet - RIP_MSG_FIXED fixedMsg; - _dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED)); - - if(fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT) - { - transactionId = ntohl(fixedMsg.xid); - if(memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || (transactionId < _dhcpInitialTransactionId) || (transactionId > _dhcpTransactionId)) - { - // Need to read the rest of the packet here regardless - _dhcpUdpSocket.flush(); - return 0; - } - - memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4); - - // Skip to the option part - // Doing this a byte at a time so we don't have to put a big buffer - // on the stack (as we don't have lots of memory lying around) - for (int i =0; i < (240 - (int)sizeof(RIP_MSG_FIXED)); i++) - { - _dhcpUdpSocket.read(); // we don't care about the returned byte - } - - while (_dhcpUdpSocket.available() > 0) - { - switch (_dhcpUdpSocket.read()) - { - case endOption : - break; - - case padOption : - break; - - case dhcpMessageType : - opt_len = _dhcpUdpSocket.read(); - type = _dhcpUdpSocket.read(); - break; - - case subnetMask : - opt_len = _dhcpUdpSocket.read(); - _dhcpUdpSocket.read(_dhcpSubnetMask, 4); - break; - - case routersOnSubnet : - opt_len = _dhcpUdpSocket.read(); - _dhcpUdpSocket.read(_dhcpGatewayIp, 4); - for (int i = 0; i < opt_len-4; i++) - { - _dhcpUdpSocket.read(); - } - break; - - case dns : - opt_len = _dhcpUdpSocket.read(); - _dhcpUdpSocket.read(_dhcpDnsServerIp, 4); - for (int i = 0; i < opt_len-4; i++) - { - _dhcpUdpSocket.read(); - } - break; - - case dhcpServerIdentifier : - opt_len = _dhcpUdpSocket.read(); - if( *((uint32_t*)_dhcpDhcpServerIp) == 0 || - IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) - { - _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp)); - } - else - { - // Skip over the rest of this option - while (opt_len--) - { - _dhcpUdpSocket.read(); - } - } - break; - - case dhcpT1value : - opt_len = _dhcpUdpSocket.read(); - _dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1)); - _dhcpT1 = ntohl(_dhcpT1); - break; - - case dhcpT2value : - opt_len = _dhcpUdpSocket.read(); - _dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2)); - _dhcpT2 = ntohl(_dhcpT2); - break; - - case dhcpIPaddrLeaseTime : - opt_len = _dhcpUdpSocket.read(); - _dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime)); - _dhcpLeaseTime = ntohl(_dhcpLeaseTime); - _renewInSec = _dhcpLeaseTime; - break; - - default : - opt_len = _dhcpUdpSocket.read(); - // Skip over the rest of this option - while (opt_len--) - { - _dhcpUdpSocket.read(); - } - break; - } - } - } - - // Need to skip to end of the packet regardless here - _dhcpUdpSocket.flush(); - - return type; -} - - -/* - returns: - 0/DHCP_CHECK_NONE: nothing happened - 1/DHCP_CHECK_RENEW_FAIL: renew failed - 2/DHCP_CHECK_RENEW_OK: renew success - 3/DHCP_CHECK_REBIND_FAIL: rebind fail - 4/DHCP_CHECK_REBIND_OK: rebind success -*/ -int DhcpClass::checkLease(){ - //this uses a signed / unsigned trick to deal with millis overflow - unsigned long now = millis(); - signed long snow = (long)now; - int rc=DHCP_CHECK_NONE; - if (_lastCheck != 0){ - signed long factor; - //calc how many ms past the timeout we are - factor = snow - (long)_secTimeout; - //if on or passed the timeout, reduce the counters - if ( factor >= 0 ){ - //next timeout should be now plus 1000 ms minus parts of second in factor - _secTimeout = snow + 1000 - factor % 1000; - //how many seconds late are we, minimum 1 - factor = factor / 1000 +1; - - //reduce the counters by that mouch - //if we can assume that the cycle time (factor) is fairly constant - //and if the remainder is less than cycle time * 2 - //do it early instead of late - if(_renewInSec < factor*2 ) - _renewInSec = 0; - else - _renewInSec -= factor; - - if(_rebindInSec < factor*2 ) - _rebindInSec = 0; - else - _rebindInSec -= factor; - } - - //if we have a lease but should renew, do it - if (_dhcp_state == STATE_DHCP_LEASED && _renewInSec <=0){ - _dhcp_state = STATE_DHCP_REREQUEST; - rc = 1 + request_DHCP_lease(); - } - - //if we have a lease or is renewing but should bind, do it - if( (_dhcp_state == STATE_DHCP_LEASED || _dhcp_state == STATE_DHCP_START) && _rebindInSec <=0){ - //this should basically restart completely - _dhcp_state = STATE_DHCP_START; - reset_DHCP_lease(); - rc = 3 + request_DHCP_lease(); - } - } - else{ - _secTimeout = snow + 1000; - } - - _lastCheck = now; - return rc; -} - -IPAddress DhcpClass::getLocalIp() -{ - return IPAddress(_dhcpLocalIp); -} - -IPAddress DhcpClass::getSubnetMask() -{ - return IPAddress(_dhcpSubnetMask); -} - -IPAddress DhcpClass::getGatewayIp() -{ - return IPAddress(_dhcpGatewayIp); -} - -IPAddress DhcpClass::getDhcpServerIp() -{ - return IPAddress(_dhcpDhcpServerIp); -} - -IPAddress DhcpClass::getDnsServerIp() -{ - return IPAddress(_dhcpDnsServerIp); -} - -void DhcpClass::printByte(char * buf, uint8_t n ) { - char *str = &buf[1]; - buf[0]='0'; - do { - unsigned long m = n; - n /= 16; - char c = m - 16 * n; - *str-- = c < 10 ? c + '0' : c + 'A' - 10; - } while(n); -} diff --git a/libraries/Ethernet/Dhcp.h b/libraries/Ethernet/Dhcp.h deleted file mode 100644 index 4a47936..0000000 --- a/libraries/Ethernet/Dhcp.h +++ /dev/null @@ -1,178 +0,0 @@ -// DHCP Library v0.3 - April 25, 2009 -// Author: Jordan Terrell - blog.jordanterrell.com - -#ifndef Dhcp_h -#define Dhcp_h - -#include "EthernetUdp.h" - -/* DHCP state machine. */ -#define STATE_DHCP_START 0 -#define STATE_DHCP_DISCOVER 1 -#define STATE_DHCP_REQUEST 2 -#define STATE_DHCP_LEASED 3 -#define STATE_DHCP_REREQUEST 4 -#define STATE_DHCP_RELEASE 5 - -#define DHCP_FLAGSBROADCAST 0x8000 - -/* UDP port numbers for DHCP */ -#define DHCP_SERVER_PORT 67 /* from server to client */ -#define DHCP_CLIENT_PORT 68 /* from client to server */ - -/* DHCP message OP code */ -#define DHCP_BOOTREQUEST 1 -#define DHCP_BOOTREPLY 2 - -/* DHCP message type */ -#define DHCP_DISCOVER 1 -#define DHCP_OFFER 2 -#define DHCP_REQUEST 3 -#define DHCP_DECLINE 4 -#define DHCP_ACK 5 -#define DHCP_NAK 6 -#define DHCP_RELEASE 7 -#define DHCP_INFORM 8 - -#define DHCP_HTYPE10MB 1 -#define DHCP_HTYPE100MB 2 - -#define DHCP_HLENETHERNET 6 -#define DHCP_HOPS 0 -#define DHCP_SECS 0 - -#define MAGIC_COOKIE 0x63825363 -#define MAX_DHCP_OPT 16 - -#define HOST_NAME "WIZnet" -#define DEFAULT_LEASE (900) //default lease time in seconds - -#define DHCP_CHECK_NONE (0) -#define DHCP_CHECK_RENEW_FAIL (1) -#define DHCP_CHECK_RENEW_OK (2) -#define DHCP_CHECK_REBIND_FAIL (3) -#define DHCP_CHECK_REBIND_OK (4) - -enum -{ - padOption = 0, - subnetMask = 1, - timerOffset = 2, - routersOnSubnet = 3, - /* timeServer = 4, - nameServer = 5,*/ - dns = 6, - /*logServer = 7, - cookieServer = 8, - lprServer = 9, - impressServer = 10, - resourceLocationServer = 11,*/ - hostName = 12, - /*bootFileSize = 13, - meritDumpFile = 14,*/ - domainName = 15, - /*swapServer = 16, - rootPath = 17, - extentionsPath = 18, - IPforwarding = 19, - nonLocalSourceRouting = 20, - policyFilter = 21, - maxDgramReasmSize = 22, - defaultIPTTL = 23, - pathMTUagingTimeout = 24, - pathMTUplateauTable = 25, - ifMTU = 26, - allSubnetsLocal = 27, - broadcastAddr = 28, - performMaskDiscovery = 29, - maskSupplier = 30, - performRouterDiscovery = 31, - routerSolicitationAddr = 32, - staticRoute = 33, - trailerEncapsulation = 34, - arpCacheTimeout = 35, - ethernetEncapsulation = 36, - tcpDefaultTTL = 37, - tcpKeepaliveInterval = 38, - tcpKeepaliveGarbage = 39, - nisDomainName = 40, - nisServers = 41, - ntpServers = 42, - vendorSpecificInfo = 43, - netBIOSnameServer = 44, - netBIOSdgramDistServer = 45, - netBIOSnodeType = 46, - netBIOSscope = 47, - xFontServer = 48, - xDisplayManager = 49,*/ - dhcpRequestedIPaddr = 50, - dhcpIPaddrLeaseTime = 51, - /*dhcpOptionOverload = 52,*/ - dhcpMessageType = 53, - dhcpServerIdentifier = 54, - dhcpParamRequest = 55, - /*dhcpMsg = 56, - dhcpMaxMsgSize = 57,*/ - dhcpT1value = 58, - dhcpT2value = 59, - /*dhcpClassIdentifier = 60,*/ - dhcpClientIdentifier = 61, - endOption = 255 -}; - -typedef struct _RIP_MSG_FIXED -{ - uint8_t op; - uint8_t htype; - uint8_t hlen; - uint8_t hops; - uint32_t xid; - uint16_t secs; - uint16_t flags; - uint8_t ciaddr[4]; - uint8_t yiaddr[4]; - uint8_t siaddr[4]; - uint8_t giaddr[4]; - uint8_t chaddr[6]; -}RIP_MSG_FIXED; - -class DhcpClass { -private: - uint32_t _dhcpInitialTransactionId; - uint32_t _dhcpTransactionId; - uint8_t _dhcpMacAddr[6]; - uint8_t _dhcpLocalIp[4]; - uint8_t _dhcpSubnetMask[4]; - uint8_t _dhcpGatewayIp[4]; - uint8_t _dhcpDhcpServerIp[4]; - uint8_t _dhcpDnsServerIp[4]; - uint32_t _dhcpLeaseTime; - uint32_t _dhcpT1, _dhcpT2; - signed long _renewInSec; - signed long _rebindInSec; - signed long _lastCheck; - unsigned long _timeout; - unsigned long _responseTimeout; - unsigned long _secTimeout; - uint8_t _dhcp_state; - EthernetUDP _dhcpUdpSocket; - - int request_DHCP_lease(); - void reset_DHCP_lease(); - void presend_DHCP(); - void send_DHCP_MESSAGE(uint8_t, uint16_t); - void printByte(char *, uint8_t); - - uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId); -public: - IPAddress getLocalIp(); - IPAddress getSubnetMask(); - IPAddress getGatewayIp(); - IPAddress getDhcpServerIp(); - IPAddress getDnsServerIp(); - - int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); - int checkLease(); -}; - -#endif diff --git a/libraries/Ethernet/Dns.cpp b/libraries/Ethernet/Dns.cpp deleted file mode 100644 index b3c1a9d..0000000 --- a/libraries/Ethernet/Dns.cpp +++ /dev/null @@ -1,423 +0,0 @@ -// Arduino DNS client for WizNet5100-based Ethernet shield -// (c) Copyright 2009-2010 MCQN Ltd. -// Released under Apache License, version 2.0 - -#include "w5100.h" -#include "EthernetUdp.h" -#include "util.h" - -#include "Dns.h" -#include -//#include -#include "Arduino.h" - - -#define SOCKET_NONE 255 -// Various flags and header field values for a DNS message -#define UDP_HEADER_SIZE 8 -#define DNS_HEADER_SIZE 12 -#define TTL_SIZE 4 -#define QUERY_FLAG (0) -#define RESPONSE_FLAG (1<<15) -#define QUERY_RESPONSE_MASK (1<<15) -#define OPCODE_STANDARD_QUERY (0) -#define OPCODE_INVERSE_QUERY (1<<11) -#define OPCODE_STATUS_REQUEST (2<<11) -#define OPCODE_MASK (15<<11) -#define AUTHORITATIVE_FLAG (1<<10) -#define TRUNCATION_FLAG (1<<9) -#define RECURSION_DESIRED_FLAG (1<<8) -#define RECURSION_AVAILABLE_FLAG (1<<7) -#define RESP_NO_ERROR (0) -#define RESP_FORMAT_ERROR (1) -#define RESP_SERVER_FAILURE (2) -#define RESP_NAME_ERROR (3) -#define RESP_NOT_IMPLEMENTED (4) -#define RESP_REFUSED (5) -#define RESP_MASK (15) -#define TYPE_A (0x0001) -#define CLASS_IN (0x0001) -#define LABEL_COMPRESSION_MASK (0xC0) -// Port number that DNS servers listen on -#define DNS_PORT 53 - -// Possible return codes from ProcessResponse -#define SUCCESS 1 -#define TIMED_OUT -1 -#define INVALID_SERVER -2 -#define TRUNCATED -3 -#define INVALID_RESPONSE -4 - -void DNSClient::begin(const IPAddress& aDNSServer) -{ - iDNSServer = aDNSServer; - iRequestId = 0; -} - - -int DNSClient::inet_aton(const char* aIPAddrString, IPAddress& aResult) -{ - // See if we've been given a valid IP address - const char* p =aIPAddrString; - while (*p && - ( (*p == '.') || (*p >= '0') || (*p <= '9') )) - { - p++; - } - - if (*p == '\0') - { - // It's looking promising, we haven't found any invalid characters - p = aIPAddrString; - int segment =0; - int segmentValue =0; - while (*p && (segment < 4)) - { - if (*p == '.') - { - // We've reached the end of a segment - if (segmentValue > 255) - { - // You can't have IP address segments that don't fit in a byte - return 0; - } - else - { - aResult[segment] = (byte)segmentValue; - segment++; - segmentValue = 0; - } - } - else - { - // Next digit - segmentValue = (segmentValue*10)+(*p - '0'); - } - p++; - } - // We've reached the end of address, but there'll still be the last - // segment to deal with - if ((segmentValue > 255) || (segment > 3)) - { - // You can't have IP address segments that don't fit in a byte, - // or more than four segments - return 0; - } - else - { - aResult[segment] = (byte)segmentValue; - return 1; - } - } - else - { - return 0; - } -} - -int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult) -{ - int ret =0; - - // See if it's a numeric IP address - if (inet_aton(aHostname, aResult)) - { - // It is, our work here is done - return 1; - } - - // Check we've got a valid DNS server to use - if (iDNSServer == INADDR_NONE) - { - return INVALID_SERVER; - } - - // Find a socket to use - if (iUdp.begin(1024+(millis() & 0xF)) == 1) - { - // Try up to three times - int retries = 0; -// while ((retries < 3) && (ret <= 0)) - { - // Send DNS request - ret = iUdp.beginPacket(iDNSServer, DNS_PORT); - if (ret != 0) - { - // Now output the request data - ret = BuildRequest(aHostname); - if (ret != 0) - { - // And finally send the request - ret = iUdp.endPacket(); - if (ret != 0) - { - // Now wait for a response - int wait_retries = 0; - ret = TIMED_OUT; - while ((wait_retries < 3) && (ret == TIMED_OUT)) - { - ret = ProcessResponse(5000, aResult); - wait_retries++; - } - } - } - } - retries++; - } - - // We're done with the socket now - iUdp.stop(); - } - - return ret; -} - -uint16_t DNSClient::BuildRequest(const char* aName) -{ - // Build header - // 1 1 1 1 1 1 - // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - // | ID | - // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - // |QR| Opcode |AA|TC|RD|RA| Z | RCODE | - // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - // | QDCOUNT | - // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - // | ANCOUNT | - // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - // | NSCOUNT | - // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - // | ARCOUNT | - // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - // As we only support one request at a time at present, we can simplify - // some of this header - iRequestId = millis(); // generate a random ID - uint16_t twoByteBuffer; - - // FIXME We should also check that there's enough space available to write to, rather - // FIXME than assume there's enough space (as the code does at present) - iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId)); - - twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG); - iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); - - twoByteBuffer = htons(1); // One question record - iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); - - twoByteBuffer = 0; // Zero answer records - iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); - - iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); - // and zero additional records - iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); - - // Build question - const char* start =aName; - const char* end =start; - uint8_t len; - // Run through the name being requested - while (*end) - { - // Find out how long this section of the name is - end = start; - while (*end && (*end != '.') ) - { - end++; - } - - if (end-start > 0) - { - // Write out the size of this section - len = end-start; - iUdp.write(&len, sizeof(len)); - // And then write out the section - iUdp.write((uint8_t*)start, end-start); - } - start = end+1; - } - - // We've got to the end of the question name, so - // terminate it with a zero-length section - len = 0; - iUdp.write(&len, sizeof(len)); - // Finally the type and class of question - twoByteBuffer = htons(TYPE_A); - iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); - - twoByteBuffer = htons(CLASS_IN); // Internet class of question - iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); - // Success! Everything buffered okay - return 1; -} - - -uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) -{ - uint32_t startTime = millis(); - - // Wait for a response packet - while(iUdp.parsePacket() <= 0) - { - if((millis() - startTime) > aTimeout) - return TIMED_OUT; - delay(50); - } - - // We've had a reply! - // Read the UDP header - uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header - // Check that it's a response from the right server and the right port - if ( (iDNSServer != iUdp.remoteIP()) || - (iUdp.remotePort() != DNS_PORT) ) - { - // It's not from who we expected - return INVALID_SERVER; - } - - // Read through the rest of the response - if (iUdp.available() < DNS_HEADER_SIZE) - { - return TRUNCATED; - } - iUdp.read(header, DNS_HEADER_SIZE); - - uint16_t header_flags = htons(*((uint16_t*)&header[2])); - // Check that it's a response to this request - if ( ( iRequestId != (*((uint16_t*)&header[0])) ) || - ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) - { - // Mark the entire packet as read - iUdp.flush(); - return INVALID_RESPONSE; - } - // Check for any errors in the response (or in our request) - // although we don't do anything to get round these - if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) ) - { - // Mark the entire packet as read - iUdp.flush(); - return -5; //INVALID_RESPONSE; - } - - // And make sure we've got (at least) one answer - uint16_t answerCount = htons(*((uint16_t*)&header[6])); - if (answerCount == 0 ) - { - // Mark the entire packet as read - iUdp.flush(); - return -6; //INVALID_RESPONSE; - } - - // Skip over any questions - for (uint16_t i =0; i < htons(*((uint16_t*)&header[4])); i++) - { - // Skip over the name - uint8_t len; - do - { - iUdp.read(&len, sizeof(len)); - if (len > 0) - { - // Don't need to actually read the data out for the string, just - // advance ptr to beyond it - while(len--) - { - iUdp.read(); // we don't care about the returned byte - } - } - } while (len != 0); - - // Now jump over the type and class - for (int i =0; i < 4; i++) - { - iUdp.read(); // we don't care about the returned byte - } - } - - // Now we're up to the bit we're interested in, the answer - // There might be more than one answer (although we'll just use the first - // type A answer) and some authority and additional resource records but - // we're going to ignore all of them. - - for (uint16_t i =0; i < answerCount; i++) - { - // Skip the name - uint8_t len; - do - { - iUdp.read(&len, sizeof(len)); - if ((len & LABEL_COMPRESSION_MASK) == 0) - { - // It's just a normal label - if (len > 0) - { - // And it's got a length - // Don't need to actually read the data out for the string, - // just advance ptr to beyond it - while(len--) - { - iUdp.read(); // we don't care about the returned byte - } - } - } - else - { - // This is a pointer to a somewhere else in the message for the - // rest of the name. We don't care about the name, and RFC1035 - // says that a name is either a sequence of labels ended with a - // 0 length octet or a pointer or a sequence of labels ending in - // a pointer. Either way, when we get here we're at the end of - // the name - // Skip over the pointer - iUdp.read(); // we don't care about the returned byte - // And set len so that we drop out of the name loop - len = 0; - } - } while (len != 0); - - // Check the type and class - uint16_t answerType; - uint16_t answerClass; - iUdp.read((uint8_t*)&answerType, sizeof(answerType)); - iUdp.read((uint8_t*)&answerClass, sizeof(answerClass)); - - // Ignore the Time-To-Live as we don't do any caching - for (int i =0; i < TTL_SIZE; i++) - { - iUdp.read(); // we don't care about the returned byte - } - - // And read out the length of this answer - // Don't need header_flags anymore, so we can reuse it here - iUdp.read((uint8_t*)&header_flags, sizeof(header_flags)); - - if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) ) - { - if (htons(header_flags) != 4) - { - // It's a weird size - // Mark the entire packet as read - iUdp.flush(); - return -9;//INVALID_RESPONSE; - } - iUdp.read(aAddress.raw_address(), 4); - return SUCCESS; - } - else - { - // This isn't an answer type we're after, move onto the next one - for (uint16_t i =0; i < htons(header_flags); i++) - { - iUdp.read(); // we don't care about the returned byte - } - } - } - - // Mark the entire packet as read - iUdp.flush(); - - // If we get here then we haven't found an answer - return -10;//INVALID_RESPONSE; -} - diff --git a/libraries/Ethernet/Dns.h b/libraries/Ethernet/Dns.h deleted file mode 100644 index 6bcb98a..0000000 --- a/libraries/Ethernet/Dns.h +++ /dev/null @@ -1,41 +0,0 @@ -// Arduino DNS client for WizNet5100-based Ethernet shield -// (c) Copyright 2009-2010 MCQN Ltd. -// Released under Apache License, version 2.0 - -#ifndef DNSClient_h -#define DNSClient_h - -#include - -class DNSClient -{ -public: - // ctor - void begin(const IPAddress& aDNSServer); - - /** Convert a numeric IP address string into a four-byte IP address. - @param aIPAddrString IP address to convert - @param aResult IPAddress structure to store the returned IP address - @result 1 if aIPAddrString was successfully converted to an IP address, - else error code - */ - int inet_aton(const char *aIPAddrString, IPAddress& aResult); - - /** Resolve the given hostname to an IP address. - @param aHostname Name to be resolved - @param aResult IPAddress structure to store the returned IP address - @result 1 if aIPAddrString was successfully converted to an IP address, - else error code - */ - int getHostByName(const char* aHostname, IPAddress& aResult); - -protected: - uint16_t BuildRequest(const char* aName); - uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress); - - IPAddress iDNSServer; - uint16_t iRequestId; - EthernetUDP iUdp; -}; - -#endif diff --git a/libraries/Ethernet/Ethernet.cpp b/libraries/Ethernet/Ethernet.cpp deleted file mode 100644 index c31a85f..0000000 --- a/libraries/Ethernet/Ethernet.cpp +++ /dev/null @@ -1,122 +0,0 @@ -#include "w5100.h" -#include "Ethernet.h" -#include "Dhcp.h" - -// XXX: don't make assumptions about the value of MAX_SOCK_NUM. -uint8_t EthernetClass::_state[MAX_SOCK_NUM] = { - 0, 0, 0, 0 }; -uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = { - 0, 0, 0, 0 }; - -int EthernetClass::begin(uint8_t *mac_address) -{ - static DhcpClass s_dhcp; - _dhcp = &s_dhcp; - - - // Initialise the basic info - W5100.init(); - W5100.setMACAddress(mac_address); - W5100.setIPAddress(IPAddress(0,0,0,0).raw_address()); - - // Now try to get our config info from a DHCP server - int ret = _dhcp->beginWithDHCP(mac_address); - if(ret == 1) - { - // We've successfully found a DHCP server and got our configuration info, so set things - // accordingly - W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); - W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); - W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); - _dnsServerAddress = _dhcp->getDnsServerIp(); - } - - return ret; -} - -void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip) -{ - // Assume the DNS server will be the machine on the same network as the local IP - // but with last octet being '1' - IPAddress dns_server = local_ip; - dns_server[3] = 1; - begin(mac_address, local_ip, dns_server); -} - -void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server) -{ - // Assume the gateway will be the machine on the same network as the local IP - // but with last octet being '1' - IPAddress gateway = local_ip; - gateway[3] = 1; - begin(mac_address, local_ip, dns_server, gateway); -} - -void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway) -{ - IPAddress subnet(255, 255, 255, 0); - begin(mac_address, local_ip, dns_server, gateway, subnet); -} - -void EthernetClass::begin(uint8_t *mac, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) -{ - W5100.init(); - W5100.setMACAddress(mac); - W5100.setIPAddress(local_ip._address); - W5100.setGatewayIp(gateway._address); - W5100.setSubnetMask(subnet._address); - _dnsServerAddress = dns_server; -} - -int EthernetClass::maintain(){ - int rc = DHCP_CHECK_NONE; - if(_dhcp != NULL){ - //we have a pointer to dhcp, use it - rc = _dhcp->checkLease(); - switch ( rc ){ - case DHCP_CHECK_NONE: - //nothing done - break; - case DHCP_CHECK_RENEW_OK: - case DHCP_CHECK_REBIND_OK: - //we might have got a new IP. - W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); - W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); - W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); - _dnsServerAddress = _dhcp->getDnsServerIp(); - break; - default: - //this is actually a error, it will retry though - break; - } - } - return rc; -} - -IPAddress EthernetClass::localIP() -{ - IPAddress ret; - W5100.getIPAddress(ret.raw_address()); - return ret; -} - -IPAddress EthernetClass::subnetMask() -{ - IPAddress ret; - W5100.getSubnetMask(ret.raw_address()); - return ret; -} - -IPAddress EthernetClass::gatewayIP() -{ - IPAddress ret; - W5100.getGatewayIp(ret.raw_address()); - return ret; -} - -IPAddress EthernetClass::dnsServerIP() -{ - return _dnsServerAddress; -} - -EthernetClass Ethernet; diff --git a/libraries/Ethernet/Ethernet.h b/libraries/Ethernet/Ethernet.h deleted file mode 100644 index 2a07ff3..0000000 --- a/libraries/Ethernet/Ethernet.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef ethernet_h -#define ethernet_h - -#include -//#include "w5100.h" -#include "IPAddress.h" -#include "EthernetClient.h" -#include "EthernetServer.h" -#include "Dhcp.h" - -#define MAX_SOCK_NUM 4 - -class EthernetClass { -private: - IPAddress _dnsServerAddress; - DhcpClass* _dhcp; -public: - static uint8_t _state[MAX_SOCK_NUM]; - static uint16_t _server_port[MAX_SOCK_NUM]; - // Initialise the Ethernet shield to use the provided MAC address and gain the rest of the - // configuration through DHCP. - // Returns 0 if the DHCP configuration failed, and 1 if it succeeded - int begin(uint8_t *mac_address); - void begin(uint8_t *mac_address, IPAddress local_ip); - void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server); - void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway); - void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); - int maintain(); - - IPAddress localIP(); - IPAddress subnetMask(); - IPAddress gatewayIP(); - IPAddress dnsServerIP(); - - friend class EthernetClient; - friend class EthernetServer; -}; - -extern EthernetClass Ethernet; - -#endif diff --git a/libraries/Ethernet/EthernetClient.cpp b/libraries/Ethernet/EthernetClient.cpp deleted file mode 100644 index 9885efb..0000000 --- a/libraries/Ethernet/EthernetClient.cpp +++ /dev/null @@ -1,165 +0,0 @@ -#include "w5100.h" -#include "socket.h" - -extern "C" { - #include "string.h" -} - -#include "Arduino.h" - -#include "Ethernet.h" -#include "EthernetClient.h" -#include "EthernetServer.h" -#include "Dns.h" - -uint16_t EthernetClient::_srcport = 1024; - -EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) { -} - -EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) { -} - -int EthernetClient::connect(const char* host, uint16_t port) { - // Look up the host first - int ret = 0; - DNSClient dns; - IPAddress remote_addr; - - dns.begin(Ethernet.dnsServerIP()); - ret = dns.getHostByName(host, remote_addr); - if (ret == 1) { - return connect(remote_addr, port); - } else { - return ret; - } -} - -int EthernetClient::connect(IPAddress ip, uint16_t port) { - if (_sock != MAX_SOCK_NUM) - return 0; - - for (int i = 0; i < MAX_SOCK_NUM; i++) { - uint8_t s = W5100.readSnSR(i); - if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) { - _sock = i; - break; - } - } - - if (_sock == MAX_SOCK_NUM) - return 0; - - _srcport++; - if (_srcport == 0) _srcport = 1024; - socket(_sock, SnMR::TCP, _srcport, 0); - - if (!::connect(_sock, rawIPAddress(ip), port)) { - _sock = MAX_SOCK_NUM; - return 0; - } - - while (status() != SnSR::ESTABLISHED) { - delay(1); - if (status() == SnSR::CLOSED) { - _sock = MAX_SOCK_NUM; - return 0; - } - } - - return 1; -} - -size_t EthernetClient::write(uint8_t b) { - return write(&b, 1); -} - -size_t EthernetClient::write(const uint8_t *buf, size_t size) { - if (_sock == MAX_SOCK_NUM) { - setWriteError(); - return 0; - } - if (!send(_sock, buf, size)) { - setWriteError(); - return 0; - } - return size; -} - -int EthernetClient::available() { - if (_sock != MAX_SOCK_NUM) - return W5100.getRXReceivedSize(_sock); - return 0; -} - -int EthernetClient::read() { - uint8_t b; - if ( recv(_sock, &b, 1) > 0 ) - { - // recv worked - return b; - } - else - { - // No data available - return -1; - } -} - -int EthernetClient::read(uint8_t *buf, size_t size) { - return recv(_sock, buf, size); -} - -int EthernetClient::peek() { - uint8_t b; - // Unlike recv, peek doesn't check to see if there's any data available, so we must - if (!available()) - return -1; - ::peek(_sock, &b); - return b; -} - -void EthernetClient::flush() { - while (available()) - read(); -} - -void EthernetClient::stop() { - if (_sock == MAX_SOCK_NUM) - return; - - // attempt to close the connection gracefully (send a FIN to other side) - disconnect(_sock); - unsigned long start = millis(); - - // wait a second for the connection to close - while (status() != SnSR::CLOSED && millis() - start < 1000) - delay(1); - - // if it hasn't closed, close it forcefully - if (status() != SnSR::CLOSED) - close(_sock); - - EthernetClass::_server_port[_sock] = 0; - _sock = MAX_SOCK_NUM; -} - -uint8_t EthernetClient::connected() { - if (_sock == MAX_SOCK_NUM) return 0; - - uint8_t s = status(); - return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT || - (s == SnSR::CLOSE_WAIT && !available())); -} - -uint8_t EthernetClient::status() { - if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED; - return W5100.readSnSR(_sock); -} - -// the next function allows us to use the client returned by -// EthernetServer::available() as the condition in an if-statement. - -EthernetClient::operator bool() { - return _sock != MAX_SOCK_NUM; -} diff --git a/libraries/Ethernet/EthernetClient.h b/libraries/Ethernet/EthernetClient.h deleted file mode 100644 index 44740fe..0000000 --- a/libraries/Ethernet/EthernetClient.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef ethernetclient_h -#define ethernetclient_h -#include "Arduino.h" -#include "Print.h" -#include "Client.h" -#include "IPAddress.h" - -class EthernetClient : public Client { - -public: - EthernetClient(); - EthernetClient(uint8_t sock); - - uint8_t status(); - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char *host, uint16_t port); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual int available(); - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - virtual void flush(); - virtual void stop(); - virtual uint8_t connected(); - virtual operator bool(); - - friend class EthernetServer; - - using Print::write; - -private: - static uint16_t _srcport; - uint8_t _sock; -}; - -#endif diff --git a/libraries/Ethernet/EthernetServer.cpp b/libraries/Ethernet/EthernetServer.cpp deleted file mode 100644 index 0308b92..0000000 --- a/libraries/Ethernet/EthernetServer.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "w5100.h" -#include "socket.h" -extern "C" { -#include "string.h" -} - -#include "Ethernet.h" -#include "EthernetClient.h" -#include "EthernetServer.h" - -EthernetServer::EthernetServer(uint16_t port) -{ - _port = port; -} - -void EthernetServer::begin() -{ - for (int sock = 0; sock < MAX_SOCK_NUM; sock++) { - EthernetClient client(sock); - if (client.status() == SnSR::CLOSED) { - socket(sock, SnMR::TCP, _port, 0); - listen(sock); - EthernetClass::_server_port[sock] = _port; - break; - } - } -} - -void EthernetServer::accept() -{ - int listening = 0; - - for (int sock = 0; sock < MAX_SOCK_NUM; sock++) { - EthernetClient client(sock); - - if (EthernetClass::_server_port[sock] == _port) { - if (client.status() == SnSR::LISTEN) { - listening = 1; - } - else if (client.status() == SnSR::CLOSE_WAIT && !client.available()) { - client.stop(); - } - } - } - - if (!listening) { - begin(); - } -} - -EthernetClient EthernetServer::available() -{ - accept(); - - for (int sock = 0; sock < MAX_SOCK_NUM; sock++) { - EthernetClient client(sock); - if (EthernetClass::_server_port[sock] == _port && - (client.status() == SnSR::ESTABLISHED || - client.status() == SnSR::CLOSE_WAIT)) { - if (client.available()) { - // XXX: don't always pick the lowest numbered socket. - return client; - } - } - } - - return EthernetClient(MAX_SOCK_NUM); -} - -size_t EthernetServer::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t EthernetServer::write(const uint8_t *buffer, size_t size) -{ - size_t n = 0; - - accept(); - - for (int sock = 0; sock < MAX_SOCK_NUM; sock++) { - EthernetClient client(sock); - - if (EthernetClass::_server_port[sock] == _port && - client.status() == SnSR::ESTABLISHED) { - n += client.write(buffer, size); - } - } - - return n; -} diff --git a/libraries/Ethernet/EthernetServer.h b/libraries/Ethernet/EthernetServer.h deleted file mode 100644 index 86ccafe..0000000 --- a/libraries/Ethernet/EthernetServer.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef ethernetserver_h -#define ethernetserver_h - -#include "Server.h" - -class EthernetClient; - -class EthernetServer : -public Server { -private: - uint16_t _port; - void accept(); -public: - EthernetServer(uint16_t); - EthernetClient available(); - virtual void begin(); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - using Print::write; -}; - -#endif diff --git a/libraries/Ethernet/EthernetUdp.cpp b/libraries/Ethernet/EthernetUdp.cpp deleted file mode 100644 index 3760052..0000000 --- a/libraries/Ethernet/EthernetUdp.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. - * This version only offers minimal wrapping of socket.c/socket.h - * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ - * - * MIT License: - * Copyright (c) 2008 Bjoern Hartmann - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * bjoern@cs.stanford.edu 12/30/2008 - */ - -#include "w5100.h" -#include "socket.h" -#include "Ethernet.h" -#include "Udp.h" -#include "Dns.h" - -/* Constructor */ -EthernetUDP::EthernetUDP() : _sock(MAX_SOCK_NUM) {} - -/* Start EthernetUDP socket, listening at local port PORT */ -uint8_t EthernetUDP::begin(uint16_t port) { - if (_sock != MAX_SOCK_NUM) - return 0; - - for (int i = 0; i < MAX_SOCK_NUM; i++) { - uint8_t s = W5100.readSnSR(i); - if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT) { - _sock = i; - break; - } - } - - if (_sock == MAX_SOCK_NUM) - return 0; - - _port = port; - _remaining = 0; - socket(_sock, SnMR::UDP, _port, 0); - - return 1; -} - -/* return number of bytes available in the current packet, - will return zero if parsePacket hasn't been called yet */ -int EthernetUDP::available() { - return _remaining; -} - -/* Release any resources being used by this EthernetUDP instance */ -void EthernetUDP::stop() -{ - if (_sock == MAX_SOCK_NUM) - return; - - close(_sock); - - EthernetClass::_server_port[_sock] = 0; - _sock = MAX_SOCK_NUM; -} - -int EthernetUDP::beginPacket(const char *host, uint16_t port) -{ - // Look up the host first - int ret = 0; - DNSClient dns; - IPAddress remote_addr; - - dns.begin(Ethernet.dnsServerIP()); - ret = dns.getHostByName(host, remote_addr); - if (ret == 1) { - return beginPacket(remote_addr, port); - } else { - return ret; - } -} - -int EthernetUDP::beginPacket(IPAddress ip, uint16_t port) -{ - _offset = 0; - return startUDP(_sock, rawIPAddress(ip), port); -} - -int EthernetUDP::endPacket() -{ - return sendUDP(_sock); -} - -size_t EthernetUDP::write(uint8_t byte) -{ - return write(&byte, 1); -} - -size_t EthernetUDP::write(const uint8_t *buffer, size_t size) -{ - uint16_t bytes_written = bufferData(_sock, _offset, buffer, size); - _offset += bytes_written; - return bytes_written; -} - -int EthernetUDP::parsePacket() -{ - // discard any remaining bytes in the last packet - flush(); - - if (W5100.getRXReceivedSize(_sock) > 0) - { - //HACK - hand-parse the UDP packet using TCP recv method - uint8_t tmpBuf[8]; - int ret =0; - //read 8 header bytes and get IP and port from it - ret = recv(_sock,tmpBuf,8); - if (ret > 0) - { - _remoteIP = tmpBuf; - _remotePort = tmpBuf[4]; - _remotePort = (_remotePort << 8) + tmpBuf[5]; - _remaining = tmpBuf[6]; - _remaining = (_remaining << 8) + tmpBuf[7]; - - // When we get here, any remaining bytes are the data - ret = _remaining; - } - return ret; - } - // There aren't any packets available - return 0; -} - -int EthernetUDP::read() -{ - uint8_t byte; - - if ((_remaining > 0) && (recv(_sock, &byte, 1) > 0)) - { - // We read things without any problems - _remaining--; - return byte; - } - - // If we get here, there's no data available - return -1; -} - -int EthernetUDP::read(unsigned char* buffer, size_t len) -{ - - if (_remaining > 0) - { - - int got; - - if (_remaining <= len) - { - // data should fit in the buffer - got = recv(_sock, buffer, _remaining); - } - else - { - // too much data for the buffer, - // grab as much as will fit - got = recv(_sock, buffer, len); - } - - if (got > 0) - { - _remaining -= got; - return got; - } - - } - - // If we get here, there's no data available or recv failed - return -1; - -} - -int EthernetUDP::peek() -{ - uint8_t b; - // Unlike recv, peek doesn't check to see if there's any data available, so we must. - // If the user hasn't called parsePacket yet then return nothing otherwise they - // may get the UDP header - if (!_remaining) - return -1; - ::peek(_sock, &b); - return b; -} - -void EthernetUDP::flush() -{ - // could this fail (loop endlessly) if _remaining > 0 and recv in read fails? - // should only occur if recv fails after telling us the data is there, lets - // hope the w5100 always behaves :) - - while (_remaining) - { - read(); - } -} - diff --git a/libraries/Ethernet/EthernetUdp.h b/libraries/Ethernet/EthernetUdp.h deleted file mode 100644 index 8a6b7ab..0000000 --- a/libraries/Ethernet/EthernetUdp.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. - * This version only offers minimal wrapping of socket.c/socket.h - * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ - * - * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) - * 1) UDP does not guarantee the order in which assembled UDP packets are received. This - * might not happen often in practice, but in larger network topologies, a UDP - * packet can be received out of sequence. - * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being - * aware of it. Again, this may not be a concern in practice on small local networks. - * For more information, see http://www.cafeaulait.org/course/week12/35.html - * - * MIT License: - * Copyright (c) 2008 Bjoern Hartmann - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * bjoern@cs.stanford.edu 12/30/2008 - */ - -#ifndef ethernetudp_h -#define ethernetudp_h - -#include - -#define UDP_TX_PACKET_MAX_SIZE 24 - -class EthernetUDP : public UDP { -private: - uint8_t _sock; // socket ID for Wiz5100 - uint16_t _port; // local port to listen on - IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed - uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed - uint16_t _offset; // offset into the packet being sent - uint16_t _remaining; // remaining bytes of incoming packet yet to be processed - -public: - EthernetUDP(); // Constructor - virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - virtual void stop(); // Finish with the UDP socket - - // Sending UDP packets - - // Start building up a packet to send to the remote host specific in ip and port - // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port - virtual int beginPacket(IPAddress ip, uint16_t port); - // Start building up a packet to send to the remote host specific in host and port - // Returns 1 if successful, 0 if there was a problem resolving the hostname or port - virtual int beginPacket(const char *host, uint16_t port); - // Finish off this packet and send it - // Returns 1 if the packet was sent successfully, 0 if there was an error - virtual int endPacket(); - // Write a single byte into the packet - virtual size_t write(uint8_t); - // Write size bytes from buffer into the packet - virtual size_t write(const uint8_t *buffer, size_t size); - - using Print::write; - - // Start processing the next available incoming packet - // Returns the size of the packet in bytes, or 0 if no packets are available - virtual int parsePacket(); - // Number of bytes remaining in the current packet - virtual int available(); - // Read a single byte from the current packet - virtual int read(); - // Read up to len bytes from the current packet and place them into buffer - // Returns the number of bytes read, or 0 if none are available - virtual int read(unsigned char* buffer, size_t len); - // Read up to len characters from the current packet and place them into buffer - // Returns the number of characters read, or 0 if none are available - virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; - // Return the next byte from the current packet without moving on to the next byte - virtual int peek(); - virtual void flush(); // Finish reading the current packet - - // Return the IP address of the host who sent the current incoming packet - virtual IPAddress remoteIP() { return _remoteIP; }; - // Return the port of the host who sent the current incoming packet - virtual uint16_t remotePort() { return _remotePort; }; -}; - -#endif diff --git a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino deleted file mode 100644 index bfbcb6d..0000000 --- a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino +++ /dev/null @@ -1,222 +0,0 @@ -/* - SCP1000 Barometric Pressure Sensor Display - - Serves the output of a Barometric Pressure Sensor as a web page. - Uses the SPI library. For details on the sensor, see: - http://www.sparkfun.com/commerce/product_info.php?products_id=8161 - http://www.vti.fi/en/support/obsolete_products/pressure_sensors/ - - This sketch adapted from Nathan Seidle's SCP1000 example for PIC: - http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip - - Circuit: - SCP1000 sensor attached to pins 6,7, and 11 - 13: - DRDY: pin 6 - CSB: pin 7 - MOSI: pin 11 - MISO: pin 12 - SCK: pin 13 - - created 31 July 2010 - by Tom Igoe - */ - -#include -// the sensor communicates using SPI, so include the library: -#include - - -// assign a MAC address for the ethernet controller. -// fill in your address here: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -// assign an IP address for the controller: -IPAddress ip(192,168,1,20); -IPAddress gateway(192,168,1,1); -IPAddress subnet(255, 255, 255, 0); - - -// Initialize the Ethernet server library -// with the IP address and port you want to use -// (port 80 is default for HTTP): -EthernetServer server(80); - - -//Sensor's memory register addresses: -const int PRESSURE = 0x1F; //3 most significant bits of pressure -const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure -const int TEMPERATURE = 0x21; //16 bit temperature reading - -// pins used for the connection with the sensor -// the others you need are controlled by the SPI library): -const int dataReadyPin = 6; -const int chipSelectPin = 7; - -float temperature = 0.0; -long pressure = 0; -long lastReadingTime = 0; - -void setup() { - // start the SPI library: - SPI.begin(); - - // start the Ethernet connection and the server: - Ethernet.begin(mac, ip); - server.begin(); - - // initalize the data ready and chip select pins: - pinMode(dataReadyPin, INPUT); - pinMode(chipSelectPin, OUTPUT); - - Serial.begin(9600); - - //Configure SCP1000 for low noise configuration: - writeRegister(0x02, 0x2D); - writeRegister(0x01, 0x03); - writeRegister(0x03, 0x02); - - // give the sensor and Ethernet shield time to set up: - delay(1000); - - //Set the sensor to high resolution mode tp start readings: - writeRegister(0x03, 0x0A); - -} - -void loop() { - // check for a reading no more than once a second. - if (millis() - lastReadingTime > 1000){ - // if there's a reading ready, read it: - // don't do anything until the data ready pin is high: - if (digitalRead(dataReadyPin) == HIGH) { - getData(); - // timestamp the last time you got a reading: - lastReadingTime = millis(); - } - } - - // listen for incoming Ethernet connections: - listenForEthernetClients(); -} - - -void getData() { - Serial.println("Getting reading"); - //Read the temperature data - int tempData = readRegister(0x21, 2); - - // convert the temperature to celsius and display it: - temperature = (float)tempData / 20.0; - - //Read the pressure data highest 3 bits: - byte pressureDataHigh = readRegister(0x1F, 1); - pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0 - - //Read the pressure data lower 16 bits: - unsigned int pressureDataLow = readRegister(0x20, 2); - //combine the two parts into one 19-bit number: - pressure = ((pressureDataHigh << 16) | pressureDataLow)/4; - - Serial.print("Temperature: "); - Serial.print(temperature); - Serial.println(" degrees C"); - Serial.print("Pressure: " + String(pressure)); - Serial.println(" Pa"); -} - -void listenForEthernetClients() { - // listen for incoming clients - EthernetClient client = server.available(); - if (client) { - Serial.println("Got a client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println(); - // print the current readings, in HTML format: - client.print("Temperature: "); - client.print(temperature); - client.print(" degrees C"); - client.println("
"); - client.print("Pressure: " + String(pressure)); - client.print(" Pa"); - client.println("
"); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - // close the connection: - client.stop(); - } -} - - -//Send a write command to SCP1000 -void writeRegister(byte registerName, byte registerValue) { - // SCP1000 expects the register name in the upper 6 bits - // of the byte: - registerName <<= 2; - // command (read or write) goes in the lower two bits: - registerName |= 0b00000010; //Write command - - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - - SPI.transfer(registerName); //Send register location - SPI.transfer(registerValue); //Send value to record into register - - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); -} - - -//Read register from the SCP1000: -unsigned int readRegister(byte registerName, int numBytes) { - byte inByte = 0; // incoming from the SPI read - unsigned int result = 0; // result to return - - // SCP1000 expects the register name in the upper 6 bits - // of the byte: - registerName <<= 2; - // command (read or write) goes in the lower two bits: - registerName &= 0b11111100; //Read command - - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - // send the device the register you want to read: - int command = SPI.transfer(registerName); - // send a value of 0 to read the first byte returned: - inByte = SPI.transfer(0x00); - - result = inByte; - // if there's more than one byte returned, - // shift the first byte then get the second byte: - if (numBytes > 1){ - result = inByte << 8; - inByte = SPI.transfer(0x00); - result = result |inByte; - } - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); - // return the result: - return(result); -} diff --git a/libraries/Ethernet/examples/ChatServer/ChatServer.ino b/libraries/Ethernet/examples/ChatServer/ChatServer.ino deleted file mode 100644 index d50e5a6..0000000 --- a/libraries/Ethernet/examples/ChatServer/ChatServer.ino +++ /dev/null @@ -1,79 +0,0 @@ -/* - Chat Server - - A simple server that distributes any incoming messages to all - connected clients. To use telnet to your device's IP address and type. - You can see the client's input in the serial monitor as well. - Using an Arduino Wiznet Ethernet shield. - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - * Analog inputs attached to pins A0 through A5 (optional) - - created 18 Dec 2009 - by David A. Mellis - modified 9 Apr 2012 - by Tom Igoe - - */ - -#include -#include - -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network. -// gateway and subnet are optional: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -IPAddress ip(192,168,1, 177); -IPAddress gateway(192,168,1, 1); -IPAddress subnet(255, 255, 0, 0); - - -// telnet defaults to port 23 -EthernetServer server(23); -boolean alreadyConnected = false; // whether or not the client was connected previously - -void setup() { - // initialize the ethernet device - Ethernet.begin(mac, ip, gateway, subnet); - // start listening for clients - server.begin(); - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - Serial.print("Chat server address:"); - Serial.println(Ethernet.localIP()); -} - -void loop() { - // wait for a new client: - EthernetClient client = server.available(); - - // when the client sends the first byte, say hello: - if (client) { - if (!alreadyConnected) { - // clead out the input buffer: - client.flush(); - Serial.println("We have a new client"); - client.println("Hello, client!"); - alreadyConnected = true; - } - - if (client.available() > 0) { - // read the bytes incoming from the client: - char thisChar = client.read(); - // echo the bytes back to the client: - server.write(thisChar); - // echo the bytes to the server as well: - Serial.write(thisChar); - } - } -} - - - diff --git a/libraries/Ethernet/examples/CosmClient/CosmClient.ino b/libraries/Ethernet/examples/CosmClient/CosmClient.ino deleted file mode 100644 index ec74278..0000000 --- a/libraries/Ethernet/examples/CosmClient/CosmClient.ino +++ /dev/null @@ -1,161 +0,0 @@ -/* - Cosm sensor client - - This sketch connects an analog sensor to Cosm (http://www.cosm.com) - using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or - the Adafruit Ethernet shield, either one will work, as long as it's got - a Wiznet Ethernet module on board. - - This example has been updated to use version 2.0 of the cosm.com API. - To make it work, create a feed with a datastream, and give it the ID - sensor1. Or change the code below to match your feed. - - - Circuit: - * Analog sensor attached to analog in 0 - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 15 March 2010 - updated 14 May 2012 - by Tom Igoe with input from Usman Haque and Joe Saavedra - -http://arduino.cc/en/Tutorial/CosmClient - This code is in the public domain. - - */ - -#include -#include - -#define APIKEY "YOUR API KEY GOES HERE" // replace your Cosm api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Project" // user agent is the project name - -// assign a MAC address for the ethernet controller. -// Newer Ethernet shields have a MAC address printed on a sticker on the shield -// fill in your address here: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; - -// fill in an available IP address on your network here, -// for manual configuration: -IPAddress ip(10,0,1,20); - -// initialize the library instance: -EthernetClient client; - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(216,52,233,121); // numeric IP for api.cosm.com -char server[] = "api.cosm.com"; // name address for cosm API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10L*1000L; // delay between updates to cosm.com - // the "L" is needed to use long type numbers - - -void setup() { - // start serial port: - Serial.begin(9600); - // start the Ethernet connection: - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // DHCP failed, so use a fixed IP address: - Ethernet.begin(mac, ip); - } -} - -void loop() { - // read the analog sensor: - int sensorReading = analogRead(A0); - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - if (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - sendData(sensorReading); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void sendData(int thisData) { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.cosm.com"); - client.print("X-ApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - - // calculate the length of the sensor reading in bytes: - // 8 bytes for "sensor1," + number of digits of the data: - int thisLength = 8 + getLength(thisData); - client.println(thisLength); - - // last pieces of the HTTP PUT request: - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request: - client.print("sensor1,"); - client.println(thisData); - - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted: - lastConnectionTime = millis(); -} - - -// This method calculates the number of digits in the -// sensor reading. Since each digit of the ASCII decimal -// representation is a byte, the number of digits equals -// the number of bytes: - -int getLength(int someValue) { - // there's at least one byte: - int digits = 1; - // continually divide the value by ten, - // adding one to the digit count for each - // time you divide, until you're at 0: - int dividend = someValue /10; - while (dividend > 0) { - dividend = dividend /10; - digits++; - } - // return the number of digits: - return digits; -} - diff --git a/libraries/Ethernet/examples/CosmClientString/CosmClientString.ino b/libraries/Ethernet/examples/CosmClientString/CosmClientString.ino deleted file mode 100644 index e619924..0000000 --- a/libraries/Ethernet/examples/CosmClientString/CosmClientString.ino +++ /dev/null @@ -1,146 +0,0 @@ -/* - Cosm sensor client with Strings - - This sketch connects an analog sensor to Cosm (http://www.cosm.com) - using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or - the Adafruit Ethernet shield, either one will work, as long as it's got - a Wiznet Ethernet module on board. - - This example has been updated to use version 2.0 of the Cosm.com API. - To make it work, create a feed with two datastreams, and give them the IDs - sensor1 and sensor2. Or change the code below to match your feed. - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * Analog sensor attached to analog in 0 - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 15 March 2010 - updated 14 May 2012 - by Tom Igoe with input from Usman Haque and Joe Saavedra - - http://arduino.cc/en/Tutorial/CosmClientString - This code is in the public domain. - - */ - -#include -#include - - -#define APIKEY "YOUR API KEY GOES HERE" // replace your Cosm api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Project" // user agent is the project name - -// assign a MAC address for the ethernet controller. -// fill in your address here: - byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; - -// fill in an available IP address on your network here, -// for manual configuration: -IPAddress ip(10,0,1,20); - -// initialize the library instance: -EthernetClient client; - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(216,52,233,121); // numeric IP for api.cosm.com -char server[] = "api.cosm.com"; // name address for Cosm API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10L*1000L; // delay between updates to Cosm.com - // the "L" is needed to use long type numbers -void setup() { - // start serial port: - Serial.begin(9600); - // give the ethernet module time to boot up: - delay(1000); - // start the Ethernet connection: - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // DHCP failed, so use a fixed IP address: - Ethernet.begin(mac, ip); - } -} - -void loop() { - // read the analog sensor: - int sensorReading = analogRead(A0); - // convert the data to a String to send it: - - String dataString = "sensor1,"; - dataString += sensorReading; - - // you can append multiple readings to this String if your - // Cosm feed is set up to handle multiple values: - int otherSensorReading = analogRead(A1); - dataString += "\nsensor2,"; - dataString += otherSensorReading; - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - if (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - sendData(dataString); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void sendData(String thisData) { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.cosm.com"); - client.print("X-ApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - client.println(thisData.length()); - - // last pieces of the HTTP PUT request: - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request: - client.println(thisData); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted: - lastConnectionTime = millis(); -} - diff --git a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino deleted file mode 100644 index 5eaaf24..0000000 --- a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino +++ /dev/null @@ -1,59 +0,0 @@ -/* - DHCP-based IP printer - - This sketch uses the DHCP extensions to the Ethernet library - to get an IP address via DHCP and print the address obtained. - using an Arduino Wiznet Ethernet shield. - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 12 April 2011 - modified 9 Apr 2012 - by Tom Igoe - - */ - -#include -#include - -// Enter a MAC address for your controller below. -// Newer Ethernet shields have a MAC address printed on a sticker on the shield -byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -EthernetClient client; - -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - // this check is only needed on the Leonardo: - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // start the Ethernet connection: - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // no point in carrying on, so do nothing forevermore: - for(;;) - ; - } - // print your local IP address: - Serial.print("My IP address: "); - for (byte thisByte = 0; thisByte < 4; thisByte++) { - // print the value of each byte of the IP address: - Serial.print(Ethernet.localIP()[thisByte], DEC); - Serial.print("."); - } - Serial.println(); -} - -void loop() { - -} - - diff --git a/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino b/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino deleted file mode 100644 index 09cbd43..0000000 --- a/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino +++ /dev/null @@ -1,87 +0,0 @@ -/* - DHCP Chat Server - - A simple server that distributes any incoming messages to all - connected clients. To use telnet to your device's IP address and type. - You can see the client's input in the serial monitor as well. - Using an Arduino Wiznet Ethernet shield. - - THis version attempts to get an IP address using DHCP - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 21 May 2011 - modified 9 Apr 2012 - by Tom Igoe - Based on ChatServer example by David A. Mellis - - */ - -#include -#include - -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network. -// gateway and subnet are optional: -byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; -IPAddress ip(192,168,1, 177); -IPAddress gateway(192,168,1, 1); -IPAddress subnet(255, 255, 0, 0); - -// telnet defaults to port 23 -EthernetServer server(23); -boolean gotAMessage = false; // whether or not you got a message from the client yet - -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - // this check is only needed on the Leonardo: - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // start the Ethernet connection: - Serial.println("Trying to get an IP address using DHCP"); - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // initialize the ethernet device not using DHCP: - Ethernet.begin(mac, ip, gateway, subnet); - } - // print your local IP address: - Serial.print("My IP address: "); - ip = Ethernet.localIP(); - for (byte thisByte = 0; thisByte < 4; thisByte++) { - // print the value of each byte of the IP address: - Serial.print(ip[thisByte], DEC); - Serial.print("."); - } - Serial.println(); - // start listening for clients - server.begin(); - -} - -void loop() { - // wait for a new client: - EthernetClient client = server.available(); - - // when the client sends the first byte, say hello: - if (client) { - if (!gotAMessage) { - Serial.println("We have a new client"); - client.println("Hello, client!"); - gotAMessage = true; - } - - // read the bytes incoming from the client: - char thisChar = client.read(); - // echo the bytes back to the client: - server.write(thisChar); - // echo the bytes to the server as well: - Serial.print(thisChar); - } -} - diff --git a/libraries/Ethernet/examples/PachubeClient/PachubeClient.ino b/libraries/Ethernet/examples/PachubeClient/PachubeClient.ino deleted file mode 100644 index dfd2d40..0000000 --- a/libraries/Ethernet/examples/PachubeClient/PachubeClient.ino +++ /dev/null @@ -1,163 +0,0 @@ -/* - Pachube sensor client - - This sketch connects an analog sensor to Pachube (http://www.pachube.com) - using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or - the Adafruit Ethernet shield, either one will work, as long as it's got - a Wiznet Ethernet module on board. - - This example has been updated to use version 2.0 of the Pachube.com API. - To make it work, create a feed with a datastream, and give it the ID - sensor1. Or change the code below to match your feed. - - - Circuit: - * Analog sensor attached to analog in 0 - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 15 March 2010 - modified 9 Apr 2012 - by Tom Igoe with input from Usman Haque and Joe Saavedra - -http://arduino.cc/en/Tutorial/PachubeClient - This code is in the public domain. - - */ - -#include -#include - -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Project" // user agent is the project name - -// assign a MAC address for the ethernet controller. -// Newer Ethernet shields have a MAC address printed on a sticker on the shield -// fill in your address here: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; - -// fill in an available IP address on your network here, -// for manual configuration: -IPAddress ip(10,0,1,20); -// initialize the library instance: -EthernetClient client; - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -IPAddress server(216,52,233,122); // numeric IP for api.pachube.com -//char server[] = "api.pachube.com"; // name address for pachube API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com - -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // start the Ethernet connection: - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // DHCP failed, so use a fixed IP address: - Ethernet.begin(mac, ip); - } -} - -void loop() { - // read the analog sensor: - int sensorReading = analogRead(A0); - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - if (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - sendData(sensorReading); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void sendData(int thisData) { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); - client.print("X-PachubeApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - - // calculate the length of the sensor reading in bytes: - // 8 bytes for "sensor1," + number of digits of the data: - int thisLength = 8 + getLength(thisData); - client.println(thisLength); - - // last pieces of the HTTP PUT request: - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request: - client.print("sensor1,"); - client.println(thisData); - - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted: - lastConnectionTime = millis(); -} - - -// This method calculates the number of digits in the -// sensor reading. Since each digit of the ASCII decimal -// representation is a byte, the number of digits equals -// the number of bytes: - -int getLength(int someValue) { - // there's at least one byte: - int digits = 1; - // continually divide the value by ten, - // adding one to the digit count for each - // time you divide, until you're at 0: - int dividend = someValue /10; - while (dividend > 0) { - dividend = dividend /10; - digits++; - } - // return the number of digits: - return digits; -} - diff --git a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino deleted file mode 100644 index 2a96e9f..0000000 --- a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino +++ /dev/null @@ -1,152 +0,0 @@ -/* - Cosm sensor client with Strings - - This sketch connects an analog sensor to Cosm (http://www.cosm.com) - using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or - the Adafruit Ethernet shield, either one will work, as long as it's got - a Wiznet Ethernet module on board. - - This example has been updated to use version 2.0 of the Cosm.com API. - To make it work, create a feed with two datastreams, and give them the IDs - sensor1 and sensor2. Or change the code below to match your feed. - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * Analog sensor attached to analog in 0 - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 15 March 2010 - modified 9 Apr 2012 - by Tom Igoe with input from Usman Haque and Joe Saavedra - - http://arduino.cc/en/Tutorial/CosmClientString - This code is in the public domain. - - */ - -#include -#include - - -/#define APIKEY "YOUR API KEY GOES HERE" // replace your Cosm api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Project" // user agent is the project name - - -// assign a MAC address for the ethernet controller. -// fill in your address here: - byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; - -// fill in an available IP address on your network here, -// for manual configuration: -IPAddress ip(10,0,1,20); - -// initialize the library instance: -EthernetClient client; - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -IPAddress server(216,52,233,121); // numeric IP for api.cosm.com -//char server[] = "api.cosm.com"; // name address for Cosm API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to Cosm.com - -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // give the ethernet module time to boot up: - delay(1000); - // start the Ethernet connection: - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // DHCP failed, so use a fixed IP address: - Ethernet.begin(mac, ip); - } -} - -void loop() { - // read the analog sensor: - int sensorReading = analogRead(A0); - // convert the data to a String to send it: - - String dataString = "sensor1,"; - dataString += sensorReading; - - // you can append multiple readings to this String if your - // Cosm feed is set up to handle multiple values: - int otherSensorReading = analogRead(A1); - dataString += "\nsensor2,"; - dataString += otherSensorReading; - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - if (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - sendData(dataString); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void sendData(String thisData) { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.cosm.com"); - client.print("X-CosmApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - client.println(thisData.length()); - - // last pieces of the HTTP PUT request: - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request: - client.println(thisData); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted: - lastConnectionTime = millis(); -} - diff --git a/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino b/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino deleted file mode 100644 index 3457125..0000000 --- a/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino +++ /dev/null @@ -1,93 +0,0 @@ -/* - Telnet client - - This sketch connects to a a telnet server (http://www.google.com) - using an Arduino Wiznet Ethernet shield. You'll need a telnet server - to test this with. - Processing's ChatServer example (part of the network library) works well, - running on port 10002. It can be found as part of the examples - in the Processing application, available at - http://processing.org/ - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 14 Sep 2010 - modified 9 Apr 2012 - by Tom Igoe - - */ - -#include -#include - -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -IPAddress ip(192,168,1,177); - -// Enter the IP address of the server you're connecting to: -IPAddress server(1,1,1,1); - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 23 is default for telnet; -// if you're using Processing's ChatServer, use port 10002): -EthernetClient client; - -void setup() { - // start the Ethernet connection: - Ethernet.begin(mac, ip); - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // give the Ethernet shield a second to initialize: - delay(1000); - Serial.println("connecting..."); - - // if you get a connection, report back via serial: - if (client.connect(server, 10002)) { - Serial.println("connected"); - } - else { - // if you didn't get a connection to the server: - Serial.println("connection failed"); - } -} - -void loop() -{ - // if there are incoming bytes available - // from the server, read them and print them: - if (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // as long as there are bytes in the serial queue, - // read them and send them out the socket if it's open: - while (Serial.available() > 0) { - char inChar = Serial.read(); - if (client.connected()) { - client.print(inChar); - } - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - // do nothing: - while(true); - } -} - - - - diff --git a/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino b/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino deleted file mode 100644 index 9fee1fe..0000000 --- a/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino +++ /dev/null @@ -1,136 +0,0 @@ -/* - Twitter Client with Strings - - This sketch connects to Twitter using an Ethernet shield. It parses the XML - returned, and looks for this is a tweet - - You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield, - either one will work, as long as it's got a Wiznet Ethernet module on board. - - This example uses the DHCP routines in the Ethernet library which is part of the - Arduino core from version 1.0 beta 1 - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 21 May 2011 - modified 9 Apr 2012 - by Tom Igoe - - This code is in the public domain. - - */ -#include -#include - - -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network: -byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 }; -IPAddress ip(192,168,1,20); - -// initialize the library instance: -EthernetClient client; - -const unsigned long requestInterval = 60000; // delay between requests - -char serverName[] = "api.twitter.com"; // twitter URL - -boolean requested; // whether you've made a request since connecting -unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds - -String currentLine = ""; // string to hold the text from server -String tweet = ""; // string to hold the tweet -boolean readingTweet = false; // if you're currently reading the tweet - -void setup() { - // reserve space for the strings: - currentLine.reserve(256); - tweet.reserve(150); - - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // attempt a DHCP connection: - Serial.println("Attempting to get an IP address using DHCP:"); - if (!Ethernet.begin(mac)) { - // if DHCP fails, start with a hard-coded address: - Serial.println("failed to get an IP address using DHCP, trying manually"); - Ethernet.begin(mac, ip); - } - Serial.print("My address:"); - Serial.println(Ethernet.localIP()); - // connect to Twitter: - connectToServer(); -} - - - -void loop() -{ - if (client.connected()) { - if (client.available()) { - // read incoming bytes: - char inChar = client.read(); - - // add incoming byte to end of line: - currentLine += inChar; - - // if you get a newline, clear the line: - if (inChar == '\n') { - currentLine = ""; - } - // if the current line ends with , it will - // be followed by the tweet: - if ( currentLine.endsWith("")) { - // tweet is beginning. Clear the tweet string: - readingTweet = true; - tweet = ""; - } - // if you're currently reading the bytes of a tweet, - // add them to the tweet String: - if (readingTweet) { - if (inChar != '<') { - tweet += inChar; - } - else { - // if you got a "<" character, - // you've reached the end of the tweet: - readingTweet = false; - Serial.println(tweet); - // close the connection to the server: - client.stop(); - } - } - } - } - else if (millis() - lastAttemptTime > requestInterval) { - // if you're not connected, and two minutes have passed since - // your last connection, then attempt to connect again: - connectToServer(); - } -} - -void connectToServer() { - // attempt to connect, and wait a millisecond: - Serial.println("connecting to server..."); - if (client.connect(serverName, 80)) { - Serial.println("making HTTP request..."); - // make HTTP GET request to twitter: - client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1"); - client.println("HOST: api.twitter.com"); - client.println("Connection: close"); - client.println(); - } - // note the time of this connect attempt: - lastAttemptTime = millis(); -} - diff --git a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino deleted file mode 100644 index 4d4045c..0000000 --- a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino +++ /dev/null @@ -1,118 +0,0 @@ -/* - UDPSendReceive.pde: - This sketch receives UDP message strings, prints them to the serial port - and sends an "acknowledge" string back to the sender - - A Processing sketch is included at the end of file that can be used to send - and received messages for testing with a computer. - - created 21 Aug 2010 - by Michael Margolis - - This code is in the public domain. - */ - - -#include // needed for Arduino versions later than 0018 -#include -#include // UDP library from: bjoern@cs.stanford.edu 12/30/2008 - - -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -IPAddress ip(192, 168, 1, 177); - -unsigned int localPort = 8888; // local port to listen on - -// buffers for receiving and sending data -char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, -char ReplyBuffer[] = "acknowledged"; // a string to send back - -// An EthernetUDP instance to let us send and receive packets over UDP -EthernetUDP Udp; - -void setup() { - // start the Ethernet and UDP: - Ethernet.begin(mac,ip); - Udp.begin(localPort); - - Serial.begin(9600); -} - -void loop() { - // if there's data available, read a packet - int packetSize = Udp.parsePacket(); - if(packetSize) - { - Serial.print("Received packet of size "); - Serial.println(packetSize); - Serial.print("From "); - IPAddress remote = Udp.remoteIP(); - for (int i =0; i < 4; i++) - { - Serial.print(remote[i], DEC); - if (i < 3) - { - Serial.print("."); - } - } - Serial.print(", port "); - Serial.println(Udp.remotePort()); - - // read the packet into packetBufffer - Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); - Serial.println("Contents:"); - Serial.println(packetBuffer); - - // send a reply, to the IP address and port that sent us the packet we received - Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); - Udp.write(ReplyBuffer); - Udp.endPacket(); - } - delay(10); -} - - -/* - Processing sketch to run with this example - ===================================================== - - // Processing UDP example to send and receive string data from Arduino - // press any key to send the "Hello Arduino" message - - - import hypermedia.net.*; - - UDP udp; // define the UDP object - - - void setup() { - udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000 - //udp.log( true ); // <-- printout the connection activity - udp.listen( true ); // and wait for incoming message - } - - void draw() - { - } - - void keyPressed() { - String ip = "192.168.1.177"; // the remote IP address - int port = 8888; // the destination port - - udp.send("Hello World", ip, port ); // the message to send - - } - - void receive( byte[] data ) { // <-- default handler - //void receive( byte[] data, String ip, int port ) { // <-- extended handler - - for(int i=0; i < data.length; i++) - print(char(data[i])); - println(); - } - */ - - diff --git a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino deleted file mode 100644 index 93ffe39..0000000 --- a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino +++ /dev/null @@ -1,141 +0,0 @@ -/* - - Udp NTP Client - - Get the time from a Network Time Protocol (NTP) time server - Demonstrates use of UDP sendPacket and ReceivePacket - For more on NTP time servers and the messages needed to communicate with them, - see http://en.wikipedia.org/wiki/Network_Time_Protocol - - created 4 Sep 2010 - by Michael Margolis - modified 9 Apr 2012 - by Tom Igoe - - This code is in the public domain. - - */ - -#include -#include -#include - -// Enter a MAC address for your controller below. -// Newer Ethernet shields have a MAC address printed on a sticker on the shield -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; - -unsigned int localPort = 8888; // local port to listen for UDP packets - -IPAddress timeServer(192, 43, 244, 18); // time.nist.gov NTP server - -const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message - -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets - -// A UDP instance to let us send and receive packets over UDP -EthernetUDP Udp; - -void setup() -{ - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // start Ethernet and UDP - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // no point in carrying on, so do nothing forevermore: - for(;;) - ; - } - Udp.begin(localPort); -} - -void loop() -{ - sendNTPpacket(timeServer); // send an NTP packet to a time server - - // wait to see if a reply is available - delay(1000); - if ( Udp.parsePacket() ) { - // We've received a packet, read the data from it - Udp.read(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer - - //the timestamp starts at byte 40 of the received packet and is four bytes, - // or two words, long. First, esxtract the two words: - - unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); - unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); - // combine the four bytes (two words) into a long integer - // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; - Serial.print("Seconds since Jan 1 1900 = " ); - Serial.println(secsSince1900); - - // now convert NTP time into everyday time: - Serial.print("Unix time = "); - // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: - const unsigned long seventyYears = 2208988800UL; - // subtract seventy years: - unsigned long epoch = secsSince1900 - seventyYears; - // print Unix time: - Serial.println(epoch); - - - // print the hour, minute and second: - Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) - Serial.print(':'); - if ( ((epoch % 3600) / 60) < 10 ) { - // In the first 10 minutes of each hour, we'll want a leading '0' - Serial.print('0'); - } - Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) - Serial.print(':'); - if ( (epoch % 60) < 10 ) { - // In the first 10 seconds of each minute, we'll want a leading '0' - Serial.print('0'); - } - Serial.println(epoch %60); // print the second - } - // wait ten seconds before asking for the time again - delay(10000); -} - -// send an NTP request to the time server at the given address -unsigned long sendNTPpacket(IPAddress& address) -{ - // set all bytes in the buffer to 0 - memset(packetBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; - packetBuffer[13] = 0x4E; - packetBuffer[14] = 49; - packetBuffer[15] = 52; - - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - Udp.beginPacket(address, 123); //NTP requests are to port 123 - Udp.write(packetBuffer,NTP_PACKET_SIZE); - Udp.endPacket(); -} - - - - - - - - - - diff --git a/libraries/Ethernet/examples/WebClient/WebClient.ino b/libraries/Ethernet/examples/WebClient/WebClient.ino deleted file mode 100644 index 40523a4..0000000 --- a/libraries/Ethernet/examples/WebClient/WebClient.ino +++ /dev/null @@ -1,88 +0,0 @@ -/* - Web client - - This sketch connects to a website (http://www.google.com) - using an Arduino Wiznet Ethernet shield. - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 18 Dec 2009 - by David A. Mellis - modified 9 Apr 2012 - by Tom Igoe, based on work by Adrian McEwen - - */ - -#include -#include - -// Enter a MAC address for your controller below. -// Newer Ethernet shields have a MAC address printed on a sticker on the shield -byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Set the static IP address to use if the DHCP fails to assign -IPAddress ip(192,168,0,177); - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -EthernetClient client; - -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // start the Ethernet connection: - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // no point in carrying on, so do nothing forevermore: - // try to congifure using IP address instead of DHCP: - Ethernet.begin(mac, ip); - } - // give the Ethernet shield a second to initialize: - delay(1000); - Serial.println("connecting..."); - - // if you get a connection, report back via serial: - if (client.connect(server, 80)) { - Serial.println("connected"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } - else { - // kf you didn't get a connection to the server: - Serial.println("connection failed"); - } -} - -void loop() -{ - // if there are incoming bytes available - // from the server, read them and print them: - if (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - - // do nothing forevermore: - while(true); - } -} - diff --git a/libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino b/libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino deleted file mode 100644 index 650f74e..0000000 --- a/libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino +++ /dev/null @@ -1,111 +0,0 @@ -/* - Repeating Web client - - This sketch connects to a a web server and makes a request - using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or - the Adafruit Ethernet shield, either one will work, as long as it's got - a Wiznet Ethernet module on board. - - This example uses DNS, by assigning the Ethernet client with a MAC address, - IP address, and DNS address. - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - - created 19 Apr 2012 - by Tom Igoe - - http://arduino.cc/en/Tutorial/WebClientRepeating - This code is in the public domain. - - */ - -#include -#include - -// assign a MAC address for the ethernet controller. -// fill in your address here: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -// fill in an available IP address on your network here, -// for manual configuration: -IPAddress ip(10,0,0,20); - -// fill in your Domain Name Server address here: -IPAddress myDns(1,1,1,1); - -// initialize the library instance: -EthernetClient client; - -char server[] = "www.arduino.cc"; - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 60L*1000L; // delay between updates, in milliseconds - // the "L" is needed to use long type numbers - -void setup() { - // start serial port: - Serial.begin(9600); - // give the ethernet module time to boot up: - delay(1000); - // start the Ethernet connection using a fixed IP address and DNS server: - Ethernet.begin(mac, ip, myDns); - // print the Ethernet board/shield's IP address: - Serial.print("My IP address: "); - Serial.println(Ethernet.localIP()); -} - -void loop() { - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - if (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - httpRequest(); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void httpRequest() { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.println("GET /latest.txt HTTP/1.1"); - client.println("Host: www.arduino.cc"); - client.println("User-Agent: arduino-ethernet"); - client.println("Connection: close"); - client.println(); - - // note the time that the connection was made: - lastConnectionTime = millis(); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println("disconnecting."); - client.stop(); - } -} - - - - diff --git a/libraries/Ethernet/examples/WebServer/WebServer.ino b/libraries/Ethernet/examples/WebServer/WebServer.ino deleted file mode 100644 index 5e5d67a..0000000 --- a/libraries/Ethernet/examples/WebServer/WebServer.ino +++ /dev/null @@ -1,100 +0,0 @@ -/* - Web Server - - A simple web server that shows the value of the analog input pins. - using an Arduino Wiznet Ethernet shield. - - Circuit: - * Ethernet shield attached to pins 10, 11, 12, 13 - * Analog inputs attached to pins A0 through A5 (optional) - - created 18 Dec 2009 - by David A. Mellis - modified 9 Apr 2012 - by Tom Igoe - - */ - -#include -#include - -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network: -byte mac[] = { - 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -IPAddress ip(192,168,1,177); - -// Initialize the Ethernet server library -// with the IP address and port you want to use -// (port 80 is default for HTTP): -EthernetServer server(80); - -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // start the Ethernet connection and the server: - Ethernet.begin(mac, ip); - server.begin(); - Serial.print("server is at "); - Serial.println(Ethernet.localIP()); -} - - -void loop() { - // listen for incoming clients - EthernetClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - diff --git a/libraries/Ethernet/keywords.txt b/libraries/Ethernet/keywords.txt deleted file mode 100644 index 6b37cbe..0000000 --- a/libraries/Ethernet/keywords.txt +++ /dev/null @@ -1,37 +0,0 @@ -####################################### -# Syntax Coloring Map For Ethernet -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Ethernet KEYWORD1 -EthernetClient KEYWORD1 -EthernetServer KEYWORD1 -IPAddress KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -status KEYWORD2 -connect KEYWORD2 -write KEYWORD2 -available KEYWORD2 -read KEYWORD2 -peek KEYWORD2 -flush KEYWORD2 -stop KEYWORD2 -connected KEYWORD2 -begin KEYWORD2 -beginPacket KEYWORD2 -endPacket KEYWORD2 -parsePacket KEYWORD2 -remoteIP KEYWORD2 -remotePort KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/libraries/Ethernet/util.h b/libraries/Ethernet/util.h deleted file mode 100644 index 5042e82..0000000 --- a/libraries/Ethernet/util.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef UTIL_H -#define UTIL_H - -#define htons(x) ( ((x)<<8) | (((x)>>8)&0xFF) ) -#define ntohs(x) htons(x) - -#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \ - ((x)<< 8 & 0x00FF0000UL) | \ - ((x)>> 8 & 0x0000FF00UL) | \ - ((x)>>24 & 0x000000FFUL) ) -#define ntohl(x) htonl(x) - -#endif diff --git a/libraries/Ethernet/utility/socket.cpp b/libraries/Ethernet/utility/socket.cpp deleted file mode 100644 index fd3e442..0000000 --- a/libraries/Ethernet/utility/socket.cpp +++ /dev/null @@ -1,400 +0,0 @@ -#include "w5100.h" -#include "socket.h" - -static uint16_t local_port; - -/** - * @brief This Socket function initialize the channel in perticular mode, and set the port and wait for W5100 done it. - * @return 1 for success else 0. - */ -uint8_t socket(SOCKET s, uint8_t protocol, uint16_t port, uint8_t flag) -{ - if ((protocol == SnMR::TCP) || (protocol == SnMR::UDP) || (protocol == SnMR::IPRAW) || (protocol == SnMR::MACRAW) || (protocol == SnMR::PPPOE)) - { - close(s); - W5100.writeSnMR(s, protocol | flag); - if (port != 0) { - W5100.writeSnPORT(s, port); - } - else { - local_port++; // if don't set the source port, set local_port number. - W5100.writeSnPORT(s, local_port); - } - - W5100.execCmdSn(s, Sock_OPEN); - - return 1; - } - - return 0; -} - - -/** - * @brief This function close the socket and parameter is "s" which represent the socket number - */ -void close(SOCKET s) -{ - W5100.execCmdSn(s, Sock_CLOSE); - W5100.writeSnIR(s, 0xFF); -} - - -/** - * @brief This function established the connection for the channel in passive (server) mode. This function waits for the request from the peer. - * @return 1 for success else 0. - */ -uint8_t listen(SOCKET s) -{ - if (W5100.readSnSR(s) != SnSR::INIT) - return 0; - W5100.execCmdSn(s, Sock_LISTEN); - return 1; -} - - -/** - * @brief This function established the connection for the channel in Active (client) mode. - * This function waits for the untill the connection is established. - * - * @return 1 for success else 0. - */ -uint8_t connect(SOCKET s, uint8_t * addr, uint16_t port) -{ - if - ( - ((addr[0] == 0xFF) && (addr[1] == 0xFF) && (addr[2] == 0xFF) && (addr[3] == 0xFF)) || - ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) || - (port == 0x00) - ) - return 0; - - // set destination IP - W5100.writeSnDIPR(s, addr); - W5100.writeSnDPORT(s, port); - W5100.execCmdSn(s, Sock_CONNECT); - - return 1; -} - - - -/** - * @brief This function used for disconnect the socket and parameter is "s" which represent the socket number - * @return 1 for success else 0. - */ -void disconnect(SOCKET s) -{ - W5100.execCmdSn(s, Sock_DISCON); -} - - -/** - * @brief This function used to send the data in TCP mode - * @return 1 for success else 0. - */ -uint16_t send(SOCKET s, const uint8_t * buf, uint16_t len) -{ - uint8_t status=0; - uint16_t ret=0; - uint16_t freesize=0; - - if (len > W5100.SSIZE) - ret = W5100.SSIZE; // check size not to exceed MAX size. - else - ret = len; - - // if freebuf is available, start. - do - { - freesize = W5100.getTXFreeSize(s); - status = W5100.readSnSR(s); - if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) - { - ret = 0; - break; - } - } - while (freesize < ret); - - // copy data - W5100.send_data_processing(s, (uint8_t *)buf, ret); - W5100.execCmdSn(s, Sock_SEND); - - /* +2008.01 bj */ - while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) - { - /* m2008.01 [bj] : reduce code */ - if ( W5100.readSnSR(s) == SnSR::CLOSED ) - { - close(s); - return 0; - } - } - /* +2008.01 bj */ - W5100.writeSnIR(s, SnIR::SEND_OK); - return ret; -} - - -/** - * @brief This function is an application I/F function which is used to receive the data in TCP mode. - * It continues to wait for data as much as the application wants to receive. - * - * @return received data size for success else -1. - */ -int16_t recv(SOCKET s, uint8_t *buf, int16_t len) -{ - // Check how much data is available - int16_t ret = W5100.getRXReceivedSize(s); - if ( ret == 0 ) - { - // No data available. - uint8_t status = W5100.readSnSR(s); - if ( status == SnSR::LISTEN || status == SnSR::CLOSED || status == SnSR::CLOSE_WAIT ) - { - // The remote end has closed its side of the connection, so this is the eof state - ret = 0; - } - else - { - // The connection is still up, but there's no data waiting to be read - ret = -1; - } - } - else if (ret > len) - { - ret = len; - } - - if ( ret > 0 ) - { - W5100.recv_data_processing(s, buf, ret); - W5100.execCmdSn(s, Sock_RECV); - } - return ret; -} - - -/** - * @brief Returns the first byte in the receive queue (no checking) - * - * @return - */ -uint16_t peek(SOCKET s, uint8_t *buf) -{ - W5100.recv_data_processing(s, buf, 1, 1); - - return 1; -} - - -/** - * @brief This function is an application I/F function which is used to send the data for other then TCP mode. - * Unlike TCP transmission, The peer's destination address and the port is needed. - * - * @return This function return send data size for success else -1. - */ -uint16_t sendto(SOCKET s, const uint8_t *buf, uint16_t len, uint8_t *addr, uint16_t port) -{ - uint16_t ret=0; - - if (len > W5100.SSIZE) ret = W5100.SSIZE; // check size not to exceed MAX size. - else ret = len; - - if - ( - ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) || - ((port == 0x00)) ||(ret == 0) - ) - { - /* +2008.01 [bj] : added return value */ - ret = 0; - } - else - { - W5100.writeSnDIPR(s, addr); - W5100.writeSnDPORT(s, port); - - // copy data - W5100.send_data_processing(s, (uint8_t *)buf, ret); - W5100.execCmdSn(s, Sock_SEND); - - /* +2008.01 bj */ - while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) - { - if (W5100.readSnIR(s) & SnIR::TIMEOUT) - { - /* +2008.01 [bj]: clear interrupt */ - W5100.writeSnIR(s, (SnIR::SEND_OK | SnIR::TIMEOUT)); /* clear SEND_OK & TIMEOUT */ - return 0; - } - } - - /* +2008.01 bj */ - W5100.writeSnIR(s, SnIR::SEND_OK); - } - return ret; -} - - -/** - * @brief This function is an application I/F function which is used to receive the data in other then - * TCP mode. This function is used to receive UDP, IP_RAW and MAC_RAW mode, and handle the header as well. - * - * @return This function return received data size for success else -1. - */ -uint16_t recvfrom(SOCKET s, uint8_t *buf, uint16_t len, uint8_t *addr, uint16_t *port) -{ - uint8_t head[8]; - uint16_t data_len=0; - uint16_t ptr=0; - - if ( len > 0 ) - { - ptr = W5100.readSnRX_RD(s); - switch (W5100.readSnMR(s) & 0x07) - { - case SnMR::UDP : - W5100.read_data(s, (uint8_t *)ptr, head, 0x08); - ptr += 8; - // read peer's IP address, port number. - addr[0] = head[0]; - addr[1] = head[1]; - addr[2] = head[2]; - addr[3] = head[3]; - *port = head[4]; - *port = (*port << 8) + head[5]; - data_len = head[6]; - data_len = (data_len << 8) + head[7]; - - W5100.read_data(s, (uint8_t *)ptr, buf, data_len); // data copy. - ptr += data_len; - - W5100.writeSnRX_RD(s, ptr); - break; - - case SnMR::IPRAW : - W5100.read_data(s, (uint8_t *)ptr, head, 0x06); - ptr += 6; - - addr[0] = head[0]; - addr[1] = head[1]; - addr[2] = head[2]; - addr[3] = head[3]; - data_len = head[4]; - data_len = (data_len << 8) + head[5]; - - W5100.read_data(s, (uint8_t *)ptr, buf, data_len); // data copy. - ptr += data_len; - - W5100.writeSnRX_RD(s, ptr); - break; - - case SnMR::MACRAW: - W5100.read_data(s,(uint8_t*)ptr,head,2); - ptr+=2; - data_len = head[0]; - data_len = (data_len<<8) + head[1] - 2; - - W5100.read_data(s,(uint8_t*) ptr,buf,data_len); - ptr += data_len; - W5100.writeSnRX_RD(s, ptr); - break; - - default : - break; - } - W5100.execCmdSn(s, Sock_RECV); - } - return data_len; -} - - -uint16_t igmpsend(SOCKET s, const uint8_t * buf, uint16_t len) -{ - uint8_t status=0; - uint16_t ret=0; - - if (len > W5100.SSIZE) - ret = W5100.SSIZE; // check size not to exceed MAX size. - else - ret = len; - - if (ret == 0) - return 0; - - W5100.send_data_processing(s, (uint8_t *)buf, ret); - W5100.execCmdSn(s, Sock_SEND); - - while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) - { - status = W5100.readSnSR(s); - if (W5100.readSnIR(s) & SnIR::TIMEOUT) - { - /* in case of igmp, if send fails, then socket closed */ - /* if you want change, remove this code. */ - close(s); - return 0; - } - } - - W5100.writeSnIR(s, SnIR::SEND_OK); - return ret; -} - -uint16_t bufferData(SOCKET s, uint16_t offset, const uint8_t* buf, uint16_t len) -{ - uint16_t ret =0; - if (len > W5100.getTXFreeSize(s)) - { - ret = W5100.getTXFreeSize(s); // check size not to exceed MAX size. - } - else - { - ret = len; - } - W5100.send_data_processing_offset(s, offset, buf, ret); - return ret; -} - -int startUDP(SOCKET s, uint8_t* addr, uint16_t port) -{ - if - ( - ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) || - ((port == 0x00)) - ) - { - return 0; - } - else - { - W5100.writeSnDIPR(s, addr); - W5100.writeSnDPORT(s, port); - return 1; - } -} - -int sendUDP(SOCKET s) -{ - W5100.execCmdSn(s, Sock_SEND); - - /* +2008.01 bj */ - while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) - { - if (W5100.readSnIR(s) & SnIR::TIMEOUT) - { - /* +2008.01 [bj]: clear interrupt */ - W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT)); - return 0; - } - } - - /* +2008.01 bj */ - W5100.writeSnIR(s, SnIR::SEND_OK); - - /* Sent ok */ - return 1; -} - diff --git a/libraries/Ethernet/utility/socket.h b/libraries/Ethernet/utility/socket.h deleted file mode 100644 index 45e0fb3..0000000 --- a/libraries/Ethernet/utility/socket.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef _SOCKET_H_ -#define _SOCKET_H_ - -#include "w5100.h" - -extern uint8_t socket(SOCKET s, uint8_t protocol, uint16_t port, uint8_t flag); // Opens a socket(TCP or UDP or IP_RAW mode) -extern void close(SOCKET s); // Close socket -extern uint8_t connect(SOCKET s, uint8_t * addr, uint16_t port); // Establish TCP connection (Active connection) -extern void disconnect(SOCKET s); // disconnect the connection -extern uint8_t listen(SOCKET s); // Establish TCP connection (Passive connection) -extern uint16_t send(SOCKET s, const uint8_t * buf, uint16_t len); // Send data (TCP) -extern int16_t recv(SOCKET s, uint8_t * buf, int16_t len); // Receive data (TCP) -extern uint16_t peek(SOCKET s, uint8_t *buf); -extern uint16_t sendto(SOCKET s, const uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); // Send data (UDP/IP RAW) -extern uint16_t recvfrom(SOCKET s, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); // Receive data (UDP/IP RAW) - -extern uint16_t igmpsend(SOCKET s, const uint8_t * buf, uint16_t len); - -// Functions to allow buffered UDP send (i.e. where the UDP datagram is built up over a -// number of calls before being sent -/* - @brief This function sets up a UDP datagram, the data for which will be provided by one - or more calls to bufferData and then finally sent with sendUDP. - @return 1 if the datagram was successfully set up, or 0 if there was an error -*/ -extern int startUDP(SOCKET s, uint8_t* addr, uint16_t port); -/* - @brief This function copies up to len bytes of data from buf into a UDP datagram to be - sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls. - @return Number of bytes successfully buffered -*/ -uint16_t bufferData(SOCKET s, uint16_t offset, const uint8_t* buf, uint16_t len); -/* - @brief Send a UDP datagram built up from a sequence of startUDP followed by one or more - calls to bufferData. - @return 1 if the datagram was successfully sent, or 0 if there was an error -*/ -int sendUDP(SOCKET s); - -#endif -/* _SOCKET_H_ */ diff --git a/libraries/Ethernet/utility/w5100.cpp b/libraries/Ethernet/utility/w5100.cpp deleted file mode 100644 index 9c748fd..0000000 --- a/libraries/Ethernet/utility/w5100.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#include -#include -#include - -#include "w5100.h" - -// W5100 controller instance -W5100Class W5100; - -#define TX_RX_MAX_BUF_SIZE 2048 -#define TX_BUF 0x1100 -#define RX_BUF (TX_BUF + TX_RX_MAX_BUF_SIZE) - -#define TXBUF_BASE 0x4000 -#define RXBUF_BASE 0x6000 - -void W5100Class::init(void) -{ - delay(300); - - SPI.begin(); - initSS(); - - writeMR(1< SSIZE) - { - // Wrap around circular buffer - uint16_t size = SSIZE - offset; - write(dstAddr, data, size); - write(SBASE[s], data + size, len - size); - } - else { - write(dstAddr, data, len); - } - - ptr += len; - writeSnTX_WR(s, ptr); -} - - -void W5100Class::recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek) -{ - uint16_t ptr; - ptr = readSnRX_RD(s); - read_data(s, (uint8_t *)ptr, data, len); - if (!peek) - { - ptr += len; - writeSnRX_RD(s, ptr); - } -} - -void W5100Class::read_data(SOCKET s, volatile uint8_t *src, volatile uint8_t *dst, uint16_t len) -{ - uint16_t size; - uint16_t src_mask; - uint16_t src_ptr; - - src_mask = (uint16_t)src & RMASK; - src_ptr = RBASE[s] + src_mask; - - if( (src_mask + len) > RSIZE ) - { - size = RSIZE - src_mask; - read(src_ptr, (uint8_t *)dst, size); - dst += size; - read(RBASE[s], (uint8_t *) dst, len - size); - } - else - read(src_ptr, (uint8_t *) dst, len); -} - - -uint8_t W5100Class::write(uint16_t _addr, uint8_t _data) -{ - setSS(); - SPI.transfer(0xF0); - SPI.transfer(_addr >> 8); - SPI.transfer(_addr & 0xFF); - SPI.transfer(_data); - resetSS(); - return 1; -} - -uint16_t W5100Class::write(uint16_t _addr, const uint8_t *_buf, uint16_t _len) -{ - for (uint16_t i=0; i<_len; i++) - { - setSS(); - SPI.transfer(0xF0); - SPI.transfer(_addr >> 8); - SPI.transfer(_addr & 0xFF); - _addr++; - SPI.transfer(_buf[i]); - resetSS(); - } - return _len; -} - -uint8_t W5100Class::read(uint16_t _addr) -{ - setSS(); - SPI.transfer(0x0F); - SPI.transfer(_addr >> 8); - SPI.transfer(_addr & 0xFF); - uint8_t _data = SPI.transfer(0); - resetSS(); - return _data; -} - -uint16_t W5100Class::read(uint16_t _addr, uint8_t *_buf, uint16_t _len) -{ - for (uint16_t i=0; i<_len; i++) - { - setSS(); - SPI.transfer(0x0F); - SPI.transfer(_addr >> 8); - SPI.transfer(_addr & 0xFF); - _addr++; - _buf[i] = SPI.transfer(0); - resetSS(); - } - return _len; -} - -void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) { - // Send command to socket - writeSnCR(s, _cmd); - // Wait for command to complete - while (readSnCR(s)) - ; -} diff --git a/libraries/Ethernet/utility/w5100.h b/libraries/Ethernet/utility/w5100.h deleted file mode 100644 index 8dccd9f..0000000 --- a/libraries/Ethernet/utility/w5100.h +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#ifndef W5100_H_INCLUDED -#define W5100_H_INCLUDED - -#include -#include - -#define MAX_SOCK_NUM 4 - -typedef uint8_t SOCKET; - -#define IDM_OR 0x8000 -#define IDM_AR0 0x8001 -#define IDM_AR1 0x8002 -#define IDM_DR 0x8003 -/* -class MR { -public: - static const uint8_t RST = 0x80; - static const uint8_t PB = 0x10; - static const uint8_t PPPOE = 0x08; - static const uint8_t LB = 0x04; - static const uint8_t AI = 0x02; - static const uint8_t IND = 0x01; -}; -*/ -/* -class IR { -public: - static const uint8_t CONFLICT = 0x80; - static const uint8_t UNREACH = 0x40; - static const uint8_t PPPoE = 0x20; - static const uint8_t SOCK0 = 0x01; - static const uint8_t SOCK1 = 0x02; - static const uint8_t SOCK2 = 0x04; - static const uint8_t SOCK3 = 0x08; - static inline uint8_t SOCK(SOCKET ch) { return (0x01 << ch); }; -}; -*/ - -class SnMR { -public: - static const uint8_t CLOSE = 0x00; - static const uint8_t TCP = 0x01; - static const uint8_t UDP = 0x02; - static const uint8_t IPRAW = 0x03; - static const uint8_t MACRAW = 0x04; - static const uint8_t PPPOE = 0x05; - static const uint8_t ND = 0x20; - static const uint8_t MULTI = 0x80; -}; - -enum SockCMD { - Sock_OPEN = 0x01, - Sock_LISTEN = 0x02, - Sock_CONNECT = 0x04, - Sock_DISCON = 0x08, - Sock_CLOSE = 0x10, - Sock_SEND = 0x20, - Sock_SEND_MAC = 0x21, - Sock_SEND_KEEP = 0x22, - Sock_RECV = 0x40 -}; - -/*class SnCmd { -public: - static const uint8_t OPEN = 0x01; - static const uint8_t LISTEN = 0x02; - static const uint8_t CONNECT = 0x04; - static const uint8_t DISCON = 0x08; - static const uint8_t CLOSE = 0x10; - static const uint8_t SEND = 0x20; - static const uint8_t SEND_MAC = 0x21; - static const uint8_t SEND_KEEP = 0x22; - static const uint8_t RECV = 0x40; -}; -*/ - -class SnIR { -public: - static const uint8_t SEND_OK = 0x10; - static const uint8_t TIMEOUT = 0x08; - static const uint8_t RECV = 0x04; - static const uint8_t DISCON = 0x02; - static const uint8_t CON = 0x01; -}; - -class SnSR { -public: - static const uint8_t CLOSED = 0x00; - static const uint8_t INIT = 0x13; - static const uint8_t LISTEN = 0x14; - static const uint8_t SYNSENT = 0x15; - static const uint8_t SYNRECV = 0x16; - static const uint8_t ESTABLISHED = 0x17; - static const uint8_t FIN_WAIT = 0x18; - static const uint8_t CLOSING = 0x1A; - static const uint8_t TIME_WAIT = 0x1B; - static const uint8_t CLOSE_WAIT = 0x1C; - static const uint8_t LAST_ACK = 0x1D; - static const uint8_t UDP = 0x22; - static const uint8_t IPRAW = 0x32; - static const uint8_t MACRAW = 0x42; - static const uint8_t PPPOE = 0x5F; -}; - -class IPPROTO { -public: - static const uint8_t IP = 0; - static const uint8_t ICMP = 1; - static const uint8_t IGMP = 2; - static const uint8_t GGP = 3; - static const uint8_t TCP = 6; - static const uint8_t PUP = 12; - static const uint8_t UDP = 17; - static const uint8_t IDP = 22; - static const uint8_t ND = 77; - static const uint8_t RAW = 255; -}; - -class W5100Class { - -public: - void init(); - - /** - * @brief This function is being used for copy the data form Receive buffer of the chip to application buffer. - * - * It calculate the actual physical address where one has to read - * the data from Receive buffer. Here also take care of the condition while it exceed - * the Rx memory uper-bound of socket. - */ - void read_data(SOCKET s, volatile uint8_t * src, volatile uint8_t * dst, uint16_t len); - - /** - * @brief This function is being called by send() and sendto() function also. - * - * This function read the Tx write pointer register and after copy the data in buffer update the Tx write pointer - * register. User should read upper byte first and lower byte later to get proper value. - */ - void send_data_processing(SOCKET s, const uint8_t *data, uint16_t len); - /** - * @brief A copy of send_data_processing that uses the provided ptr for the - * write offset. Only needed for the "streaming" UDP API, where - * a single UDP packet is built up over a number of calls to - * send_data_processing_ptr, because TX_WR doesn't seem to get updated - * correctly in those scenarios - * @param ptr value to use in place of TX_WR. If 0, then the value is read - * in from TX_WR - * @return New value for ptr, to be used in the next call - */ -// FIXME Update documentation - void send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len); - - /** - * @brief This function is being called by recv() also. - * - * This function read the Rx read pointer register - * and after copy the data from receive buffer update the Rx write pointer register. - * User should read upper byte first and lower byte later to get proper value. - */ - void recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek = 0); - - inline void setGatewayIp(uint8_t *_addr); - inline void getGatewayIp(uint8_t *_addr); - - inline void setSubnetMask(uint8_t *_addr); - inline void getSubnetMask(uint8_t *_addr); - - inline void setMACAddress(uint8_t * addr); - inline void getMACAddress(uint8_t * addr); - - inline void setIPAddress(uint8_t * addr); - inline void getIPAddress(uint8_t * addr); - - inline void setRetransmissionTime(uint16_t timeout); - inline void setRetransmissionCount(uint8_t _retry); - - void execCmdSn(SOCKET s, SockCMD _cmd); - - uint16_t getTXFreeSize(SOCKET s); - uint16_t getRXReceivedSize(SOCKET s); - - - // W5100 Registers - // --------------- -private: - static uint8_t write(uint16_t _addr, uint8_t _data); - static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len); - static uint8_t read(uint16_t addr); - static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len); - -#define __GP_REGISTER8(name, address) \ - static inline void write##name(uint8_t _data) { \ - write(address, _data); \ - } \ - static inline uint8_t read##name() { \ - return read(address); \ - } -#define __GP_REGISTER16(name, address) \ - static void write##name(uint16_t _data) { \ - write(address, _data >> 8); \ - write(address+1, _data & 0xFF); \ - } \ - static uint16_t read##name() { \ - uint16_t res = read(address); \ - res = (res << 8) + read(address + 1); \ - return res; \ - } -#define __GP_REGISTER_N(name, address, size) \ - static uint16_t write##name(uint8_t *_buff) { \ - return write(address, _buff, size); \ - } \ - static uint16_t read##name(uint8_t *_buff) { \ - return read(address, _buff, size); \ - } - -public: - __GP_REGISTER8 (MR, 0x0000); // Mode - __GP_REGISTER_N(GAR, 0x0001, 4); // Gateway IP address - __GP_REGISTER_N(SUBR, 0x0005, 4); // Subnet mask address - __GP_REGISTER_N(SHAR, 0x0009, 6); // Source MAC address - __GP_REGISTER_N(SIPR, 0x000F, 4); // Source IP address - __GP_REGISTER8 (IR, 0x0015); // Interrupt - __GP_REGISTER8 (IMR, 0x0016); // Interrupt Mask - __GP_REGISTER16(RTR, 0x0017); // Timeout address - __GP_REGISTER8 (RCR, 0x0019); // Retry count - __GP_REGISTER8 (RMSR, 0x001A); // Receive memory size - __GP_REGISTER8 (TMSR, 0x001B); // Transmit memory size - __GP_REGISTER8 (PATR, 0x001C); // Authentication type address in PPPoE mode - __GP_REGISTER8 (PTIMER, 0x0028); // PPP LCP Request Timer - __GP_REGISTER8 (PMAGIC, 0x0029); // PPP LCP Magic Number - __GP_REGISTER_N(UIPR, 0x002A, 4); // Unreachable IP address in UDP mode - __GP_REGISTER16(UPORT, 0x002E); // Unreachable Port address in UDP mode - -#undef __GP_REGISTER8 -#undef __GP_REGISTER16 -#undef __GP_REGISTER_N - - // W5100 Socket registers - // ---------------------- -private: - static inline uint8_t readSn(SOCKET _s, uint16_t _addr); - static inline uint8_t writeSn(SOCKET _s, uint16_t _addr, uint8_t _data); - static inline uint16_t readSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t len); - static inline uint16_t writeSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t len); - - static const uint16_t CH_BASE = 0x0400; - static const uint16_t CH_SIZE = 0x0100; - -#define __SOCKET_REGISTER8(name, address) \ - static inline void write##name(SOCKET _s, uint8_t _data) { \ - writeSn(_s, address, _data); \ - } \ - static inline uint8_t read##name(SOCKET _s) { \ - return readSn(_s, address); \ - } -#define __SOCKET_REGISTER16(name, address) \ - static void write##name(SOCKET _s, uint16_t _data) { \ - writeSn(_s, address, _data >> 8); \ - writeSn(_s, address+1, _data & 0xFF); \ - } \ - static uint16_t read##name(SOCKET _s) { \ - uint16_t res = readSn(_s, address); \ - uint16_t res2 = readSn(_s,address + 1); \ - res = res << 8; \ - res2 = res2 & 0xFF; \ - res = res | res2; \ - return res; \ - } -#define __SOCKET_REGISTER_N(name, address, size) \ - static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \ - return writeSn(_s, address, _buff, size); \ - } \ - static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \ - return readSn(_s, address, _buff, size); \ - } - -public: - __SOCKET_REGISTER8(SnMR, 0x0000) // Mode - __SOCKET_REGISTER8(SnCR, 0x0001) // Command - __SOCKET_REGISTER8(SnIR, 0x0002) // Interrupt - __SOCKET_REGISTER8(SnSR, 0x0003) // Status - __SOCKET_REGISTER16(SnPORT, 0x0004) // Source Port - __SOCKET_REGISTER_N(SnDHAR, 0x0006, 6) // Destination Hardw Addr - __SOCKET_REGISTER_N(SnDIPR, 0x000C, 4) // Destination IP Addr - __SOCKET_REGISTER16(SnDPORT, 0x0010) // Destination Port - __SOCKET_REGISTER16(SnMSSR, 0x0012) // Max Segment Size - __SOCKET_REGISTER8(SnPROTO, 0x0014) // Protocol in IP RAW Mode - __SOCKET_REGISTER8(SnTOS, 0x0015) // IP TOS - __SOCKET_REGISTER8(SnTTL, 0x0016) // IP TTL - __SOCKET_REGISTER16(SnTX_FSR, 0x0020) // TX Free Size - __SOCKET_REGISTER16(SnTX_RD, 0x0022) // TX Read Pointer - __SOCKET_REGISTER16(SnTX_WR, 0x0024) // TX Write Pointer - __SOCKET_REGISTER16(SnRX_RSR, 0x0026) // RX Free Size - __SOCKET_REGISTER16(SnRX_RD, 0x0028) // RX Read Pointer - __SOCKET_REGISTER16(SnRX_WR, 0x002A) // RX Write Pointer (supported?) - -#undef __SOCKET_REGISTER8 -#undef __SOCKET_REGISTER16 -#undef __SOCKET_REGISTER_N - - -private: - static const uint8_t RST = 7; // Reset BIT - - static const int SOCKETS = 4; - static const uint16_t SMASK = 0x07FF; // Tx buffer MASK - static const uint16_t RMASK = 0x07FF; // Rx buffer MASK -public: - static const uint16_t SSIZE = 2048; // Max Tx buffer size -private: - static const uint16_t RSIZE = 2048; // Max Rx buffer size - uint16_t SBASE[SOCKETS]; // Tx buffer base address - uint16_t RBASE[SOCKETS]; // Rx buffer base address - -private: -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - inline static void initSS() { DDRB |= _BV(4); }; - inline static void setSS() { PORTB &= ~_BV(4); }; - inline static void resetSS() { PORTB |= _BV(4); }; -#elif defined(__AVR_ATmega32U4__) - inline static void initSS() { DDRB |= _BV(6); }; - inline static void setSS() { PORTB &= ~_BV(6); }; - inline static void resetSS() { PORTB |= _BV(6); }; -#elif defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB162__) - inline static void initSS() { DDRB |= _BV(0); }; - inline static void setSS() { PORTB &= ~_BV(0); }; - inline static void resetSS() { PORTB |= _BV(0); }; -#else - inline static void initSS() { DDRB |= _BV(2); }; - inline static void setSS() { PORTB &= ~_BV(2); }; - inline static void resetSS() { PORTB |= _BV(2); }; -#endif - -}; - -extern W5100Class W5100; - -uint8_t W5100Class::readSn(SOCKET _s, uint16_t _addr) { - return read(CH_BASE + _s * CH_SIZE + _addr); -} - -uint8_t W5100Class::writeSn(SOCKET _s, uint16_t _addr, uint8_t _data) { - return write(CH_BASE + _s * CH_SIZE + _addr, _data); -} - -uint16_t W5100Class::readSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t _len) { - return read(CH_BASE + _s * CH_SIZE + _addr, _buf, _len); -} - -uint16_t W5100Class::writeSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t _len) { - return write(CH_BASE + _s * CH_SIZE + _addr, _buf, _len); -} - -void W5100Class::getGatewayIp(uint8_t *_addr) { - readGAR(_addr); -} - -void W5100Class::setGatewayIp(uint8_t *_addr) { - writeGAR(_addr); -} - -void W5100Class::getSubnetMask(uint8_t *_addr) { - readSUBR(_addr); -} - -void W5100Class::setSubnetMask(uint8_t *_addr) { - writeSUBR(_addr); -} - -void W5100Class::getMACAddress(uint8_t *_addr) { - readSHAR(_addr); -} - -void W5100Class::setMACAddress(uint8_t *_addr) { - writeSHAR(_addr); -} - -void W5100Class::getIPAddress(uint8_t *_addr) { - readSIPR(_addr); -} - -void W5100Class::setIPAddress(uint8_t *_addr) { - writeSIPR(_addr); -} - -void W5100Class::setRetransmissionTime(uint16_t _timeout) { - writeRTR(_timeout); -} - -void W5100Class::setRetransmissionCount(uint8_t _retry) { - writeRCR(_retry); -} - -#endif -- cgit v1.2.3-18-g5258 From a7aabfb3a3bc26489983370b4f6e32fb39e907f7 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Thu, 27 Jun 2013 12:16:14 +0200 Subject: EEPROM library to the new format --- libraries/EEPROM/EEPROM.cpp | 50 ---------------------- libraries/EEPROM/EEPROM.h | 35 --------------- .../EEPROM/examples/eeprom_clear/eeprom_clear.ino | 23 ---------- .../EEPROM/examples/eeprom_read/eeprom_read.ino | 43 ------------------- .../EEPROM/examples/eeprom_write/eeprom_write.ino | 38 ---------------- libraries/EEPROM/keywords.txt | 18 -------- 6 files changed, 207 deletions(-) delete mode 100644 libraries/EEPROM/EEPROM.cpp delete mode 100644 libraries/EEPROM/EEPROM.h delete mode 100644 libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino delete mode 100644 libraries/EEPROM/examples/eeprom_read/eeprom_read.ino delete mode 100644 libraries/EEPROM/examples/eeprom_write/eeprom_write.ino delete mode 100644 libraries/EEPROM/keywords.txt diff --git a/libraries/EEPROM/EEPROM.cpp b/libraries/EEPROM/EEPROM.cpp deleted file mode 100644 index dfa1deb..0000000 --- a/libraries/EEPROM/EEPROM.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - EEPROM.cpp - EEPROM library - Copyright (c) 2006 David A. Mellis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -/****************************************************************************** - * Includes - ******************************************************************************/ - -#include -#include "Arduino.h" -#include "EEPROM.h" - -/****************************************************************************** - * Definitions - ******************************************************************************/ - -/****************************************************************************** - * Constructors - ******************************************************************************/ - -/****************************************************************************** - * User API - ******************************************************************************/ - -uint8_t EEPROMClass::read(int address) -{ - return eeprom_read_byte((unsigned char *) address); -} - -void EEPROMClass::write(int address, uint8_t value) -{ - eeprom_write_byte((unsigned char *) address, value); -} - -EEPROMClass EEPROM; diff --git a/libraries/EEPROM/EEPROM.h b/libraries/EEPROM/EEPROM.h deleted file mode 100644 index aa2b577..0000000 --- a/libraries/EEPROM/EEPROM.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - EEPROM.h - EEPROM library - Copyright (c) 2006 David A. Mellis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef EEPROM_h -#define EEPROM_h - -#include - -class EEPROMClass -{ - public: - uint8_t read(int); - void write(int, uint8_t); -}; - -extern EEPROMClass EEPROM; - -#endif - diff --git a/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino b/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino deleted file mode 100644 index d1e29bd..0000000 --- a/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino +++ /dev/null @@ -1,23 +0,0 @@ -/* - * EEPROM Clear - * - * Sets all of the bytes of the EEPROM to 0. - * This example code is in the public domain. - - */ - -#include - -void setup() -{ - // write a 0 to all 512 bytes of the EEPROM - for (int i = 0; i < 512; i++) - EEPROM.write(i, 0); - - // turn the LED on when we're done - digitalWrite(13, HIGH); -} - -void loop() -{ -} diff --git a/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino b/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino deleted file mode 100644 index 0709b2d..0000000 --- a/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino +++ /dev/null @@ -1,43 +0,0 @@ -/* - * EEPROM Read - * - * Reads the value of each byte of the EEPROM and prints it - * to the computer. - * This example code is in the public domain. - */ - -#include - -// start reading from the first byte (address 0) of the EEPROM -int address = 0; -byte value; - -void setup() -{ - // initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } -} - -void loop() -{ - // read a byte from the current address of the EEPROM - value = EEPROM.read(address); - - Serial.print(address); - Serial.print("\t"); - Serial.print(value, DEC); - Serial.println(); - - // advance to the next address of the EEPROM - address = address + 1; - - // there are only 512 bytes of EEPROM, from 0 to 511, so if we're - // on address 512, wrap around to address 0 - if (address == 512) - address = 0; - - delay(500); -} diff --git a/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino b/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino deleted file mode 100644 index ae7c57e..0000000 --- a/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino +++ /dev/null @@ -1,38 +0,0 @@ -/* - * EEPROM Write - * - * Stores values read from analog input 0 into the EEPROM. - * These values will stay in the EEPROM when the board is - * turned off and may be retrieved later by another sketch. - */ - -#include - -// the current address in the EEPROM (i.e. which byte -// we're going to write to next) -int addr = 0; - -void setup() -{ -} - -void loop() -{ - // need to divide by 4 because analog inputs range from - // 0 to 1023 and each byte of the EEPROM can only hold a - // value from 0 to 255. - int val = analogRead(0) / 4; - - // write the value to the appropriate byte of the EEPROM. - // these values will remain there when the board is - // turned off. - EEPROM.write(addr, val); - - // advance to the next address. there are 512 bytes in - // the EEPROM, so go back to 0 when we hit 512. - addr = addr + 1; - if (addr == 512) - addr = 0; - - delay(100); -} diff --git a/libraries/EEPROM/keywords.txt b/libraries/EEPROM/keywords.txt deleted file mode 100644 index d3218fe..0000000 --- a/libraries/EEPROM/keywords.txt +++ /dev/null @@ -1,18 +0,0 @@ -####################################### -# Syntax Coloring Map For Ultrasound -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -EEPROM KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -####################################### -# Constants (LITERAL1) -####################################### - -- cgit v1.2.3-18-g5258 From 5abc6d147f2e834fe310388d3197bf184bdd4cb7 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Thu, 27 Jun 2013 13:12:07 +0200 Subject: Servo library to the new format --- libraries/Servo/Servo.cpp | 337 ------------------------------- libraries/Servo/Servo.h | 126 ------------ libraries/Servo/examples/Knob/Knob.ino | 22 -- libraries/Servo/examples/Sweep/Sweep.ino | 31 --- libraries/Servo/keywords.txt | 24 --- 5 files changed, 540 deletions(-) delete mode 100644 libraries/Servo/Servo.cpp delete mode 100644 libraries/Servo/Servo.h delete mode 100644 libraries/Servo/examples/Knob/Knob.ino delete mode 100644 libraries/Servo/examples/Sweep/Sweep.ino delete mode 100644 libraries/Servo/keywords.txt diff --git a/libraries/Servo/Servo.cpp b/libraries/Servo/Servo.cpp deleted file mode 100644 index a17ed34..0000000 --- a/libraries/Servo/Servo.cpp +++ /dev/null @@ -1,337 +0,0 @@ -/* - Servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 - Copyright (c) 2009 Michael Margolis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* - - A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method. - The servos are pulsed in the background using the value most recently written using the write() method - - Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached. - Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four. - - The methods are: - - Servo - Class for manipulating servo motors connected to Arduino pins. - - attach(pin ) - Attaches a servo motor to an i/o pin. - attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds - default min is 544, max is 2400 - - write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) - writeMicroseconds() - Sets the servo pulse width in microseconds - read() - Gets the last written servo pulse width as an angle between 0 and 180. - readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) - attached() - Returns true if there is a servo attached. - detach() - Stops an attached servos from pulsing its i/o pin. - -*/ - -#include -#include - -#include "Servo.h" - -#define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8) // converts microseconds to tick (assumes prescale of 8) // 12 Aug 2009 -#define ticksToUs(_ticks) (( (unsigned)_ticks * 8)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds - - -#define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays // 12 August 2009 - -//#define NBR_TIMERS (MAX_SERVOS / SERVOS_PER_TIMER) - -static servo_t servos[MAX_SERVOS]; // static array of servo structures -static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval) - -uint8_t ServoCount = 0; // the total number of attached servos - - -// convenience macros -#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo -#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer -#define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel -#define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel - -#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in uS for this servo -#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in uS for this servo - -/************ static functions common to all instances ***********************/ - -static inline void handle_interrupts(timer16_Sequence_t timer, volatile uint16_t *TCNTn, volatile uint16_t* OCRnA) -{ - if( Channel[timer] < 0 ) - *TCNTn = 0; // channel set to -1 indicated that refresh interval completed so reset the timer - else{ - if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true ) - digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,LOW); // pulse this channel low if activated - } - - Channel[timer]++; // increment to the next channel - if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) { - *OCRnA = *TCNTn + SERVO(timer,Channel[timer]).ticks; - if(SERVO(timer,Channel[timer]).Pin.isActive == true) // check if activated - digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // its an active channel so pulse it high - } - else { - // finished all channels so wait for the refresh period to expire before starting over - if( ((unsigned)*TCNTn) + 4 < usToTicks(REFRESH_INTERVAL) ) // allow a few ticks to ensure the next OCR1A not missed - *OCRnA = (unsigned int)usToTicks(REFRESH_INTERVAL); - else - *OCRnA = *TCNTn + 4; // at least REFRESH_INTERVAL has elapsed - Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel - } -} - -#ifndef WIRING // Wiring pre-defines signal handlers so don't define any if compiling for the Wiring platform -// Interrupt handlers for Arduino -#if defined(_useTimer1) -ISR(TIMER1_COMPA_vect) -{ - handle_interrupts(_timer1, &TCNT1, &OCR1A); -} -#endif - -#if defined(_useTimer3) -ISR(TIMER3_COMPA_vect) -{ - handle_interrupts(_timer3, &TCNT3, &OCR3A); -} -#endif - -#if defined(_useTimer4) -ISR(TIMER4_COMPA_vect) -{ - handle_interrupts(_timer4, &TCNT4, &OCR4A); -} -#endif - -#if defined(_useTimer5) -ISR(TIMER5_COMPA_vect) -{ - handle_interrupts(_timer5, &TCNT5, &OCR5A); -} -#endif - -#elif defined WIRING -// Interrupt handlers for Wiring -#if defined(_useTimer1) -void Timer1Service() -{ - handle_interrupts(_timer1, &TCNT1, &OCR1A); -} -#endif -#if defined(_useTimer3) -void Timer3Service() -{ - handle_interrupts(_timer3, &TCNT3, &OCR3A); -} -#endif -#endif - - -static void initISR(timer16_Sequence_t timer) -{ -#if defined (_useTimer1) - if(timer == _timer1) { - TCCR1A = 0; // normal counting mode - TCCR1B = _BV(CS11); // set prescaler of 8 - TCNT1 = 0; // clear the timer count -#if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__) - TIFR |= _BV(OCF1A); // clear any pending interrupts; - TIMSK |= _BV(OCIE1A) ; // enable the output compare interrupt -#else - // here if not ATmega8 or ATmega128 - TIFR1 |= _BV(OCF1A); // clear any pending interrupts; - TIMSK1 |= _BV(OCIE1A) ; // enable the output compare interrupt -#endif -#if defined(WIRING) - timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service); -#endif - } -#endif - -#if defined (_useTimer3) - if(timer == _timer3) { - TCCR3A = 0; // normal counting mode - TCCR3B = _BV(CS31); // set prescaler of 8 - TCNT3 = 0; // clear the timer count -#if defined(__AVR_ATmega128__) - TIFR |= _BV(OCF3A); // clear any pending interrupts; - ETIMSK |= _BV(OCIE3A); // enable the output compare interrupt -#else - TIFR3 = _BV(OCF3A); // clear any pending interrupts; - TIMSK3 = _BV(OCIE3A) ; // enable the output compare interrupt -#endif -#if defined(WIRING) - timerAttach(TIMER3OUTCOMPAREA_INT, Timer3Service); // for Wiring platform only -#endif - } -#endif - -#if defined (_useTimer4) - if(timer == _timer4) { - TCCR4A = 0; // normal counting mode - TCCR4B = _BV(CS41); // set prescaler of 8 - TCNT4 = 0; // clear the timer count - TIFR4 = _BV(OCF4A); // clear any pending interrupts; - TIMSK4 = _BV(OCIE4A) ; // enable the output compare interrupt - } -#endif - -#if defined (_useTimer5) - if(timer == _timer5) { - TCCR5A = 0; // normal counting mode - TCCR5B = _BV(CS51); // set prescaler of 8 - TCNT5 = 0; // clear the timer count - TIFR5 = _BV(OCF5A); // clear any pending interrupts; - TIMSK5 = _BV(OCIE5A) ; // enable the output compare interrupt - } -#endif -} - -static void finISR(timer16_Sequence_t timer) -{ - //disable use of the given timer -#if defined WIRING // Wiring - if(timer == _timer1) { - #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) - TIMSK1 &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt - #else - TIMSK &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt - #endif - timerDetach(TIMER1OUTCOMPAREA_INT); - } - else if(timer == _timer3) { - #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) - TIMSK3 &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt - #else - ETIMSK &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt - #endif - timerDetach(TIMER3OUTCOMPAREA_INT); - } -#else - //For arduino - in future: call here to a currently undefined function to reset the timer -#endif -} - -static boolean isTimerActive(timer16_Sequence_t timer) -{ - // returns true if any servo is active on this timer - for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { - if(SERVO(timer,channel).Pin.isActive == true) - return true; - } - return false; -} - - -/****************** end of static functions ******************************/ - -Servo::Servo() -{ - if( ServoCount < MAX_SERVOS) { - this->servoIndex = ServoCount++; // assign a servo index to this instance - servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values - 12 Aug 2009 - } - else - this->servoIndex = INVALID_SERVO ; // too many servos -} - -uint8_t Servo::attach(int pin) -{ - return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); -} - -uint8_t Servo::attach(int pin, int min, int max) -{ - if(this->servoIndex < MAX_SERVOS ) { - pinMode( pin, OUTPUT) ; // set servo pin to output - servos[this->servoIndex].Pin.nbr = pin; - // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 - this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 uS - this->max = (MAX_PULSE_WIDTH - max)/4; - // initialize the timer if it has not already been initialized - timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); - if(isTimerActive(timer) == false) - initISR(timer); - servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive - } - return this->servoIndex ; -} - -void Servo::detach() -{ - servos[this->servoIndex].Pin.isActive = false; - timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); - if(isTimerActive(timer) == false) { - finISR(timer); - } -} - -void Servo::write(int value) -{ - if(value < MIN_PULSE_WIDTH) - { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) - if(value < 0) value = 0; - if(value > 180) value = 180; - value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); - } - this->writeMicroseconds(value); -} - -void Servo::writeMicroseconds(int value) -{ - // calculate and store the values for the given channel - byte channel = this->servoIndex; - if( (channel < MAX_SERVOS) ) // ensure channel is valid - { - if( value < SERVO_MIN() ) // ensure pulse width is valid - value = SERVO_MIN(); - else if( value > SERVO_MAX() ) - value = SERVO_MAX(); - - value = value - TRIM_DURATION; - value = usToTicks(value); // convert to ticks after compensating for interrupt overhead - 12 Aug 2009 - - uint8_t oldSREG = SREG; - cli(); - servos[channel].ticks = value; - SREG = oldSREG; - } -} - -int Servo::read() // return the value as degrees -{ - return map( this->readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); -} - -int Servo::readMicroseconds() -{ - unsigned int pulsewidth; - if( this->servoIndex != INVALID_SERVO ) - pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION ; // 12 aug 2009 - else - pulsewidth = 0; - - return pulsewidth; -} - -bool Servo::attached() -{ - return servos[this->servoIndex].Pin.isActive ; -} diff --git a/libraries/Servo/Servo.h b/libraries/Servo/Servo.h deleted file mode 100644 index 8168494..0000000 --- a/libraries/Servo/Servo.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 - Copyright (c) 2009 Michael Margolis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -/* - - A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method. - The servos are pulsed in the background using the value most recently written using the write() method - - Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached. - Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four. - The sequence used to sieze timers is defined in timers.h - - The methods are: - - Servo - Class for manipulating servo motors connected to Arduino pins. - - attach(pin ) - Attaches a servo motor to an i/o pin. - attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds - default min is 544, max is 2400 - - write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) - writeMicroseconds() - Sets the servo pulse width in microseconds - read() - Gets the last written servo pulse width as an angle between 0 and 180. - readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) - attached() - Returns true if there is a servo attached. - detach() - Stops an attached servos from pulsing its i/o pin. - */ - -#ifndef Servo_h -#define Servo_h - -#include - -/* - * Defines for 16 bit timers used with Servo library - * - * If _useTimerX is defined then TimerX is a 16 bit timer on the curent board - * timer16_Sequence_t enumerates the sequence that the timers should be allocated - * _Nbr_16timers indicates how many 16 bit timers are available. - * - */ - -// Say which 16 bit timers can be used and in what order -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define _useTimer5 -#define _useTimer1 -#define _useTimer3 -#define _useTimer4 -typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t ; - -#elif defined(__AVR_ATmega32U4__) -#define _useTimer1 -typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ; - -#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) -#define _useTimer3 -#define _useTimer1 -typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t ; - -#elif defined(__AVR_ATmega128__) ||defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) -#define _useTimer3 -#define _useTimer1 -typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t ; - -#else // everything else -#define _useTimer1 -typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ; -#endif - -#define Servo_VERSION 2 // software version of this library - -#define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo -#define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo -#define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached -#define REFRESH_INTERVAL 20000 // minumim time to refresh servos in microseconds - -#define SERVOS_PER_TIMER 12 // the maximum number of servos controlled by one timer -#define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER) - -#define INVALID_SERVO 255 // flag indicating an invalid servo index - -typedef struct { - uint8_t nbr :6 ; // a pin number from 0 to 63 - uint8_t isActive :1 ; // true if this channel is enabled, pin not pulsed if false -} ServoPin_t ; - -typedef struct { - ServoPin_t Pin; - unsigned int ticks; -} servo_t; - -class Servo -{ -public: - Servo(); - uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure - uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes. - void detach(); - void write(int value); // if value is < 200 its treated as an angle, otherwise as pulse width in microseconds - void writeMicroseconds(int value); // Write pulse width in microseconds - int read(); // returns current pulse width as an angle between 0 and 180 degrees - int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release) - bool attached(); // return true if this servo is attached, otherwise false -private: - uint8_t servoIndex; // index into the channel data for this servo - int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH - int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH -}; - -#endif diff --git a/libraries/Servo/examples/Knob/Knob.ino b/libraries/Servo/examples/Knob/Knob.ino deleted file mode 100644 index 886e107..0000000 --- a/libraries/Servo/examples/Knob/Knob.ino +++ /dev/null @@ -1,22 +0,0 @@ -// Controlling a servo position using a potentiometer (variable resistor) -// by Michal Rinott - -#include - -Servo myservo; // create servo object to control a servo - -int potpin = 0; // analog pin used to connect the potentiometer -int val; // variable to read the value from the analog pin - -void setup() -{ - myservo.attach(9); // attaches the servo on pin 9 to the servo object -} - -void loop() -{ - val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) - val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180) - myservo.write(val); // sets the servo position according to the scaled value - delay(15); // waits for the servo to get there -} diff --git a/libraries/Servo/examples/Sweep/Sweep.ino b/libraries/Servo/examples/Sweep/Sweep.ino deleted file mode 100644 index fb326e7..0000000 --- a/libraries/Servo/examples/Sweep/Sweep.ino +++ /dev/null @@ -1,31 +0,0 @@ -// Sweep -// by BARRAGAN -// This example code is in the public domain. - - -#include - -Servo myservo; // create servo object to control a servo - // a maximum of eight servo objects can be created - -int pos = 0; // variable to store the servo position - -void setup() -{ - myservo.attach(9); // attaches the servo on pin 9 to the servo object -} - - -void loop() -{ - for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees - { // in steps of 1 degree - myservo.write(pos); // tell servo to go to position in variable 'pos' - delay(15); // waits 15ms for the servo to reach the position - } - for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees - { - myservo.write(pos); // tell servo to go to position in variable 'pos' - delay(15); // waits 15ms for the servo to reach the position - } -} diff --git a/libraries/Servo/keywords.txt b/libraries/Servo/keywords.txt deleted file mode 100644 index ca5ba79..0000000 --- a/libraries/Servo/keywords.txt +++ /dev/null @@ -1,24 +0,0 @@ -####################################### -# Syntax Coloring Map Servo -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Servo KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -attach KEYWORD2 -detach KEYWORD2 -write KEYWORD2 -read KEYWORD2 -attached KEYWORD2 -writeMicroseconds KEYWORD2 -readMicroseconds KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### -- cgit v1.2.3-18-g5258 From e01b23840354acd6c260b1f552bf0c5f5d7cdede Mon Sep 17 00:00:00 2001 From: Fede85 Date: Thu, 27 Jun 2013 19:24:16 +0200 Subject: Stepper library to the new format --- libraries/Stepper/Stepper.cpp | 220 --------------------- libraries/Stepper/Stepper.h | 83 -------- libraries/Stepper/examples/MotorKnob/MotorKnob.ino | 41 ---- .../stepper_oneRevolution.ino | 44 ----- .../stepper_oneStepAtATime.ino | 44 ----- .../stepper_speedControl/stepper_speedControl.ino | 48 ----- libraries/Stepper/keywords.txt | 28 --- 7 files changed, 508 deletions(-) delete mode 100644 libraries/Stepper/Stepper.cpp delete mode 100644 libraries/Stepper/Stepper.h delete mode 100644 libraries/Stepper/examples/MotorKnob/MotorKnob.ino delete mode 100644 libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino delete mode 100644 libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino delete mode 100644 libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino delete mode 100644 libraries/Stepper/keywords.txt diff --git a/libraries/Stepper/Stepper.cpp b/libraries/Stepper/Stepper.cpp deleted file mode 100644 index 5d6b5e5..0000000 --- a/libraries/Stepper/Stepper.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/* - Stepper.cpp - - Stepper library for Wiring/Arduino - Version 0.4 - - Original library (0.1) by Tom Igoe. - Two-wire modifications (0.2) by Sebastian Gassner - Combination version (0.3) by Tom Igoe and David Mellis - Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley - - Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires - - When wiring multiple stepper motors to a microcontroller, - you quickly run out of output pins, with each motor requiring 4 connections. - - By making use of the fact that at any time two of the four motor - coils are the inverse of the other two, the number of - control connections can be reduced from 4 to 2. - - A slightly modified circuit around a Darlington transistor array or an L293 H-bridge - connects to only 2 microcontroler pins, inverts the signals received, - and delivers the 4 (2 plus 2 inverted ones) output signals required - for driving a stepper motor. - - The sequence of control signals for 4 control wires is as follows: - - Step C0 C1 C2 C3 - 1 1 0 1 0 - 2 0 1 1 0 - 3 0 1 0 1 - 4 1 0 0 1 - - The sequence of controls signals for 2 control wires is as follows - (columns C1 and C2 from above): - - Step C0 C1 - 1 0 1 - 2 1 1 - 3 1 0 - 4 0 0 - - The circuits can be found at - -http://www.arduino.cc/en/Tutorial/Stepper - - - */ - - -#include "Arduino.h" -#include "Stepper.h" - -/* - * two-wire constructor. - * Sets which wires should control the motor. - */ -Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2) -{ - this->step_number = 0; // which step the motor is on - this->speed = 0; // the motor speed, in revolutions per minute - this->direction = 0; // motor direction - this->last_step_time = 0; // time stamp in ms of the last step taken - this->number_of_steps = number_of_steps; // total number of steps for this motor - - // Arduino pins for the motor control connection: - this->motor_pin_1 = motor_pin_1; - this->motor_pin_2 = motor_pin_2; - - // setup the pins on the microcontroller: - pinMode(this->motor_pin_1, OUTPUT); - pinMode(this->motor_pin_2, OUTPUT); - - // When there are only 2 pins, set the other two to 0: - this->motor_pin_3 = 0; - this->motor_pin_4 = 0; - - // pin_count is used by the stepMotor() method: - this->pin_count = 2; -} - - -/* - * constructor for four-pin version - * Sets which wires should control the motor. - */ - -Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4) -{ - this->step_number = 0; // which step the motor is on - this->speed = 0; // the motor speed, in revolutions per minute - this->direction = 0; // motor direction - this->last_step_time = 0; // time stamp in ms of the last step taken - this->number_of_steps = number_of_steps; // total number of steps for this motor - - // Arduino pins for the motor control connection: - this->motor_pin_1 = motor_pin_1; - this->motor_pin_2 = motor_pin_2; - this->motor_pin_3 = motor_pin_3; - this->motor_pin_4 = motor_pin_4; - - // setup the pins on the microcontroller: - pinMode(this->motor_pin_1, OUTPUT); - pinMode(this->motor_pin_2, OUTPUT); - pinMode(this->motor_pin_3, OUTPUT); - pinMode(this->motor_pin_4, OUTPUT); - - // pin_count is used by the stepMotor() method: - this->pin_count = 4; -} - -/* - Sets the speed in revs per minute - -*/ -void Stepper::setSpeed(long whatSpeed) -{ - this->step_delay = 60L * 1000L / this->number_of_steps / whatSpeed; -} - -/* - Moves the motor steps_to_move steps. If the number is negative, - the motor moves in the reverse direction. - */ -void Stepper::step(int steps_to_move) -{ - int steps_left = abs(steps_to_move); // how many steps to take - - // determine direction based on whether steps_to_mode is + or -: - if (steps_to_move > 0) {this->direction = 1;} - if (steps_to_move < 0) {this->direction = 0;} - - - // decrement the number of steps, moving one step each time: - while(steps_left > 0) { - // move only if the appropriate delay has passed: - if (millis() - this->last_step_time >= this->step_delay) { - // get the timeStamp of when you stepped: - this->last_step_time = millis(); - // increment or decrement the step number, - // depending on direction: - if (this->direction == 1) { - this->step_number++; - if (this->step_number == this->number_of_steps) { - this->step_number = 0; - } - } - else { - if (this->step_number == 0) { - this->step_number = this->number_of_steps; - } - this->step_number--; - } - // decrement the steps left: - steps_left--; - // step the motor to step number 0, 1, 2, or 3: - stepMotor(this->step_number % 4); - } - } -} - -/* - * Moves the motor forward or backwards. - */ -void Stepper::stepMotor(int thisStep) -{ - if (this->pin_count == 2) { - switch (thisStep) { - case 0: /* 01 */ - digitalWrite(motor_pin_1, LOW); - digitalWrite(motor_pin_2, HIGH); - break; - case 1: /* 11 */ - digitalWrite(motor_pin_1, HIGH); - digitalWrite(motor_pin_2, HIGH); - break; - case 2: /* 10 */ - digitalWrite(motor_pin_1, HIGH); - digitalWrite(motor_pin_2, LOW); - break; - case 3: /* 00 */ - digitalWrite(motor_pin_1, LOW); - digitalWrite(motor_pin_2, LOW); - break; - } - } - if (this->pin_count == 4) { - switch (thisStep) { - case 0: // 1010 - digitalWrite(motor_pin_1, HIGH); - digitalWrite(motor_pin_2, LOW); - digitalWrite(motor_pin_3, HIGH); - digitalWrite(motor_pin_4, LOW); - break; - case 1: // 0110 - digitalWrite(motor_pin_1, LOW); - digitalWrite(motor_pin_2, HIGH); - digitalWrite(motor_pin_3, HIGH); - digitalWrite(motor_pin_4, LOW); - break; - case 2: //0101 - digitalWrite(motor_pin_1, LOW); - digitalWrite(motor_pin_2, HIGH); - digitalWrite(motor_pin_3, LOW); - digitalWrite(motor_pin_4, HIGH); - break; - case 3: //1001 - digitalWrite(motor_pin_1, HIGH); - digitalWrite(motor_pin_2, LOW); - digitalWrite(motor_pin_3, LOW); - digitalWrite(motor_pin_4, HIGH); - break; - } - } -} - -/* - version() returns the version of the library: -*/ -int Stepper::version(void) -{ - return 4; -} diff --git a/libraries/Stepper/Stepper.h b/libraries/Stepper/Stepper.h deleted file mode 100644 index 4094aee..0000000 --- a/libraries/Stepper/Stepper.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - Stepper.h - - Stepper library for Wiring/Arduino - Version 0.4 - - Original library (0.1) by Tom Igoe. - Two-wire modifications (0.2) by Sebastian Gassner - Combination version (0.3) by Tom Igoe and David Mellis - Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley - - Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires - - When wiring multiple stepper motors to a microcontroller, - you quickly run out of output pins, with each motor requiring 4 connections. - - By making use of the fact that at any time two of the four motor - coils are the inverse of the other two, the number of - control connections can be reduced from 4 to 2. - - A slightly modified circuit around a Darlington transistor array or an L293 H-bridge - connects to only 2 microcontroler pins, inverts the signals received, - and delivers the 4 (2 plus 2 inverted ones) output signals required - for driving a stepper motor. - - The sequence of control signals for 4 control wires is as follows: - - Step C0 C1 C2 C3 - 1 1 0 1 0 - 2 0 1 1 0 - 3 0 1 0 1 - 4 1 0 0 1 - - The sequence of controls signals for 2 control wires is as follows - (columns C1 and C2 from above): - - Step C0 C1 - 1 0 1 - 2 1 1 - 3 1 0 - 4 0 0 - - The circuits can be found at - http://www.arduino.cc/en/Tutorial/Stepper -*/ - -// ensure this library description is only included once -#ifndef Stepper_h -#define Stepper_h - -// library interface description -class Stepper { - public: - // constructors: - Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2); - Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4); - - // speed setter method: - void setSpeed(long whatSpeed); - - // mover method: - void step(int number_of_steps); - - int version(void); - - private: - void stepMotor(int this_step); - - int direction; // Direction of rotation - int speed; // Speed in RPMs - unsigned long step_delay; // delay between steps, in ms, based on speed - int number_of_steps; // total number of steps this motor can take - int pin_count; // whether you're driving the motor with 2 or 4 pins - int step_number; // which step the motor is on - - // motor pin numbers: - int motor_pin_1; - int motor_pin_2; - int motor_pin_3; - int motor_pin_4; - - long last_step_time; // time stamp in ms of when the last step was taken -}; - -#endif - diff --git a/libraries/Stepper/examples/MotorKnob/MotorKnob.ino b/libraries/Stepper/examples/MotorKnob/MotorKnob.ino deleted file mode 100644 index d428186..0000000 --- a/libraries/Stepper/examples/MotorKnob/MotorKnob.ino +++ /dev/null @@ -1,41 +0,0 @@ -/* - * MotorKnob - * - * A stepper motor follows the turns of a potentiometer - * (or other sensor) on analog input 0. - * - * http://www.arduino.cc/en/Reference/Stepper - * This example code is in the public domain. - */ - -#include - -// change this to the number of steps on your motor -#define STEPS 100 - -// create an instance of the stepper class, specifying -// the number of steps of the motor and the pins it's -// attached to -Stepper stepper(STEPS, 8, 9, 10, 11); - -// the previous reading from the analog input -int previous = 0; - -void setup() -{ - // set the speed of the motor to 30 RPMs - stepper.setSpeed(30); -} - -void loop() -{ - // get the sensor value - int val = analogRead(0); - - // move a number of steps equal to the change in the - // sensor reading - stepper.step(val - previous); - - // remember the previous value of the sensor - previous = val; -} \ No newline at end of file diff --git a/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino b/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino deleted file mode 100644 index 2dbb57d..0000000 --- a/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino +++ /dev/null @@ -1,44 +0,0 @@ - -/* - Stepper Motor Control - one revolution - - This program drives a unipolar or bipolar stepper motor. - The motor is attached to digital pins 8 - 11 of the Arduino. - - The motor should revolve one revolution in one direction, then - one revolution in the other direction. - - - Created 11 Mar. 2007 - Modified 30 Nov. 2009 - by Tom Igoe - - */ - -#include - -const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution - // for your motor - -// initialize the stepper library on pins 8 through 11: -Stepper myStepper(stepsPerRevolution, 8,9,10,11); - -void setup() { - // set the speed at 60 rpm: - myStepper.setSpeed(60); - // initialize the serial port: - Serial.begin(9600); -} - -void loop() { - // step one revolution in one direction: - Serial.println("clockwise"); - myStepper.step(stepsPerRevolution); - delay(500); - - // step one revolution in the other direction: - Serial.println("counterclockwise"); - myStepper.step(-stepsPerRevolution); - delay(500); -} - diff --git a/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino b/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino deleted file mode 100644 index 36d3299..0000000 --- a/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino +++ /dev/null @@ -1,44 +0,0 @@ - -/* - Stepper Motor Control - one step at a time - - This program drives a unipolar or bipolar stepper motor. - The motor is attached to digital pins 8 - 11 of the Arduino. - - The motor will step one step at a time, very slowly. You can use this to - test that you've got the four wires of your stepper wired to the correct - pins. If wired correctly, all steps should be in the same direction. - - Use this also to count the number of steps per revolution of your motor, - if you don't know it. Then plug that number into the oneRevolution - example to see if you got it right. - - Created 30 Nov. 2009 - by Tom Igoe - - */ - -#include - -const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution - // for your motor - -// initialize the stepper library on pins 8 through 11: -Stepper myStepper(stepsPerRevolution, 8,9,10,11); - -int stepCount = 0; // number of steps the motor has taken - -void setup() { - // initialize the serial port: - Serial.begin(9600); -} - -void loop() { - // step one step: - myStepper.step(1); - Serial.print("steps:" ); - Serial.println(stepCount); - stepCount++; - delay(500); -} - diff --git a/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino b/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino deleted file mode 100644 index 1a67a55..0000000 --- a/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino +++ /dev/null @@ -1,48 +0,0 @@ - -/* - Stepper Motor Control - speed control - - This program drives a unipolar or bipolar stepper motor. - The motor is attached to digital pins 8 - 11 of the Arduino. - A potentiometer is connected to analog input 0. - - The motor will rotate in a clockwise direction. The higher the potentiometer value, - the faster the motor speed. Because setSpeed() sets the delay between steps, - you may notice the motor is less responsive to changes in the sensor value at - low speeds. - - Created 30 Nov. 2009 - Modified 28 Oct 2010 - by Tom Igoe - - */ - -#include - -const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution -// for your motor - - -// initialize the stepper library on pins 8 through 11: -Stepper myStepper(stepsPerRevolution, 8,9,10,11); - -int stepCount = 0; // number of steps the motor has taken - -void setup() { - // nothing to do inside the setup -} - -void loop() { - // read the sensor value: - int sensorReading = analogRead(A0); - // map it to a range from 0 to 100: - int motorSpeed = map(sensorReading, 0, 1023, 0, 100); - // set the motor speed: - if (motorSpeed > 0) { - myStepper.setSpeed(motorSpeed); - // step 1/100 of a revolution: - myStepper.step(stepsPerRevolution/100); - } -} - - diff --git a/libraries/Stepper/keywords.txt b/libraries/Stepper/keywords.txt deleted file mode 100644 index 19a0fad..0000000 --- a/libraries/Stepper/keywords.txt +++ /dev/null @@ -1,28 +0,0 @@ -####################################### -# Syntax Coloring Map For Test -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Stepper KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -step KEYWORD2 -setSpeed KEYWORD2 -version KEYWORD2 - -###################################### -# Instances (KEYWORD2) -####################################### -direction KEYWORD2 -speed KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### -- cgit v1.2.3-18-g5258 From cb3003082e7e140850071eba914c0b4347bc3bf1 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Wed, 3 Jul 2013 16:25:45 +0200 Subject: TFT library to new format --- libraries/TFT/README.md | 18 - libraries/TFT/TFT.cpp | 19 - libraries/TFT/TFT.h | 28 - .../Arduino/TFTBitmapLogo/TFTBitmapLogo.ino | 108 ---- .../TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp | Bin 6966 -> 0 bytes .../Arduino/TFTColorPicker/TFTColorPicker.ino | 67 -- .../Arduino/TFTDisplayText/TFTDisplayText.ino | 74 --- .../Arduino/TFTEtchASketch/TFTEtchASketch.ino | 84 --- .../TFT/examples/Arduino/TFTGraph/TFTGraph.ino | 71 --- libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino | 135 ----- .../EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino | 101 ---- .../Esplora/EsploraTFTBitmapLogo/arduino.bmp | Bin 6966 -> 0 bytes .../EsploraTFTColorPicker.ino | 54 -- .../EsploraTFTEtchASketch.ino | 83 --- .../Esplora/EsploraTFTGraph/EsploraTFTGraph.ino | 56 -- .../EsploraTFTHorizon/EsploraTFTHorizon.ino | 63 -- .../Esplora/EsploraTFTPong/EsploraTFTPong.ino | 126 ---- .../Esplora/EsploraTFTTemp/EsploraTFTTemp.ino | 64 -- libraries/TFT/keywords.txt | 20 - libraries/TFT/utility/Adafruit-README.txt | 21 - libraries/TFT/utility/Adafruit-license.txt | 25 - libraries/TFT/utility/Adafruit_GFX.cpp | 671 --------------------- libraries/TFT/utility/Adafruit_GFX.h | 367 ----------- libraries/TFT/utility/Adafruit_ST7735.cpp | 603 ------------------ libraries/TFT/utility/Adafruit_ST7735.h | 150 ----- libraries/TFT/utility/PImage.h | 64 -- libraries/TFT/utility/glcdfont.c | 268 -------- libraries/TFT/utility/keywords.txt | 70 --- 28 files changed, 3410 deletions(-) delete mode 100644 libraries/TFT/README.md delete mode 100644 libraries/TFT/TFT.cpp delete mode 100644 libraries/TFT/TFT.h delete mode 100644 libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino delete mode 100644 libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp delete mode 100644 libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino delete mode 100644 libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino delete mode 100644 libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino delete mode 100644 libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino delete mode 100644 libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino delete mode 100644 libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino delete mode 100644 libraries/TFT/keywords.txt delete mode 100644 libraries/TFT/utility/Adafruit-README.txt delete mode 100644 libraries/TFT/utility/Adafruit-license.txt delete mode 100644 libraries/TFT/utility/Adafruit_GFX.cpp delete mode 100644 libraries/TFT/utility/Adafruit_GFX.h delete mode 100755 libraries/TFT/utility/Adafruit_ST7735.cpp delete mode 100755 libraries/TFT/utility/Adafruit_ST7735.h delete mode 100644 libraries/TFT/utility/PImage.h delete mode 100644 libraries/TFT/utility/glcdfont.c delete mode 100644 libraries/TFT/utility/keywords.txt diff --git a/libraries/TFT/README.md b/libraries/TFT/README.md deleted file mode 100644 index 8489a20..0000000 --- a/libraries/TFT/README.md +++ /dev/null @@ -1,18 +0,0 @@ -TFT Library -============ - -An Arduino library for the Arduino TFT LCD screen. - -This library enables an Arduino board to communicate with an Arduino TFT LCD screen. It simplifies the process for drawing shapes, lines, images, and text to the screen. -The Arduino TFT library extends the Adafruit GFX, and Adafruit ST7735 libraries that it is based on. The GFX library is responsible for the drawing routines, while the ST7735 library is specific to the screen on the Arduino GTFT. The Arduino specific additions were designed to work as similarly to the Processing API as possible. - -Onboard the screen is a SD card slot, which can be used through the SD library. - -The TFT library relies on the SPI library for communication with the screen and SD card, and needs to be included in all sketches. - -https://github.com/adafruit/Adafruit-GFX-Library -https://github.com/adafruit/Adafruit-ST7735-Library -http://arduino.cc/en/Reference/SD -http://arduino.cc/en/Reference/SPI - -http://arduino.cc/en/Reference/TFTLibrary \ No newline at end of file diff --git a/libraries/TFT/TFT.cpp b/libraries/TFT/TFT.cpp deleted file mode 100644 index 57f71f2..0000000 --- a/libraries/TFT/TFT.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "TFT.h" - -#if (USB_VID == 0x2341) && (USB_PID == 0x803C) // are we building for Esplora? -TFT EsploraTFT(7, 0, 1); -#endif - -TFT::TFT(uint8_t CS, uint8_t RS, uint8_t RST) - : Adafruit_ST7735(CS, RS, RST) -{ - // as we already know the orientation (landscape, therefore rotated), - // set default width and height without need to call begin() first. - _width = ST7735_TFTHEIGHT; - _height = ST7735_TFTWIDTH; -} - -void TFT::begin() { - initR(INITR_REDTAB); - setRotation(1); -} diff --git a/libraries/TFT/TFT.h b/libraries/TFT/TFT.h deleted file mode 100644 index 06b6ac3..0000000 --- a/libraries/TFT/TFT.h +++ /dev/null @@ -1,28 +0,0 @@ - -#ifndef _ARDUINO_TFT_H -#define _ARDUINO_TFT_H - -#include "Arduino.h" -#include "utility/Adafruit_GFX.h" -#include "utility/Adafruit_ST7735.h" - -/// The Arduino LCD is a ST7735-based device. -/// By default, it is mounted horizontally. -/// TFT class follows the convention of other -/// Arduino library classes by adding a begin() method -/// to be called in the setup() routine. -/// @author Enrico Gueli -class TFT : public Adafruit_ST7735 { -public: - TFT(uint8_t CS, uint8_t RS, uint8_t RST); - - void begin(); -}; - -/// Esplora boards have hard-wired connections with -/// the Arduino LCD if mounted on the onboard connector. -#if (USB_VID == 0x2341) && (USB_PID == 0x803C) // are we building for Esplora? -extern TFT EsploraTFT; -#endif - -#endif // _ARDUINO_TFT_H diff --git a/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino b/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino deleted file mode 100644 index da7a94d..0000000 --- a/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino +++ /dev/null @@ -1,108 +0,0 @@ -/* - - Arduino TFT Bitmap Logo example - - This example reads an image file from a micro-SD card - and draws it on the screen, at random locations. - - In this sketch, the Arduino logo is read from a micro-SD card. - There is a .bmp file included with this sketch. - - open the sketch folder (Ctrl-K or Cmd-K) - - copy the "arduino.bmp" file to a micro-SD - - put the SD into the SD slot of the Arduino TFT module. - - This example code is in the public domain. - - Created 19 April 2013 by Enrico Gueli - - http://arduino.cc/en/Tutorial/TFTBitmapLogo - - */ - -// include the necessary libraries -#include -#include -#include // Arduino LCD library - -// pin definition for the Uno -#define sd_cs 4 -#define lcd_cs 10 -#define dc 9 -#define rst 8 - -// pin definition for the Leonardo -//#define sd_cs 8 -//#define lcd_cs 7 -//#define dc 0 -//#define rst 1 - -TFT TFTscreen = TFT(lcd_cs, dc, rst); - -// this variable represents the image to be drawn on screen -PImage logo; - - -void setup() { - // initialize the GLCD and show a message - // asking the user to open the serial line - TFTscreen.begin(); - TFTscreen.background(255, 255, 255); - - TFTscreen.stroke(0, 0, 255); - TFTscreen.println(); - TFTscreen.println("Arduino TFT Bitmap Example"); - TFTscreen.stroke(0, 0, 0); - TFTscreen.println("Open serial monitor"); - TFTscreen.println("to run the sketch"); - - // initialize the serial port: it will be used to - // print some diagnostic info - Serial.begin(9600); - while (!Serial) { - // wait for serial line to be ready - } - - // clear the GLCD screen before starting - TFTscreen.background(255, 255, 255); - - // try to access the SD card. If that fails (e.g. - // no card present), the setup process will stop. - Serial.print("Initializing SD card..."); - if (!SD.begin(sd_cs)) { - Serial.println("failed!"); - return; - } - Serial.println("OK!"); - - // initialize and clear the GLCD screen - TFTscreen.begin(); - TFTscreen.background(255, 255, 255); - - // now that the SD card can be access, try to load the - // image file. - logo = TFTscreen.loadImage("arduino.bmp"); - if (!logo.isValid()) { - Serial.println("error while loading arduino.bmp"); - } -} - -void loop() { - // don't do anything if the image wasn't loaded correctly. - if (logo.isValid() == false) { - return; - } - - Serial.println("drawing image"); - - // get a random location where to draw the image. - // To avoid the image to be draw outside the screen, - // take into account the image size. - int x = random(TFTscreen.width() - logo.width()); - int y = random(TFTscreen.height() - logo.height()); - - // draw the image to the screen - TFTscreen.image(logo, x, y); - - // wait a little bit before drawing again - delay(1500); -} diff --git a/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp b/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp deleted file mode 100644 index 09c670a..0000000 Binary files a/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp and /dev/null differ diff --git a/libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino b/libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino deleted file mode 100644 index 74fc176..0000000 --- a/libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino +++ /dev/null @@ -1,67 +0,0 @@ -/* - - TFT Color Picker - - This example for the Arduino screen reads the input of - potentiometers or analog sensors attached to A0, A1, - and A2 and uses the values to change the screen's color. - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/TFTColorPicker - - */ - -// pin definition for the Uno -#define cs 10 -#define dc 9 -#define rst 8 - -// pin definition for the Leonardo -// #define cs 7 -// #define dc 0 -// #define rst 1 - -#include // Arduino LCD library -#include - -TFT TFTscreen = TFT(cs, dc, rst); - -void setup() { - // begin serial communication - Serial.begin(9600); - - // initialize the display - TFTscreen.begin(); - - // set the background to white - TFTscreen.background(255, 255, 255); - -} - -void loop() { - - // read the values from your sensors and scale them to 0-255 - int redVal = map(analogRead(A0), 0, 1023, 0, 255); - int greenVal = map(analogRead(A1), 0, 1023, 0, 255); - int blueVal = map(analogRead(A2), 0, 1023, 0, 255); - - // draw the background based on the mapped values - TFTscreen.background(redVal, greenVal, blueVal); - - // send the values to the serial monitor - Serial.print("background("); - Serial.print(redVal); - Serial.print(" , "); - Serial.print(greenVal); - Serial.print(" , "); - Serial.print(blueVal); - Serial.println(")"); - - // wait for a moment - delay(33); - -} - diff --git a/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino b/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino deleted file mode 100644 index f482bd1..0000000 --- a/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino +++ /dev/null @@ -1,74 +0,0 @@ -/* - Arduino TFT text example - - This example demonstrates how to draw text on the - TFT with an Arduino. The Arduino reads the value - of an analog sensor attached to pin A0, and writes - the value to the LCD screen, updating every - quarter second. - - This example code is in the public domain - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/TFTDisplayText - - */ - -#include // Arduino LCD library -#include - -// pin definition for the Uno -#define cs 10 -#define dc 9 -#define rst 8 - -// pin definition for the Leonardo -// #define cs 7 -// #define dc 0 -// #define rst 1 - -// create an instance of the library -TFT TFTscreen = TFT(cs, dc, rst); - -// char array to print to the screen -char sensorPrintout[4]; - -void setup() { - - // Put this line at the beginning of every sketch that uses the GLCD: - TFTscreen.begin(); - - // clear the screen with a black background - TFTscreen.background(0, 0, 0); - - // write the static text to the screen - // set the font color to white - TFTscreen.stroke(255,255,255); - // set the font size - TFTscreen.setTextSize(2); - // write the text to the top left corner of the screen - TFTscreen.text("Sensor Value :\n ",0,0); - // ste the font size very large for the loop - TFTscreen.setTextSize(5); -} - -void loop() { - - // Read the value of the sensor on A0 - String sensorVal = String(analogRead(A0)); - - // convert the reading to a char array - sensorVal.toCharArray(sensorPrintout, 4); - - // set the font color - TFTscreen.stroke(255,255,255); - // print the sensor value - TFTscreen.text(sensorPrintout, 0, 20); - // wait for a moment - delay(250); - // erase the text you just wrote - TFTscreen.stroke(0,0,0); - TFTscreen.text(sensorPrintout, 0, 20); -} - diff --git a/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino b/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino deleted file mode 100644 index 29e3483..0000000 --- a/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino +++ /dev/null @@ -1,84 +0,0 @@ -/* - - TFT EtchASketch - - This example for the Arduino screen draws a white point - on the GLCD based on the values of 2 potentiometers. - To clear the screen, press a button attached to pin 2. - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/TFTEtchASketch - - */ - -#include // Arduino LCD library -#include - -// pin definition for the Uno -#define cs 10 -#define dc 9 -#define rst 8 - -// pin definition for the Leonardo -// #define cs 7 -// #define dc 0 -// #define rst 1 - -TFT TFTscreen = TFT(cs, dc, rst); - -// initial position of the cursor -int xPos = TFTscreen.width()/2; -int yPos = TFTscreen.height()/2; - -// pin the erase switch is connected to -int erasePin = 2; - -void setup() { - // declare inputs - pinMode(erasePin, INPUT); - // initialize the screen - TFTscreen.begin(); - // make the background black - TFTscreen.background(0,0,0); -} - -void loop() -{ - // read the potentiometers on A0 and A1 - int xValue = analogRead(A0); - int yValue = analogRead(A1); - - // map the values and update the position - xPos = xPos + (map(xValue, 0, 1023, 2, -2)); - yPos = yPos + (map(yValue, 0, 1023, -2, 2)); - -// don't let the point go past the screen edges - if(xPos > 159){ - (xPos = 159); - } - - if(xPos < 0){ - (xPos = 0); - } - if(yPos > 127){ - (yPos = 127); - } - - if(yPos < 0){ - (yPos = 0); - } - - // draw the point - TFTscreen.stroke(255,255,255); - TFTscreen.point(xPos,yPos); - - // read the value of the pin, and erase the screen if pressed - if(digitalRead(erasePin) == HIGH){ - TFTscreen.background(0,0,0); - } - - delay(33); -} diff --git a/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino b/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino deleted file mode 100644 index 39ae49b..0000000 --- a/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino +++ /dev/null @@ -1,71 +0,0 @@ -/* - - TFT Graph - - This example for an Arduino screen reads - the value of an analog sensor on A0, and - graphs the values on the screen. - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/TFTGraph - - */ - -#include // Arduino LCD library -#include - - // pin definition for the Uno -#define cs 10 -#define dc 9 -#define rst 8 - -// pin definition for the Leonardo -// #define cs 7 -// #define dc 0 -// #define rst 1 - -TFT TFTscreen = TFT(cs, dc, rst); - -// position of the line on screen -int xPos = 0; - -void setup(){ - // initialize the serial port - Serial.begin(9600); - - // initialize the display - TFTscreen.begin(); - - // clear the screen with a pretty color - TFTscreen.background(250,16,200); -} - -void loop(){ - // read the sensor and map it to the screen height - int sensor = analogRead(A0); - int drawHeight = map(sensor,0,1023,0,TFTscreen.height()); - - // print out the height to the serial monitor - Serial.println(drawHeight); - - // draw a line in a nice color - TFTscreen.stroke(250,180,10); - TFTscreen.line(xPos, TFTscreen.height()-drawHeight, xPos, TFTscreen.height()); - - // if the graph has reached the screen edge - // erase the screen and start again - if (xPos >= 160) { - xPos = 0; - TFTscreen.background(250,16,200); - } - else { - // increment the horizontal position: - xPos++; - } - - delay(16); -} - diff --git a/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino b/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino deleted file mode 100644 index 02ea11c..0000000 --- a/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino +++ /dev/null @@ -1,135 +0,0 @@ -/* - - TFT Pong - - This example for the Arduino screen reads the values - of 2 potentiometers to move a rectangular platform - on the x and y axes. The platform can intersect - with a ball causing it to bounce. - - This example code is in the public domain. - - Created by Tom Igoe December 2012 - Modified 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/TFTPong - - */ - -#include // Arduino LCD library -#include - -// pin definition for the Uno -#define cs 10 -#define dc 9 -#define rst 8 - -// pin definition for the Leonardo -// #define cs 7 -// #define dc 0 -// #define rst 1 - -TFT TFTscreen = TFT(cs, dc, rst); - -// variables for the position of the ball and paddle -int paddleX = 0; -int paddleY = 0; -int oldPaddleX, oldPaddleY; -int ballDirectionX = 1; -int ballDirectionY = 1; - -int ballSpeed = 10; // lower numbers are faster - -int ballX, ballY, oldBallX, oldBallY; - -void setup() { - // initialize the display - TFTscreen.begin(); - // black background - TFTscreen.background(0,0,0); -} - -void loop() { - - // save the width and height of the screen - int myWidth = TFTscreen.width(); - int myHeight = TFTscreen.height(); - - // map the paddle's location to the position of the potentiometers - paddleX = map(analogRead(A0), 512, -512, 0, myWidth) - 20/2; - paddleY = map(analogRead(A1), 512, -512, 0, myHeight) - 5/2; - - // set the fill color to black and erase the previous - // position of the paddle if different from present - TFTscreen.fill(0,0,0); - - if (oldPaddleX != paddleX || oldPaddleY != paddleY) { - TFTscreen.rect(oldPaddleX, oldPaddleY, 20, 5); - } - - // draw the paddle on screen, save the current position - // as the previous. - TFTscreen.fill(255,255,255); - - TFTscreen.rect(paddleX, paddleY, 20, 5); - oldPaddleX = paddleX; - oldPaddleY = paddleY; - - // update the ball's position and draw it on screen - if (millis() % ballSpeed < 2) { - moveBall(); - } -} - -// this function determines the ball's position on screen -void moveBall() { - // if the ball goes offscreen, reverse the direction: - if (ballX > TFTscreen.width() || ballX < 0) { - ballDirectionX = -ballDirectionX; - } - - if (ballY > TFTscreen.height() || ballY < 0) { - ballDirectionY = -ballDirectionY; - } - - // check if the ball and the paddle occupy the same space on screen - if (inPaddle(ballX, ballY, paddleX, paddleY, 20, 5)) { - ballDirectionX = -ballDirectionX; - ballDirectionY = -ballDirectionY; - } - - // update the ball's position - ballX += ballDirectionX; - ballY += ballDirectionY; - -// erase the ball's previous position - TFTscreen.fill(0,0,0); - - if (oldBallX != ballX || oldBallY != ballY) { - TFTscreen.rect(oldBallX, oldBallY, 5, 5); - } - - - // draw the ball's current position - TFTscreen.fill(255,255,255); - TFTscreen.rect(ballX, ballY, 5, 5); - - oldBallX = ballX; - oldBallY = ballY; - -} - -// this function checks the position of the ball -// to see if it intersects with the paddle -boolean inPaddle(int x, int y, int rectX, int rectY, int rectWidth, int rectHeight) { - boolean result = false; - - if ((x >= rectX && x <= (rectX + rectWidth)) && - (y >= rectY && y <= (rectY + rectHeight))) { - result = true; - } - -return result; -} - - diff --git a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino deleted file mode 100644 index 3d3f230..0000000 --- a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino +++ /dev/null @@ -1,101 +0,0 @@ -/* - - Esplora TFT Bitmap Logos - - This example for the Arduino TFT screen is for use - with an Arduino Esplora. - - This example reads an image file from a micro-SD card - and draws it on the screen, at random locations. - - There is a .bmp file included with this sketch. - - open the sketch folder (Ctrl-K or Cmd-K) - - copy the "arduino.bmp" file to a micro-SD - - put the SD into the SD slot of the Arduino LCD module. - - This example code is in the public domain. - - Created 19 April 2013 by Enrico Gueli - - http://arduino.cc/en/Tutorial/EsploraTFTBitmapLogo - - */ - -// include the necessary libraries -#include -#include -#include -#include // Arduino LCD library - -// the Esplora pin connected to the chip select line for SD card -#define SD_CS 8 - -// this variable represents the image to be drawn on screen -PImage logo; - -void setup() { - // initialize the GLCD and show a message - // asking the user to open the serial line - EsploraTFT.begin(); - EsploraTFT.background(255, 255, 255); - - EsploraTFT.stroke(0, 0, 255); - EsploraTFT.println(); - EsploraTFT.println("Arduino LCD Bitmap Example"); - EsploraTFT.stroke(0, 0, 0); - EsploraTFT.println("Open serial monitor"); - EsploraTFT.println("to run the sketch"); - - // initialize the serial port: it will be used to - // print some diagnostic info - Serial.begin(9600); - while (!Serial) { - // wait for serial monitor to be open - } - - // try to access the SD card. If that fails (e.g. - // no card present), the Esplora's LED will turn red. - Serial.print("Initializing SD card..."); - if (!SD.begin(SD_CS)) { - Serial.println("failed!"); - Esplora.writeRed(255); - return; - } - Serial.println("OK!"); - - // clear the GLCD screen before starting - EsploraTFT.background(255, 255, 255); - - // now that the SD card can be access, try to load the - // image file. The Esplora LED will turn green or red if - // the loading went OK or not. - Esplora.writeRGB(0, 0, 0); - logo = EsploraTFT.loadImage("arduino.bmp"); - if (logo.isValid()) { - Esplora.writeGreen(255); - } - else - Esplora.writeRed(255); - -} - -void loop() { - // don't do anything if the image wasn't loaded correctly. - if (logo.isValid() == false) { - return; - } - - Serial.println("drawing image"); - - // get a random location where to draw the image. - // To avoid the image to be draw outside the screen, - // take into account the image size. - int x = random(EsploraTFT.width() - logo.width()); - int y = random(EsploraTFT.height() - logo.height()); - - // draw the image to the screen - EsploraTFT.image(logo, x, y); - - // wait a little bit before drawing again - delay(1500); -} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp deleted file mode 100644 index 09c670a..0000000 Binary files a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp and /dev/null differ diff --git a/libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino b/libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino deleted file mode 100644 index 63a0ee2..0000000 --- a/libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino +++ /dev/null @@ -1,54 +0,0 @@ -/* - - Esplora TFT Color Picker - - This example for the Esplora with an Arduino TFT reads - the input of the joystick and slider, using the values - to change the screen's color. - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/TFTColorPicker - - */ - -#include -#include // Arduino LCD library -#include - -void setup() { - Serial.begin(9600); - - // initialize the LCD - EsploraTFT.begin(); - - // start out with a white screen - EsploraTFT.background(255, 255, 255); - -} - -void loop() { - - // map the values from sensors - int xValue = map(Esplora.readJoystickX(), -512, 512, 0, 255); // read the joystick's X position - int yValue = map(Esplora.readJoystickY(), -512, 512, 0, 255); // read the joystick's Y position - int slider = map(Esplora.readSlider(), 0, 1023, 0, 255); // read the slider's position - - // change the background color based on the mapped values - EsploraTFT.background(xValue, yValue, slider); - - // print the mapped values to the Serial monitor - Serial.print("background("); - Serial.print(xValue); - Serial.print(" , "); - Serial.print(yValue); - Serial.print(" , "); - Serial.print(slider); - Serial.println(")"); - - delay(33); - -} - diff --git a/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino b/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino deleted file mode 100644 index a1430d3..0000000 --- a/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino +++ /dev/null @@ -1,83 +0,0 @@ -/* - - Esplora TFT EtchASketch - - This example for the Arduino TFT and Esplora draws - a white line on the screen, based on the position - of the joystick. To clear the screen, shake the - Esplora, using the values from the accelerometer. - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/EsploraTFTEtchASketch - - */ - -#include -#include // Arduino LCD library -#include - -// initial position of the cursor -int xPos = EsploraTFT.width()/2; -int yPos = EsploraTFT.height()/2; - -void setup() { - // initialize the display - EsploraTFT.begin(); - - // clear the background - EsploraTFT.background(0,0,0); -} - -void loop() -{ - - int xAxis = Esplora.readJoystickX(); // read the X axis - int yAxis = Esplora.readJoystickY(); // read the Y axis - - // update the position of the line - // depending on the position of the joystick - if (xAxis<10 && xAxis>-10){ - xPos=xPos; - } - else{ - xPos = xPos + (map(xAxis, -512, 512, 2, -2)); - } - if (yAxis<10 && yAxis>-10){ - yAxis=yAxis; - } - else{ - yPos = yPos + (map(yAxis, -512, 512, -2, 2)); - } - -// don't let the point go past the screen edges - if(xPos > 159){ - (xPos = 159); - } - - if(xPos < 0){ - (xPos = 0); - } - if(yPos > 127){ - (yPos = 127); - } - - if(yPos < 0){ - (yPos = 0); - } - - // draw the point - EsploraTFT.stroke(255,255,255); - EsploraTFT.point(xPos,yPos); - - // check the accelerometer values and clear - // the screen if it is being shaken - if(abs(Esplora.readAccelerometer(X_AXIS))>200 || abs(Esplora.readAccelerometer(Y_AXIS))>200){ - EsploraTFT.background(0,0,0); - } - - delay(33); -} - diff --git a/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino b/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino deleted file mode 100644 index 7f2a427..0000000 --- a/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino +++ /dev/null @@ -1,56 +0,0 @@ -/* - - Esplora TFT Graph - - This example for the Esplora with an Arduino TFT reads - the value of the light sensor, and graphs the values on - the screen. - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/EsploraTFTGraph - - */ - -#include -#include // Arduino LCD library -#include - -// position of the line on screen -int xPos = 0; - -void setup(){ - - // initialize the screen - EsploraTFT.begin(); - - // clear the screen with a nice color - EsploraTFT.background(250,16,200); -} - -void loop(){ - - // read the sensor value - int sensor = Esplora.readLightSensor(); - // map the sensor value to the height of the screen - int graphHeight = map(sensor,0,1023,0,EsploraTFT.height()); - - // draw the line in a pretty color - EsploraTFT.stroke(250,180,10); - EsploraTFT.line(xPos, EsploraTFT.height() - graphHeight, xPos, EsploraTFT.height()); - - // if the graph reaches the edge of the screen - // erase it and start over from the other side - if (xPos >= 160) { - xPos = 0; - EsploraTFT.background(250,16,200); - } - else { - // increment the horizontal position: - xPos++; - } - - delay(16); -} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino b/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino deleted file mode 100644 index a7945c9..0000000 --- a/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino +++ /dev/null @@ -1,63 +0,0 @@ -/* - - Esplora TFT Horizon - - This example for the Arduino TFT and Esplora draws - a line on the screen that stays level with the ground - as you tile the Esplora side to side - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/EsploraTFTHorizon - - */ - -#include -#include // Arduino LCD library -#include - -// horizontal start and end positions -int yStart = EsploraTFT.height()/2; -int yEnd = EsploraTFT.height()/2; - -// previous start and end positions -int oldEndY; -int oldStartY; - -void setup() { - // initialize the display - EsploraTFT.begin(); - // make the background black - EsploraTFT.background(0,0,0); -} - -void loop() -{ - // read the x-axis of te accelerometer - int tilt = Esplora.readAccelerometer(X_AXIS); - - // the values are 100 when tilted to the left - // and -100 when tilted to the right - // map these values to the start and end points - yStart = map(tilt,-100,100,EsploraTFT.height(),0); - yEnd = map(tilt,-100,100,0,EsploraTFT.height()); - - // if the previous values are different than the current values - // erase the previous line - if (oldStartY != yStart || oldEndY != yEnd) { - EsploraTFT.stroke(0,0,0); - EsploraTFT.line(0, oldStartY, EsploraTFT.width(), oldEndY); - } - - // draw the line in magenta - EsploraTFT.stroke(255,0,255); - EsploraTFT.line(0,yStart,EsploraTFT.width(),yEnd); - - // save the current start and end points - // to compare int he next loop - oldStartY= yStart; - oldEndY = yEnd; - delay(10); -} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino b/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino deleted file mode 100644 index e3422d4..0000000 --- a/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino +++ /dev/null @@ -1,126 +0,0 @@ -/* - - Esplora TFT Pong - - This example for the Esplora with an Arduino TFT screen reads - the value of the joystick to move a rectangular platform - on the x and y axes. The platform can intersect with a ball - causing it to bounce. The Esplora's slider adjusts the speed - of the ball. - - This example code is in the public domain. - - Created by Tom Igoe December 2012 - Modified 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/EsploraTFTPong - - */ - -#include -#include // Arduino LCD library -#include - -// variables for the position of the ball and paddle -int paddleX = 0; -int paddleY = 0; -int oldPaddleX, oldPaddleY; -int ballDirectionX = 1; -int ballDirectionY = 1; - -int ballX, ballY, oldBallX, oldBallY; - -void setup() { - - Serial.begin(9600); - - // initialize the display - EsploraTFT.begin(); - // set the background the black - EsploraTFT.background(0,0,0); -} - -void loop() { - // save the width and height of the screen - int myWidth = EsploraTFT.width(); - int myHeight = EsploraTFT.height(); - - // map the paddle's location to the joystick's position - paddleX = map(Esplora.readJoystickX(), 512, -512, 0, myWidth) - 20/2; - paddleY = map(Esplora.readJoystickY(), -512, 512, 0, myHeight) - 5/2; - Serial.print(paddleX); - Serial.print(" "); - Serial.println(paddleY); - - // set the fill color to black and erase the previous - // position of the paddle if different from present - EsploraTFT.fill(0,0,0); - - if (oldPaddleX != paddleX || oldPaddleY != paddleY) { - EsploraTFT.rect(oldPaddleX, oldPaddleY, 20, 5); - } - - // draw the paddle on screen, save the current position - // as the previous. - EsploraTFT.fill(255,255,255); - EsploraTFT.rect(paddleX, paddleY, 20, 5); - oldPaddleX = paddleX; - oldPaddleY = paddleY; - - // read the slider to determinde the speed of the ball - int ballSpeed = map(Esplora.readSlider(), 0, 1023, 0, 80)+1; - if (millis() % ballSpeed < 2) { - moveBall(); - } -} - - -// this function determines the ball's position on screen -void moveBall() { - // if the ball goes offscreen, reverse the direction: - if (ballX > EsploraTFT.width() || ballX < 0) { - ballDirectionX = -ballDirectionX; - } - - if (ballY > EsploraTFT.height() || ballY < 0) { - ballDirectionY = -ballDirectionY; - } - - // check if the ball and the paddle occupy the same space on screen - if (inPaddle(ballX, ballY, paddleX, paddleY, 20, 5)) { - ballDirectionY = -ballDirectionY; - } - - // update the ball's position - ballX += ballDirectionX; - ballY += ballDirectionY; - - // erase the ball's previous position - EsploraTFT.fill(0,0,0); - - if (oldBallX != ballX || oldBallY != ballY) { - EsploraTFT.rect(oldBallX, oldBallY, 5, 5); - } - - // draw the ball's current position - EsploraTFT.fill(255,255,255); - - EsploraTFT.rect(ballX, ballY, 5, 5); - - oldBallX = ballX; - oldBallY = ballY; - -} - -// this function checks the position of the ball -// to see if it intersects with the paddle -boolean inPaddle(int x, int y, int rectX, int rectY, int rectWidth, int rectHeight) { - boolean result = false; - - if ((x >= rectX && x <= (rectX + rectWidth)) && - (y >= rectY && y <= (rectY + rectHeight))) { - result = true; - } - - return result; -} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino b/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino deleted file mode 100644 index b475d2d..0000000 --- a/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino +++ /dev/null @@ -1,64 +0,0 @@ -/* - - Esplora TFT Temperature Display - - This example for the Arduino TFT screen is for use - with an Arduino Esplora. - - This example reads the temperature of the Esplora's - on board thermisistor and displays it on an attached - LCD screen, updating every second. - - This example code is in the public domain. - - Created 15 April 2013 by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/EsploraTFTTemp - - */ - -// include the necessary libraries -#include -#include // Arduino LCD library -#include - -char tempPrintout[3]; // array to hold the temperature data - -void setup() { - - // Put this line at the beginning of every sketch that uses the GLCD - EsploraTFT.begin(); - - // clear the screen with a black background - EsploraTFT.background(0,0,0); - - // set the text color to magenta - EsploraTFT.stroke(200,20,180); - // set the text to size 2 - EsploraTFT.setTextSize(2); - // start the text at the top left of the screen - // this text is going to remain static - EsploraTFT.text("Degrees in C :\n ",0,0); - - // set the text in the loop to size 5 - EsploraTFT.setTextSize(5); -} - -void loop() { - - // read the temperature in Celcius and store it in a String - String temperature = String(Esplora.readTemperature(DEGREES_C)); - - // convert the string to a char array - temperature.toCharArray(tempPrintout, 3); - - // set the text color to white - EsploraTFT.stroke(255,255,255); - // print the temperature one line below the static text - EsploraTFT.text(tempPrintout, 0, 30); - - delay(1000); - // erase the text for the next loop - EsploraTFT.stroke(0,0,0); - EsploraTFT.text(tempPrintout, 0, 30); -} diff --git a/libraries/TFT/keywords.txt b/libraries/TFT/keywords.txt deleted file mode 100644 index 0ddb3b5..0000000 --- a/libraries/TFT/keywords.txt +++ /dev/null @@ -1,20 +0,0 @@ -####################################### -# Syntax Coloring Map For Arduino GLCD -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -TFT KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - - -####################################### -# Constants (LITERAL1) -####################################### - -EsploraTFT LITERAL1 diff --git a/libraries/TFT/utility/Adafruit-README.txt b/libraries/TFT/utility/Adafruit-README.txt deleted file mode 100644 index 6f3b682..0000000 --- a/libraries/TFT/utility/Adafruit-README.txt +++ /dev/null @@ -1,21 +0,0 @@ -This is a library for the Adafruit 1.8" SPI display. -This library works with the Adafruit 1.8" TFT Breakout w/SD card - ----> http://www.adafruit.com/products/358 -as well as Adafruit raw 1.8" TFT display - ----> http://www.adafruit.com/products/618 - -Check out the links above for our tutorials and wiring diagrams. -These displays use SPI to communicate, 4 or 5 pins are required -to interface (RST is optional). -Adafruit invests time and resources providing this open source code, -please support Adafruit and open-source hardware by purchasing -products from Adafruit! - -Written by Limor Fried/Ladyada for Adafruit Industries. -MIT license, all text above must be included in any redistribution - -To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_ST7735. Check that the Adafruit_ST7735 folder contains Adafruit_ST7735.cpp and Adafruit_ST7735. - -Place the Adafruit_ST7735 library folder your /libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE - -Also requires the Adafruit_GFX library for Arduino. diff --git a/libraries/TFT/utility/Adafruit-license.txt b/libraries/TFT/utility/Adafruit-license.txt deleted file mode 100644 index 4bbfa39..0000000 --- a/libraries/TFT/utility/Adafruit-license.txt +++ /dev/null @@ -1,25 +0,0 @@ -Software License Agreement (BSD License) - -Copyright (c) 2012, Adafruit Industries. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. -3. Neither the name of the copyright holders nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libraries/TFT/utility/Adafruit_GFX.cpp b/libraries/TFT/utility/Adafruit_GFX.cpp deleted file mode 100644 index a7a541c..0000000 --- a/libraries/TFT/utility/Adafruit_GFX.cpp +++ /dev/null @@ -1,671 +0,0 @@ -/****************************************************************** - This is the core graphics library for all our displays, providing - basic graphics primitives (points, lines, circles, etc.). It needs - to be paired with a hardware-specific library for each display - device we carry (handling the lower-level functions). - - Adafruit invests time and resources providing this open - source code, please support Adafruit and open-source hardware - by purchasing products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, check license.txt for more information. - All text above must be included in any redistribution. - ******************************************************************/ - -#include "Adafruit_GFX.h" -#include "glcdfont.c" -#include - -void Adafruit_GFX::constructor(int16_t w, int16_t h) { - _width = WIDTH = w; - _height = HEIGHT = h; - - rotation = 0; - cursor_y = cursor_x = 0; - textsize = 1; - textcolor = textbgcolor = 0xFFFF; - wrap = true; - - strokeColor = 0; - useStroke = true; - fillColor = 0; - useFill = false; - -} - - -// draw a circle outline -void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, - uint16_t color) { - int16_t f = 1 - r; - int16_t ddF_x = 1; - int16_t ddF_y = -2 * r; - int16_t x = 0; - int16_t y = r; - - drawPixel(x0, y0+r, color); - drawPixel(x0, y0-r, color); - drawPixel(x0+r, y0, color); - drawPixel(x0-r, y0, color); - - while (x= 0) { - y--; - ddF_y += 2; - f += ddF_y; - } - x++; - ddF_x += 2; - f += ddF_x; - - drawPixel(x0 + x, y0 + y, color); - drawPixel(x0 - x, y0 + y, color); - drawPixel(x0 + x, y0 - y, color); - drawPixel(x0 - x, y0 - y, color); - drawPixel(x0 + y, y0 + x, color); - drawPixel(x0 - y, y0 + x, color); - drawPixel(x0 + y, y0 - x, color); - drawPixel(x0 - y, y0 - x, color); - - } -} - -void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, - int16_t r, uint8_t cornername, uint16_t color) { - int16_t f = 1 - r; - int16_t ddF_x = 1; - int16_t ddF_y = -2 * r; - int16_t x = 0; - int16_t y = r; - - while (x= 0) { - y--; - ddF_y += 2; - f += ddF_y; - } - x++; - ddF_x += 2; - f += ddF_x; - if (cornername & 0x4) { - drawPixel(x0 + x, y0 + y, color); - drawPixel(x0 + y, y0 + x, color); - } - if (cornername & 0x2) { - drawPixel(x0 + x, y0 - y, color); - drawPixel(x0 + y, y0 - x, color); - } - if (cornername & 0x8) { - drawPixel(x0 - y, y0 + x, color); - drawPixel(x0 - x, y0 + y, color); - } - if (cornername & 0x1) { - drawPixel(x0 - y, y0 - x, color); - drawPixel(x0 - x, y0 - y, color); - } - } -} - -void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, - uint16_t color) { - drawFastVLine(x0, y0-r, 2*r+1, color); - fillCircleHelper(x0, y0, r, 3, 0, color); -} - -// used to do circles and roundrects! -void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, - uint8_t cornername, int16_t delta, uint16_t color) { - - int16_t f = 1 - r; - int16_t ddF_x = 1; - int16_t ddF_y = -2 * r; - int16_t x = 0; - int16_t y = r; - - while (x= 0) { - y--; - ddF_y += 2; - f += ddF_y; - } - x++; - ddF_x += 2; - f += ddF_x; - - if (cornername & 0x1) { - drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); - drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); - } - if (cornername & 0x2) { - drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); - drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); - } - } -} - -// bresenham's algorithm - thx wikpedia -void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, - int16_t x1, int16_t y1, - uint16_t color) { - int16_t steep = abs(y1 - y0) > abs(x1 - x0); - if (steep) { - swap(x0, y0); - swap(x1, y1); - } - - if (x0 > x1) { - swap(x0, x1); - swap(y0, y1); - } - - int16_t dx, dy; - dx = x1 - x0; - dy = abs(y1 - y0); - - int16_t err = dx / 2; - int16_t ystep; - - if (y0 < y1) { - ystep = 1; - } else { - ystep = -1; - } - - for (; x0<=x1; x0++) { - if (steep) { - drawPixel(y0, x0, color); - } else { - drawPixel(x0, y0, color); - } - err -= dy; - if (err < 0) { - y0 += ystep; - err += dx; - } - } -} - - -// draw a rectangle -void Adafruit_GFX::drawRect(int16_t x, int16_t y, - int16_t w, int16_t h, - uint16_t color) { - drawFastHLine(x, y, w, color); - drawFastHLine(x, y+h-1, w, color); - drawFastVLine(x, y, h, color); - drawFastVLine(x+w-1, y, h, color); -} - -void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, - int16_t h, uint16_t color) { - // stupidest version - update in subclasses if desired! - drawLine(x, y, x, y+h-1, color); -} - - -void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, - int16_t w, uint16_t color) { - // stupidest version - update in subclasses if desired! - drawLine(x, y, x+w-1, y, color); -} - -void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color) { - // stupidest version - update in subclasses if desired! - for (int16_t i=x; i= y1 >= y0) - if (y0 > y1) { - swap(y0, y1); swap(x0, x1); - } - if (y1 > y2) { - swap(y2, y1); swap(x2, x1); - } - if (y0 > y1) { - swap(y0, y1); swap(x0, x1); - } - - if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing - a = b = x0; - if(x1 < a) a = x1; - else if(x1 > b) b = x1; - if(x2 < a) a = x2; - else if(x2 > b) b = x2; - drawFastHLine(a, y0, b-a+1, color); - return; - } - - int16_t - dx01 = x1 - x0, - dy01 = y1 - y0, - dx02 = x2 - x0, - dy02 = y2 - y0, - dx12 = x2 - x1, - dy12 = y2 - y1, - sa = 0, - sb = 0; - - // For upper part of triangle, find scanline crossings for segments - // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 - // is included here (and second loop will be skipped, avoiding a /0 - // error there), otherwise scanline y1 is skipped here and handled - // in the second loop...which also avoids a /0 error here if y0=y1 - // (flat-topped triangle). - if(y1 == y2) last = y1; // Include y1 scanline - else last = y1-1; // Skip it - - for(y=y0; y<=last; y++) { - a = x0 + sa / dy01; - b = x0 + sb / dy02; - sa += dx01; - sb += dx02; - /* longhand: - a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); - b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); - */ - if(a > b) swap(a,b); - drawFastHLine(a, y, b-a+1, color); - } - - // For lower part of triangle, find scanline crossings for segments - // 0-2 and 1-2. This loop is skipped if y1=y2. - sa = dx12 * (y - y1); - sb = dx02 * (y - y0); - for(; y<=y2; y++) { - a = x1 + sa / dy12; - b = x0 + sb / dy02; - sa += dx12; - sb += dx02; - /* longhand: - a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); - b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); - */ - if(a > b) swap(a,b); - drawFastHLine(a, y, b-a+1, color); - } -} - -void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, - const uint8_t *bitmap, int16_t w, int16_t h, - uint16_t color) { - - int16_t i, j, byteWidth = (w + 7) / 8; - - for(j=0; j> (i & 7))) { - drawPixel(x+i, y+j, color); - } - } - } -} - - -#if ARDUINO >= 100 -size_t Adafruit_GFX::write(uint8_t c) { -#else -void Adafruit_GFX::write(uint8_t c) { -#endif - if (c == '\n') { - cursor_y += textsize*8; - cursor_x = 0; - } else if (c == '\r') { - // skip em - } else { - drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); - cursor_x += textsize*6; - if (wrap && (cursor_x > (_width - textsize*6))) { - cursor_y += textsize*8; - cursor_x = 0; - } - } -#if ARDUINO >= 100 - return 1; -#endif -} - -// draw a character -void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, - uint16_t color, uint16_t bg, uint8_t size) { - - if((x >= _width) || // Clip right - (y >= _height) || // Clip bottom - ((x + 5 * size - 1) < 0) || // Clip left - ((y + 8 * size - 1) < 0)) // Clip top - return; - - for (int8_t i=0; i<6; i++ ) { - uint8_t line; - if (i == 5) - line = 0x0; - else - line = pgm_read_byte(font+(c*5)+i); - for (int8_t j = 0; j<8; j++) { - if (line & 0x1) { - if (size == 1) // default size - drawPixel(x+i, y+j, color); - else { // big size - fillRect(x+(i*size), y+(j*size), size, size, color); - } - } else if (bg != color) { - if (size == 1) // default size - drawPixel(x+i, y+j, bg); - else { // big size - fillRect(x+i*size, y+j*size, size, size, bg); - } - } - line >>= 1; - } - } -} - -void Adafruit_GFX::setCursor(int16_t x, int16_t y) { - cursor_x = x; - cursor_y = y; -} - - -void Adafruit_GFX::setTextSize(uint8_t s) { - textsize = (s > 0) ? s : 1; -} - - -void Adafruit_GFX::setTextColor(uint16_t c) { - textcolor = c; - textbgcolor = c; - // for 'transparent' background, we'll set the bg - // to the same as fg instead of using a flag -} - - void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) { - textcolor = c; - textbgcolor = b; - } - -void Adafruit_GFX::setTextWrap(boolean w) { - wrap = w; -} - -uint8_t Adafruit_GFX::getRotation(void) { - rotation %= 4; - return rotation; -} - -void Adafruit_GFX::setRotation(uint8_t x) { - x %= 4; // cant be higher than 3 - rotation = x; - switch (x) { - case 0: - case 2: - _width = WIDTH; - _height = HEIGHT; - break; - case 1: - case 3: - _width = HEIGHT; - _height = WIDTH; - break; - } -} - -void Adafruit_GFX::invertDisplay(boolean i) { - // do nothing, can be subclassed -} - - -// return the size of the display which depends on the rotation! -int16_t Adafruit_GFX::width(void) { - return _width; -} - -int16_t Adafruit_GFX::height(void) { - return _height; -} - - - -uint16_t Adafruit_GFX::newColor(uint8_t r, uint8_t g, uint8_t b) { - return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); -} - - -void Adafruit_GFX::background(uint8_t red, uint8_t green, uint8_t blue) { - background(newColor(red, green, blue)); -} - -void Adafruit_GFX::background(color c) { - fillScreen(c); -} - -void Adafruit_GFX::stroke(uint8_t red, uint8_t green, uint8_t blue) { - stroke(newColor(red, green, blue)); -} - -void Adafruit_GFX::stroke(color c) { - useStroke = true; - strokeColor = c; - setTextColor(c); -} - -void Adafruit_GFX::noStroke() { - useStroke = false; -} - -void Adafruit_GFX::noFill() { - useFill = false; -} - -void Adafruit_GFX::fill(uint8_t red, uint8_t green, uint8_t blue) { - fill(newColor(red, green, blue)); -} - -void Adafruit_GFX::fill(color c) { - useFill = true; - fillColor = c; -} - - -void Adafruit_GFX::text(const char * text, int16_t x, int16_t y) { - if (!useStroke) - return; - - setTextWrap(false); - setTextColor(strokeColor); - setCursor(x, y); - print(text); -} - -void Adafruit_GFX::textWrap(const char * text, int16_t x, int16_t y) { - if (!useStroke) - return; - - setTextWrap(true); - setTextColor(strokeColor); - setCursor(x, y); - print(text); -} - - -void Adafruit_GFX::textSize(uint8_t size) { - setTextSize(size); -} - -void Adafruit_GFX::point(int16_t x, int16_t y) { - if (!useStroke) - return; - - drawPixel(x, y, strokeColor); -} - -void Adafruit_GFX::line(int16_t x1, int16_t y1, int16_t x2, int16_t y2) { - if (!useStroke) - return; - - if (x1 == x2) { - if (y1 < y2) - drawFastVLine(x1, y1, y2 - y1, strokeColor); - else - drawFastVLine(x1, y2, y1 - y2, strokeColor); - } - else if (y1 == y2) { - if (x1 < x2) - drawFastHLine(x1, y1, x2 - x1, strokeColor); - else - drawFastHLine(x2, y1, x1 - x2, strokeColor); - } - else { - drawLine(x1, y1, x2, y2, strokeColor); - } -} - -void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height) { - if (useFill) { - fillRect(x, y, width, height, fillColor); - } - if (useStroke) { - drawRect(x, y, width, height, strokeColor); - } -} - -void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius) { - if (radius == 0) { - rect(x, y, width, height); - } - if (useFill) { - fillRoundRect(x, y, width, height, radius, fillColor); - } - if (useStroke) { - drawRoundRect(x, y, width, height, radius, strokeColor); - } -} - -void Adafruit_GFX::circle(int16_t x, int16_t y, int16_t r) { - if (r == 0) - return; - - if (useFill) { - fillCircle(x, y, r, fillColor); - } - if (useStroke) { - drawCircle(x, y, r, strokeColor); - } -} - -void Adafruit_GFX::triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3) { - if (useFill) { - fillTriangle(x1, y1, x2, y2, x3, y3, fillColor); - } - if (useStroke) { - drawTriangle(x1, y1, x2, y2, x3, y3, strokeColor); - } -} - -#if defined(__SD_H__) // Arduino SD library - -#define BUFFPIXEL 20 - -void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { - int w, h, row, col; - uint8_t r, g, b; - uint32_t pos = 0; - uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) - uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer - - // Crop area to be loaded - w = img._bmpWidth; - h = img._bmpHeight; - if((x+w-1) >= width()) w = width() - x; - if((y+h-1) >= height()) h = height() - y; - - /* - // Set TFT address window to clipped image bounds - setAddrWindow(x, y, x+w-1, y+h-1); - */ - - for (row=0; row= sizeof(sdbuffer)) { // Indeed - img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); - buffidx = 0; // Set index to beginning - } - - // Convert pixel from BMP to TFT format, push to display - b = sdbuffer[buffidx++]; - g = sdbuffer[buffidx++]; - r = sdbuffer[buffidx++]; - //pushColor(tft.Color565(r,g,b)); - drawPixel(x + col, y + row, newColor(r, g, b)); - - } // end pixel - } // end scanline - -} - -#endif \ No newline at end of file diff --git a/libraries/TFT/utility/Adafruit_GFX.h b/libraries/TFT/utility/Adafruit_GFX.h deleted file mode 100644 index b49aa0f..0000000 --- a/libraries/TFT/utility/Adafruit_GFX.h +++ /dev/null @@ -1,367 +0,0 @@ -/****************************************************************** - This is the core graphics library for all our displays, providing - basic graphics primitives (points, lines, circles, etc.). It needs - to be paired with a hardware-specific library for each display - device we carry (handling the lower-level functions). - - Adafruit invests time and resources providing this open - source code, please support Adafruit and open-source hardware - by purchasing products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - Processing-like API written by Enrico Gueli for Officine Arduino. - BSD license, check license.txt for more information. - All text above must be included in any redistribution. - ******************************************************************/ - -#ifndef _ADAFRUIT_GFX_H -#define _ADAFRUIT_GFX_H - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif - -/* - * This library can work with or without the presence of an SD - * reading library (to load images). At the moment, only the - * Arduino SD library is supported; it is included in - * standard Arduino libraries. - * - * The presence of the SD library is detected by looking at the - * __SD_H__ preprocessor variable, defined into - * Arduino SD library to avoid double inclusion. This means - * that in order to use the image-related API of Adafruit_GFX, - * SD.h *must* be included before Adafruit_GFX. - * - * The bottom part of this include file contains the actual image - * loading code; if it was in a separate .cpp file, there were no - * way to check if the SD library was present or not. - * - * A partial solution was to include SD.h anyway, see if that works - * (i.e. it is found in the include search path) and act accordingly. - * But this solution relied on the preprocessor to issue only a - * warning when an include file is not found. Avr-gcc, used for - * Arduino 8-bit MCUs, does that, but the standard gcc-4.4, used for - * Arduino Due, issues a fatal error and stops compilation. - * - * The best solution so far is to put the code here. It works if this - * include is used only in one .cpp file in the build (this is the - * case of most Arduino sketches); if used in multiple .cpp files, - * the linker may complain about duplicate definitions. - * - */ - -#if defined(__SD_H__) // Arduino SD library -# include "PImage.h" -#else -# warning "The SD library was not found. loadImage() and image() won't be supported." -#endif - -#define swap(a, b) { int16_t t = a; a = b; b = t; } - -/* TODO -enum RectMode { - CORNER, - CORNERS, - RADIUS, - CENTER -}; -*/ - -typedef uint16_t color; - -class Adafruit_GFX : public Print { - public: - - //Adafruit_GFX(); - // i have no idea why we have to formally call the constructor. kinda sux - void constructor(int16_t w, int16_t h); - - // this must be defined by the subclass - virtual void drawPixel(int16_t x, int16_t y, uint16_t color); - virtual void invertDisplay(boolean i); - - // these are 'generic' drawing functions, so we can share them! - virtual void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - uint16_t color); - virtual void drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color); - virtual void drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color); - virtual void drawRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color); - virtual void fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color); - virtual void fillScreen(uint16_t color); - - void drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color); - void drawCircleHelper(int16_t x0, int16_t y0, - int16_t r, uint8_t cornername, uint16_t color); - void fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color); - void fillCircleHelper(int16_t x0, int16_t y0, int16_t r, - uint8_t cornername, int16_t delta, uint16_t color); - - void drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - int16_t x2, int16_t y2, uint16_t color); - void fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - int16_t x2, int16_t y2, uint16_t color); - void drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, - int16_t radius, uint16_t color); - void fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, - int16_t radius, uint16_t color); - - void drawBitmap(int16_t x, int16_t y, - const uint8_t *bitmap, int16_t w, int16_t h, - uint16_t color); - void drawChar(int16_t x, int16_t y, unsigned char c, - uint16_t color, uint16_t bg, uint8_t size); -#if ARDUINO >= 100 - virtual size_t write(uint8_t); -#else - virtual void write(uint8_t); -#endif - void setCursor(int16_t x, int16_t y); - void setTextColor(uint16_t c); - void setTextColor(uint16_t c, uint16_t bg); - void setTextSize(uint8_t s); - void setTextWrap(boolean w); - - int16_t height(void); - int16_t width(void); - - void setRotation(uint8_t r); - uint8_t getRotation(void); - - - /* - * Processing-like graphics primitives - */ - - /// transforms a color in 16-bit form given the RGB components. - /// The default implementation makes a 5-bit red, a 6-bit - /// green and a 5-bit blue (MSB to LSB). Devices that use - /// different scheme should override this. - virtual uint16_t newColor(uint8_t red, uint8_t green, uint8_t blue); - - - // http://processing.org/reference/background_.html - void background(uint8_t red, uint8_t green, uint8_t blue); - void background(color c); - - // http://processing.org/reference/fill_.html - void fill(uint8_t red, uint8_t green, uint8_t blue); - void fill(color c); - - // http://processing.org/reference/noFill_.html - void noFill(); - - // http://processing.org/reference/stroke_.html - void stroke(uint8_t red, uint8_t green, uint8_t blue); - void stroke(color c); - - // http://processing.org/reference/noStroke_.html - void noStroke(); - - void text (const char * text, int16_t x, int16_t y); - void textWrap(const char * text, int16_t x, int16_t y); - - void textSize(uint8_t size); - - // similar to ellipse() in Processing, but with - // a single radius. - // http://processing.org/reference/ellipse_.html - void circle(int16_t x, int16_t y, int16_t r); - - void point(int16_t x, int16_t y); - - void line(int16_t x1, int16_t y1, int16_t x2, int16_t y2); - - void quad(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3, int16_t x4, int16_t y4); - - void rect(int16_t x, int16_t y, int16_t width, int16_t height); - - void rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius); - - void triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3); - - /* TODO - void rectMode(RectMode mode); - - void pushStyle(); - void popStyle(); - */ - -#if defined(__SD_H__) // Arduino SD library - PImage loadImage(const char * fileName) { return PImage::loadImage(fileName); } - - void image(PImage & img, uint16_t x, uint16_t y); -#endif - - protected: - int16_t WIDTH, HEIGHT; // this is the 'raw' display w/h - never changes - int16_t _width, _height; // dependent on rotation - int16_t cursor_x, cursor_y; - uint16_t textcolor, textbgcolor; - uint8_t textsize; - uint8_t rotation; - boolean wrap; // If set, 'wrap' text at right edge of display - - /* - * Processing-style graphics state - */ - - color strokeColor; - bool useStroke; - color fillColor; - bool useFill; -}; - -#if defined(__SD_H__) // Arduino SD library - -#define BUFFPIXEL 20 - -void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { - int w, h, row, col; - uint8_t r, g, b; - uint32_t pos = 0; - uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) - uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer - - // Crop area to be loaded - w = img._bmpWidth; - h = img._bmpHeight; - if((x+w-1) >= width()) w = width() - x; - if((y+h-1) >= height()) h = height() - y; - - /* - // Set TFT address window to clipped image bounds - setAddrWindow(x, y, x+w-1, y+h-1); - */ - - for (row=0; row= sizeof(sdbuffer)) { // Indeed - img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); - buffidx = 0; // Set index to beginning - } - - // Convert pixel from BMP to TFT format, push to display - b = sdbuffer[buffidx++]; - g = sdbuffer[buffidx++]; - r = sdbuffer[buffidx++]; - //pushColor(tft.Color565(r,g,b)); - drawPixel(x + col, y + row, newColor(r, g, b)); - - } // end pixel - } // end scanline - -} - - - - -// These read 16- and 32-bit types from the SD card file. -// BMP data is stored little-endian, Arduino is little-endian too. -// May need to reverse subscript order if porting elsewhere. - -uint16_t PImage::read16(File f) { - uint16_t result; - ((uint8_t *)&result)[0] = f.read(); // LSB - ((uint8_t *)&result)[1] = f.read(); // MSB - return result; -} - -uint32_t PImage::read32(File f) { - uint32_t result; - ((uint8_t *)&result)[0] = f.read(); // LSB - ((uint8_t *)&result)[1] = f.read(); - ((uint8_t *)&result)[2] = f.read(); - ((uint8_t *)&result)[3] = f.read(); // MSB - return result; -} - - -PImage PImage::loadImage(const char * fileName) { - File bmpFile; - int bmpWidth, bmpHeight; // W+H in pixels - uint8_t bmpDepth; // Bit depth (currently must be 24) - uint32_t bmpImageoffset; // Start of image data in file - uint32_t rowSize; // Not always = bmpWidth; may have padding - bool flip = true; // BMP is stored bottom-to-top - - - // Open requested file on SD card - if ((bmpFile = SD.open(fileName)) == NULL) { - Serial.print("loadImage: file not found: "); - Serial.println(fileName); - return PImage(); // load error - } - - - - // Parse BMP header - if(read16(bmpFile) != 0x4D42) { // BMP signature - Serial.println("loadImage: file doesn't look like a BMP"); - return PImage(); - } - - Serial.print("File size: "); Serial.println(read32(bmpFile)); - (void)read32(bmpFile); // Read & ignore creator bytes - bmpImageoffset = read32(bmpFile); // Start of image data - Serial.print("Image Offset: "); Serial.println(bmpImageoffset, DEC); - // Read DIB header - Serial.print("Header size: "); Serial.println(read32(bmpFile)); - bmpWidth = read32(bmpFile); - bmpHeight = read32(bmpFile); - if(read16(bmpFile) != 1) { // # planes -- must be '1' - Serial.println("loadImage: invalid n. of planes"); - return PImage(); - } - - bmpDepth = read16(bmpFile); // bits per pixel - Serial.print("Bit Depth: "); Serial.println(bmpDepth); - if((bmpDepth != 24) || (read32(bmpFile) != 0)) { // 0 = uncompressed { - Serial.println("loadImage: invalid pixel format"); - return PImage(); - } - - Serial.print("Image size: "); - Serial.print(bmpWidth); - Serial.print('x'); - Serial.println(bmpHeight); - - // BMP rows are padded (if needed) to 4-byte boundary - rowSize = (bmpWidth * 3 + 3) & ~3; - - // If bmpHeight is negative, image is in top-down order. - // This is not canon but has been observed in the wild. - if(bmpHeight < 0) { - bmpHeight = -bmpHeight; - flip = false; - } - - return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip); -} - -#endif - - - -#endif diff --git a/libraries/TFT/utility/Adafruit_ST7735.cpp b/libraries/TFT/utility/Adafruit_ST7735.cpp deleted file mode 100755 index ed57bf7..0000000 --- a/libraries/TFT/utility/Adafruit_ST7735.cpp +++ /dev/null @@ -1,603 +0,0 @@ -/*************************************************** - This is a library for the Adafruit 1.8" SPI display. - This library works with the Adafruit 1.8" TFT Breakout w/SD card - ----> http://www.adafruit.com/products/358 - as well as Adafruit raw 1.8" TFT display - ----> http://www.adafruit.com/products/618 - - Check out the links above for our tutorials and wiring diagrams - These displays use SPI to communicate, 4 or 5 pins are required to - interface (RST is optional) - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - MIT license, all text above must be included in any redistribution - ****************************************************/ - -#include "Adafruit_ST7735.h" -#include -#include -#include "pins_arduino.h" -#include "wiring_private.h" -#include - -inline uint16_t swapcolor(uint16_t x) { - return (x << 11) | (x & 0x07E0) | (x >> 11); -} - - -// Constructor when using software SPI. All output pins are configurable. -Adafruit_ST7735::Adafruit_ST7735(uint8_t cs, uint8_t rs, uint8_t sid, - uint8_t sclk, uint8_t rst) { - _cs = cs; - _rs = rs; - _sid = sid; - _sclk = sclk; - _rst = rst; - hwSPI = false; -} - - -// Constructor when using hardware SPI. Faster, but must use SPI pins -// specific to each board type (e.g. 11,13 for Uno, 51,52 for Mega, etc.) -Adafruit_ST7735::Adafruit_ST7735(uint8_t cs, uint8_t rs, uint8_t rst) { - _cs = cs; - _rs = rs; - _rst = rst; - hwSPI = true; - _sid = _sclk = 0; -} - - -inline void Adafruit_ST7735::spiwrite(uint8_t c) { - - //Serial.println(c, HEX); - - if (hwSPI) { - SPI.transfer(c); - } else { - // Fast SPI bitbang swiped from LPD8806 library - for(uint8_t bit = 0x80; bit; bit >>= 1) { - if(c & bit) *dataport |= datapinmask; - else *dataport &= ~datapinmask; - *clkport |= clkpinmask; - *clkport &= ~clkpinmask; - } - } -} - - -void Adafruit_ST7735::writecommand(uint8_t c) { - *rsport &= ~rspinmask; - *csport &= ~cspinmask; - - //Serial.print("C "); - spiwrite(c); - - *csport |= cspinmask; -} - - -void Adafruit_ST7735::writedata(uint8_t c) { - *rsport |= rspinmask; - *csport &= ~cspinmask; - - //Serial.print("D "); - spiwrite(c); - - *csport |= cspinmask; -} - - -// Rather than a bazillion writecommand() and writedata() calls, screen -// initialization commands and arguments are organized in these tables -// stored in PROGMEM. The table may look bulky, but that's mostly the -// formatting -- storage-wise this is hundreds of bytes more compact -// than the equivalent code. Companion function follows. -#define DELAY 0x80 -PROGMEM static prog_uchar - Bcmd[] = { // Initialization commands for 7735B screens - 18, // 18 commands in list: - ST7735_SWRESET, DELAY, // 1: Software reset, no args, w/delay - 50, // 50 ms delay - ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, no args, w/delay - 255, // 255 = 500 ms delay - ST7735_COLMOD , 1+DELAY, // 3: Set color mode, 1 arg + delay: - 0x05, // 16-bit color - 10, // 10 ms delay - ST7735_FRMCTR1, 3+DELAY, // 4: Frame rate control, 3 args + delay: - 0x00, // fastest refresh - 0x06, // 6 lines front porch - 0x03, // 3 lines back porch - 10, // 10 ms delay - ST7735_MADCTL , 1 , // 5: Memory access ctrl (directions), 1 arg: - 0x08, // Row addr/col addr, bottom to top refresh - ST7735_DISSET5, 2 , // 6: Display settings #5, 2 args, no delay: - 0x15, // 1 clk cycle nonoverlap, 2 cycle gate - // rise, 3 cycle osc equalize - 0x02, // Fix on VTL - ST7735_INVCTR , 1 , // 7: Display inversion control, 1 arg: - 0x0, // Line inversion - ST7735_PWCTR1 , 2+DELAY, // 8: Power control, 2 args + delay: - 0x02, // GVDD = 4.7V - 0x70, // 1.0uA - 10, // 10 ms delay - ST7735_PWCTR2 , 1 , // 9: Power control, 1 arg, no delay: - 0x05, // VGH = 14.7V, VGL = -7.35V - ST7735_PWCTR3 , 2 , // 10: Power control, 2 args, no delay: - 0x01, // Opamp current small - 0x02, // Boost frequency - ST7735_VMCTR1 , 2+DELAY, // 11: Power control, 2 args + delay: - 0x3C, // VCOMH = 4V - 0x38, // VCOML = -1.1V - 10, // 10 ms delay - ST7735_PWCTR6 , 2 , // 12: Power control, 2 args, no delay: - 0x11, 0x15, - ST7735_GMCTRP1,16 , // 13: Magical unicorn dust, 16 args, no delay: - 0x09, 0x16, 0x09, 0x20, // (seriously though, not sure what - 0x21, 0x1B, 0x13, 0x19, // these config values represent) - 0x17, 0x15, 0x1E, 0x2B, - 0x04, 0x05, 0x02, 0x0E, - ST7735_GMCTRN1,16+DELAY, // 14: Sparkles and rainbows, 16 args + delay: - 0x0B, 0x14, 0x08, 0x1E, // (ditto) - 0x22, 0x1D, 0x18, 0x1E, - 0x1B, 0x1A, 0x24, 0x2B, - 0x06, 0x06, 0x02, 0x0F, - 10, // 10 ms delay - ST7735_CASET , 4 , // 15: Column addr set, 4 args, no delay: - 0x00, 0x02, // XSTART = 2 - 0x00, 0x81, // XEND = 129 - ST7735_RASET , 4 , // 16: Row addr set, 4 args, no delay: - 0x00, 0x02, // XSTART = 1 - 0x00, 0x81, // XEND = 160 - ST7735_NORON , DELAY, // 17: Normal display on, no args, w/delay - 10, // 10 ms delay - ST7735_DISPON , DELAY, // 18: Main screen turn on, no args, w/delay - 255 }, // 255 = 500 ms delay - - Rcmd1[] = { // Init for 7735R, part 1 (red or green tab) - 15, // 15 commands in list: - ST7735_SWRESET, DELAY, // 1: Software reset, 0 args, w/delay - 150, // 150 ms delay - ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, 0 args, w/delay - 255, // 500 ms delay - ST7735_FRMCTR1, 3 , // 3: Frame rate ctrl - normal mode, 3 args: - 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) - ST7735_FRMCTR2, 3 , // 4: Frame rate control - idle mode, 3 args: - 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) - ST7735_FRMCTR3, 6 , // 5: Frame rate ctrl - partial mode, 6 args: - 0x01, 0x2C, 0x2D, // Dot inversion mode - 0x01, 0x2C, 0x2D, // Line inversion mode - ST7735_INVCTR , 1 , // 6: Display inversion ctrl, 1 arg, no delay: - 0x07, // No inversion - ST7735_PWCTR1 , 3 , // 7: Power control, 3 args, no delay: - 0xA2, - 0x02, // -4.6V - 0x84, // AUTO mode - ST7735_PWCTR2 , 1 , // 8: Power control, 1 arg, no delay: - 0xC5, // VGH25 = 2.4C VGSEL = -10 VGH = 3 * AVDD - ST7735_PWCTR3 , 2 , // 9: Power control, 2 args, no delay: - 0x0A, // Opamp current small - 0x00, // Boost frequency - ST7735_PWCTR4 , 2 , // 10: Power control, 2 args, no delay: - 0x8A, // BCLK/2, Opamp current small & Medium low - 0x2A, - ST7735_PWCTR5 , 2 , // 11: Power control, 2 args, no delay: - 0x8A, 0xEE, - ST7735_VMCTR1 , 1 , // 12: Power control, 1 arg, no delay: - 0x0E, - ST7735_INVOFF , 0 , // 13: Don't invert display, no args, no delay - ST7735_MADCTL , 1 , // 14: Memory access control (directions), 1 arg: - 0xC8, // row addr/col addr, bottom to top refresh - ST7735_COLMOD , 1 , // 15: set color mode, 1 arg, no delay: - 0x05 }, // 16-bit color - - Rcmd2green[] = { // Init for 7735R, part 2 (green tab only) - 2, // 2 commands in list: - ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: - 0x00, 0x02, // XSTART = 0 - 0x00, 0x7F+0x02, // XEND = 127 - ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: - 0x00, 0x01, // XSTART = 0 - 0x00, 0x9F+0x01 }, // XEND = 159 - Rcmd2red[] = { // Init for 7735R, part 2 (red tab only) - 2, // 2 commands in list: - ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: - 0x00, 0x00, // XSTART = 0 - 0x00, 0x7F, // XEND = 127 - ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: - 0x00, 0x00, // XSTART = 0 - 0x00, 0x9F }, // XEND = 159 - - Rcmd3[] = { // Init for 7735R, part 3 (red or green tab) - 4, // 4 commands in list: - ST7735_GMCTRP1, 16 , // 1: Magical unicorn dust, 16 args, no delay: - 0x02, 0x1c, 0x07, 0x12, - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, - ST7735_GMCTRN1, 16 , // 2: Sparkles and rainbows, 16 args, no delay: - 0x03, 0x1d, 0x07, 0x06, - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, - ST7735_NORON , DELAY, // 3: Normal display on, no args, w/delay - 10, // 10 ms delay - ST7735_DISPON , DELAY, // 4: Main screen turn on, no args w/delay - 100 }; // 100 ms delay - - -// Companion code to the above tables. Reads and issues -// a series of LCD commands stored in PROGMEM byte array. -void Adafruit_ST7735::commandList(uint8_t *addr) { - - uint8_t numCommands, numArgs; - uint16_t ms; - - numCommands = pgm_read_byte(addr++); // Number of commands to follow - while(numCommands--) { // For each command... - writecommand(pgm_read_byte(addr++)); // Read, issue command - numArgs = pgm_read_byte(addr++); // Number of args to follow - ms = numArgs & DELAY; // If hibit set, delay follows args - numArgs &= ~DELAY; // Mask out delay bit - while(numArgs--) { // For each argument... - writedata(pgm_read_byte(addr++)); // Read, issue argument - } - - if(ms) { - ms = pgm_read_byte(addr++); // Read post-command delay time (ms) - if(ms == 255) ms = 500; // If 255, delay for 500 ms - delay(ms); - } - } -} - - -// Initialization code common to both 'B' and 'R' type displays -void Adafruit_ST7735::commonInit(uint8_t *cmdList) { - - constructor(ST7735_TFTWIDTH, ST7735_TFTHEIGHT); - colstart = rowstart = 0; // May be overridden in init func - - pinMode(_rs, OUTPUT); - pinMode(_cs, OUTPUT); - csport = portOutputRegister(digitalPinToPort(_cs)); - cspinmask = digitalPinToBitMask(_cs); - rsport = portOutputRegister(digitalPinToPort(_rs)); - rspinmask = digitalPinToBitMask(_rs); - - if(hwSPI) { // Using hardware SPI - SPI.begin(); -#if defined(ARDUINO_ARCH_SAM) - SPI.setClockDivider(24); // 4 MHz (half speed) -#else - SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHz (half speed) -#endif - SPI.setBitOrder(MSBFIRST); - SPI.setDataMode(SPI_MODE0); - } else { - pinMode(_sclk, OUTPUT); - pinMode(_sid , OUTPUT); - clkport = portOutputRegister(digitalPinToPort(_sclk)); - clkpinmask = digitalPinToBitMask(_sclk); - dataport = portOutputRegister(digitalPinToPort(_sid)); - datapinmask = digitalPinToBitMask(_sid); - *clkport &= ~clkpinmask; - *dataport &= ~datapinmask; - } - - // toggle RST low to reset; CS low so it'll listen to us - *csport &= ~cspinmask; - if (_rst) { - pinMode(_rst, OUTPUT); - digitalWrite(_rst, HIGH); - delay(500); - digitalWrite(_rst, LOW); - delay(500); - digitalWrite(_rst, HIGH); - delay(500); - } - - if(cmdList) commandList(cmdList); -} - - -// Initialization for ST7735B screens -void Adafruit_ST7735::initB(void) { - commonInit(Bcmd); -} - - -// Initialization for ST7735R screens (green or red tabs) -void Adafruit_ST7735::initR(uint8_t options) { - commonInit(Rcmd1); - if(options == INITR_GREENTAB) { - commandList(Rcmd2green); - colstart = 2; - rowstart = 1; - } else { - // colstart, rowstart left at default '0' values - commandList(Rcmd2red); - } - commandList(Rcmd3); - tabcolor = options; -} - - -void Adafruit_ST7735::setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, - uint8_t y1) { - - writecommand(ST7735_CASET); // Column addr set - writedata(0x00); - writedata(x0+colstart); // XSTART - writedata(0x00); - writedata(x1+colstart); // XEND - - writecommand(ST7735_RASET); // Row addr set - writedata(0x00); - writedata(y0+rowstart); // YSTART - writedata(0x00); - writedata(y1+rowstart); // YEND - - writecommand(ST7735_RAMWR); // write to RAM -} - - -void Adafruit_ST7735::pushColor(uint16_t color) { - *rsport |= rspinmask; - *csport &= ~cspinmask; - - if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); - spiwrite(color >> 8); - spiwrite(color); - - *csport |= cspinmask; -} - -void Adafruit_ST7735::drawPixel(int16_t x, int16_t y, uint16_t color) { - - if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; - - setAddrWindow(x,y,x+1,y+1); - - *rsport |= rspinmask; - *csport &= ~cspinmask; - - if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); - - spiwrite(color >> 8); - spiwrite(color); - - *csport |= cspinmask; -} - - -void Adafruit_ST7735::drawFastVLine(int16_t x, int16_t y, int16_t h, - uint16_t color) { - - // Rudimentary clipping - if((x >= _width) || (y >= _height)) return; - if((y+h-1) >= _height) h = _height-y; - setAddrWindow(x, y, x, y+h-1); - - if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); - - uint8_t hi = color >> 8, lo = color; - *rsport |= rspinmask; - *csport &= ~cspinmask; - while (h--) { - spiwrite(hi); - spiwrite(lo); - } - *csport |= cspinmask; -} - - -void Adafruit_ST7735::drawFastHLine(int16_t x, int16_t y, int16_t w, - uint16_t color) { - - // Rudimentary clipping - if((x >= _width) || (y >= _height)) return; - if((x+w-1) >= _width) w = _width-x; - setAddrWindow(x, y, x+w-1, y); - - if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); - - uint8_t hi = color >> 8, lo = color; - *rsport |= rspinmask; - *csport &= ~cspinmask; - while (w--) { - spiwrite(hi); - spiwrite(lo); - } - *csport |= cspinmask; -} - - - -void Adafruit_ST7735::fillScreen(uint16_t color) { - fillRect(0, 0, _width, _height, color); -} - - - -// fill a rectangle -void Adafruit_ST7735::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color) { - - // rudimentary clipping (drawChar w/big text requires this) - if((x >= _width) || (y >= _height)) return; - if((x + w - 1) >= _width) w = _width - x; - if((y + h - 1) >= _height) h = _height - y; - - if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); - - setAddrWindow(x, y, x+w-1, y+h-1); - - uint8_t hi = color >> 8, lo = color; - *rsport |= rspinmask; - *csport &= ~cspinmask; - for(y=h; y>0; y--) { - for(x=w; x>0; x--) { - spiwrite(hi); - spiwrite(lo); - } - } - - *csport |= cspinmask; -} - - -#define MADCTL_MY 0x80 -#define MADCTL_MX 0x40 -#define MADCTL_MV 0x20 -#define MADCTL_ML 0x10 -#define MADCTL_RGB 0x08 -#define MADCTL_MH 0x04 - -void Adafruit_ST7735::setRotation(uint8_t m) { - - writecommand(ST7735_MADCTL); - rotation = m % 4; // can't be higher than 3 - switch (rotation) { - case 0: - writedata(MADCTL_MX | MADCTL_MY | MADCTL_RGB); - _width = ST7735_TFTWIDTH; - _height = ST7735_TFTHEIGHT; - break; - case 1: - writedata(MADCTL_MY | MADCTL_MV | MADCTL_RGB); - _width = ST7735_TFTHEIGHT; - _height = ST7735_TFTWIDTH; - break; - case 2: - writedata(MADCTL_RGB); - _width = ST7735_TFTWIDTH; - _height = ST7735_TFTHEIGHT; - break; - case 3: - writedata(MADCTL_MX | MADCTL_MV | MADCTL_RGB); - _width = ST7735_TFTHEIGHT; - _height = ST7735_TFTWIDTH; - break; - } -} - - -void Adafruit_ST7735::invertDisplay(boolean i) { - writecommand(i ? ST7735_INVON : ST7735_INVOFF); -} - - -////////// stuff not actively being used, but kept for posterity -/* - - uint8_t Adafruit_ST7735::spiread(void) { - uint8_t r = 0; - if (_sid > 0) { - r = shiftIn(_sid, _sclk, MSBFIRST); - } else { - //SID_DDR &= ~_BV(SID); - //int8_t i; - //for (i=7; i>=0; i--) { - // SCLK_PORT &= ~_BV(SCLK); - // r <<= 1; - // r |= (SID_PIN >> SID) & 0x1; - // SCLK_PORT |= _BV(SCLK); - //} - //SID_DDR |= _BV(SID); - - } - return r; - } - - - void Adafruit_ST7735::dummyclock(void) { - - if (_sid > 0) { - digitalWrite(_sclk, LOW); - digitalWrite(_sclk, HIGH); - } else { - // SCLK_PORT &= ~_BV(SCLK); - //SCLK_PORT |= _BV(SCLK); - } - } - uint8_t Adafruit_ST7735::readdata(void) { - *portOutputRegister(rsport) |= rspin; - - *portOutputRegister(csport) &= ~ cspin; - - uint8_t r = spiread(); - - *portOutputRegister(csport) |= cspin; - - return r; - - } - - uint8_t Adafruit_ST7735::readcommand8(uint8_t c) { - digitalWrite(_rs, LOW); - - *portOutputRegister(csport) &= ~ cspin; - - spiwrite(c); - - digitalWrite(_rs, HIGH); - pinMode(_sid, INPUT); // input! - digitalWrite(_sid, LOW); // low - spiread(); - uint8_t r = spiread(); - - - *portOutputRegister(csport) |= cspin; - - - pinMode(_sid, OUTPUT); // back to output - return r; - } - - - uint16_t Adafruit_ST7735::readcommand16(uint8_t c) { - digitalWrite(_rs, LOW); - if (_cs) - digitalWrite(_cs, LOW); - - spiwrite(c); - pinMode(_sid, INPUT); // input! - uint16_t r = spiread(); - r <<= 8; - r |= spiread(); - if (_cs) - digitalWrite(_cs, HIGH); - - pinMode(_sid, OUTPUT); // back to output - return r; - } - - uint32_t Adafruit_ST7735::readcommand32(uint8_t c) { - digitalWrite(_rs, LOW); - if (_cs) - digitalWrite(_cs, LOW); - spiwrite(c); - pinMode(_sid, INPUT); // input! - - dummyclock(); - dummyclock(); - - uint32_t r = spiread(); - r <<= 8; - r |= spiread(); - r <<= 8; - r |= spiread(); - r <<= 8; - r |= spiread(); - if (_cs) - digitalWrite(_cs, HIGH); - - pinMode(_sid, OUTPUT); // back to output - return r; - } - - */ diff --git a/libraries/TFT/utility/Adafruit_ST7735.h b/libraries/TFT/utility/Adafruit_ST7735.h deleted file mode 100755 index c0d5de0..0000000 --- a/libraries/TFT/utility/Adafruit_ST7735.h +++ /dev/null @@ -1,150 +0,0 @@ -/*************************************************** - This is a library for the Adafruit 1.8" SPI display. - This library works with the Adafruit 1.8" TFT Breakout w/SD card - ----> http://www.adafruit.com/products/358 - as well as Adafruit raw 1.8" TFT display - ----> http://www.adafruit.com/products/618 - - Check out the links above for our tutorials and wiring diagrams - These displays use SPI to communicate, 4 or 5 pins are required to - interface (RST is optional) - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - MIT license, all text above must be included in any redistribution - ****************************************************/ - -#ifndef _ADAFRUIT_ST7735H_ -#define _ADAFRUIT_ST7735H_ - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif -#include -#include - -// some flags for initR() :( -#define INITR_GREENTAB 0x0 -#define INITR_REDTAB 0x1 -#define INITR_BLACKTAB 0x2 - -#define ST7735_TFTWIDTH 128 -#define ST7735_TFTHEIGHT 160 - -#define ST7735_NOP 0x00 -#define ST7735_SWRESET 0x01 -#define ST7735_RDDID 0x04 -#define ST7735_RDDST 0x09 - -#define ST7735_SLPIN 0x10 -#define ST7735_SLPOUT 0x11 -#define ST7735_PTLON 0x12 -#define ST7735_NORON 0x13 - -#define ST7735_INVOFF 0x20 -#define ST7735_INVON 0x21 -#define ST7735_DISPOFF 0x28 -#define ST7735_DISPON 0x29 -#define ST7735_CASET 0x2A -#define ST7735_RASET 0x2B -#define ST7735_RAMWR 0x2C -#define ST7735_RAMRD 0x2E - -#define ST7735_PTLAR 0x30 -#define ST7735_COLMOD 0x3A -#define ST7735_MADCTL 0x36 - -#define ST7735_FRMCTR1 0xB1 -#define ST7735_FRMCTR2 0xB2 -#define ST7735_FRMCTR3 0xB3 -#define ST7735_INVCTR 0xB4 -#define ST7735_DISSET5 0xB6 - -#define ST7735_PWCTR1 0xC0 -#define ST7735_PWCTR2 0xC1 -#define ST7735_PWCTR3 0xC2 -#define ST7735_PWCTR4 0xC3 -#define ST7735_PWCTR5 0xC4 -#define ST7735_VMCTR1 0xC5 - -#define ST7735_RDID1 0xDA -#define ST7735_RDID2 0xDB -#define ST7735_RDID3 0xDC -#define ST7735_RDID4 0xDD - -#define ST7735_PWCTR6 0xFC - -#define ST7735_GMCTRP1 0xE0 -#define ST7735_GMCTRN1 0xE1 - -// Color definitions -#define ST7735_BLACK 0x0000 -#define ST7735_BLUE 0x001F -#define ST7735_RED 0xF800 -#define ST7735_GREEN 0x07E0 -#define ST7735_CYAN 0x07FF -#define ST7735_MAGENTA 0xF81F -#define ST7735_YELLOW 0xFFE0 -#define ST7735_WHITE 0xFFFF - - -class Adafruit_ST7735 : public Adafruit_GFX { - - public: - - Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t SID, uint8_t SCLK, - uint8_t RST); - Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t RST); - - void initB(void), // for ST7735B displays - initR(uint8_t options = INITR_GREENTAB), // for ST7735R - setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1), - pushColor(uint16_t color), - fillScreen(uint16_t color), - drawPixel(int16_t x, int16_t y, uint16_t color), - drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), - drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), - fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color), - setRotation(uint8_t r), - invertDisplay(boolean i); - uint16_t Color565(uint8_t r, uint8_t g, uint8_t b) { return newColor(r, g, b);} - - /* These are not for current use, 8-bit protocol only! - uint8_t readdata(void), - readcommand8(uint8_t); - uint16_t readcommand16(uint8_t); - uint32_t readcommand32(uint8_t); - void dummyclock(void); - */ - - private: - uint8_t tabcolor; - - void spiwrite(uint8_t), - writecommand(uint8_t c), - writedata(uint8_t d), - commandList(uint8_t *addr), - commonInit(uint8_t *cmdList); -//uint8_t spiread(void); - - boolean hwSPI; - #if defined(ARDUINO_ARCH_SAM) - volatile uint32_t *dataport, *clkport, *csport, *rsport; - uint32_t _cs, _rs, _rst, _sid, _sclk, - datapinmask, clkpinmask, cspinmask, rspinmask, - colstart, rowstart; // some displays need this changed - #else - volatile uint8_t *dataport, *clkport, *csport, *rsport; - uint8_t _cs, _rs, _rst, _sid, _sclk, - datapinmask, clkpinmask, cspinmask, rspinmask, - colstart, rowstart; // some displays need this changed - #endif -}; - -#endif diff --git a/libraries/TFT/utility/PImage.h b/libraries/TFT/utility/PImage.h deleted file mode 100644 index d37bf71..0000000 --- a/libraries/TFT/utility/PImage.h +++ /dev/null @@ -1,64 +0,0 @@ - - -#ifndef _PIMAGE_H -#define _PIMAGE_H - -class Adafruit_GFX; - -#if defined(__SD_H__) // Arduino SD library - - -/// This class mimics Processing's PImage, but with fewer -/// capabilities. It allows an image stored in the SD card to be -/// drawn to the display. -/// @author Enrico Gueli -class PImage { -public: - PImage() : - _valid(false), - _bmpWidth(0), - _bmpHeight(0) { } - - void draw(Adafruit_GFX & glcd, int16_t x, int16_t y); - - static PImage loadImage(const char * fileName); - - - bool isValid() { return _valid; } - - int width() { return _bmpWidth; } - int height() { return _bmpHeight; } - -private: - friend class Adafruit_GFX; - - File _bmpFile; - int _bmpWidth, _bmpHeight; // W+H in pixels - uint8_t _bmpDepth; // Bit depth (currently must be 24) - uint32_t _bmpImageoffset; // Start of image data in file - uint32_t _rowSize; // Not always = bmpWidth; may have padding - bool _flip; - - bool _valid; - - PImage(File & bmpFile, int bmpWidth, int bmpHeight, uint8_t bmpDepth, uint32_t bmpImageoffset, uint32_t rowSize, bool flip) : - _bmpFile(bmpFile), - _bmpWidth(bmpWidth), - _bmpHeight(bmpHeight), - _bmpDepth(bmpDepth), - _bmpImageoffset(bmpImageoffset), - _rowSize(rowSize), - _flip(flip), - _valid(true) // since Adafruit_GFX is friend, we could just let it write the variables and save some CPU cycles - { } - - static uint16_t read16(File f); - static uint32_t read32(File f); - - // TODO close the file in ~PImage and PImage(const PImage&) - -}; - -#endif - -#endif // _PIMAGE_H diff --git a/libraries/TFT/utility/glcdfont.c b/libraries/TFT/utility/glcdfont.c deleted file mode 100644 index a325057..0000000 --- a/libraries/TFT/utility/glcdfont.c +++ /dev/null @@ -1,268 +0,0 @@ -#ifndef ARDUINO_ARCH_SAM -#include -#endif -#include - -#ifndef FONT5X7_H -#define FONT5X7_H - -// standard ascii 5x7 font - -static unsigned char font[] PROGMEM = { - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, - 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, - 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, - 0x18, 0x3C, 0x7E, 0x3C, 0x18, - 0x1C, 0x57, 0x7D, 0x57, 0x1C, - 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, - 0x00, 0x18, 0x3C, 0x18, 0x00, - 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, - 0x00, 0x18, 0x24, 0x18, 0x00, - 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, - 0x30, 0x48, 0x3A, 0x06, 0x0E, - 0x26, 0x29, 0x79, 0x29, 0x26, - 0x40, 0x7F, 0x05, 0x05, 0x07, - 0x40, 0x7F, 0x05, 0x25, 0x3F, - 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, - 0x7F, 0x3E, 0x1C, 0x1C, 0x08, - 0x08, 0x1C, 0x1C, 0x3E, 0x7F, - 0x14, 0x22, 0x7F, 0x22, 0x14, - 0x5F, 0x5F, 0x00, 0x5F, 0x5F, - 0x06, 0x09, 0x7F, 0x01, 0x7F, - 0x00, 0x66, 0x89, 0x95, 0x6A, - 0x60, 0x60, 0x60, 0x60, 0x60, - 0x94, 0xA2, 0xFF, 0xA2, 0x94, - 0x08, 0x04, 0x7E, 0x04, 0x08, - 0x10, 0x20, 0x7E, 0x20, 0x10, - 0x08, 0x08, 0x2A, 0x1C, 0x08, - 0x08, 0x1C, 0x2A, 0x08, 0x08, - 0x1E, 0x10, 0x10, 0x10, 0x10, - 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, - 0x30, 0x38, 0x3E, 0x38, 0x30, - 0x06, 0x0E, 0x3E, 0x0E, 0x06, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x5F, 0x00, 0x00, - 0x00, 0x07, 0x00, 0x07, 0x00, - 0x14, 0x7F, 0x14, 0x7F, 0x14, - 0x24, 0x2A, 0x7F, 0x2A, 0x12, - 0x23, 0x13, 0x08, 0x64, 0x62, - 0x36, 0x49, 0x56, 0x20, 0x50, - 0x00, 0x08, 0x07, 0x03, 0x00, - 0x00, 0x1C, 0x22, 0x41, 0x00, - 0x00, 0x41, 0x22, 0x1C, 0x00, - 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, - 0x08, 0x08, 0x3E, 0x08, 0x08, - 0x00, 0x80, 0x70, 0x30, 0x00, - 0x08, 0x08, 0x08, 0x08, 0x08, - 0x00, 0x00, 0x60, 0x60, 0x00, - 0x20, 0x10, 0x08, 0x04, 0x02, - 0x3E, 0x51, 0x49, 0x45, 0x3E, - 0x00, 0x42, 0x7F, 0x40, 0x00, - 0x72, 0x49, 0x49, 0x49, 0x46, - 0x21, 0x41, 0x49, 0x4D, 0x33, - 0x18, 0x14, 0x12, 0x7F, 0x10, - 0x27, 0x45, 0x45, 0x45, 0x39, - 0x3C, 0x4A, 0x49, 0x49, 0x31, - 0x41, 0x21, 0x11, 0x09, 0x07, - 0x36, 0x49, 0x49, 0x49, 0x36, - 0x46, 0x49, 0x49, 0x29, 0x1E, - 0x00, 0x00, 0x14, 0x00, 0x00, - 0x00, 0x40, 0x34, 0x00, 0x00, - 0x00, 0x08, 0x14, 0x22, 0x41, - 0x14, 0x14, 0x14, 0x14, 0x14, - 0x00, 0x41, 0x22, 0x14, 0x08, - 0x02, 0x01, 0x59, 0x09, 0x06, - 0x3E, 0x41, 0x5D, 0x59, 0x4E, - 0x7C, 0x12, 0x11, 0x12, 0x7C, - 0x7F, 0x49, 0x49, 0x49, 0x36, - 0x3E, 0x41, 0x41, 0x41, 0x22, - 0x7F, 0x41, 0x41, 0x41, 0x3E, - 0x7F, 0x49, 0x49, 0x49, 0x41, - 0x7F, 0x09, 0x09, 0x09, 0x01, - 0x3E, 0x41, 0x41, 0x51, 0x73, - 0x7F, 0x08, 0x08, 0x08, 0x7F, - 0x00, 0x41, 0x7F, 0x41, 0x00, - 0x20, 0x40, 0x41, 0x3F, 0x01, - 0x7F, 0x08, 0x14, 0x22, 0x41, - 0x7F, 0x40, 0x40, 0x40, 0x40, - 0x7F, 0x02, 0x1C, 0x02, 0x7F, - 0x7F, 0x04, 0x08, 0x10, 0x7F, - 0x3E, 0x41, 0x41, 0x41, 0x3E, - 0x7F, 0x09, 0x09, 0x09, 0x06, - 0x3E, 0x41, 0x51, 0x21, 0x5E, - 0x7F, 0x09, 0x19, 0x29, 0x46, - 0x26, 0x49, 0x49, 0x49, 0x32, - 0x03, 0x01, 0x7F, 0x01, 0x03, - 0x3F, 0x40, 0x40, 0x40, 0x3F, - 0x1F, 0x20, 0x40, 0x20, 0x1F, - 0x3F, 0x40, 0x38, 0x40, 0x3F, - 0x63, 0x14, 0x08, 0x14, 0x63, - 0x03, 0x04, 0x78, 0x04, 0x03, - 0x61, 0x59, 0x49, 0x4D, 0x43, - 0x00, 0x7F, 0x41, 0x41, 0x41, - 0x02, 0x04, 0x08, 0x10, 0x20, - 0x00, 0x41, 0x41, 0x41, 0x7F, - 0x04, 0x02, 0x01, 0x02, 0x04, - 0x40, 0x40, 0x40, 0x40, 0x40, - 0x00, 0x03, 0x07, 0x08, 0x00, - 0x20, 0x54, 0x54, 0x78, 0x40, - 0x7F, 0x28, 0x44, 0x44, 0x38, - 0x38, 0x44, 0x44, 0x44, 0x28, - 0x38, 0x44, 0x44, 0x28, 0x7F, - 0x38, 0x54, 0x54, 0x54, 0x18, - 0x00, 0x08, 0x7E, 0x09, 0x02, - 0x18, 0xA4, 0xA4, 0x9C, 0x78, - 0x7F, 0x08, 0x04, 0x04, 0x78, - 0x00, 0x44, 0x7D, 0x40, 0x00, - 0x20, 0x40, 0x40, 0x3D, 0x00, - 0x7F, 0x10, 0x28, 0x44, 0x00, - 0x00, 0x41, 0x7F, 0x40, 0x00, - 0x7C, 0x04, 0x78, 0x04, 0x78, - 0x7C, 0x08, 0x04, 0x04, 0x78, - 0x38, 0x44, 0x44, 0x44, 0x38, - 0xFC, 0x18, 0x24, 0x24, 0x18, - 0x18, 0x24, 0x24, 0x18, 0xFC, - 0x7C, 0x08, 0x04, 0x04, 0x08, - 0x48, 0x54, 0x54, 0x54, 0x24, - 0x04, 0x04, 0x3F, 0x44, 0x24, - 0x3C, 0x40, 0x40, 0x20, 0x7C, - 0x1C, 0x20, 0x40, 0x20, 0x1C, - 0x3C, 0x40, 0x30, 0x40, 0x3C, - 0x44, 0x28, 0x10, 0x28, 0x44, - 0x4C, 0x90, 0x90, 0x90, 0x7C, - 0x44, 0x64, 0x54, 0x4C, 0x44, - 0x00, 0x08, 0x36, 0x41, 0x00, - 0x00, 0x00, 0x77, 0x00, 0x00, - 0x00, 0x41, 0x36, 0x08, 0x00, - 0x02, 0x01, 0x02, 0x04, 0x02, - 0x3C, 0x26, 0x23, 0x26, 0x3C, - 0x1E, 0xA1, 0xA1, 0x61, 0x12, - 0x3A, 0x40, 0x40, 0x20, 0x7A, - 0x38, 0x54, 0x54, 0x55, 0x59, - 0x21, 0x55, 0x55, 0x79, 0x41, - 0x21, 0x54, 0x54, 0x78, 0x41, - 0x21, 0x55, 0x54, 0x78, 0x40, - 0x20, 0x54, 0x55, 0x79, 0x40, - 0x0C, 0x1E, 0x52, 0x72, 0x12, - 0x39, 0x55, 0x55, 0x55, 0x59, - 0x39, 0x54, 0x54, 0x54, 0x59, - 0x39, 0x55, 0x54, 0x54, 0x58, - 0x00, 0x00, 0x45, 0x7C, 0x41, - 0x00, 0x02, 0x45, 0x7D, 0x42, - 0x00, 0x01, 0x45, 0x7C, 0x40, - 0xF0, 0x29, 0x24, 0x29, 0xF0, - 0xF0, 0x28, 0x25, 0x28, 0xF0, - 0x7C, 0x54, 0x55, 0x45, 0x00, - 0x20, 0x54, 0x54, 0x7C, 0x54, - 0x7C, 0x0A, 0x09, 0x7F, 0x49, - 0x32, 0x49, 0x49, 0x49, 0x32, - 0x32, 0x48, 0x48, 0x48, 0x32, - 0x32, 0x4A, 0x48, 0x48, 0x30, - 0x3A, 0x41, 0x41, 0x21, 0x7A, - 0x3A, 0x42, 0x40, 0x20, 0x78, - 0x00, 0x9D, 0xA0, 0xA0, 0x7D, - 0x39, 0x44, 0x44, 0x44, 0x39, - 0x3D, 0x40, 0x40, 0x40, 0x3D, - 0x3C, 0x24, 0xFF, 0x24, 0x24, - 0x48, 0x7E, 0x49, 0x43, 0x66, - 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, - 0xFF, 0x09, 0x29, 0xF6, 0x20, - 0xC0, 0x88, 0x7E, 0x09, 0x03, - 0x20, 0x54, 0x54, 0x79, 0x41, - 0x00, 0x00, 0x44, 0x7D, 0x41, - 0x30, 0x48, 0x48, 0x4A, 0x32, - 0x38, 0x40, 0x40, 0x22, 0x7A, - 0x00, 0x7A, 0x0A, 0x0A, 0x72, - 0x7D, 0x0D, 0x19, 0x31, 0x7D, - 0x26, 0x29, 0x29, 0x2F, 0x28, - 0x26, 0x29, 0x29, 0x29, 0x26, - 0x30, 0x48, 0x4D, 0x40, 0x20, - 0x38, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x38, - 0x2F, 0x10, 0xC8, 0xAC, 0xBA, - 0x2F, 0x10, 0x28, 0x34, 0xFA, - 0x00, 0x00, 0x7B, 0x00, 0x00, - 0x08, 0x14, 0x2A, 0x14, 0x22, - 0x22, 0x14, 0x2A, 0x14, 0x08, - 0xAA, 0x00, 0x55, 0x00, 0xAA, - 0xAA, 0x55, 0xAA, 0x55, 0xAA, - 0x00, 0x00, 0x00, 0xFF, 0x00, - 0x10, 0x10, 0x10, 0xFF, 0x00, - 0x14, 0x14, 0x14, 0xFF, 0x00, - 0x10, 0x10, 0xFF, 0x00, 0xFF, - 0x10, 0x10, 0xF0, 0x10, 0xF0, - 0x14, 0x14, 0x14, 0xFC, 0x00, - 0x14, 0x14, 0xF7, 0x00, 0xFF, - 0x00, 0x00, 0xFF, 0x00, 0xFF, - 0x14, 0x14, 0xF4, 0x04, 0xFC, - 0x14, 0x14, 0x17, 0x10, 0x1F, - 0x10, 0x10, 0x1F, 0x10, 0x1F, - 0x14, 0x14, 0x14, 0x1F, 0x00, - 0x10, 0x10, 0x10, 0xF0, 0x00, - 0x00, 0x00, 0x00, 0x1F, 0x10, - 0x10, 0x10, 0x10, 0x1F, 0x10, - 0x10, 0x10, 0x10, 0xF0, 0x10, - 0x00, 0x00, 0x00, 0xFF, 0x10, - 0x10, 0x10, 0x10, 0x10, 0x10, - 0x10, 0x10, 0x10, 0xFF, 0x10, - 0x00, 0x00, 0x00, 0xFF, 0x14, - 0x00, 0x00, 0xFF, 0x00, 0xFF, - 0x00, 0x00, 0x1F, 0x10, 0x17, - 0x00, 0x00, 0xFC, 0x04, 0xF4, - 0x14, 0x14, 0x17, 0x10, 0x17, - 0x14, 0x14, 0xF4, 0x04, 0xF4, - 0x00, 0x00, 0xFF, 0x00, 0xF7, - 0x14, 0x14, 0x14, 0x14, 0x14, - 0x14, 0x14, 0xF7, 0x00, 0xF7, - 0x14, 0x14, 0x14, 0x17, 0x14, - 0x10, 0x10, 0x1F, 0x10, 0x1F, - 0x14, 0x14, 0x14, 0xF4, 0x14, - 0x10, 0x10, 0xF0, 0x10, 0xF0, - 0x00, 0x00, 0x1F, 0x10, 0x1F, - 0x00, 0x00, 0x00, 0x1F, 0x14, - 0x00, 0x00, 0x00, 0xFC, 0x14, - 0x00, 0x00, 0xF0, 0x10, 0xF0, - 0x10, 0x10, 0xFF, 0x10, 0xFF, - 0x14, 0x14, 0x14, 0xFF, 0x14, - 0x10, 0x10, 0x10, 0x1F, 0x00, - 0x00, 0x00, 0x00, 0xF0, 0x10, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, - 0xFF, 0xFF, 0xFF, 0x00, 0x00, - 0x00, 0x00, 0x00, 0xFF, 0xFF, - 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, - 0x38, 0x44, 0x44, 0x38, 0x44, - 0x7C, 0x2A, 0x2A, 0x3E, 0x14, - 0x7E, 0x02, 0x02, 0x06, 0x06, - 0x02, 0x7E, 0x02, 0x7E, 0x02, - 0x63, 0x55, 0x49, 0x41, 0x63, - 0x38, 0x44, 0x44, 0x3C, 0x04, - 0x40, 0x7E, 0x20, 0x1E, 0x20, - 0x06, 0x02, 0x7E, 0x02, 0x02, - 0x99, 0xA5, 0xE7, 0xA5, 0x99, - 0x1C, 0x2A, 0x49, 0x2A, 0x1C, - 0x4C, 0x72, 0x01, 0x72, 0x4C, - 0x30, 0x4A, 0x4D, 0x4D, 0x30, - 0x30, 0x48, 0x78, 0x48, 0x30, - 0xBC, 0x62, 0x5A, 0x46, 0x3D, - 0x3E, 0x49, 0x49, 0x49, 0x00, - 0x7E, 0x01, 0x01, 0x01, 0x7E, - 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, - 0x44, 0x44, 0x5F, 0x44, 0x44, - 0x40, 0x51, 0x4A, 0x44, 0x40, - 0x40, 0x44, 0x4A, 0x51, 0x40, - 0x00, 0x00, 0xFF, 0x01, 0x03, - 0xE0, 0x80, 0xFF, 0x00, 0x00, - 0x08, 0x08, 0x6B, 0x6B, 0x08, - 0x36, 0x12, 0x36, 0x24, 0x36, - 0x06, 0x0F, 0x09, 0x0F, 0x06, - 0x00, 0x00, 0x18, 0x18, 0x00, - 0x00, 0x00, 0x10, 0x10, 0x00, - 0x30, 0x40, 0xFF, 0x01, 0x01, - 0x00, 0x1F, 0x01, 0x01, 0x1E, - 0x00, 0x19, 0x1D, 0x17, 0x12, - 0x00, 0x3C, 0x3C, 0x3C, 0x3C, - 0x00, 0x00, 0x00, 0x00, 0x00, -}; -#endif diff --git a/libraries/TFT/utility/keywords.txt b/libraries/TFT/utility/keywords.txt deleted file mode 100644 index 9614847..0000000 --- a/libraries/TFT/utility/keywords.txt +++ /dev/null @@ -1,70 +0,0 @@ -####################################### -# Syntax Coloring Map For Adafruit_GFX -# and Adafruit_ST7735 -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Adafruit_GFX KEYWORD1 -Adafruit_ST7735 KEYWORD1 -PImage KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -drawPixel KEYWORD2 -invertDisplay KEYWORD2 -drawLine KEYWORD2 -drawFastVLine KEYWORD2 -drawFastHLine KEYWORD2 -drawRect KEYWORD2 -fillRect KEYWORD2 -fillScreen KEYWORD2 -drawCircle KEYWORD2 -drawCircleHelper KEYWORD2 -fillCircle KEYWORD2 -fillCircleHelper KEYWORD2 -drawTriangle KEYWORD2 -fillTriangle KEYWORD2 -drawRoundRect KEYWORD2 -fillRoundRect KEYWORD2 -drawBitmap KEYWORD2 -drawChar KEYWORD2 -setCursor KEYWORD2 -setTextColor KEYWORD2 -setTextSize KEYWORD2 -setTextWrap KEYWORD2 -height KEYWORD2 -width KEYWORD2 -setRotation KEYWORD2 -getRotation KEYWORD2 - - - -newColor KEYWORD2 -background KEYWORD2 -fill KEYWORD2 -noFill KEYWORD2 -stroke KEYWORD2 -noStroke KEYWORD2 -text KEYWORD2 -textWrap KEYWORD2 -textSize KEYWORD2 -circle KEYWORD2 -point KEYWORD2 -quad KEYWORD2 -rect KEYWORD2 -triangle KEYWORD2 -loadImage KEYWORD2 -image KEYWORD2 - -draw KEYWORD2 -isValid KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - -- cgit v1.2.3-18-g5258 From fd8c367304fe62a107332db19880c88f9ac0d082 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Wed, 3 Jul 2013 22:00:02 +0200 Subject: SPI library to the new format and moved Robot_Motor and Robot_Control libraries --- libraries/Robot_Control/Adafruit_GFX.cpp | 688 -------------- libraries/Robot_Control/Adafruit_GFX.h | 190 ---- libraries/Robot_Control/ArduinoRobot.cpp | 40 - libraries/Robot_Control/ArduinoRobot.h | 360 -------- libraries/Robot_Control/Arduino_LCD.cpp | 706 --------------- libraries/Robot_Control/Arduino_LCD.h | 141 --- libraries/Robot_Control/Compass.cpp | 34 - libraries/Robot_Control/Compass.h | 24 - libraries/Robot_Control/EEPROM_I2C.cpp | 62 -- libraries/Robot_Control/EEPROM_I2C.h | 31 - libraries/Robot_Control/EasyTransfer2.cpp | 152 ---- libraries/Robot_Control/EasyTransfer2.h | 76 -- libraries/Robot_Control/Fat16.cpp | 990 --------------------- libraries/Robot_Control/Fat16.h | 378 -------- libraries/Robot_Control/Fat16Config.h | 38 - libraries/Robot_Control/Fat16mainpage.h | 208 ----- libraries/Robot_Control/Fat16util.h | 74 -- libraries/Robot_Control/FatStructs.h | 418 --------- libraries/Robot_Control/Melody.cpp | 100 --- libraries/Robot_Control/Motors.cpp | 1 - libraries/Robot_Control/Multiplexer.cpp | 37 - libraries/Robot_Control/Multiplexer.h | 24 - libraries/Robot_Control/RobotSdCard.cpp | 22 - libraries/Robot_Control/SPI.cpp | 66 -- libraries/Robot_Control/SPI.h | 70 -- libraries/Robot_Control/SdCard.cpp | 279 ------ libraries/Robot_Control/SdCard.h | 192 ---- libraries/Robot_Control/SdInfo.h | 117 --- libraries/Robot_Control/Sensors.cpp | 274 ------ libraries/Robot_Control/Squawk.cpp | 601 ------------- libraries/Robot_Control/Squawk.h | 265 ------ libraries/Robot_Control/SquawkSD.cpp | 182 ---- libraries/Robot_Control/SquawkSD.h | 17 - libraries/Robot_Control/Wire.cpp | 298 ------- libraries/Robot_Control/Wire.h | 79 -- libraries/Robot_Control/communication.cpp | 1 - .../examples/explore/R01_Logo/R01_Logo.ino | 134 --- .../explore/R02_Line_Follow/R02_Line_Follow.ino | 73 -- .../explore/R03_Disco_Bot/R03_Disco_Bot.ino | 179 ---- .../examples/explore/R04_Compass/R04_Compass.ino | 70 -- .../examples/explore/R05_Inputs/R05_Inputs.ino | 166 ---- .../R06_Wheel_Calibration.ino | 103 --- .../R07_Runaway_Robot/R07_Runaway_Robot.ino | 78 -- .../R08_Remote_Control/R08_Remote_Control.ino | 123 --- .../R09_Picture_Browser/R09_Picture_Browser.ino | 159 ---- .../examples/explore/R10_Rescue/R10_Rescue.ino | 124 --- .../explore/R11_Hello_User/R11_Hello_User.ino | 181 ---- .../examples/learn/AllIOPorts/AllIOPorts.ino | 149 ---- .../Robot_Control/examples/learn/Beep/Beep.ino | 39 - .../examples/learn/CleanEEPROM/CleanEEPROM.ino | 41 - .../examples/learn/Compass/Compass.ino | 41 - .../examples/learn/IRArray/IRArray.ino | 44 - .../examples/learn/LCDDebugPrint/LCDDebugPrint.ino | 37 - .../examples/learn/LCDPrint/LCDPrint.ino | 44 - .../examples/learn/LCDWriteText/LCDWriteText.ino | 41 - .../LineFollowWithPause/LineFollowWithPause.ino | 49 - .../Robot_Control/examples/learn/Melody/Melody.ino | 62 -- .../examples/learn/MotorTest/MotorTest.ino | 41 - .../SpeedByPotentiometer/SpeedByPotentiometer.ino | 39 - .../examples/learn/TurnTest/TurnTest.ino | 32 - .../examples/learn/TurnTest/TurnTest.ino.orig | 37 - .../examples/learn/keyboardTest/keyboardTest.ino | 38 - .../learn/keyboardTest/keyboardTest.ino.orig | 49 - libraries/Robot_Control/glcdfont.c | 266 ------ libraries/Robot_Control/helper.cpp | 45 - libraries/Robot_Control/information.cpp | 41 - libraries/Robot_Control/keyboard.cpp | 65 -- libraries/Robot_Control/lcd.cpp | 279 ------ .../Robot_Control/utility/RobotTextManager.cpp | 192 ---- libraries/Robot_Control/utility/RobotTextManager.h | 77 -- .../Robot_Control/utility/VirtualKeyboard.cpp | 127 --- libraries/Robot_Control/utility/VirtualKeyboard.h | 28 - .../Robot_Control/utility/scripts_Hello_User.h | 51 -- libraries/Robot_Control/utility/twi.c | 527 ----------- libraries/Robot_Control/utility/twi.h | 53 -- libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp | 265 ------ libraries/Robot_Motor/ArduinoRobotMotorBoard.h | 125 --- libraries/Robot_Motor/EasyTransfer2.cpp | 152 ---- libraries/Robot_Motor/EasyTransfer2.h | 76 -- libraries/Robot_Motor/LineFollow.h | 40 - libraries/Robot_Motor/Multiplexer.cpp | 37 - libraries/Robot_Motor/Multiplexer.h | 24 - .../Robot_IR_Array_Test/Robot_IR_Array_Test.ino | 26 - .../examples/Robot_Motor_Core/Robot_Motor_Core.ino | 18 - libraries/Robot_Motor/lineFollow.cpp | 152 ---- libraries/SPI/SPI.cpp | 66 -- libraries/SPI/SPI.h | 70 -- .../BarometricPressureSensor.ino | 143 --- .../BarometricPressureSensor.ino | 143 --- .../DigitalPotControl/DigitalPotControl.ino | 71 -- libraries/SPI/keywords.txt | 36 - 91 files changed, 12603 deletions(-) delete mode 100644 libraries/Robot_Control/Adafruit_GFX.cpp delete mode 100644 libraries/Robot_Control/Adafruit_GFX.h delete mode 100644 libraries/Robot_Control/ArduinoRobot.cpp delete mode 100644 libraries/Robot_Control/ArduinoRobot.h delete mode 100644 libraries/Robot_Control/Arduino_LCD.cpp delete mode 100644 libraries/Robot_Control/Arduino_LCD.h delete mode 100644 libraries/Robot_Control/Compass.cpp delete mode 100644 libraries/Robot_Control/Compass.h delete mode 100644 libraries/Robot_Control/EEPROM_I2C.cpp delete mode 100644 libraries/Robot_Control/EEPROM_I2C.h delete mode 100644 libraries/Robot_Control/EasyTransfer2.cpp delete mode 100644 libraries/Robot_Control/EasyTransfer2.h delete mode 100644 libraries/Robot_Control/Fat16.cpp delete mode 100644 libraries/Robot_Control/Fat16.h delete mode 100644 libraries/Robot_Control/Fat16Config.h delete mode 100644 libraries/Robot_Control/Fat16mainpage.h delete mode 100644 libraries/Robot_Control/Fat16util.h delete mode 100644 libraries/Robot_Control/FatStructs.h delete mode 100644 libraries/Robot_Control/Melody.cpp delete mode 100644 libraries/Robot_Control/Motors.cpp delete mode 100644 libraries/Robot_Control/Multiplexer.cpp delete mode 100644 libraries/Robot_Control/Multiplexer.h delete mode 100644 libraries/Robot_Control/RobotSdCard.cpp delete mode 100644 libraries/Robot_Control/SPI.cpp delete mode 100644 libraries/Robot_Control/SPI.h delete mode 100644 libraries/Robot_Control/SdCard.cpp delete mode 100644 libraries/Robot_Control/SdCard.h delete mode 100644 libraries/Robot_Control/SdInfo.h delete mode 100644 libraries/Robot_Control/Sensors.cpp delete mode 100644 libraries/Robot_Control/Squawk.cpp delete mode 100644 libraries/Robot_Control/Squawk.h delete mode 100644 libraries/Robot_Control/SquawkSD.cpp delete mode 100644 libraries/Robot_Control/SquawkSD.h delete mode 100644 libraries/Robot_Control/Wire.cpp delete mode 100644 libraries/Robot_Control/Wire.h delete mode 100644 libraries/Robot_Control/communication.cpp delete mode 100644 libraries/Robot_Control/examples/explore/R01_Logo/R01_Logo.ino delete mode 100644 libraries/Robot_Control/examples/explore/R02_Line_Follow/R02_Line_Follow.ino delete mode 100644 libraries/Robot_Control/examples/explore/R03_Disco_Bot/R03_Disco_Bot.ino delete mode 100644 libraries/Robot_Control/examples/explore/R04_Compass/R04_Compass.ino delete mode 100644 libraries/Robot_Control/examples/explore/R05_Inputs/R05_Inputs.ino delete mode 100644 libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/R06_Wheel_Calibration.ino delete mode 100644 libraries/Robot_Control/examples/explore/R07_Runaway_Robot/R07_Runaway_Robot.ino delete mode 100644 libraries/Robot_Control/examples/explore/R08_Remote_Control/R08_Remote_Control.ino delete mode 100644 libraries/Robot_Control/examples/explore/R09_Picture_Browser/R09_Picture_Browser.ino delete mode 100644 libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino delete mode 100644 libraries/Robot_Control/examples/explore/R11_Hello_User/R11_Hello_User.ino delete mode 100644 libraries/Robot_Control/examples/learn/AllIOPorts/AllIOPorts.ino delete mode 100644 libraries/Robot_Control/examples/learn/Beep/Beep.ino delete mode 100644 libraries/Robot_Control/examples/learn/CleanEEPROM/CleanEEPROM.ino delete mode 100644 libraries/Robot_Control/examples/learn/Compass/Compass.ino delete mode 100644 libraries/Robot_Control/examples/learn/IRArray/IRArray.ino delete mode 100644 libraries/Robot_Control/examples/learn/LCDDebugPrint/LCDDebugPrint.ino delete mode 100644 libraries/Robot_Control/examples/learn/LCDPrint/LCDPrint.ino delete mode 100644 libraries/Robot_Control/examples/learn/LCDWriteText/LCDWriteText.ino delete mode 100644 libraries/Robot_Control/examples/learn/LineFollowWithPause/LineFollowWithPause.ino delete mode 100644 libraries/Robot_Control/examples/learn/Melody/Melody.ino delete mode 100644 libraries/Robot_Control/examples/learn/MotorTest/MotorTest.ino delete mode 100644 libraries/Robot_Control/examples/learn/SpeedByPotentiometer/SpeedByPotentiometer.ino delete mode 100644 libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino delete mode 100644 libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino.orig delete mode 100644 libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino delete mode 100644 libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino.orig delete mode 100644 libraries/Robot_Control/glcdfont.c delete mode 100644 libraries/Robot_Control/helper.cpp delete mode 100644 libraries/Robot_Control/information.cpp delete mode 100644 libraries/Robot_Control/keyboard.cpp delete mode 100644 libraries/Robot_Control/lcd.cpp delete mode 100644 libraries/Robot_Control/utility/RobotTextManager.cpp delete mode 100644 libraries/Robot_Control/utility/RobotTextManager.h delete mode 100644 libraries/Robot_Control/utility/VirtualKeyboard.cpp delete mode 100644 libraries/Robot_Control/utility/VirtualKeyboard.h delete mode 100644 libraries/Robot_Control/utility/scripts_Hello_User.h delete mode 100644 libraries/Robot_Control/utility/twi.c delete mode 100644 libraries/Robot_Control/utility/twi.h delete mode 100644 libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp delete mode 100644 libraries/Robot_Motor/ArduinoRobotMotorBoard.h delete mode 100644 libraries/Robot_Motor/EasyTransfer2.cpp delete mode 100644 libraries/Robot_Motor/EasyTransfer2.h delete mode 100644 libraries/Robot_Motor/LineFollow.h delete mode 100644 libraries/Robot_Motor/Multiplexer.cpp delete mode 100644 libraries/Robot_Motor/Multiplexer.h delete mode 100644 libraries/Robot_Motor/examples/Robot_IR_Array_Test/Robot_IR_Array_Test.ino delete mode 100644 libraries/Robot_Motor/examples/Robot_Motor_Core/Robot_Motor_Core.ino delete mode 100644 libraries/Robot_Motor/lineFollow.cpp delete mode 100644 libraries/SPI/SPI.cpp delete mode 100644 libraries/SPI/SPI.h delete mode 100644 libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino delete mode 100644 libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.ino delete mode 100644 libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino delete mode 100644 libraries/SPI/keywords.txt diff --git a/libraries/Robot_Control/Adafruit_GFX.cpp b/libraries/Robot_Control/Adafruit_GFX.cpp deleted file mode 100644 index acfed1d..0000000 --- a/libraries/Robot_Control/Adafruit_GFX.cpp +++ /dev/null @@ -1,688 +0,0 @@ -/****************************************************************** - This is the core graphics library for all our displays, providing - basic graphics primitives (points, lines, circles, etc.). It needs - to be paired with a hardware-specific library for each display - device we carry (handling the lower-level functions). - - Adafruit invests time and resources providing this open - source code, please support Adafruit and open-source hardware - by purchasing products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, check license.txt for more information. - All text above must be included in any redistribution. - ******************************************************************/ - -#include "Adafruit_GFX.h" -#include "glcdfont.c" -#include - -void Adafruit_GFX::constructor(int16_t w, int16_t h) { - _width = WIDTH = w; - _height = HEIGHT = h; - - rotation = 0; - cursor_y = cursor_x = 0; - textsize = 1; - textcolor = textbgcolor = 0xFFFF; - wrap = true; - - strokeColor = 0; - useStroke = true; - fillColor = 0; - useFill = false; - -} - - -// draw a circle outline -void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, - uint16_t color) { - int16_t f = 1 - r; - int16_t ddF_x = 1; - int16_t ddF_y = -2 * r; - int16_t x = 0; - int16_t y = r; - - drawPixel(x0, y0+r, color); - drawPixel(x0, y0-r, color); - drawPixel(x0+r, y0, color); - drawPixel(x0-r, y0, color); - - while (x= 0) { - y--; - ddF_y += 2; - f += ddF_y; - } - x++; - ddF_x += 2; - f += ddF_x; - - drawPixel(x0 + x, y0 + y, color); - drawPixel(x0 - x, y0 + y, color); - drawPixel(x0 + x, y0 - y, color); - drawPixel(x0 - x, y0 - y, color); - drawPixel(x0 + y, y0 + x, color); - drawPixel(x0 - y, y0 + x, color); - drawPixel(x0 + y, y0 - x, color); - drawPixel(x0 - y, y0 - x, color); - - } -} - -void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, - int16_t r, uint8_t cornername, uint16_t color) { - int16_t f = 1 - r; - int16_t ddF_x = 1; - int16_t ddF_y = -2 * r; - int16_t x = 0; - int16_t y = r; - - while (x= 0) { - y--; - ddF_y += 2; - f += ddF_y; - } - x++; - ddF_x += 2; - f += ddF_x; - if (cornername & 0x4) { - drawPixel(x0 + x, y0 + y, color); - drawPixel(x0 + y, y0 + x, color); - } - if (cornername & 0x2) { - drawPixel(x0 + x, y0 - y, color); - drawPixel(x0 + y, y0 - x, color); - } - if (cornername & 0x8) { - drawPixel(x0 - y, y0 + x, color); - drawPixel(x0 - x, y0 + y, color); - } - if (cornername & 0x1) { - drawPixel(x0 - y, y0 - x, color); - drawPixel(x0 - x, y0 - y, color); - } - } -} - -void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, - uint16_t color) { - drawFastVLine(x0, y0-r, 2*r+1, color); - fillCircleHelper(x0, y0, r, 3, 0, color); -} - -// used to do circles and roundrects! -void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, - uint8_t cornername, int16_t delta, uint16_t color) { - - int16_t f = 1 - r; - int16_t ddF_x = 1; - int16_t ddF_y = -2 * r; - int16_t x = 0; - int16_t y = r; - - while (x= 0) { - y--; - ddF_y += 2; - f += ddF_y; - } - x++; - ddF_x += 2; - f += ddF_x; - - if (cornername & 0x1) { - drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); - drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); - } - if (cornername & 0x2) { - drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); - drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); - } - } -} - -// bresenham's algorithm - thx wikpedia -void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, - int16_t x1, int16_t y1, - uint16_t color) { - int16_t steep = abs(y1 - y0) > abs(x1 - x0); - if (steep) { - swap(x0, y0); - swap(x1, y1); - } - - if (x0 > x1) { - swap(x0, x1); - swap(y0, y1); - } - - int16_t dx, dy; - dx = x1 - x0; - dy = abs(y1 - y0); - - int16_t err = dx / 2; - int16_t ystep; - - if (y0 < y1) { - ystep = 1; - } else { - ystep = -1; - } - - for (; x0<=x1; x0++) { - if (steep) { - drawPixel(y0, x0, color); - } else { - drawPixel(x0, y0, color); - } - err -= dy; - if (err < 0) { - y0 += ystep; - err += dx; - } - } -} - - -// draw a rectangle -void Adafruit_GFX::drawRect(int16_t x, int16_t y, - int16_t w, int16_t h, - uint16_t color) { - drawFastHLine(x, y, w, color); - drawFastHLine(x, y+h-1, w, color); - drawFastVLine(x, y, h, color); - drawFastVLine(x+w-1, y, h, color); -} - -void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, - int16_t h, uint16_t color) { - // stupidest version - update in subclasses if desired! - drawLine(x, y, x, y+h-1, color); -} - - -void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, - int16_t w, uint16_t color) { - // stupidest version - update in subclasses if desired! - drawLine(x, y, x+w-1, y, color); -} - -void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color) { - // stupidest version - update in subclasses if desired! - for (int16_t i=x; i= y1 >= y0) - if (y0 > y1) { - swap(y0, y1); swap(x0, x1); - } - if (y1 > y2) { - swap(y2, y1); swap(x2, x1); - } - if (y0 > y1) { - swap(y0, y1); swap(x0, x1); - } - - if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing - a = b = x0; - if(x1 < a) a = x1; - else if(x1 > b) b = x1; - if(x2 < a) a = x2; - else if(x2 > b) b = x2; - drawFastHLine(a, y0, b-a+1, color); - return; - } - - int16_t - dx01 = x1 - x0, - dy01 = y1 - y0, - dx02 = x2 - x0, - dy02 = y2 - y0, - dx12 = x2 - x1, - dy12 = y2 - y1, - sa = 0, - sb = 0; - - // For upper part of triangle, find scanline crossings for segments - // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 - // is included here (and second loop will be skipped, avoiding a /0 - // error there), otherwise scanline y1 is skipped here and handled - // in the second loop...which also avoids a /0 error here if y0=y1 - // (flat-topped triangle). - if(y1 == y2) last = y1; // Include y1 scanline - else last = y1-1; // Skip it - - for(y=y0; y<=last; y++) { - a = x0 + sa / dy01; - b = x0 + sb / dy02; - sa += dx01; - sb += dx02; - /* longhand: - a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); - b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); - */ - if(a > b) swap(a,b); - drawFastHLine(a, y, b-a+1, color); - } - - // For lower part of triangle, find scanline crossings for segments - // 0-2 and 1-2. This loop is skipped if y1=y2. - sa = dx12 * (y - y1); - sb = dx02 * (y - y0); - for(; y<=y2; y++) { - a = x1 + sa / dy12; - b = x0 + sb / dy02; - sa += dx12; - sb += dx02; - /* longhand: - a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); - b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); - */ - if(a > b) swap(a,b); - drawFastHLine(a, y, b-a+1, color); - } -} - -void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, - const uint8_t *bitmap, int16_t w, int16_t h, - uint16_t color) { - - int16_t i, j, byteWidth = (w + 7) / 8; - - for(j=0; j> (i & 7))) { - drawPixel(x+i, y+j, color); - } - } - } -} - - -#if ARDUINO >= 100 -size_t Adafruit_GFX::write(uint8_t c) { -#else -void Adafruit_GFX::write(uint8_t c) { -#endif - if (c == '\n') { - cursor_y += textsize*8; - cursor_x = 0; - } else if (c == '\r') { - // skip em - } else { - drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); - cursor_x += textsize*6; - if (wrap && (cursor_x > (_width - textsize*6))) { - cursor_y += textsize*8; - cursor_x = 0; - } - } -#if ARDUINO >= 100 - return 1; -#endif -} - -// draw a character -void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, - uint16_t color, uint16_t bg, uint8_t size) { - - if((x >= _width) || // Clip right - (y >= _height) || // Clip bottom - ((x + 5 * size - 1) < 0) || // Clip left - ((y + 8 * size - 1) < 0)) // Clip top - return; - - for (int8_t i=0; i<6; i++ ) { - uint8_t line; - if (i == 5) - line = 0x0; - else - line = pgm_read_byte(font+(c*5)+i); - for (int8_t j = 0; j<8; j++) { - if (line & 0x1) { - if (size == 1) // default size - drawPixel(x+i, y+j, color); - else { // big size - fillRect(x+(i*size), y+(j*size), size, size, color); - } - } else if (bg != color) { - if (size == 1) // default size - drawPixel(x+i, y+j, bg); - else { // big size - fillRect(x+i*size, y+j*size, size, size, bg); - } - } - line >>= 1; - } - } -} - -void Adafruit_GFX::setCursor(int16_t x, int16_t y) { - cursor_x = x; - cursor_y = y; -} - - -void Adafruit_GFX::setTextSize(uint8_t s) { - textsize = (s > 0) ? s : 1; -} - - -void Adafruit_GFX::setTextColor(uint16_t c) { - textcolor = c; - textbgcolor = c; - // for 'transparent' background, we'll set the bg - // to the same as fg instead of using a flag -} - - void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) { - textcolor = c; - textbgcolor = b; - } - -void Adafruit_GFX::setTextWrap(boolean w) { - wrap = w; -} - -uint8_t Adafruit_GFX::getRotation(void) { - rotation %= 4; - return rotation; -} - -void Adafruit_GFX::setRotation(uint8_t x) { - x %= 4; // cant be higher than 3 - rotation = x; - switch (x) { - case 0: - case 2: - _width = WIDTH; - _height = HEIGHT; - break; - case 1: - case 3: - _width = HEIGHT; - _height = WIDTH; - break; - } -} - -void Adafruit_GFX::invertDisplay(boolean i) { - // do nothing, can be subclassed -} - - -// return the size of the display which depends on the rotation! -int16_t Adafruit_GFX::width(void) { - return _width; -} - -int16_t Adafruit_GFX::height(void) { - return _height; -} - - - -uint16_t Adafruit_GFX::newColor(uint8_t r, uint8_t g, uint8_t b) { - return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); -} - - -void Adafruit_GFX::background(uint8_t red, uint8_t green, uint8_t blue) { - background(newColor(red, green, blue)); -} - -void Adafruit_GFX::background(color c) { - fillScreen(c); -} - -void Adafruit_GFX::stroke(uint8_t red, uint8_t green, uint8_t blue) { - stroke(newColor(red, green, blue)); -} - -void Adafruit_GFX::stroke(color c) { - useStroke = true; - strokeColor = c; - setTextColor(c); -} - -void Adafruit_GFX::noStroke() { - useStroke = false; -} - -void Adafruit_GFX::noFill() { - useFill = false; -} - -void Adafruit_GFX::fill(uint8_t red, uint8_t green, uint8_t blue) { - fill(newColor(red, green, blue)); -} - -void Adafruit_GFX::fill(color c) { - useFill = true; - fillColor = c; -} - -void Adafruit_GFX::text(int value, uint8_t x, uint8_t y){ - if (!useStroke) - return; - - setTextWrap(false); - setTextColor(strokeColor); - setCursor(x, y); - print(value); -} -void Adafruit_GFX::text(long value, uint8_t x, uint8_t y){ - if (!useStroke) - return; - - setTextWrap(false); - setTextColor(strokeColor); - setCursor(x, y); - print(value); -} -void Adafruit_GFX::text(char value, uint8_t x, uint8_t y){ - if (!useStroke) - return; - - setTextWrap(false); - setTextColor(strokeColor); - setCursor(x, y); - print(value); -} - -void Adafruit_GFX::text(const char * text, int16_t x, int16_t y) { - if (!useStroke) - return; - - setTextWrap(false); - setTextColor(strokeColor); - setCursor(x, y); - print(text); -} - -void Adafruit_GFX::textWrap(const char * text, int16_t x, int16_t y) { - if (!useStroke) - return; - - setTextWrap(true); - setTextColor(strokeColor); - setCursor(x, y); - print(text); -} - - -void Adafruit_GFX::textSize(uint8_t size) { - setTextSize(size); -} - -void Adafruit_GFX::point(int16_t x, int16_t y) { - if (!useStroke) - return; - - drawPixel(x, y, strokeColor); -} - -void Adafruit_GFX::line(int16_t x1, int16_t y1, int16_t x2, int16_t y2) { - if (!useStroke) - return; - - if (x1 == x2) { - drawFastVLine(x1, y1, y2 - y1, strokeColor); - } - else if (y1 == y2) { - drawFastHLine(x1, y1, x2 - x1, strokeColor); - } - else { - drawLine(x1, y1, x2, y2, strokeColor); - } -} - -void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height) { - if (useFill) { - fillRect(x, y, width, height, fillColor); - } - if (useStroke) { - drawRect(x, y, width, height, strokeColor); - } -} - -void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius) { - if (radius == 0) { - rect(x, y, width, height); - } - if (useFill) { - fillRoundRect(x, y, width, height, radius, fillColor); - } - if (useStroke) { - drawRoundRect(x, y, width, height, radius, strokeColor); - } -} - -void Adafruit_GFX::circle(int16_t x, int16_t y, int16_t r) { - if (r == 0) - return; - - if (useFill) { - fillCircle(x, y, r, fillColor); - } - if (useStroke) { - drawCircle(x, y, r, strokeColor); - } -} - -void Adafruit_GFX::triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3) { - if (useFill) { - fillTriangle(x1, y1, x2, y2, x3, y3, fillColor); - } - if (useStroke) { - drawTriangle(x1, y1, x2, y2, x3, y3, strokeColor); - } -} - -#define BUFFPIXEL 20 -/* -void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { - int w, h, row, col; - uint8_t r, g, b; - uint32_t pos = 0; - uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) - uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer - - // Crop area to be loaded - w = img._bmpWidth; - h = img._bmpHeight; - if((x+w-1) >= width()) w = width() - x; - if((y+h-1) >= height()) h = height() - y; - - - // Set TFT address window to clipped image bounds - //setAddrWindow(x, y, x+w-1, y+h-1); - - - for (row=0; row= sizeof(sdbuffer)) { // Indeed - img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); - buffidx = 0; // Set index to beginning - } - - // Convert pixel from BMP to TFT format, push to display - b = sdbuffer[buffidx++]; - g = sdbuffer[buffidx++]; - r = sdbuffer[buffidx++]; - //pushColor(tft.Color565(r,g,b)); - drawPixel(x + col, y + row, newColor(r, g, b)); - - } // end pixel - } // end scanline - -}*/ diff --git a/libraries/Robot_Control/Adafruit_GFX.h b/libraries/Robot_Control/Adafruit_GFX.h deleted file mode 100644 index 1f6b8d8..0000000 --- a/libraries/Robot_Control/Adafruit_GFX.h +++ /dev/null @@ -1,190 +0,0 @@ -/****************************************************************** - This is the core graphics library for all our displays, providing - basic graphics primitives (points, lines, circles, etc.). It needs - to be paired with a hardware-specific library for each display - device we carry (handling the lower-level functions). - - Adafruit invests time and resources providing this open - source code, please support Adafruit and open-source hardware - by purchasing products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, check license.txt for more information. - All text above must be included in any redistribution. - ******************************************************************/ - -#ifndef _ADAFRUIT_GFX_H -#define _ADAFRUIT_GFX_H - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif - -//#include "PImage.h" - -#define swap(a, b) { int16_t t = a; a = b; b = t; } - -/* TODO -enum RectMode { - CORNER, - CORNERS, - RADIUS, - CENTER -}; -*/ - -typedef uint16_t color; - -class Adafruit_GFX : public Print { - public: - - //Adafruit_GFX(); - // i have no idea why we have to formally call the constructor. kinda sux - void constructor(int16_t w, int16_t h); - - // this must be defined by the subclass - virtual void drawPixel(int16_t x, int16_t y, uint16_t color); - virtual void invertDisplay(boolean i); - - // these are 'generic' drawing functions, so we can share them! - virtual void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - uint16_t color); - virtual void drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color); - virtual void drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color); - virtual void drawRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color); - virtual void fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color); - virtual void fillScreen(uint16_t color); - - void drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color); - void drawCircleHelper(int16_t x0, int16_t y0, - int16_t r, uint8_t cornername, uint16_t color); - void fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color); - void fillCircleHelper(int16_t x0, int16_t y0, int16_t r, - uint8_t cornername, int16_t delta, uint16_t color); - - void drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - int16_t x2, int16_t y2, uint16_t color); - void fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - int16_t x2, int16_t y2, uint16_t color); - void drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, - int16_t radius, uint16_t color); - void fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, - int16_t radius, uint16_t color); - - void drawBitmap(int16_t x, int16_t y, - const uint8_t *bitmap, int16_t w, int16_t h, - uint16_t color); - void drawChar(int16_t x, int16_t y, unsigned char c, - uint16_t color, uint16_t bg, uint8_t size); -#if ARDUINO >= 100 - virtual size_t write(uint8_t); -#else - virtual void write(uint8_t); -#endif - void setCursor(int16_t x, int16_t y); - void setTextColor(uint16_t c); - void setTextColor(uint16_t c, uint16_t bg); - void setTextSize(uint8_t s); - void setTextWrap(boolean w); - - int16_t height(void); - int16_t width(void); - - void setRotation(uint8_t r); - uint8_t getRotation(void); - - - /* - * Processing-like graphics primitives - */ - - /// transforms a color in 16-bit form given the RGB components. - /// The default implementation makes a 5-bit red, a 6-bit - /// green and a 5-bit blue (MSB to LSB). Devices that use - /// different scheme should override this. - virtual uint16_t newColor(uint8_t red, uint8_t green, uint8_t blue); - - - // http://processing.org/reference/background_.html - void background(uint8_t red, uint8_t green, uint8_t blue); - void background(color c); - - // http://processing.org/reference/fill_.html - void fill(uint8_t red, uint8_t green, uint8_t blue); - void fill(color c); - - // http://processing.org/reference/noFill_.html - void noFill(); - - // http://processing.org/reference/stroke_.html - void stroke(uint8_t red, uint8_t green, uint8_t blue); - void stroke(color c); - - // http://processing.org/reference/noStroke_.html - void noStroke(); - - void text(const char * text, int16_t x, int16_t y); - void text(int value, uint8_t posX, uint8_t posY); - void text(long value, uint8_t posX, uint8_t posY); - void text(char value, uint8_t posX, uint8_t posY); - - void textWrap(const char * text, int16_t x, int16_t y); - - void textSize(uint8_t size); - - // similar to ellipse() in Processing, but with - // a single radius. - // http://processing.org/reference/ellipse_.html - void circle(int16_t x, int16_t y, int16_t r); - - void point(int16_t x, int16_t y); - - void line(int16_t x1, int16_t y1, int16_t x2, int16_t y2); - - void quad(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3, int16_t x4, int16_t y4); - - void rect(int16_t x, int16_t y, int16_t width, int16_t height); - - void rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius); - - void triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3); - - /* TODO - void rectMode(RectMode mode); - - void pushStyle(); - void popStyle(); - */ - -// PImage loadImage(const char * fileName) { return PImage::loadImage(fileName); } - -// void image(PImage & img, uint16_t x, uint16_t y); - - protected: - int16_t WIDTH, HEIGHT; // this is the 'raw' display w/h - never changes - int16_t _width, _height; // dependent on rotation - int16_t cursor_x, cursor_y; - uint16_t textcolor, textbgcolor; - uint8_t textsize; - uint8_t rotation; - boolean wrap; // If set, 'wrap' text at right edge of display - - /* - * Processing-style graphics state - */ - - color strokeColor; - bool useStroke; - color fillColor; - bool useFill; -}; - - - - -#endif diff --git a/libraries/Robot_Control/ArduinoRobot.cpp b/libraries/Robot_Control/ArduinoRobot.cpp deleted file mode 100644 index 3adac73..0000000 --- a/libraries/Robot_Control/ArduinoRobot.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "ArduinoRobot.h" -#include "Multiplexer.h" -#include "Wire.h" -#include "EasyTransfer2.h" - -//RobotControl::RobotControl(){} - -RobotControl::RobotControl():Arduino_LCD(LCD_CS,DC_LCD,RST_LCD){ - -} - -void RobotControl::begin(){ - Wire.begin(); - //Compass - //nothing here - - //TK sensors - uint8_t MuxPins[]={MUXA,MUXB,MUXC,MUXD}; - Multiplexer::begin(MuxPins,MUX_IN,4); - - //piezo - pinMode(BUZZ,OUTPUT); - - //communication - Serial1.begin(9600); - messageOut.begin(&Serial1); - messageIn.begin(&Serial1); - - //TFT initialization - //Arduino_LCD::initR(INITR_GREENTAB); -} - -void RobotControl::setMode(uint8_t mode){ - messageOut.writeByte(COMMAND_SWITCH_MODE); - messageOut.writeByte(mode); - messageOut.sendData(); -} - - -RobotControl Robot=RobotControl(); \ No newline at end of file diff --git a/libraries/Robot_Control/ArduinoRobot.h b/libraries/Robot_Control/ArduinoRobot.h deleted file mode 100644 index becdca8..0000000 --- a/libraries/Robot_Control/ArduinoRobot.h +++ /dev/null @@ -1,360 +0,0 @@ -#ifndef ArduinoRobot_h -#define ArduinoRobot_h - -#include "Arduino_LCD.h" // Hardware-specific library -//#include "FormattedText.h" -#include "SquawkSD.h" -#include "Multiplexer.h" -#include "EasyTransfer2.h" -#include "EEPROM_I2C.h" -#include "Compass.h" -#include "Fat16.h" - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - - -#define BUTTON_NONE -1 -#define BUTTON_LEFT 0 -#define BUTTON_DOWN 1 -#define BUTTON_UP 2 -#define BUTTON_RIGHT 3 -#define BUTTON_MIDDLE 4 -#define NUMBER_BUTTONS 5 - -//beep length -#define BEEP_SIMPLE 0 -#define BEEP_DOUBLE 1 -#define BEEP_LONG 2 - -// image locations on the EEPROM - #define HOME_BMP 0 -#define BATTERY_BMP 2048 -#define COMPASS_BMP 4096 -#define CONTROL_BMP 6144 -#define GEARS_BMP 8192 -#define LIGHT_BMP 10240 -#define OSCILLO_BMP 12288 -#define VOLT_BMP 14336 -#define INICIO_BMP 16384 // this is a full screen splash - -//Command code -#define COMMAND_SWITCH_MODE 0 -#define COMMAND_RUN 10 -#define COMMAND_MOTORS_STOP 11 -#define COMMAND_ANALOG_WRITE 20 -#define COMMAND_DIGITAL_WRITE 30 -#define COMMAND_ANALOG_READ 40 -#define COMMAND_ANALOG_READ_RE 41 -#define COMMAND_DIGITAL_READ 50 -#define COMMAND_DIGITAL_READ_RE 51 -#define COMMAND_READ_IR 60 -#define COMMAND_READ_IR_RE 61 -#define COMMAND_ACTION_DONE 70 -#define COMMAND_READ_TRIM 80 -#define COMMAND_READ_TRIM_RE 81 -#define COMMAND_PAUSE_MODE 90 -#define COMMAND_LINE_FOLLOW_CONFIG 100 - -//component codename -#define CN_LEFT_MOTOR 0 -#define CN_RIGHT_MOTOR 1 -#define CN_IR 2 - -//motor board modes -#define MODE_SIMPLE 0 -#define MODE_LINE_FOLLOW 1 -#define MODE_ADJUST_MOTOR 2 -#define MODE_IR_CONTROL 3 - -//port types, for R/W -#define TYPE_TOP_TK 0 -#define TYPE_TOP_TKD 1 -#define TYPE_BOTTOM_TK 2 - -//top TKs -#define TK0 100 -#define TK1 101 -#define TK2 102 -#define TK3 103 -#define TK4 104 -#define TK5 105 -#define TK6 106 -#define TK7 107 - -//bottom TKs, just for communication purpose -#define B_TK1 201 -#define B_TK2 202 -#define B_TK3 203 -#define B_TK4 204 - -//bottom IRs, for communication purpose -#define B_IR0 210 -#define B_IR1 211 -#define B_IR2 212 -#define B_IR3 213 -#define B_IR4 214 - -#ifndef LED1 -#define LED1 17 -#endif - -//320 - 337 username, -#define ADDRESS_USERNAME 320 -//338 - 355 robotname, -#define ADDRESS_ROBOTNAME 338 -//356 - 373 cityname, -#define ADDRESS_CITYNAME 356 - //374- 391 countryname, -#define ADDRESS_COUNTRYNAME 374 -//508-511 robot info -#define ADDRESS_ROBOTINFO 508 - -#define BLACK ILI9163C_BLACK -#define BLUE ILI9163C_BLUE -#define RED ILI9163C_RED -#define GREEN ILI9163C_GREEN -#define CYAN ILI9163C_CYAN -#define MAGENTA ILI9163C_MAGENTA -#define YELLOW ILI9163C_YELLOW -#define WHITE ILI9163C_WHITE - -//A data structure for storing the current state of motor board -struct MOTOR_BOARD_DATA{ - int _B_TK1; - int _B_TK2; - int _B_TK3; - int _B_TK4; - - /*int _B_IR0; - int _B_IR1; - int _B_IR2; - int _B_IR3; - int _B_IR4;*/ -}; - -/* -A message structure will be: -switch mode: - byte COMMAND_SWITCH_MODE, byte mode -run: - byte COMMAND_RUN, int speedL, int speedR -analogWrite: - byte COMMAND_ANALOG_WRITE, byte codename, byte value; -digitalWrite: - byte COMMAND_DIGITAL_WRITE, byte codename, byte value; -analogRead: - byte COMMAND_ANALOG_READ, byte codename; -analogRead return: - byte COMMAND_ANALOG_READ_RE, byte codename, int value; -digitalRead return: - byte COMMAND_DIGITAL_READ_RE, byte codename, byte value; -read IR: - byte COMMAND_READ_IR, int valueA, int valueB, int valueC, int valueD; - - -*/ -#define NUM_EEPROM_BMP 10 -struct EEPROM_BMP{ - char name[8]; - uint8_t width; - uint8_t height; - uint16_t address; -}; - -//if you call #undef USE_SQUAWK_SYNTH_SD at the beginning of your sketch, -//it's going to remove anything regarding sound playing - -class RobotControl:public Multiplexer, -public EEPROM_I2C, -public Compass, -public SquawkSynthSD, -//public FormattedText -public Arduino_LCD -{ - public: - RobotControl(); - void begin(); - void setMode(uint8_t mode); - - //Read & Write, TK0 - TK7, TKD0 - TKD1, bottom TK0 - TK4 - bool digitalRead(uint8_t port); - int analogRead(uint8_t port); - void digitalWrite(uint8_t port, bool value); - void analogWrite(uint8_t port, uint8_t value);//It's not available, as there's no pin can be used for analog write - - //IR sensors from the bottom board - //define an array as "int arr[4];", and supply the arry name here - uint16_t IRarray[5]; - void updateIR(); - - //on board Potentiometor - int knobRead(); - //Potentiometor of the motor board - int trimRead(); - - //on board piezo - void beginSpeaker(uint16_t frequency=44100); - void playMelody(char* script); - void playFile(char* filename); - void stopPlayFile(); - void beep(int beep_length=BEEP_SIMPLE); - void tempoWrite(int tempo); - void tuneWrite(float tune); - - //compass - uint16_t compassRead(); - void drawCompass(uint16_t value); - void drawBase(); - void drawDire(int16_t dire); - - //keyboard - void keyboardCalibrate(int *vals); - int8_t keyboardRead();//return the key that is being pressed?Has been pressed(with _processKeyboard)? - - //movement - void moveForward(int speed); - void moveBackward(int speed); - void turnLeft(int speed); - void turnRight(int speed); - void motorsStop(); - void motorsWritePct(int speedLeftPct, int speedRightPct); - - void motorsWrite(int speedLeft,int speedRight); - void pointTo(int degrees);//turn to an absolute angle from the compass - void turn(int degress);//turn certain degrees from the current heading - - //Line Following - void lineFollowConfig(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime);//default 11 5 50 10 - - //TFT LCD - //use the same commands as Arduino_LCD - void beginTFT(uint16_t foreGround=BLACK, uint16_t background=WHITE); - /*void text(int value, uint8_t posX, uint8_t posY, bool EW); - void text(long value, uint8_t posX, uint8_t posY, bool EW); - void text(char* value, uint8_t posX, uint8_t posY, bool EW); - void text(char value, uint8_t posX, uint8_t posY, bool EW);*/ - void debugPrint(long value, uint8_t x=0, uint8_t y=0); - void clearScreen(); - - void drawBMP(char* filename, uint8_t x, uint8_t y);//detect if draw with EEPROM or SD, and draw it - void _drawBMP(uint32_t iconOffset, uint8_t x, uint8_t y, uint8_t width, uint8_t height);//draw from EEPROM - void _drawBMP(char* filename, uint8_t x, uint8_t y);//draw from SD - void beginBMPFromEEPROM(); - void endBMPFromEEPROM(); - - uint16_t foreGround;//foreground color - uint16_t backGround;//background color - - - //SD card - void beginSD(); - - //Information - void userNameRead(char* container); - void robotNameRead(char* container); - void cityNameRead(char* container); - void countryNameRead(char* container); - - void userNameWrite(char* text); - void robotNameWrite(char* text); - void cityNameWrite(char* text); - void countryNameWrite(char* text); - - //Others - bool isActionDone(); - void pauseMode(uint8_t onOff); - void displayLogos(); - void waitContinue(uint8_t key=BUTTON_MIDDLE); - - private: - //Read & Write - uint8_t _getTypeCode(uint8_t port);//different ports need different actions - uint8_t _portToTopMux(uint8_t port);//get the number for multiplexer within top TKs - uint8_t _topDPortToAPort(uint8_t port);//get the corrensponding analogIn pin for top TKDs - - bool _digitalReadTopMux(uint8_t port);//TK0 - TK7 - int _analogReadTopMux(uint8_t port); - - bool _digitalReadTopPin(uint8_t port); - int _analogReadTopPin(uint8_t port); - void _digitalWriteTopPin(uint8_t port, bool value); - - MOTOR_BOARD_DATA motorBoardData; - int* parseMBDPort(uint8_t port); - int get_motorBoardData(uint8_t port); - void set_motorBoardData(uint8_t port, int value); - - bool _requestDigitalRead(uint8_t port); - int _requestAnalogRead(uint8_t port); - void _requestDigitalWrite(uint8_t port, uint8_t value); - - //LCD - void _enableLCD(); - void _setWrite(uint8_t posX, uint8_t posY); - void _setErase(uint8_t posX, uint8_t posY); - - - //SD - SdCard card; - Fat16 file; - Fat16 melody; - void _enableSD(); - - //keyboard - void _processKeyboard(); //need to run in loop, detect if the key is actually pressed - int averageAnalogInput(int pinNum); - - //Ultrasonic ranger - //uint8_t pinTrigger_UR; - //uint8_t pinEcho_UR; - - //Melody - void playNote(byte period, word length, char modifier); - - //Communication - - EasyTransfer2 messageOut; - EasyTransfer2 messageIn; - - //TFT LCD - bool _isEEPROM_BMP_Allocated; - EEPROM_BMP * _eeprom_bmp; - void _drawBMP_EEPROM(uint16_t address, uint8_t width, uint8_t height); - void _drawBMP_SD(char* filename, uint8_t x, uint8_t y); - - -}; - -inline void RobotControl::userNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_USERNAME,(uint8_t*)container,18); -} -inline void RobotControl::robotNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_ROBOTNAME,(uint8_t*)container,18); -} -inline void RobotControl::cityNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_CITYNAME,(uint8_t*)container,18); -} -inline void RobotControl::countryNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_COUNTRYNAME,(uint8_t*)container,18); -} - -inline void RobotControl::userNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_USERNAME,(uint8_t*)text,18); -} -inline void RobotControl::robotNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_ROBOTNAME,(uint8_t*)text,18); -} -inline void RobotControl::cityNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_CITYNAME,(uint8_t*)text,18); -} -inline void RobotControl::countryNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_COUNTRYNAME,(uint8_t*)text,18); -} - -extern RobotControl Robot; - -#endif \ No newline at end of file diff --git a/libraries/Robot_Control/Arduino_LCD.cpp b/libraries/Robot_Control/Arduino_LCD.cpp deleted file mode 100644 index db28cd0..0000000 --- a/libraries/Robot_Control/Arduino_LCD.cpp +++ /dev/null @@ -1,706 +0,0 @@ -/*************************************************** - This is a library for the Adafruit 1.8" SPI display. - This library works with the Adafruit 1.8" TFT Breakout w/SD card - ----> http://www.adafruit.com/products/358 - as well as Adafruit raw 1.8" TFT display - ----> http://www.adafruit.com/products/618 - - Check out the links above for our tutorials and wiring diagrams - These displays use SPI to communicate, 4 or 5 pins are required to - interface (RST is optional) - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - MIT license, all text above must be included in any redistribution - ****************************************************/ - -#include "Arduino_LCD.h" -//#include -#include -//#include "pins_arduino.h" -#include "wiring_private.h" -#include - - -// Constructor when using software SPI. All output pins are configurable. -Arduino_LCD::Arduino_LCD(uint8_t cs, uint8_t rs, uint8_t sid, - uint8_t sclk, uint8_t rst) { - _cs = cs; - _rs = rs; - _sid = sid; - _sclk = sclk; - _rst = rst; - hwSPI = false; -} - - -// Constructor when using hardware SPI. Faster, but must use SPI pins -// specific to each board type (e.g. 11,13 for Uno, 51,52 for Mega, etc.) -Arduino_LCD::Arduino_LCD(uint8_t cs, uint8_t rs, uint8_t rst) { - _cs = cs; - _rs = rs; - _rst = rst; - hwSPI = true; - _sid = _sclk = 0; -} - - -inline void Arduino_LCD::spiwrite(uint8_t c) { - - //Serial.println(c, HEX); - -/* if (hwSPI) { - SPDR = c; - while(!(SPSR & _BV(SPIF))); - } else { - // Fast SPI bitbang swiped from LPD8806 library - for(uint8_t bit = 0x80; bit; bit >>= 1) { - if(c & bit) *dataport |= datapinmask; - else *dataport &= ~datapinmask; - *clkport |= clkpinmask; - *clkport &= ~clkpinmask; - } - } -*/ -SPI.transfer(c); -} - - -void Arduino_LCD::writecommand(uint8_t c) { -// *rsport &= ~rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, LOW); -digitalWrite(_cs, LOW); - - //Serial.print("C "); - spiwrite(c); -//SPI.transfer(c); -// *csport |= cspinmask; -digitalWrite(_cs, HIGH); -} - - -void Arduino_LCD::writedata(uint8_t c) { -// *rsport &= ~rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, HIGH); -digitalWrite(_cs, LOW); - - //Serial.print("D "); - spiwrite(c); -//SPI.transfer(c); -// *csport |= cspinmask; -digitalWrite(_cs, HIGH); -} - - -// Rather than a bazillion writecommand() and writedata() calls, screen -// initialization commands and arguments are organized in these tables -// stored in PROGMEM. The table may look bulky, but that's mostly the -// formatting -- storage-wise this is hundreds of bytes more compact -// than the equivalent code. Companion function follows. -#define DELAY 0x80 -//PROGMEM static prog_uchar -/*uint8_t - Bcmd[] = { // Initialization commands for 7735B screens - 18, // 18 commands in list: - ILI9163C_SWRESET, DELAY, // 1: Software reset, no args, w/delay - 50, // 50 ms delay - ILI9163C_SLPOUT , DELAY, // 2: Out of sleep mode, no args, w/delay - 255, // 255 = 500 ms delay - ILI9163C_COLMOD , 1+DELAY, // 3: Set color mode, 1 arg + delay: // I THINK THERE WAS SOMETHING HERE BECAUSE THE COMMAND IS CALLED 3A on Adafruits - 0x05, // 16-bit color - 10, // 10 ms delay - ILI9163C_FRMCTR1, 3+DELAY, // 4: Frame rate control, 3 args + delay: - 0x00, // fastest refresh - 0x06, // 6 lines front porch - 0x03, // 3 lines back porch - 10, // 10 ms delay - ILI9163C_MADCTL , 1 , // 5: Memory access ctrl (directions), 1 arg: - 0x08, // Row addr/col addr, bottom to top refresh - ILI9163C_DISSET5, 2 , // 6: Display settings #5, 2 args, no delay: - 0x15, // 1 clk cycle nonoverlap, 2 cycle gate - // rise, 3 cycle osc equalize - 0x02, // Fix on VTL - ILI9163C_INVCTR , 1 , // 7: Display inversion control, 1 arg: - 0x0, // Line inversion - ILI9163C_PWCTR1 , 2+DELAY, // 8: Power control, 2 args + delay: - 0x02, // GVDD = 4.7V - 0x70, // 1.0uA - 10, // 10 ms delay - ILI9163C_PWCTR2 , 1 , // 9: Power control, 1 arg, no delay: - 0x05, // VGH = 14.7V, VGL = -7.35V - ILI9163C_PWCTR3 , 2 , // 10: Power control, 2 args, no delay: - 0x01, // Opamp current small - 0x02, // Boost frequency - ILI9163C_VMCTR1 , 2+DELAY, // 11: Power control, 2 args + delay: - 0x3C, // VCOMH = 4V - 0x38, // VCOML = -1.1V - 10, // 10 ms delay - ILI9163C_PWCTR6 , 2 , // 12: Power control, 2 args, no delay: - 0x11, 0x15, - ILI9163C_GMCTRP1,16 , // 13: Magical unicorn dust, 16 args, no delay: - 0x09, 0x16, 0x09, 0x20, // (seriously though, not sure what - 0x21, 0x1B, 0x13, 0x19, // these config values represent) - 0x17, 0x15, 0x1E, 0x2B, - 0x04, 0x05, 0x02, 0x0E, - ILI9163C_GMCTRN1,16+DELAY, // 14: Sparkles and rainbows, 16 args + delay: - 0x0B, 0x14, 0x08, 0x1E, // (ditto) - 0x22, 0x1D, 0x18, 0x1E, - 0x1B, 0x1A, 0x24, 0x2B, - 0x06, 0x06, 0x02, 0x0F, - 10, // 10 ms delay - ILI9163C_CASET , 4 , // 15: Column addr set, 4 args, no delay: - 0x00, 0x02, // XSTART = 2 - 0x00, 0x81, // XEND = 129 - ILI9163C_RASET , 4 , // 16: Row addr set, 4 args, no delay: - 0x00, 0x02, // XSTART = 1 - 0x00, 0x81, // XEND = 160 - ILI9163C_NORON , DELAY, // 17: Normal display on, no args, w/delay - 10, // 10 ms delay - ILI9163C_DISPON , DELAY, // 18: Main screen turn on, no args, w/delay - 255 }, // 255 = 500 ms delay -*/ -uint8_t - Bcmd[] = { // Initialization commands for 7735B screens - 19, // 19 commands in list: - ILI9163C_SWRESET, DELAY, // 1: Software reset, no args, w/delay - 50, // 50 ms delay - 0x11 , DELAY, // 2: Out of sleep mode, no args, w/delay - 100, // 255 = 500 ms delay - 0x26 , 1, // 3: Set default gamma - 0x04, // 16-bit color - 0xb1, 2, // 4: Frame Rate - 0x0b, - 0x14, - 0xc0, 2, // 5: VRH1[4:0] & VC[2:0] - 0x08, - 0x00, - 0xc1, 1, // 6: BT[2:0] - 0x05, - 0xc5, 2, // 7: VMH[6:0] & VML[6:0] - 0x41, - 0x30, - 0xc7, 1, // 8: LCD Driving control - 0xc1, - 0xEC, 1, // 9: Set pumping color freq - 0x1b, - 0x3a , 1 + DELAY, // 10: Set color format - 0x55, // 16-bit color - 100, - 0x2a, 4, // 11: Set Column Address - 0x00, - 0x00, - 0x00, - 0x7f, - 0x2b, 4, // 12: Set Page Address - 0x00, - 0x00, - 0x00, - 0x9f, - 0x36, 1, // 12+1: Set Scanning Direction - 0xc8, - 0xb7, 1, // 14: Set Source Output Direciton - 0x00, - 0xf2, 1, // 15: Enable Gamma bit - 0x01, - 0xe0, 15 + DELAY, // 16: magic - 0x28, 0x24, 0x22, 0x31, - 0x2b, 0x0e, 0x53, 0xa5, - 0x42, 0x16, 0x18, 0x12, - 0x1a, 0x14, 0x03, - 50, - 0xe1, 15 + DELAY, // 17: more magic - 0x17, 0x1b, 0x1d, 0x0e, - 0x14, 0x11, 0x2c, 0xa5, - 0x3d, 0x09, 0x27, 0x2d, - 0x25, 0x2b, 0x3c, - 50, - ILI9163C_NORON , DELAY, // 18: Normal display on, no args, w/delay - 10, // 10 ms delay - ILI9163C_DISPON , DELAY, // 19: Main screen turn on, no args w/delay - 100 }, // 100 ms delay -Rcmd1[] = { // Init for 7735R, part 1 (red or green tab) - 15, // 15 commands in list: - ILI9163C_SWRESET, DELAY, // 1: Software reset, 0 args, w/delay - 150, // 150 ms delay - ILI9163C_SLPOUT , DELAY, // 2: Out of sleep mode, 0 args, w/delay - 255, // 500 ms delay - ILI9163C_FRMCTR1, 3 , // 3: Frame rate ctrl - normal mode, 3 args: - 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) - ILI9163C_FRMCTR2, 3 , // 4: Frame rate control - idle mode, 3 args: - 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) - ILI9163C_FRMCTR3, 6 , // 5: Frame rate ctrl - partial mode, 6 args: - 0x01, 0x2C, 0x2D, // Dot inversion mode - 0x01, 0x2C, 0x2D, // Line inversion mode - ILI9163C_INVCTR , 1 , // 6: Display inversion ctrl, 1 arg, no delay: - 0x07, // No inversion - ILI9163C_PWCTR1 , 3 , // 7: Power control, 3 args, no delay: - 0xA2, - 0x02, // -4.6V - 0x84, // AUTO mode - ILI9163C_PWCTR2 , 1 , // 8: Power control, 1 arg, no delay: - 0xC5, // VGH25 = 2.4C VGSEL = -10 VGH = 3 * AVDD - ILI9163C_PWCTR3 , 2 , // 9: Power control, 2 args, no delay: - 0x0A, // Opamp current small - 0x00, // Boost frequency - ILI9163C_PWCTR4 , 2 , // 10: Power control, 2 args, no delay: - 0x8A, // BCLK/2, Opamp current small & Medium low - 0x2A, - ILI9163C_PWCTR5 , 2 , // 11: Power control, 2 args, no delay: - 0x8A, 0xEE, - ILI9163C_VMCTR1 , 1 , // 12: Power control, 1 arg, no delay: - 0x0E, - ILI9163C_INVOFF , 0 , // 13: Don't invert display, no args, no delay - ILI9163C_MADCTL , 1 , // 14: Memory access control (directions), 1 arg: - 0xC8, // row addr/col addr, bottom to top refresh - ILI9163C_COLMOD , 1 , // 15: set color mode, 1 arg, no delay: - 0x05 }, // 16-bit color - - Rcmd2green[] = { // Init for 7735R, part 2 (green tab only) - 2, // 2 commands in list: - ILI9163C_CASET , 4 , // 1: Column addr set, 4 args, no delay: - 0x00, 0x02, // XSTART = 0 - 0x00, 0x7F+0x02, // XEND = 127 - ILI9163C_RASET , 4 , // 2: Row addr set, 4 args, no delay: - 0x00, 0x01, // XSTART = 0 - 0x00, 0x9F+0x01 }, // XEND = 159 - Rcmd2red[] = { // Init for 7735R, part 2 (red tab only) - 2, // 2 commands in list: - ILI9163C_CASET , 4 , // 1: Column addr set, 4 args, no delay: - 0x00, 0x00, // XSTART = 0 - 0x00, 0x7F, // XEND = 127 - ILI9163C_RASET , 4 , // 2: Row addr set, 4 args, no delay: - 0x00, 0x00, // XSTART = 0 - 0x00, 0x9F }, // XEND = 159 - - Rcmd3[] = { // Init for 7735R, part 3 (red or green tab) - 4, // 4 commands in list: - ILI9163C_GMCTRP1, 16 , // 1: Magical unicorn dust, 16 args, no delay: - 0x02, 0x1c, 0x07, 0x12, - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, - ILI9163C_GMCTRN1, 16 , // 2: Sparkles and rainbows, 16 args, no delay: - 0x03, 0x1d, 0x07, 0x06, - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, - ILI9163C_NORON , DELAY, // 3: Normal display on, no args, w/delay - 10, // 10 ms delay - ILI9163C_DISPON , DELAY, // 4: Main screen turn on, no args w/delay - 100 }; // 100 ms delay - - -// Companion code to the above tables. Reads and issues -// a series of LCD commands stored in PROGMEM byte array. -//void Arduino_LCD::commandList(prog_uchar *addr) { -void Arduino_LCD::commandList(uint8_t *addr) { - - uint8_t numCommands, numArgs; - uint16_t ms; - - numCommands = *addr++; // Number of commands to follow - while(numCommands--) { // For each command... - writecommand(*addr++); // Read, issue command - numArgs = *addr++; // Number of args to follow - ms = numArgs & DELAY; // If hibit set, delay follows args - numArgs &= ~DELAY; // Mask out delay bit - while(numArgs--) { // For each argument... - writedata(*addr++); // Read, issue argument - } - - if(ms) { - ms = *addr++; // Read post-command delay time (ms) - if(ms == 255) ms = 500; // If 255, delay for 500 ms - delay(ms); - } - } -} - - -// Initialization code common to both 'B' and 'R' type displays -//void Arduino_LCD::commonInit(prog_uchar *cmdList) { -void Arduino_LCD::commonInit(uint8_t *cmdList) { - - constructor(ILI9163C_TFTWIDTH, ILI9163C_TFTHEIGHT); - colstart = rowstart = 0; // May be overridden in init func - - pinMode(_rs, OUTPUT); - pinMode(_cs, OUTPUT); -/* - csport = portOutputRegister(digitalPinToPort(_cs)); - cspinmask = digitalPinToBitMask(_cs); - rsport = portOutputRegister(digitalPinToPort(_rs)); - rspinmask = digitalPinToBitMask(_rs); -*/ - -// if(hwSPI) { // Using hardware SPI - SPI.begin(); - SPI.setClockDivider(21); // 4 MHz (half speed) -// SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHz (half speed) -// SPI.setBitOrder(MSBFIRST); -// there is no setBitOrder on the SPI library for the Due - SPI.setDataMode(SPI_MODE0); -/* - } else { - pinMode(_sclk, OUTPUT); - pinMode(_sid , OUTPUT); - clkport = portOutputRegister(digitalPinToPort(_sclk)); - clkpinmask = digitalPinToBitMask(_sclk); - dataport = portOutputRegister(digitalPinToPort(_sid)); - datapinmask = digitalPinToBitMask(_sid); - *clkport &= ~clkpinmask; - *dataport &= ~datapinmask; - } -*/ - - // toggle RST low to reset; CS low so it'll listen to us -// *csport &= ~cspinmask; - digitalWrite(_cs, LOW); - if (_rst) { - pinMode(_rst, OUTPUT); - digitalWrite(_rst, HIGH); - delay(500); - digitalWrite(_rst, LOW); - delay(500); - digitalWrite(_rst, HIGH); - delay(500); - } - - if(cmdList) commandList(cmdList); -} - - -// Initialization for ST7735B screens -void Arduino_LCD::initB(void) { - commonInit(Bcmd); - commandList(Rcmd3); -} - - -// Initialization for ST7735R screens (green or red tabs) -void Arduino_LCD::initR(uint8_t options) { - commonInit(Rcmd1); - if(options == INITR_GREENTAB) { - commandList(Rcmd2green); - colstart = 2; - rowstart = 1; - } else { - // colstart, rowstart left at default '0' values - commandList(Rcmd2red); - } - commandList(Rcmd3); -} - - -void Arduino_LCD::setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, - uint8_t y1) { - - writecommand(ILI9163C_CASET); // Column addr set - writedata(0x00); - writedata(x0+colstart); // XSTART - writedata(0x00); - writedata(x1+colstart); // XEND - - writecommand(ILI9163C_RASET); // Row addr set - writedata(0x00); - writedata(y0+rowstart); // YSTART - writedata(0x00); - writedata(y1+rowstart); // YEND - - writecommand(ILI9163C_RAMWR); // write to RAM -} - - -void Arduino_LCD::fillScreen(uint16_t color) { - - uint8_t x, y, hi = color >> 8, lo = color; - - setAddrWindow(0, 0, _width-1, _height-1); - -// *rsport |= rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, HIGH); - digitalWrite(_cs, LOW); - - for(y=_height; y>0; y--) { - for(x=_width; x>0; x--) { -//SPI.transfer(hi); -//SPI.transfer(lo); - spiwrite(hi); - spiwrite(lo); - } - } - -// *csport |= cspinmask; - digitalWrite(_cs, HIGH); -} - - -void Arduino_LCD::pushColor(uint16_t color) { -// *rsport |= rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, HIGH); - digitalWrite(_cs, LOW); - - spiwrite(color >> 8); - spiwrite(color); -//SPI.transfer(color>>8); -//SPI.transfer(color); - -// *csport |= cspinmask; - digitalWrite(_cs, HIGH); -} - - -void Arduino_LCD::drawPixel(int16_t x, int16_t y, uint16_t color) { - - if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; - - setAddrWindow(x,y,x+1,y+1); - -// *rsport |= rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, HIGH); - digitalWrite(_cs, LOW); - - spiwrite(color >> 8); - spiwrite(color); -//SPI.transfer(color>>8); -//SPI.transfer(color); - -// *csport |= cspinmask; - digitalWrite(_cs, HIGH); -} - - -void Arduino_LCD::drawFastVLine(int16_t x, int16_t y, int16_t h, - uint16_t color) { - - // Rudimentary clipping - if((x >= _width) || (y >= _height)) return; - if((y+h-1) >= _height) h = _height-y; - setAddrWindow(x, y, x, y+h-1); - - uint8_t hi = color >> 8, lo = color; -// *rsport |= rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, HIGH); - digitalWrite(_cs, LOW); - while (h--) { - spiwrite(hi); - spiwrite(lo); -//SPI.transfer(hi); -//SPI.transfer(lo); - } -// *csport |= cspinmask; - digitalWrite(_cs, HIGH); -} - - -void Arduino_LCD::drawFastHLine(int16_t x, int16_t y, int16_t w, - uint16_t color) { - - // Rudimentary clipping - if((x >= _width) || (y >= _height)) return; - if((x+w-1) >= _width) w = _width-x; - setAddrWindow(x, y, x+w-1, y); - - uint8_t hi = color >> 8, lo = color; -// *rsport |= rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, HIGH); - digitalWrite(_cs, LOW); - while (w--) { - spiwrite(hi); - spiwrite(lo); -//SPI.transfer(hi); -//SPI.transfer(lo); - } -// *csport |= cspinmask; - digitalWrite(_cs, HIGH); -} - - -// fill a rectangle -void Arduino_LCD::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color) { - - // rudimentary clipping (drawChar w/big text requires this) - if((x >= _width) || (y >= _height)) return; - if((x + w - 1) >= _width) w = _width - x; - if((y + h - 1) >= _height) h = _height - y; - - setAddrWindow(x, y, x+w-1, y+h-1); - - uint8_t hi = color >> 8, lo = color; -// *rsport |= rspinmask; -// *csport &= ~cspinmask; -digitalWrite(_rs, HIGH); -digitalWrite(_cs, LOW); - for(y=h; y>0; y--) { - for(x=w; x>0; x--) { - spiwrite(hi); - spiwrite(lo); -//SPI.transfer(hi); -//SPI.transfer(lo); - } - } - -// *csport |= cspinmask; -digitalWrite(_cs, HIGH); -} - - -// Pass 8-bit (each) R,G,B, get back 16-bit packed color -uint16_t Arduino_LCD::Color565(uint8_t r, uint8_t g, uint8_t b) { - return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); -} - - -#define MADCTL_MY 0x80 -#define MADCTL_MX 0x40 -#define MADCTL_MV 0x20 -#define MADCTL_ML 0x10 -#define MADCTL_RGB 0x08 -#define MADCTL_MH 0x04 - -void Arduino_LCD::setRotation(uint8_t m) { - - writecommand(ILI9163C_MADCTL); - rotation = m % 4; // can't be higher than 3 - switch (rotation) { - case 0: - writedata(MADCTL_MX | MADCTL_MY | MADCTL_RGB); - _width = ILI9163C_TFTWIDTH; - _height = ILI9163C_TFTHEIGHT; - break; - case 1: - writedata(MADCTL_MY | MADCTL_MV | MADCTL_RGB); - _width = ILI9163C_TFTHEIGHT; - _height = ILI9163C_TFTWIDTH; - break; - case 2: - writedata(MADCTL_RGB); - _width = ILI9163C_TFTWIDTH; - _height = ILI9163C_TFTHEIGHT; - break; - case 3: - writedata(MADCTL_MX | MADCTL_MV | MADCTL_RGB); - _width = ILI9163C_TFTHEIGHT; - _height = ILI9163C_TFTWIDTH; - break; - } -} - - -void Arduino_LCD::invertDisplay(boolean i) { - writecommand(i ? ILI9163C_INVON : ILI9163C_INVOFF); -} - -/* - 18, // there are 17 commands - ILI9163C_SWRESET, DELAY, // 1: Software reset, no args, w/delay - 50, // 50 ms delay - - 0x11, //Exit Sleep - DELAY,50, - - 0x26, //Set Default Gamma - 0x104, - - //0xF2, //E0h & E1h Enable/Disable - //0x100, - - 0xB1, - 0x10C, - 0x114, - - 0xC0, //Set VRH1[4:0] & VC[2:0] for VCI1 & GVDD - 0x10C, - 0x105, - - 0xC1, //Set BT[2:0] for AVDD & VCL & VGH & VGL - 0x102, - - 0xC5, //Set VMH[6:0] & VML[6:0] for VOMH & VCOML - 0x129, - 0x143, - - 0xC7, - 0x140, - - 0x3a, //Set Color Format - 0x105, - - 0x2A, //Set Column Address - 0x100, - 0x100, - 0x100, - 0x17F, - - 0x2B, //Set Page Address - 0x100, - 0x100, - 0x100, - 0x19F, - - 0x36, //Set Scanning Direction, RGB - 0x1C0, - - 0xB7, //Set Source Output Direction - 0x100, - - 0xf2, //Enable Gamma bit - 0x101, - - 0xE0, - 0x136,//p1 - 0x129,//p2 - 0x112,//p3 - 0x122,//p4 - 0x11C,//p5 - 0x115,//p6 - 0x142,//p7 - 0x1B7,//p8 - 0x12F,//p9 - 0x113,//p10 - 0x112,//p11 - 0x10A,//p12 - 0x111,//p13 - 0x10B,//p14 - 0x106,//p15 - - 0xE1, - 0x109,//p1 - 0x116,//p2 - 0x12D,//p3 - 0x10D,//p4 - 0x113,//p5 - 0x115,//p6 - 0x140,//p7 - 0x148,//p8 - 0x153,//p9 - 0x10C,//p10 - 0x11D,//p11 - 0x125,//p12 - 0x12E,//p13 - 0x134,//p14 - 0x139,//p15 - - 0x33, // scroll setup - 0x100, - 0x100, - 0x100, - 0x1C1, - 0x100, - 0x100, - - 0x29, // Display On - 0x2C}, // write gram - -*/ - diff --git a/libraries/Robot_Control/Arduino_LCD.h b/libraries/Robot_Control/Arduino_LCD.h deleted file mode 100644 index a518133..0000000 --- a/libraries/Robot_Control/Arduino_LCD.h +++ /dev/null @@ -1,141 +0,0 @@ -/*************************************************** - This is a library for the Adafruit 1.8" SPI display. - This library works with the Adafruit 1.8" TFT Breakout w/SD card - ----> http://www.adafruit.com/products/358 - as well as Adafruit raw 1.8" TFT display - ----> http://www.adafruit.com/products/618 - - Check out the links above for our tutorials and wiring diagrams - These displays use SPI to communicate, 4 or 5 pins are required to - interface (RST is optional) - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - MIT license, all text above must be included in any redistribution - ****************************************************/ - -#ifndef _ARDUINO_LCDH_ -#define _ARDUINO_LCDH_ - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif -#include "Adafruit_GFX.h" -//#include - -// some flags for initR() :( -#define INITR_GREENTAB 0x0 -#define INITR_REDTAB 0x1 - -#define ILI9163C_TFTWIDTH 128 -#define ILI9163C_TFTHEIGHT 160 - -#define ILI9163C_NOP 0x00 -#define ILI9163C_SWRESET 0x01 -#define ILI9163C_RDDID 0x04 -#define ILI9163C_RDDST 0x09 - -#define ILI9163C_SLPIN 0x10 -#define ILI9163C_SLPOUT 0x11 -#define ILI9163C_PTLON 0x12 -#define ILI9163C_NORON 0x13 - -#define ILI9163C_INVOFF 0x20 -#define ILI9163C_INVON 0x21 -#define ILI9163C_DISPOFF 0x28 -#define ILI9163C_DISPON 0x29 -#define ILI9163C_CASET 0x2A -#define ILI9163C_RASET 0x2B -#define ILI9163C_RAMWR 0x2C -#define ILI9163C_RAMRD 0x2E - -#define ILI9163C_PTLAR 0x30 -#define ILI9163C_COLMOD 0x3A // this is interface pixel format, this might be the issue -#define ILI9163C_MADCTL 0x36 - -#define ILI9163C_FRMCTR1 0xB1 -#define ILI9163C_FRMCTR2 0xB2 -#define ILI9163C_FRMCTR3 0xB3 -#define ILI9163C_INVCTR 0xB4 -#define ILI9163C_DISSET5 0xB6 - -#define ILI9163C_PWCTR1 0xC0 -#define ILI9163C_PWCTR2 0xC1 -#define ILI9163C_PWCTR3 0xC2 -#define ILI9163C_PWCTR4 0xC3 -#define ILI9163C_PWCTR5 0xC4 -#define ILI9163C_VMCTR1 0xC5 - -#define ILI9163C_RDID1 0xDA -#define ILI9163C_RDID2 0xDB -#define ILI9163C_RDID3 0xDC -#define ILI9163C_RDID4 0xDD - -#define ILI9163C_PWCTR6 0xFC - -#define ILI9163C_GMCTRP1 0xE0 -#define ILI9163C_GMCTRN1 0xE1 - -// Color definitions -#define ILI9163C_BLACK 0x0000 -#define ILI9163C_BLUE 0x001F -#define ILI9163C_RED 0xF800 -#define ILI9163C_GREEN 0x07E0 -#define ILI9163C_CYAN 0x07FF -#define ILI9163C_MAGENTA 0xF81F -#define ILI9163C_YELLOW 0xFFE0 -#define ILI9163C_WHITE 0xFFFF - - -class Arduino_LCD : public Adafruit_GFX { - - public: - - Arduino_LCD(uint8_t CS, uint8_t RS, uint8_t SID, uint8_t SCLK, uint8_t RST); - Arduino_LCD(uint8_t CS, uint8_t RS, uint8_t RST); - - void initB(void), // for ST7735B displays - initR(uint8_t options = INITR_GREENTAB), // for ST7735R - setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1), - pushColor(uint16_t color), - fillScreen(uint16_t color), - drawPixel(int16_t x, int16_t y, uint16_t color), - drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), - drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), - fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), - setRotation(uint8_t r), - invertDisplay(boolean i); - uint16_t Color565(uint8_t r, uint8_t g, uint8_t b); - - /* These are not for current use, 8-bit protocol only! - uint8_t readdata(void), - readcommand8(uint8_t); - uint16_t readcommand16(uint8_t); - uint32_t readcommand32(uint8_t); - void dummyclock(void); - */ - - private: - - void spiwrite(uint8_t), - writecommand(uint8_t c), - writedata(uint8_t d), -// commandList(prog_uchar *addr), -// commonInit(prog_uchar *cmdList); - commandList(uint8_t *addr), - commonInit(uint8_t *cmdList); -//uint8_t spiread(void); - - boolean hwSPI; - volatile uint8_t *dataport, *clkport, *csport, *rsport; - uint8_t _cs, _rs, _rst, _sid, _sclk, - datapinmask, clkpinmask, cspinmask, rspinmask, - colstart, rowstart; // some displays need this changed -}; - -#endif diff --git a/libraries/Robot_Control/Compass.cpp b/libraries/Robot_Control/Compass.cpp deleted file mode 100644 index 1b1ef31..0000000 --- a/libraries/Robot_Control/Compass.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "Compass.h" -#include - -void Compass::begin(){ - Wire.begin(); -} -float Compass::getReading(){ - _beginTransmission(); - _endTransmission(); - - //time delays required by HMC6352 upon receipt of the command - //Get Data. Compensate and Calculate New Heading : 6ms - delay(6); - - Wire.requestFrom(HMC6352SlaveAddress, 2); //get the two data bytes, MSB and LSB - - //"The heading output data will be the value in tenths of degrees - //from zero to 3599 and provided in binary format over the two bytes." - byte MSB = Wire.read(); - byte LSB = Wire.read(); - - float headingSum = (MSB << 8) + LSB; //(MSB / LSB sum) - float headingInt = headingSum / 10; - - return headingInt; -} - -void Compass::_beginTransmission(){ - Wire.beginTransmission(HMC6352SlaveAddress); - Wire.write(HMC6352ReadAddress); -} -void Compass::_endTransmission(){ - Wire.endTransmission(); -} \ No newline at end of file diff --git a/libraries/Robot_Control/Compass.h b/libraries/Robot_Control/Compass.h deleted file mode 100644 index aa085a9..0000000 --- a/libraries/Robot_Control/Compass.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef Compass_h -#define Compass_h - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -//0x21==0x42>>1, from bildr's code -#define HMC6352SlaveAddress 0x21 -#define HMC6352ReadAddress 0x41 - -class Compass{ - public: - void begin(); - float getReading(); - private: - void _beginTransmission(); - void _endTransmission(); - -}; - -#endif \ No newline at end of file diff --git a/libraries/Robot_Control/EEPROM_I2C.cpp b/libraries/Robot_Control/EEPROM_I2C.cpp deleted file mode 100644 index dd12695..0000000 --- a/libraries/Robot_Control/EEPROM_I2C.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "EEPROM_I2C.h" -#include - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -void EEPROM_I2C::begin(){ - Wire.begin(); -} - -void EEPROM_I2C::writeByte(unsigned int eeaddress, byte data){ - int rdata = data; - this->_beginTransmission(eeaddress); - Wire.write(rdata); - this->_endTransmission(); -} - -byte EEPROM_I2C::readByte(unsigned int eeaddress){ - int rdata; - this->_beginTransmission(eeaddress); - this->_endTransmission(); - - Wire.requestFrom(DEVICEADDRESS,1); - if (Wire.available()) rdata = Wire.read(); - return rdata; -} - -void EEPROM_I2C::writePage(unsigned int eeaddress, byte* data, byte length ){ - this->_beginTransmission(eeaddress); - - byte c; - - for ( c = 0; c < length; c++) - Wire.write(data[c]); - - this->_endTransmission(); - - delay(10); // need some delay -} - -void EEPROM_I2C::readBuffer(unsigned int eeaddress, byte *buffer, int length ){ - this->_beginTransmission(eeaddress); - this->_endTransmission(); - Wire.requestFrom(DEVICEADDRESS,length); - - for ( int c = 0; c < length; c++ ) - if (Wire.available()) buffer[c] = Wire.read(); -} - - - -void EEPROM_I2C::_beginTransmission(unsigned int eeaddress){ - Wire.beginTransmission(DEVICEADDRESS); - Wire.write((eeaddress >> 8)); // Address High Byte - Wire.write((eeaddress & 0xFF)); // Address Low Byte -} -void EEPROM_I2C::_endTransmission(){ - Wire.endTransmission(); -} \ No newline at end of file diff --git a/libraries/Robot_Control/EEPROM_I2C.h b/libraries/Robot_Control/EEPROM_I2C.h deleted file mode 100644 index 9bd0f6a..0000000 --- a/libraries/Robot_Control/EEPROM_I2C.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef EEPROM_I2C_h -#define EEPROM_I2C_h - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -#define EE24LC512MAXBYTES 64000 -#define DEVICEADDRESS 0x50 - -class EEPROM_I2C{ - public: - void begin(); - - void writeByte(unsigned int eeaddresspage, byte data); - byte readByte(unsigned int eeaddresspage); - - void writePage(unsigned int eeaddresspage, byte* data, byte length ); - void readBuffer(unsigned int eeaddress, byte *buffer, int length ); - - //uint16_t readPixel(uint16_t theMemoryAddress); - //void readImage(uint16_t theMemoryAddress, int width, int height); - - protected: - void _beginTransmission(unsigned int eeaddress); - void _endTransmission(); -}; - -#endif \ No newline at end of file diff --git a/libraries/Robot_Control/EasyTransfer2.cpp b/libraries/Robot_Control/EasyTransfer2.cpp deleted file mode 100644 index 24427cc..0000000 --- a/libraries/Robot_Control/EasyTransfer2.cpp +++ /dev/null @@ -1,152 +0,0 @@ -#include "EasyTransfer2.h" - - - - -//Captures address and size of struct -void EasyTransfer2::begin(HardwareSerial *theSerial){ - _serial = theSerial; - - //dynamic creation of rx parsing buffer in RAM - //rx_buffer = (uint8_t*) malloc(size); - - resetData(); -} - -void EasyTransfer2::writeByte(uint8_t dat){ - if(position<20) - data[position++]=dat; - size++; -} -void EasyTransfer2::writeInt(int dat){ - if(position<19){ - data[position++]=dat>>8; - data[position++]=dat; - size+=2; - } -} -uint8_t EasyTransfer2::readByte(){ - if(position>=size)return 0; - return data[position++]; -} -int EasyTransfer2::readInt(){ - if(position+1>=size)return 0; - int dat_1=data[position++]<<8; - int dat_2=data[position++]; - int dat= dat_1 | dat_2; - return dat; -} - -void EasyTransfer2::resetData(){ - for(int i=0;i<20;i++){ - data[i]=0; - } - size=0; - position=0; -} - -//Sends out struct in binary, with header, length info and checksum -void EasyTransfer2::sendData(){ - uint8_t CS = size; - _serial->write(0x06); - _serial->write(0x85); - _serial->write(size); - for(int i = 0; iwrite(*(data+i)); - //Serial.print(*(data+i)); - //Serial.print(","); - } - //Serial.println(""); - _serial->write(CS); - - resetData(); -} - -boolean EasyTransfer2::receiveData(){ - - //start off by looking for the header bytes. If they were already found in a previous call, skip it. - if(rx_len == 0){ - //this size check may be redundant due to the size check below, but for now I'll leave it the way it is. - if(_serial->available() >= 3){ - //this will block until a 0x06 is found or buffer size becomes less then 3. - while(_serial->read() != 0x06) { - //This will trash any preamble junk in the serial buffer - //but we need to make sure there is enough in the buffer to process while we trash the rest - //if the buffer becomes too empty, we will escape and try again on the next call - if(_serial->available() < 3) - return false; - } - //Serial.println("head"); - if (_serial->read() == 0x85){ - rx_len = _serial->read(); - //Serial.print("rx_len:"); - //Serial.println(rx_len); - resetData(); - - //make sure the binary structs on both Arduinos are the same size. - /*if(rx_len != size){ - rx_len = 0; - return false; - }*/ - } - } - //Serial.println("nothing"); - } - - //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned. - if(rx_len != 0){ - - while(_serial->available() && rx_array_inx <= rx_len){ - data[rx_array_inx++] = _serial->read(); - } - - if(rx_len == (rx_array_inx-1)){ - //seem to have got whole message - //last uint8_t is CS - calc_CS = rx_len; - //Serial.print("len:"); - //Serial.println(rx_len); - for (int i = 0; i -* -*This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. -*To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or -*send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. -******************************************************************/ -#ifndef EasyTransfer2_h -#define EasyTransfer2_h - - -//make it a little prettier on the front end. -#define details(name) (byte*)&name,sizeof(name) - -//Not neccessary, but just in case. -#if ARDUINO > 22 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif -#include "HardwareSerial.h" -//#include -#include -#include -#include -#include - -class EasyTransfer2 { -public: -void begin(HardwareSerial *theSerial); -//void begin(uint8_t *, uint8_t, NewSoftSerial *theSerial); -void sendData(); -boolean receiveData(); - -void writeByte(uint8_t dat); -void writeInt(int dat); -uint8_t readByte(); -int readInt(); - - -private: -HardwareSerial *_serial; - -void resetData(); - -uint8_t data[20]; //data storage, for both read and send -uint8_t position; -uint8_t size; //size of data in bytes. Both for read and send -//uint8_t * address; //address of struct -//uint8_t size; //size of struct -//uint8_t * rx_buffer; //address for temporary storage and parsing buffer -//uint8_t rx_buffer[20]; -uint8_t rx_array_inx; //index for RX parsing buffer -uint8_t rx_len; //RX packet length according to the packet -uint8_t calc_CS; //calculated Chacksum -}; - - - -#endif \ No newline at end of file diff --git a/libraries/Robot_Control/Fat16.cpp b/libraries/Robot_Control/Fat16.cpp deleted file mode 100644 index aa8f585..0000000 --- a/libraries/Robot_Control/Fat16.cpp +++ /dev/null @@ -1,990 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ -#include -#if ARDUINO < 100 -#include -#else // ARDUINO -#include -#endif // ARDUINO -#include -//----------------------------------------------------------------------------- -// volume info -uint8_t Fat16::volumeInitialized_ = 0; // true if FAT16 volume is valid -uint8_t Fat16::fatCount_; // number of file allocation tables -uint8_t Fat16::blocksPerCluster_; // must be power of 2 -uint16_t Fat16::rootDirEntryCount_; // should be 512 for FAT16 -fat_t Fat16::blocksPerFat_; // number of blocks in one FAT -fat_t Fat16::clusterCount_; // total clusters in volume -uint32_t Fat16::fatStartBlock_; // start of first FAT -uint32_t Fat16::rootDirStartBlock_; // start of root dir -uint32_t Fat16::dataStartBlock_; // start of data clusters -//------------------------------------------------------------------------------ -// raw block cache -SdCard *Fat16::rawDev_ = 0; // class for block read and write -uint32_t Fat16::cacheBlockNumber_ = 0XFFFFFFFF; // init to invalid block number -cache16_t Fat16::cacheBuffer_; // 512 byte cache for SdCard -uint8_t Fat16::cacheDirty_ = 0; // cacheFlush() will write block if true -uint32_t Fat16::cacheMirrorBlock_ = 0; // mirror block for second FAT -//------------------------------------------------------------------------------ -// callback function for date/time -void (*Fat16::dateTime_)(uint16_t* date, uint16_t* time) = NULL; - -#if ALLOW_DEPRECATED_FUNCTIONS -void (*Fat16::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT -#endif // ALLOW_DEPRECATED_FUNCTIONS -//------------------------------------------------------------------------------ -// format 8.3 name for directory entry -static uint8_t make83Name(const char* str, uint8_t* name) { - uint8_t c; - uint8_t n = 7; // max index for part before dot - uint8_t i = 0; - // blank fill name and extension - while (i < 11) name[i++] = ' '; - i = 0; - while ((c = *str++) != '\0') { - if (c == '.') { - if (n == 10) return false; // only one dot allowed - n = 10; // max index for full 8.3 name - i = 8; // place for extension - } else { - // illegal FAT characters - PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); - uint8_t b; - while ((b = pgm_read_byte(p++))) if (b == c) return false; - // check length and only allow ASCII printable characters - if (i > n || c < 0X21 || c > 0X7E) return false; - // only upper case allowed in 8.3 names - convert lower to upper - name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a'); - } - } - // must have a file name, extension is optional - return name[0] != ' '; -} -//============================================================================== -// Fat16 member functions -//------------------------------------------------------------------------------ -uint8_t Fat16::addCluster(void) { - // start search after last cluster of file or at cluster two in FAT - fat_t freeCluster = curCluster_ ? curCluster_ : 1; - for (fat_t i = 0; ; i++) { - // return no free clusters - if (i >= clusterCount_) return false; - // Fat has clusterCount + 2 entries - if (freeCluster > clusterCount_) freeCluster = 1; - freeCluster++; - fat_t value; - if (!fatGet(freeCluster, &value)) return false; - if (value == 0) break; - } - // mark cluster allocated - if (!fatPut(freeCluster, FAT16EOC)) return false; - - if (curCluster_ != 0) { - // link cluster to chain - if (!fatPut(curCluster_, freeCluster)) return false; - } else { - // first cluster of file so update directory entry - flags_ |= F_FILE_DIR_DIRTY; - firstCluster_ = freeCluster; - } - curCluster_ = freeCluster; - return true; -} -//------------------------------------------------------------------------------ -// -dir_t* Fat16::cacheDirEntry(uint16_t index, uint8_t action) { - if (index >= rootDirEntryCount_) return NULL; - if (!cacheRawBlock(rootDirStartBlock_ + (index >> 4), action)) return NULL; - return &cacheBuffer_.dir[index & 0XF]; -} -//------------------------------------------------------------------------------ -// -uint8_t Fat16::cacheFlush(void) { - if (cacheDirty_) { - if (!rawDev_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) { - return false; - } - // mirror FAT tables - if (cacheMirrorBlock_) { - if (!rawDev_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) { - return false; - } - cacheMirrorBlock_ = 0; - } - cacheDirty_ = 0; - } - return true; -} -//------------------------------------------------------------------------------ -// -uint8_t Fat16::cacheRawBlock(uint32_t blockNumber, uint8_t action) { - if (cacheBlockNumber_ != blockNumber) { - if (!cacheFlush()) return false; - if (!rawDev_->readBlock(blockNumber, cacheBuffer_.data)) return false; - cacheBlockNumber_ = blockNumber; - } - cacheDirty_ |= action; - return true; -} -//------------------------------------------------------------------------------ -/** - * Close a file and force cached data and directory information - * to be written to the storage device. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * Reasons for failure include no file is open or an I/O error. - */ -uint8_t Fat16::close(void) { - if (!sync()) return false; - flags_ = 0; - return true; -} -//------------------------------------------------------------------------------ -/** - * Return a files directory entry - * - * \param[out] dir Location for return of the files directory entry. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - */ -uint8_t Fat16::dirEntry(dir_t* dir) { - if (!sync()) return false; - dir_t* p = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); - if (!p) return false; - memcpy(dir, p, sizeof(dir_t)); - return true; -} -//------------------------------------------------------------------------------ -uint8_t Fat16::fatGet(fat_t cluster, fat_t* value) { - if (cluster > (clusterCount_ + 1)) return false; - uint32_t lba = fatStartBlock_ + (cluster >> 8); - if (lba != cacheBlockNumber_) { - if (!cacheRawBlock(lba)) return false; - } - *value = cacheBuffer_.fat[cluster & 0XFF]; - return true; -} -//------------------------------------------------------------------------------ -uint8_t Fat16::fatPut(fat_t cluster, fat_t value) { - if (cluster < 2) return false; - if (cluster > (clusterCount_ + 1)) return false; - uint32_t lba = fatStartBlock_ + (cluster >> 8); - if (lba != cacheBlockNumber_) { - if (!cacheRawBlock(lba)) return false; - } - cacheBuffer_.fat[cluster & 0XFF] = value; - cacheSetDirty(); - // mirror second FAT - if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; - return true; -} -//------------------------------------------------------------------------------ -// free a cluster chain -uint8_t Fat16::freeChain(fat_t cluster) { - while (1) { - fat_t next; - if (!fatGet(cluster, &next)) return false; - if (!fatPut(cluster, 0)) return false; - if (isEOC(next)) return true; - cluster = next; - } -} -//------------------------------------------------------------------------------ -/** - * Initialize a FAT16 volume. - * - * \param[in] dev The SdCard where the volume is located. - * - * \param[in] part The partition to be used. Legal values for \a part are - * 1-4 to use the corresponding partition on a device formatted with - * a MBR, Master Boot Record, or zero if the device is formatted as - * a super floppy with the FAT boot sector in block zero. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. reasons for - * failure include not finding a valid FAT16 file system in the - * specified partition, a call to init() after a volume has - * been successful initialized or an I/O error. - * - */ -uint8_t Fat16::init(SdCard* dev, uint8_t part) { - // error if invalid partition - if (part > 4) return false; - rawDev_ = dev; - uint32_t volumeStartBlock = 0; - // if part == 0 assume super floppy with FAT16 boot sector in block zero - // if part > 0 assume mbr volume with partition table - if (part) { - if (!cacheRawBlock(volumeStartBlock)) return false; - volumeStartBlock = cacheBuffer_.mbr.part[part - 1].firstSector; - } - if (!cacheRawBlock(volumeStartBlock)) return false; - // check boot block signature - if (cacheBuffer_.data[510] != BOOTSIG0 || - cacheBuffer_.data[511] != BOOTSIG1) return false; - bpb_t* bpb = &cacheBuffer_.fbs.bpb; - fatCount_ = bpb->fatCount; - blocksPerCluster_ = bpb->sectorsPerCluster; - blocksPerFat_ = bpb->sectorsPerFat16; - rootDirEntryCount_ = bpb->rootDirEntryCount; - fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount; - rootDirStartBlock_ = fatStartBlock_ + bpb->fatCount*bpb->sectorsPerFat16; - dataStartBlock_ = rootDirStartBlock_ - + ((32*bpb->rootDirEntryCount + 511)/512); - uint32_t totalBlocks = bpb->totalSectors16 ? - bpb->totalSectors16 : bpb->totalSectors32; - clusterCount_ = (totalBlocks - (dataStartBlock_ - volumeStartBlock)) - /bpb->sectorsPerCluster; - // verify valid FAT16 volume - if (bpb->bytesPerSector != 512 // only allow 512 byte blocks - || bpb->sectorsPerFat16 == 0 // zero for FAT32 - || clusterCount_ < 4085 // FAT12 if true - || totalBlocks > 0X800000 // Max size for FAT16 volume - || bpb->reservedSectorCount == 0 // invalid volume - || bpb->fatCount == 0 // invalid volume - || bpb->sectorsPerFat16 < (clusterCount_ >> 8) // invalid volume - || bpb->sectorsPerCluster == 0 // invalid volume - // power of 2 test - || bpb->sectorsPerCluster & (bpb->sectorsPerCluster - 1)) { - // not a usable FAT16 bpb - return false; - } - volumeInitialized_ = 1; - return true; -} -//------------------------------------------------------------------------------ -/** List directory contents to Serial. - * - * \param[in] flags The inclusive OR of - * - * LS_DATE - %Print file modification date - * - * LS_SIZE - %Print file size. - */ -void Fat16::ls(uint8_t flags) { - dir_t d; - for (uint16_t index = 0; readDir(&d, &index, DIR_ATT_VOLUME_ID); index++) { - // print file name with possible blank fill - printDirName(d, flags & (LS_DATE | LS_SIZE) ? 14 : 0); - - // print modify date/time if requested - if (flags & LS_DATE) { - printFatDate(d.lastWriteDate); - Serial.write(' '); - printFatTime(d.lastWriteTime); - } - - // print size if requested - if (DIR_IS_FILE(&d) && (flags & LS_SIZE)) { - Serial.write(' '); - Serial.print(d.fileSize); - } - Serial.println(); - } -} -//------------------------------------------------------------------------------ -/** - * Open a file by file name. - * - * \note The file must be in the root directory and must have a DOS - * 8.3 name. - * - * \param[in] fileName A valid 8.3 DOS name for a file in the root directory. - * - * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive - * OR of flags from the following list - * - * O_READ - Open for reading. - * - * O_RDONLY - Same as O_READ. - * - * O_WRITE - Open for writing. - * - * O_WRONLY - Same as O_WRITE. - * - * O_RDWR - Open for reading and writing. - * - * O_APPEND - If set, the file offset shall be set to the end of the - * file prior to each write. - * - * O_CREAT - If the file exists, this flag has no effect except as noted - * under O_EXCL below. Otherwise, the file shall be created - * - * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. - * - * O_SYNC - Call sync() after each write. This flag should not be used with - * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. - * These functions do character a time writes so sync() will be called - * after each byte. - * - * O_TRUNC - If the file exists and is a regular file, and the file is - * successfully opened and is not read only, its length shall be truncated to 0. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * Reasons for failure include the FAT volume has not been initialized, - * a file is already open, \a fileName is invalid, the file does not exist, - * is a directory, or can't be opened in the access mode specified by oflag. - */ -uint8_t Fat16::open(const char* fileName, uint8_t oflag) { - uint8_t dname[11]; // name formated for dir entry - int16_t empty = -1; // index of empty slot - dir_t* p; // pointer to cached dir entry - - if (!volumeInitialized_ || isOpen()) return false; - - // error if invalid name - if (!make83Name(fileName, dname)) return false; - - for (uint16_t index = 0; index < rootDirEntryCount_; index++) { - if (!(p = cacheDirEntry(index))) return false; - if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { - // remember first empty slot - if (empty < 0) empty = index; - // done if no entries follow - if (p->name[0] == DIR_NAME_FREE) break; - } else if (!memcmp(dname, p->name, 11)) { - // don't open existing file if O_CREAT and O_EXCL - if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false; - - // open existing file - return open(index, oflag); - } - } - // error if directory is full - if (empty < 0) return false; - - // only create file if O_CREAT and O_WRITE - if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false; - - if (!(p = cacheDirEntry(empty, CACHE_FOR_WRITE))) return false; - - // initialize as empty file - memset(p, 0, sizeof(dir_t)); - memcpy(p->name, dname, 11); - - // set timestamps - if (dateTime_) { - // call user function - dateTime_(&p->creationDate, &p->creationTime); - } else { - // use default date/time - p->creationDate = FAT_DEFAULT_DATE; - p->creationTime = FAT_DEFAULT_TIME; - } - p->lastAccessDate = p->creationDate; - p->lastWriteDate = p->creationDate; - p->lastWriteTime = p->creationTime; - - // insure created directory entry will be written to storage device - if (!cacheFlush()) return false; - - // open entry - return open(empty, oflag); -} -//------------------------------------------------------------------------------ -/** - * Open a file by file index. - * - * \param[in] index The root directory index of the file to be opened. See \link - * Fat16::readDir() readDir()\endlink. - * - * \param[in] oflag See \link Fat16::open(const char*, uint8_t)\endlink. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * Reasons for failure include the FAT volume has not been initialized, - * a file is already open, \a index is invalid or is not the index of a - * file or the file cannot be opened in the access mode specified by oflag. - */ -uint8_t Fat16::open(uint16_t index, uint8_t oflag) { - if (!volumeInitialized_ || isOpen()) return false; - if ((oflag & O_TRUNC) && !(oflag & O_WRITE)) return false; - dir_t* d = cacheDirEntry(index); - // if bad file index or I/O error - if (!d) return false; - - // error if unused entry - if (d->name[0] == DIR_NAME_FREE || d->name[0] == DIR_NAME_DELETED) { - return false; - } - // error if long name, volume label or subdirectory - if ((d->attributes & (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)) != 0) { - return false; - } - // don't allow write or truncate if read-only - if (d->attributes & DIR_ATT_READ_ONLY) { - if (oflag & (O_WRITE | O_TRUNC)) return false; - } - - curCluster_ = 0; - curPosition_ = 0; - dirEntryIndex_ = index; - fileSize_ = d->fileSize; - firstCluster_ = d->firstClusterLow; - flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); - - if (oflag & O_TRUNC ) return truncate(0); - return true; -} -//------------------------------------------------------------------------------ -/** %Print the name field of a directory entry in 8.3 format to Serial. - * - * \param[in] dir The directory structure containing the name. - * \param[in] width Blank fill name if length is less than \a width. - */ -void Fat16::printDirName(const dir_t& dir, uint8_t width) { - uint8_t w = 0; - for (uint8_t i = 0; i < 11; i++) { - if (dir.name[i] == ' ') continue; - if (i == 8) { - Serial.write('.'); - w++; - } - Serial.write(dir.name[i]); - w++; - } - if (DIR_IS_SUBDIR(&dir)) { - Serial.write('/'); - w++; - } - while (w < width) { - Serial.write(' '); - w++; - } -} -//------------------------------------------------------------------------------ -/** %Print a directory date field to Serial. - * - * Format is yyyy-mm-dd. - * - * \param[in] fatDate The date field from a directory entry. - */ -void Fat16::printFatDate(uint16_t fatDate) { - Serial.print(FAT_YEAR(fatDate)); - Serial.write('-'); - printTwoDigits(FAT_MONTH(fatDate)); - Serial.write('-'); - printTwoDigits(FAT_DAY(fatDate)); -} -//------------------------------------------------------------------------------ -/** %Print a directory time field to Serial. - * - * Format is hh:mm:ss. - * - * \param[in] fatTime The time field from a directory entry. - */ -void Fat16::printFatTime(uint16_t fatTime) { - printTwoDigits(FAT_HOUR(fatTime)); - Serial.write(':'); - printTwoDigits(FAT_MINUTE(fatTime)); - Serial.write(':'); - printTwoDigits(FAT_SECOND(fatTime)); -} - -//------------------------------------------------------------------------------ -/** %Print a value as two digits to Serial. - * - * \param[in] v Value to be printed, 0 <= \a v <= 99 - */ -void Fat16::printTwoDigits(uint8_t v) { - char str[3]; - str[0] = '0' + v/10; - str[1] = '0' + v % 10; - str[2] = 0; - Serial.print(str); -} -//------------------------------------------------------------------------------ -/** - * Read the next byte from a file. - * - * \return For success read returns the next byte in the file as an int. - * If an error occurs or end of file is reached -1 is returned. - */ -int16_t Fat16::read(void) { - uint8_t b; - return read(&b, 1) == 1 ? b : -1; -} -//------------------------------------------------------------------------------ -/** - * Read data from a file at starting at the current file position. - * - * \param[out] buf Pointer to the location that will receive the data. - * - * \param[in] nbyte Maximum number of bytes to read. - * - * \return For success read returns the number of bytes read. - * A value less than \a nbyte, including zero, may be returned - * if end of file is reached. - * If an error occurs, read returns -1. Possible errors include - * read called before a file has been opened, the file has not been opened in - * read mode, a corrupt file system, or an I/O error. - */ -int16_t Fat16::read(void* buf, uint16_t nbyte) { - // convert void pointer to uin8_t pointer - uint8_t* dst = reinterpret_cast(buf); - - // error if not open for read - if (!(flags_ & O_READ)) return -1; - - // don't read beyond end of file - if ((curPosition_ + nbyte) > fileSize_) nbyte = fileSize_ - curPosition_; - - // bytes left to read in loop - uint16_t nToRead = nbyte; - while (nToRead > 0) { - uint8_t blkOfCluster = blockOfCluster(curPosition_); - uint16_t blockOffset = cacheDataOffset(curPosition_); - if (blkOfCluster == 0 && blockOffset == 0) { - // start next cluster - if (curCluster_ == 0) { - curCluster_ = firstCluster_; - } else { - if (!fatGet(curCluster_, &curCluster_)) return -1; - } - // return error if bad cluster chain - if (curCluster_ < 2 || isEOC(curCluster_)) return -1; - } - // cache data block - if (!cacheRawBlock(dataBlockLba(curCluster_, blkOfCluster))) return -1; - - // location of data in cache - uint8_t* src = cacheBuffer_.data + blockOffset; - - // max number of byte available in block - uint16_t n = 512 - blockOffset; - - // lesser of available and amount to read - if (n > nToRead) n = nToRead; - - // copy data to caller - memcpy(dst, src, n); - - curPosition_ += n; - dst += n; - nToRead -= n; - } - return nbyte; -} -//------------------------------------------------------------------------------ -/** - * Read the next short, 8.3, directory entry. - * - * Unused entries and entries for long names are skipped. - * - * \param[out] dir Location that will receive the entry. - * - * \param[in,out] index The search starts at \a index and \a index is - * updated with the root directory index of the found directory entry. - * If the entry is a file, it may be opened by calling - * \link Fat16::open(uint16_t, uint8_t) \endlink. - * - * \param[in] skip Skip entries that have these attributes. If \a skip - * is not specified, the default is to skip the volume label and directories. - * - * \return The value one, true, is returned for success and the value zero, - * false, is returned if an error occurs or the end of the root directory is - * reached. On success, \a entry is set to the index of the found directory - * entry. - */ -uint8_t Fat16::readDir(dir_t* dir, uint16_t* index, uint8_t skip) { - dir_t* p; - for (uint16_t i = *index; ; i++) { - if (i >= rootDirEntryCount_) return false; - if (!(p = cacheDirEntry(i))) return false; - - // done if beyond last used entry - if (p->name[0] == DIR_NAME_FREE) return false; - - // skip deleted entry - if (p->name[0] == DIR_NAME_DELETED) continue; - - // skip long names - if ((p->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME) continue; - - // skip if attribute match - if (p->attributes & skip) continue; - - // return found index - *index = i; - break; - } - memcpy(dir, p, sizeof(dir_t)); - return true; -} -//------------------------------------------------------------------------------ -/** - * Remove a file. The directory entry and all data for the file are deleted. - * - * \note This function should not be used to delete the 8.3 version of a - * file that has a long name. For example if a file has the long name - * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * Reasons for failure include the file is not open for write - * or an I/O error occurred. - */ -uint8_t Fat16::remove(void) { - // error if file is not open for write - if (!(flags_ & O_WRITE)) return false; - if (firstCluster_) { - if (!freeChain(firstCluster_)) return false; - } - dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); - if (!d) return false; - d->name[0] = DIR_NAME_DELETED; - flags_ = 0; - return cacheFlush(); -} -//------------------------------------------------------------------------------ -/** - * Remove a file. - * - * The directory entry and all data for the file are deleted. - * - * \param[in] fileName The name of the file to be removed. - * - * \note This function should not be used to delete the 8.3 version of a - * file that has a long name. For example if a file has the long name - * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * Reasons for failure include the file is read only, \a fileName is not found - * or an I/O error occurred. - */ -uint8_t Fat16::remove(const char* fileName) { - Fat16 file; - if (!file.open(fileName, O_WRITE)) return false; - return file.remove(); -} -//------------------------------------------------------------------------------ -/** - * Sets the file's read/write position. - * - * \param[in] pos The new position in bytes from the beginning of the file. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - */ -uint8_t Fat16::seekSet(uint32_t pos) { - // error if file not open or seek past end of file - if (!isOpen() || pos > fileSize_) return false; - if (pos == 0) { - // set position to start of file - curCluster_ = 0; - curPosition_ = 0; - return true; - } - fat_t n = ((pos - 1) >> 9)/blocksPerCluster_; - if (pos < curPosition_ || curPosition_ == 0) { - // must follow chain from first cluster - curCluster_ = firstCluster_; - } else { - // advance from curPosition - n -= ((curPosition_ - 1) >> 9)/blocksPerCluster_; - } - while (n--) { - if (!fatGet(curCluster_, &curCluster_)) return false; - } - curPosition_ = pos; - return true; -} -//------------------------------------------------------------------------------ -/** - * The sync() call causes all modified data and directory fields - * to be written to the storage device. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * Reasons for failure include a call to sync() before a file has been - * opened or an I/O error. - */ -uint8_t Fat16::sync(void) { - if (flags_ & F_FILE_DIR_DIRTY) { - // cache directory entry - dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); - if (!d) return false; - - // update file size and first cluster - d->fileSize = fileSize_; - d->firstClusterLow = firstCluster_; - - // set modify time if user supplied a callback date/time function - if (dateTime_) { - dateTime_(&d->lastWriteDate, &d->lastWriteTime); - d->lastAccessDate = d->lastWriteDate; - } - flags_ &= ~F_FILE_DIR_DIRTY; - } - return cacheFlush(); -} -//------------------------------------------------------------------------------ -/** - * The timestamp() call sets a file's timestamps in its directory entry. - * - * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive - * OR of flags from the following list - * - * T_ACCESS - Set the file's last access date. - * - * T_CREATE - Set the file's creation date and time. - * - * T_WRITE - Set the file's last write/modification date and time. - * - * \param[in] year Valid range 1980 - 2107 inclusive. - * - * \param[in] month Valid range 1 - 12 inclusive. - * - * \param[in] day Valid range 1 - 31 inclusive. - * - * \param[in] hour Valid range 0 - 23 inclusive. - * - * \param[in] minute Valid range 0 - 59 inclusive. - * - * \param[in] second Valid range 0 - 59 inclusive - * - * \note It is possible to set an invalid date since there is no check for - * the number of days in a month. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - */ -uint8_t Fat16::timestamp(uint8_t flags, uint16_t year, uint8_t month, - uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { - if (!isOpen() - || year < 1980 - || year > 2107 - || month < 1 - || month > 12 - || day < 1 - || day > 31 - || hour > 23 - || minute > 59 - || second > 59) { - return false; - } - dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE); - if (!d) return false; - uint16_t dirDate = FAT_DATE(year, month, day); - uint16_t dirTime = FAT_TIME(hour, minute, second); - if (flags & T_ACCESS) { - d->lastAccessDate = dirDate; - } - if (flags & T_CREATE) { - d->creationDate = dirDate; - d->creationTime = dirTime; - // seems to be units of 1/100 second not 1/10 as Microsoft standard states - d->creationTimeTenths = second & 1 ? 100 : 0; - } - if (flags & T_WRITE) { - d->lastWriteDate = dirDate; - d->lastWriteTime = dirTime; - } - cacheSetDirty(); - return sync(); -} -//------------------------------------------------------------------------------ -/** - * Truncate a file to a specified length. The current file position - * will be maintained if it is less than or equal to \a length otherwise - * it will be set to end of file. - * - * \param[in] length The desired length for the file. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * Reasons for failure include file is read only, file is a directory, - * \a length is greater than the current file size or an I/O error occurs. - */ -uint8_t Fat16::truncate(uint32_t length) { - // error if file is not open for write - if (!(flags_ & O_WRITE)) return false; - - if (length > fileSize_) return false; - - // fileSize and length are zero - nothing to do - if (fileSize_ == 0) return true; - uint32_t newPos = curPosition_ > length ? length : curPosition_; - if (length == 0) { - // free all clusters - if (!freeChain(firstCluster_)) return false; - curCluster_ = firstCluster_ = 0; - } else { - fat_t toFree; - if (!seekSet(length)) return false; - if (!fatGet(curCluster_, &toFree)) return false; - if (!isEOC(toFree)) { - // free extra clusters - if (!fatPut(curCluster_, FAT16EOC)) return false; - if (!freeChain(toFree)) return false; - } - } - fileSize_ = length; - flags_ |= F_FILE_DIR_DIRTY; - if (!sync()) return false; - return seekSet(newPos); -} -//------------------------------------------------------------------------------ -/** - * Write data at the current position of an open file. - * - * \note Data is moved to the cache but may not be written to the - * storage device until sync() is called. - * - * \param[in] buf Pointer to the location of the data to be written. - * - * \param[in] nbyte Number of bytes to write. - * - * \return For success write() returns the number of bytes written, always - * \a nbyte. If an error occurs, write() returns -1. Possible errors include - * write() is called before a file has been opened, the file has not been opened - * for write, device is full, a corrupt file system or an I/O error. - * - */ -int16_t Fat16::write(const void* buf, uint16_t nbyte) { - uint16_t nToWrite = nbyte; - const uint8_t* src = reinterpret_cast(buf); - - // error if file is not open for write - if (!(flags_ & O_WRITE)) goto writeErrorReturn; - - // go to end of file if O_APPEND - if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { - if (!seekEnd()) goto writeErrorReturn; - } - while (nToWrite > 0) { - uint8_t blkOfCluster = blockOfCluster(curPosition_); - uint16_t blockOffset = cacheDataOffset(curPosition_); - if (blkOfCluster == 0 && blockOffset == 0) { - // start of new cluster - if (curCluster_ == 0) { - if (firstCluster_ == 0) { - // allocate first cluster of file - if (!addCluster()) goto writeErrorReturn; - } else { - curCluster_ = firstCluster_; - } - } else { - fat_t next; - if (!fatGet(curCluster_, &next)) goto writeErrorReturn; - if (isEOC(next)) { - // add cluster if at end of chain - if (!addCluster()) goto writeErrorReturn; - } else { - curCluster_ = next; - } - } - } - uint32_t lba = dataBlockLba(curCluster_, blkOfCluster); - if (blockOffset == 0 && curPosition_ >= fileSize_) { - // start of new block don't need to read into cache - if (!cacheFlush()) goto writeErrorReturn; - cacheBlockNumber_ = lba; - cacheSetDirty(); - } else { - // rewrite part of block - if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return -1; - } - uint8_t* dst = cacheBuffer_.data + blockOffset; - - // max space in block - uint16_t n = 512 - blockOffset; - - // lesser of space and amount to write - if (n > nToWrite) n = nToWrite; - - // copy data to cache - memcpy(dst, src, n); - - curPosition_ += n; - nToWrite -= n; - src += n; - } - if (curPosition_ > fileSize_) { - // update fileSize and insure sync will update dir entry - fileSize_ = curPosition_; - flags_ |= F_FILE_DIR_DIRTY; - } else if (dateTime_ && nbyte) { - // insure sync will update modified date and time - flags_ |= F_FILE_DIR_DIRTY; - } - - if (flags_ & O_SYNC) { - if (!sync()) goto writeErrorReturn; - } - return nbyte; - - writeErrorReturn: - writeError = true; - return -1; -} -//------------------------------------------------------------------------------ -/** - * Write a byte to a file. Required by the Arduino Print class. - * - * Use Fat16::writeError to check for errors. - */ -#if ARDUINO < 100 -void Fat16::write(uint8_t b) { - write(&b, 1); -} -#else // ARDUINO < 100 -size_t Fat16::write(uint8_t b) { - return write(&b, 1) == 1 ? 1 : 0; -} -#endif // ARDUINO < 100 -//------------------------------------------------------------------------------ -/** - * Write a string to a file. Used by the Arduino Print class. - * - * Use Fat16::writeError to check for errors. - */ -#if ARDUINO < 100 -void Fat16::write(const char* str) { - write(str, strlen(str)); -} -#else // ARDUINO < 100 -int16_t Fat16::write(const char* str) { - return write(str, strlen(str)); -} -#endif // ARDUINO < 100 -//------------------------------------------------------------------------------ -/** - * Write a PROGMEM string to a file. - * - * Use Fat16::writeError to check for errors. - */ -void Fat16::write_P(PGM_P str) { - for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c); -} -//------------------------------------------------------------------------------ -/** - * Write a PROGMEM string followed by CR/LF to a file. - * - * Use Fat16::writeError to check for errors. - */ -void Fat16::writeln_P(PGM_P str) { - write_P(str); - println(); -} diff --git a/libraries/Robot_Control/Fat16.h b/libraries/Robot_Control/Fat16.h deleted file mode 100644 index 935b9b0..0000000 --- a/libraries/Robot_Control/Fat16.h +++ /dev/null @@ -1,378 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ -#ifndef Fat16_h -#define Fat16_h -/** - * \file - * Fat16 class - */ -#include -#include -#include -#include -#include -#include -//------------------------------------------------------------------------------ -/** Fat16 version YYYYMMDD */ -#define FAT16_VERSION 20111205 -//------------------------------------------------------------------------------ -// flags for ls() -/** ls() flag to print modify date */ -uint8_t const LS_DATE = 1; -/** ls() flag to print file size */ -uint8_t const LS_SIZE = 2; - -// use the gnu style oflags -/** open for reading */ -uint8_t const O_READ = 0X01; -/** same as O_READ */ -uint8_t const O_RDONLY = O_READ; -/** open for write */ -uint8_t const O_WRITE = 0X02; -/** same as O_WRITE */ -uint8_t const O_WRONLY = O_WRITE; -/** open for reading and writing */ -uint8_t const O_RDWR = O_READ | O_WRITE; -/** mask for access modes */ -uint8_t const O_ACCMODE = O_READ | O_WRITE; -/** The file offset shall be set to the end of the file prior to each write. */ -uint8_t const O_APPEND = 0X04; -/** synchronous writes - call sync() after each write */ -uint8_t const O_SYNC = 0X08; -/** create the file if nonexistent */ -uint8_t const O_CREAT = 0X10; -/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */ -uint8_t const O_EXCL = 0X20; -/** truncate the file to zero length */ -uint8_t const O_TRUNC = 0X40; - -// flags for timestamp -/** set the file's last access date */ -uint8_t const T_ACCESS = 1; -/** set the file's creation date and time */ -uint8_t const T_CREATE = 2; -/** Set the file's write date and time */ -uint8_t const T_WRITE = 4; - -/** date field for FAT directory entry */ -static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { - return (year - 1980) << 9 | month << 5 | day; -} -/** year part of FAT directory date field */ -static inline uint16_t FAT_YEAR(uint16_t fatDate) { - return 1980 + (fatDate >> 9); -} -/** month part of FAT directory date field */ -static inline uint8_t FAT_MONTH(uint16_t fatDate) { - return (fatDate >> 5) & 0XF; -} -/** day part of FAT directory date field */ -static inline uint8_t FAT_DAY(uint16_t fatDate) { - return fatDate & 0X1F; -} -/** time field for FAT directory entry */ -static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { - return hour << 11 | minute << 5 | second >> 1; -} -/** hour part of FAT directory time field */ -static inline uint8_t FAT_HOUR(uint16_t fatTime) { - return fatTime >> 11; -} -/** minute part of FAT directory time field */ -static inline uint8_t FAT_MINUTE(uint16_t fatTime) { - return(fatTime >> 5) & 0X3F; -} -/** second part of FAT directory time field */ -static inline uint8_t FAT_SECOND(uint16_t fatTime) { - return 2*(fatTime & 0X1F); -} -/** Default date for file timestamps is 1 Jan 2000 */ -uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; -/** Default time for file timestamp is 1 am */ -uint16_t const FAT_DEFAULT_TIME = (1 << 11); -//------------------------------------------------------------------------------ -/** - * \typedef fat_t - * - * \brief Type for FAT16 entry - */ -typedef uint16_t fat_t; -/** - * \union cache16_t - * - * \brief Cache buffer data type - * - */ -union cache16_t { - /** Used to access cached file data blocks. */ - uint8_t data[512]; - /** Used to access cached FAT entries. */ - fat_t fat[256]; - /** Used to access cached directory entries. */ - dir_t dir[16]; - /** Used to access a cached Master Boot Record. */ - mbr_t mbr; - /** Used to access to a cached FAT16 boot sector. */ - fbs_t fbs; -}; -//------------------------------------------------------------------------------ -/** \class Fat16 - * \brief Fat16 implements a minimal Arduino FAT16 Library - * - * Fat16 does not support subdirectories or long file names. - */ -class Fat16 : public Print { - public: - /* - * Public functions - */ - /** create with file closed */ - Fat16(void) : flags_(0) {} - /** \return The current cluster number. */ - fat_t curCluster(void) const {return curCluster_;} - uint8_t close(void); - /** \return The count of clusters in the FAT16 volume. */ - static fat_t clusterCount(void) {return clusterCount_;} - /** \return The number of 512 byte blocks in a cluster */ - static uint8_t clusterSize(void) {return blocksPerCluster_;} - /** \return The current file position. */ - uint32_t curPosition(void) const {return curPosition_;} - /** - * Set the date/time callback function - * - * \param[in] dateTime The user's callback function. The callback - * function is of the form: - * - * \code - * void dateTime(uint16_t* date, uint16_t* time) { - * uint16_t year; - * uint8_t month, day, hour, minute, second; - * - * // User gets date and time from GPS or real-time clock here - * - * // return date using FAT_DATE macro to format fields - * *date = FAT_DATE(year, month, day); - * - * // return time using FAT_TIME macro to format fields - * *time = FAT_TIME(hour, minute, second); - * } - * \endcode - * - * Sets the function that is called when a file is created or when - * a file's directory entry is modified by sync(). All timestamps, - * access, creation, and modify, are set when a file is created. - * sync() maintains the last access date and last modify date/time. - * - * See the timestamp() function. - */ - static void dateTimeCallback( - void (*dateTime)(uint16_t* date, uint16_t* time)) { - dateTime_ = dateTime; - } - /** - * Cancel the date/time callback function. - */ - static void dateTimeCallbackCancel(void) {dateTime_ = NULL;} - uint8_t dirEntry(dir_t* dir); - - /** \return The file's size in bytes. */ - uint32_t fileSize(void) const {return fileSize_;} - static uint8_t init(SdCard* dev, uint8_t part); - /** - * Initialize a FAT16 volume. - * - * First try partition 1 then try super floppy format. - * - * \param[in] dev The SdCard where the volume is located. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. reasons for - * failure include not finding a valid FAT16 file system, a call - * to init() after a volume has been successful initialized or - * an I/O error. - * - */ - static uint8_t init(SdCard* dev) { - return init(dev, 1) ? true : init(dev, 0); - } - /** - * Checks the file's open/closed status for this instance of Fat16. - * \return The value true if a file is open otherwise false; - */ - uint8_t isOpen(void) const {return (flags_ & O_ACCMODE) != 0;} - static void ls(uint8_t flags = 0); - uint8_t open(const char* fileName, uint8_t oflag); - uint8_t open(uint16_t entry, uint8_t oflag); - static void printDirName(const dir_t& dir, uint8_t width); - static void printFatDate(uint16_t fatDate); - static void printFatTime(uint16_t fatTime); - static void printTwoDigits(uint8_t v); - int16_t read(void); - int16_t read(void* buf, uint16_t nbyte); - static uint8_t readDir(dir_t* dir, uint16_t* index, - uint8_t skip = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)); - - uint8_t remove(void); - static uint8_t remove(const char* fileName); - /** Sets the file's current position to zero. */ - void rewind(void) {curPosition_ = curCluster_ = 0;} - /** \return The number of entries in the root directory. */ - static uint16_t rootDirEntryCount(void) {return rootDirEntryCount_;} - /** Seek to current position plus \a pos bytes. See Fat16::seekSet(). */ - uint8_t seekCur(uint32_t pos) {return seekSet(curPosition_ + pos);} - /** Seek to end of file. See Fat16::seekSet(). */ - uint8_t seekEnd(void) {return seekSet(fileSize_);} - uint8_t seekSet(uint32_t pos); - uint8_t sync(void); - uint8_t timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, - uint8_t hour, uint8_t minute, uint8_t second); - uint8_t truncate(uint32_t size); - /** Fat16::writeError is set to true if an error occurs during a write(). - * Set Fat16::writeError to false before calling print() and/or write() and check - * for true after calls to write() and/or print(). - */ - bool writeError; - int16_t write(const void *buf, uint16_t nbyte); -#if ARDUINO < 100 - void write(uint8_t b); - void write(const char* str); -#else // ARDUINO < 100 - size_t write(uint8_t b); - int16_t write(const char* str); -#endif // ARDUINO < 100 - void write_P(PGM_P str); - void writeln_P(PGM_P str); -//------------------------------------------------------------------------------ -#if FAT16_DEBUG_SUPPORT - /** For debug only. Do not use in applications. */ - static cache16_t* dbgBufAdd(void) {return &cacheBuffer_;} - /** For debug only. Do not use in applications. */ - static void dbgSetDev(SdCard* dev) {rawDev_ = dev;} - /** For debug only. Do not use in applications. */ - static uint8_t* dbgCacheBlock(uint32_t blockNumber) { - return cacheRawBlock(blockNumber) ? cacheBuffer_.data : 0; } - /** For debug only. Do not use in applications. */ - static dir_t* dbgCacheDir(uint16_t index) { - return cacheDirEntry(index);} -#endif // FAT16_DEBUG_SUPPORT -//------------------------------------------------------------------------------ -#if ALLOW_DEPRECATED_FUNCTIONS -// Deprecated functions - suppress cpplint messages with NOLINT comment - public: - /** - * Deprecated - Use: - * static void Fat16::dateTimeCallback( - * void (*dateTime)(uint16_t* date, uint16_t* time)); - */ - static void dateTimeCallback( - void (*dateTime)(uint16_t& date, uint16_t& time)) { // NOLINT - oldDateTime_ = dateTime; - dateTime_ = dateTime ? oldToNew : 0; - } - /** Deprecated - Use: uint8_t Fat16::dirEntry(dir_t* dir); */ - uint8_t dirEntry(dir_t& dir) { // NOLINT - return dirEntry(&dir); - } - /** Deprecated - Use: static uint8_t Fat16::init(SdCard *dev); */ - static uint8_t init(SdCard& dev) {return init(&dev);} // NOLINT - - /** Deprecated - Use: static uint8_t Fat16::init(SdCard *dev, uint8_t part) */ - static uint8_t init(SdCard& dev, uint8_t part) { // NOLINT - return init(&dev, part); - } - /** - * Deprecated - Use: - * uint8_t Fat16::readDir(dir_t* dir, uint16_t* index, uint8_t skip); - */ - static uint8_t readDir(dir_t& dir, uint16_t& index, // NOLINT - uint8_t skip = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)) { - return readDir(&dir, &index, skip); - } -//------------------------------------------------------------------------------ - private: - static void (*oldDateTime_)(uint16_t& date, uint16_t& time); // NOLINT - static void oldToNew(uint16_t *date, uint16_t *time) { - uint16_t d; - uint16_t t; - oldDateTime_(d, t); - *date = d; - *time = t; - } -#endif // ALLOW_DEPRECATED_FUNCTIONS -//------------------------------------------------------------------------------ - private: - // Volume info - static uint8_t volumeInitialized_; // true if volume has been initialized - static uint8_t fatCount_; // number of FATs - static uint8_t blocksPerCluster_; // must be power of 2 - static uint16_t rootDirEntryCount_; // should be 512 for FAT16 - static fat_t blocksPerFat_; // number of blocks in one FAT - static fat_t clusterCount_; // total clusters in volume - static uint32_t fatStartBlock_; // start of first FAT - static uint32_t rootDirStartBlock_; // start of root dir - static uint32_t dataStartBlock_; // start of data clusters - - // block cache - static uint8_t const CACHE_FOR_READ = 0; // cache a block for read - static uint8_t const CACHE_FOR_WRITE = 1; // cache a block and set dirty - static SdCard *rawDev_; // Device - static cache16_t cacheBuffer_; // 512 byte cache for raw blocks - static uint32_t cacheBlockNumber_; // Logical number of block in the cache - static uint8_t cacheDirty_; // cacheFlush() will write block if true - static uint32_t cacheMirrorBlock_; // mirror block for second FAT - - // callback function for date/time - static void (*dateTime_)(uint16_t* date, uint16_t* time); - - // define fields in flags_ - static uint8_t const F_OFLAG = O_ACCMODE | O_APPEND | O_SYNC; - static uint8_t const F_FILE_DIR_DIRTY = 0X80; // require sync directory entry - - uint8_t flags_; // see above for bit definitions - int16_t dirEntryIndex_; // index of directory entry for open file - fat_t firstCluster_; // first cluster of file - uint32_t fileSize_; // fileSize - fat_t curCluster_; // current cluster - uint32_t curPosition_; // current byte offset - - // private functions for cache - static uint8_t blockOfCluster(uint32_t position) { - // depends on blocks per cluster being power of two - return (position >> 9) & (blocksPerCluster_ - 1); - } - static uint16_t cacheDataOffset(uint32_t position) {return position & 0X1FF;} - static dir_t* cacheDirEntry(uint16_t index, uint8_t action = 0); - static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action = 0); - static uint8_t cacheFlush(void); - static void cacheSetDirty(void) {cacheDirty_ |= CACHE_FOR_WRITE;} - static uint32_t dataBlockLba(fat_t cluster, uint8_t blockOfCluster) { - return dataStartBlock_ + (uint32_t)(cluster - 2) * blocksPerCluster_ - + blockOfCluster; - } - static uint8_t fatGet(fat_t cluster, fat_t* value); - static uint8_t fatPut(fat_t cluster, fat_t value); - // end of chain test - static uint8_t isEOC(fat_t cluster) {return cluster >= 0XFFF8;} - // allocate a cluster to a file - uint8_t addCluster(void); - // free a cluster chain - uint8_t freeChain(fat_t cluster); -}; -#endif // Fat16_h diff --git a/libraries/Robot_Control/Fat16Config.h b/libraries/Robot_Control/Fat16Config.h deleted file mode 100644 index d598b56..0000000 --- a/libraries/Robot_Control/Fat16Config.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ - /** - * \file - * Configuration file - */ -#ifndef Fat16Config_h -#define Fat16Config_h -/** - * Allow use of deprecated functions if non-zero - */ -#define ALLOW_DEPRECATED_FUNCTIONS 1 -/** - * SdCard::writeBlock will protect block zero if set non-zero - */ -#define SD_PROTECT_BLOCK_ZERO 1 -/** - * Set non-zero to allow access to Fat16 internals by cardInfo debug sketch - */ -#define FAT16_DEBUG_SUPPORT 1 -#endif // Fat16Config_h diff --git a/libraries/Robot_Control/Fat16mainpage.h b/libraries/Robot_Control/Fat16mainpage.h deleted file mode 100644 index 2c4f773..0000000 --- a/libraries/Robot_Control/Fat16mainpage.h +++ /dev/null @@ -1,208 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ - -/** -\mainpage Arduino Fat16 Library -
Copyright © 2008 by William Greiman -
- -\section Intro Introduction -The Arduino Fat16 Library is a minimal implementation of the FAT16 file system -on standard SD flash memory cards. Fat16 supports read, write, file -creation, deletion, and truncation. - -The Fat16 class only supports access to files in the root directory and only -supports short 8.3 names. Directory time and date fields for creation -and modification can be maintained by providing a date/time callback -function \link Fat16::dateTimeCallback() dateTimeCallback()\endlink -or calling \link Fat16::timestamp() timestamp()\endlink. - -Fat16 was designed to use the Arduino Print class which -allows files to be written with \link Print::print() print() \endlink and -\link Print::println() println()\endlink. - -\section comment Bugs and Comments - -If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. - - -\section SDcard SD Cards - -Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and -most consumer devices use the 4-bit parallel SD protocol. A card that -functions well on A PC or Mac may not work well on the Arduino. - -Most cards have good SPI read performance but cards vary widely in SPI -write performance. Write performance is limited by how efficiently the -card manages internal erase/remapping operations. The Arduino cannot -optimize writes to reduce erase operations because of its limit RAM. - -SanDisk cards generally have good write performance. They seem to have -more internal RAM buffering than other cards and therefore can limit -the number of flash erase operations that the Arduino forces due to its -limited RAM. - -Some Dane-Elec cards have a write speed that is only 20% as fast as -a good SanDisk card. - - -\section Hardware Hardware Configuration -Fat16 was developed using an Adafruit Industries - GPS Shield. - -The hardware interface to the SD card should not use a resistor based level -shifter. SdCard::init() sets the SPI bus frequency to 8 MHz which results in -signal rise times that are too slow for the edge detectors in many newer SD card -controllers when resistor voltage dividers are used. - -The 5 to 3.3 V level shifter for 5 V arduinos should be IC based like the -74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield -uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the -74LCX245. - -If you are using a resistor based level shifter and are having problems try -setting the SPI bus frequency to 4 MHz. This can be done by using -card.init(true) to initialize the SD card. - - -\section Fat16Class Fat16 Usage - -The class Fat16 is a minimal implementation of FAT16 on standard SD cards. -High Capacity SD cards, SDHC, are not supported. It should work on all -standard cards from 8MB to 2GB formatted with a FAT16 file system. - -\note - The Arduino Print class uses character -at a time writes so it was necessary to use a \link Fat16::sync() sync() \endlink -function to control when data is written to the SD card. - -\par -An application which writes to a file using \link Print::print() print()\endlink, -\link Print::println() println() \endlink -or \link Fat16::write write() \endlink must call \link Fat16::sync() sync() \endlink -at the appropriate time to force data and directory information to be written -to the SD Card. Data and directory information are also written to the SD card -when \link Fat16::close() close() \endlink is called. - -\par -Applications must use care calling \link Fat16::sync() sync() \endlink -since 2048 bytes of I/O is required to update file and -directory information. This includes writing the current data block, reading -the block that contains the directory entry for update, writing the directory -block back and reading back the current data block. - -Fat16 only supports access to files in the root directory and only supports -short 8.3 names. - -It is possible to open a file with two or more instances of Fat16. A file may -be corrupted if data is written to the file by more than one instance of Fat16. - -Short names are limited to 8 characters followed by an optional period (.) -and extension of up to 3 characters. The characters may be any combination -of letters and digits. The following special characters are also allowed: - -$ % ' - _ @ ~ ` ! ( ) { } ^ # & - -Short names are always converted to upper case and their original case -value is lost. - -Fat16 uses a slightly restricted form of short names. -Only printable ASCII characters are supported. No characters with code point -values greater than 127 are allowed. Space is not allowed even though space -was allowed in the API of early versions of DOS. - -Fat16 has been optimized for The Arduino ATmega168. Minimizing RAM use is the -highest priority goal followed by flash use and finally performance. -Most SD cards only support 512 byte block write operations so a 512 byte -cache buffer is used by Fat16. This is the main use of RAM. A small -amount of RAM is used to store key volume and file information. -Flash memory usage can be controlled by selecting options in Fat16Config.h. - -\section HowTo How to format SD Cards as FAT16 Volumes - -Microsoft operating systems support removable media formatted with a -Master Boot Record, MBR, or formatted as a super floppy with a FAT Boot Sector -in block zero. - -Microsoft operating systems expect MBR formatted removable media -to have only one partition. The first partition should be used. - -Microsoft operating systems do not support partitioning SD flash cards. -If you erase an SD card with a program like KillDisk, Most versions of -Windows will format the card as a super floppy. - -The best way to restore an SD card's MBR is to use SDFormatter -which can be downloaded from: - -http://www.sdcard.org/consumers/formatter/ - -SDFormatter does not have an option for FAT type so it may format -small cards as FAT12. - -After the MBR is restored by SDFormatter you may need to reformat small -cards that have been formatted FAT12 to force the volume type to be FAT16. - -The FAT type, FAT12, FAT16, or FAT32, is determined by the count -of clusters on the volume and nothing else. - -Microsoft published the following code for determining FAT type: - -\code -if (CountOfClusters < 4085) { - // Volume is FAT12 -} -else if (CountOfClusters < 65525) { - // Volume is FAT16 -} -else { - // Volume is FAT32 -} - -\endcode -If you format a FAT volume with an OS utility , choose a cluster size that -will result in: - -4084 < CountOfClusters && CountOfClusters < 65525 - -The volume will then be FAT16. - -If you are formatting an SD card on OS X or Linux, be sure to use the first -partition. Format this partition with a cluster count in above range. - -\section References References - -The Arduino site: - -http://www.arduino.cc/ - -For more information about FAT file systems see: - -http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx - -For information about using SD cards as SPI devices see: - -http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf - -The ATmega328 datasheet: - -http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf - - - */ \ No newline at end of file diff --git a/libraries/Robot_Control/Fat16util.h b/libraries/Robot_Control/Fat16util.h deleted file mode 100644 index 1fea068..0000000 --- a/libraries/Robot_Control/Fat16util.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef Fat16util_h -#define Fat16util_h -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ -/** - * \file - * Useful utility functions. - */ -#if ARDUINO < 100 -#include -#else // ARDUINO -#include -#endif // ARDUINO -#include -/** Store and print a string in flash memory.*/ -#define PgmPrint(x) SerialPrint_P(PSTR(x)) -/** Store and print a string in flash memory followed by a CR/LF.*/ -#define PgmPrintln(x) SerialPrintln_P(PSTR(x)) -/** Defined so doxygen works for function definitions. */ -#define NOINLINE __attribute__((noinline)) -//------------------------------------------------------------------------------ -/** Return the number of bytes currently free in RAM. */ -static int FreeRam(void) { - extern int __bss_end; - extern int* __brkval; - int free_memory; - if (reinterpret_cast(__brkval) == 0) { - // if no heap use from end of bss section - free_memory = reinterpret_cast(&free_memory) - - reinterpret_cast(&__bss_end); - } else { - // use from top of stack to heap - free_memory = reinterpret_cast(&free_memory) - - reinterpret_cast(__brkval); - } - return free_memory; -} -//------------------------------------------------------------------------------ -/** - * %Print a string in flash memory to the serial port. - * - * \param[in] str Pointer to string stored in flash memory. - */ -static NOINLINE void SerialPrint_P(PGM_P str) { - for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.write(c); -} -//------------------------------------------------------------------------------ -/** - * %Print a string in flash memory followed by a CR/LF. - * - * \param[in] str Pointer to string stored in flash memory. - */ -static NOINLINE void SerialPrintln_P(PGM_P str) { - SerialPrint_P(str); - Serial.println(); -} -#endif // #define Fat16util_h diff --git a/libraries/Robot_Control/FatStructs.h b/libraries/Robot_Control/FatStructs.h deleted file mode 100644 index 431bf30..0000000 --- a/libraries/Robot_Control/FatStructs.h +++ /dev/null @@ -1,418 +0,0 @@ -/* Arduino Fat16 Library - * Copyright (C) 2009 by William Greiman - * - * This file is part of the Arduino Fat16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ -#ifndef FatStructs_h -#define FatStructs_h -/** - * \file - * FAT file structures - */ -/* - * mostly from Microsoft document fatgen103.doc - * http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx - */ -//------------------------------------------------------------------------------ -/** Value for byte 510 of boot block or MBR */ -uint8_t const BOOTSIG0 = 0X55; -/** Value for byte 511 of boot block or MBR */ -uint8_t const BOOTSIG1 = 0XAA; -//------------------------------------------------------------------------------ -/** - * \struct partitionTable - * \brief MBR partition table entry - * - * A partition table entry for a MBR formatted storage device. - * The MBR partition table has four entries. - */ -struct partitionTable { - /** - * Boot Indicator . Indicates whether the volume is the active - * partition. Legal values include: 0X00. Do not use for booting. - * 0X80 Active partition. - */ - uint8_t boot; - /** - * Head part of Cylinder-head-sector address of the first block in - * the partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t beginHead; - /** - * Sector part of Cylinder-head-sector address of the first block in - * the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned beginSector : 6; - /** High bits cylinder for first block in partition. */ - unsigned beginCylinderHigh : 2; - /** - * Combine beginCylinderLow with beginCylinderHigh. Legal values - * are 0-1023. Only used in old PC BIOS. - */ - uint8_t beginCylinderLow; - /** - * Partition type. See defines that begin with PART_TYPE_ for - * some Microsoft partition types. - */ - uint8_t type; - /** - * head part of cylinder-head-sector address of the last sector in the - * partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t endHead; - /** - * Sector part of cylinder-head-sector address of the last sector in - * the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned endSector : 6; - /** High bits of end cylinder */ - unsigned endCylinderHigh : 2; - /** - * Combine endCylinderLow with endCylinderHigh. Legal values - * are 0-1023. Only used in old PC BIOS. - */ - uint8_t endCylinderLow; - /** Logical block address of the first block in the partition. */ - uint32_t firstSector; - /** Length of the partition, in blocks. */ - uint32_t totalSectors; -}; -/** Type name for partitionTable */ -typedef struct partitionTable part_t; -//------------------------------------------------------------------------------ -/** - * \struct masterBootRecord - * - * \brief Master Boot Record - * - * The first block of a storage device that is formatted with a MBR. - */ -struct masterBootRecord { - /** Code Area for master boot program. */ - uint8_t codeArea[440]; - /** Optional WindowsNT disk signature. May contain more boot code. */ - uint32_t diskSignature; - /** Usually zero but may be more boot code. */ - uint16_t usuallyZero; - /** Partition tables. */ - part_t part[4]; - /** First MBR signature byte. Must be 0X55 */ - uint8_t mbrSig0; - /** Second MBR signature byte. Must be 0XAA */ - uint8_t mbrSig1; -}; -/** Type name for masterBootRecord */ -typedef struct masterBootRecord mbr_t; -//------------------------------------------------------------------------------ -/** - * \struct biosParmBlock - * - * \brief BIOS parameter block - * - * The BIOS parameter block describes the physical layout of a FAT volume. - */ -struct biosParmBlock { - /** - * Count of bytes per sector. This value may take on only the - * following values: 512, 1024, 2048 or 4096 - */ - uint16_t bytesPerSector; - /** - * Number of sectors per allocation unit. This value must be a - * power of 2 that is greater than 0. The legal values are - * 1, 2, 4, 8, 16, 32, 64, and 128. - */ - uint8_t sectorsPerCluster; - /** - * Number of sectors before the first FAT. - * This value must not be zero. - */ - uint16_t reservedSectorCount; - /** The count of FAT data structures on the volume. This field should - * always contain the value 2 for any FAT volume of any type. - */ - uint8_t fatCount; - /** - * For FAT12 and FAT16 volumes, this field contains the count of - * 32-byte directory entries in the root directory. For FAT32 volumes, - * this field must be set to 0. For FAT12 and FAT16 volumes, this - * value should always specify a count that when multiplied by 32 - * results in a multiple of bytesPerSector. FAT16 volumes should - * use the value 512. - */ - uint16_t rootDirEntryCount; - /** - * This field is the old 16-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then totalSectors32 - * must be non-zero. For FAT32 volumes, this field must be 0. For - * FAT12 and FAT16 volumes, this field contains the sector count, and - * totalSectors32 is 0 if the total sector count fits - * (is less than 0x10000). - */ - uint16_t totalSectors16; - /** - * This dates back to the old MS-DOS 1.x media determination and is - * no longer usually used for anything. 0xF8 is the standard value - * for fixed (non-removable) media. For removable media, 0xF0 is - * frequently used. Legal values are 0xF0 or 0xF8-0xFF. - */ - uint8_t mediaType; - /** - * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. - * On FAT32 volumes this field must be 0, and sectorsPerFat32 - * contains the FAT size count. - */ - uint16_t sectorsPerFat16; - /** Sectors per track for interrupt 0x13. Not used otherwise. */ - uint16_t sectorsPerTrtack; - /** Number of heads for interrupt 0x13. Not used otherwise. */ - uint16_t headCount; - /** - * Count of hidden sectors preceding the partition that contains this - * FAT volume. This field is generally only relevant for media - * visible on interrupt 0x13. - */ - uint32_t hidddenSectors; - /** - * This field is the new 32-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then - * totalSectors16 must be non-zero. - */ - uint32_t totalSectors32; - /** - * Count of sectors occupied by one FAT on FAT32 volumes. - */ - uint32_t sectorsPerFat32; - /** - * This field is only defined for FAT32 media and does not exist on - * FAT12 and FAT16 media. - * Bits 0-3 -- Zero-based number of active FAT. - * Only valid if mirroring is disabled. - * Bits 4-6 -- Reserved. - * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. - * -- 1 means only one FAT is active; it is the one referenced in bits 0-3. - * Bits 8-15 -- Reserved. - */ - uint16_t fat32Flags; - /** - * FAT32 version. High byte is major revision number. - * Low byte is minor revision number. Only 0.0 define. - */ - uint16_t fat32Version; - /** - * Cluster number of the first cluster of the root directory for FAT32. - * This usually 2 but not required to be 2. - */ - uint32_t fat32RootCluster; - /** - * Sector number of FSINFO structure in the reserved area of the - * FAT32 volume. Usually 1. - */ - uint16_t fat32FSInfo; - /** - * If non-zero, indicates the sector number in the reserved area - * of the volume of a copy of the boot record. Usually 6. - * No value other than 6 is recommended. - */ - uint16_t fat32BackBootBlock; - /** - * Reserved for future expansion. Code that formats FAT32 volumes - * should always set all of the bytes of this field to 0. - */ - uint8_t fat32Reserved[12]; -}; -/** Type name for biosParmBlock */ -typedef struct biosParmBlock bpb_t; -//------------------------------------------------------------------------------ -/** - * \struct fat32BootSector - * - * \brief Boot sector for a FAT16 or FAT32 volume. - * - */ -struct fat32BootSector { - /** X86 jmp to boot program */ - uint8_t jmpToBootCode[3]; - /** informational only - don't depend on it */ - char oemName[8]; - /** BIOS Parameter Block */ - bpb_t bpb; - /** for int0x13 use value 0X80 for hard drive */ - uint8_t driveNumber; - /** used by Windows NT - should be zero for FAT */ - uint8_t reserved1; - /** 0X29 if next three fields are valid */ - uint8_t bootSignature; - /** usually generated by combining date and time */ - uint32_t volumeSerialNumber; - /** should match volume label in root dir */ - char volumeLabel[11]; - /** informational only - don't depend on it */ - char fileSystemType[8]; - /** X86 boot code */ - uint8_t bootCode[420]; - /** must be 0X55 */ - uint8_t bootSectorSig0; - /** must be 0XAA */ - uint8_t bootSectorSig1; -}; -//------------------------------------------------------------------------------ -// End Of Chain values for FAT entries -/** FAT16 end of chain value used by Microsoft. */ -uint16_t const FAT16EOC = 0XFFFF; -/** Minimum value for FAT16 EOC. Use to test for EOC. */ -uint16_t const FAT16EOC_MIN = 0XFFF8; -/** FAT32 end of chain value used by Microsoft. */ -uint32_t const FAT32EOC = 0X0FFFFFFF; -/** Minimum value for FAT32 EOC. Use to test for EOC. */ -uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; -/** Mask a for FAT32 entry. Entries are 28 bits. */ -uint32_t const FAT32MASK = 0X0FFFFFFF; - -/** Type name for fat32BootSector */ -typedef struct fat32BootSector fbs_t; -//------------------------------------------------------------------------------ -/** - * \struct directoryEntry - * \brief FAT short directory entry - * - * Short means short 8.3 name, not the entry size. - * - * Date Format. A FAT directory entry date stamp is a 16-bit field that is - * basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the - * format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the - * 16-bit word): - * - * Bits 9-15: Count of years from 1980, valid value range 0-127 - * inclusive (1980-2107). - * - * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. - * - * Bits 0-4: Day of month, valid value range 1-31 inclusive. - * - * Time Format. A FAT directory entry time stamp is a 16-bit field that has - * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the - * 16-bit word, bit 15 is the MSB of the 16-bit word). - * - * Bits 11-15: Hours, valid value range 0-23 inclusive. - * - * Bits 5-10: Minutes, valid value range 0-59 inclusive. - * - * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). - * - * The valid time range is from Midnight 00:00:00 to 23:59:58. - */ -struct directoryEntry { - /** - * Short 8.3 name. - * The first eight bytes contain the file name with blank fill. - * The last three bytes contain the file extension with blank fill. - */ - uint8_t name[11]; - /** Entry attributes. - * - * The upper two bits of the attribute byte are reserved and should - * always be set to 0 when a file is created and never modified or - * looked at after that. See defines that begin with DIR_ATT_. - */ - uint8_t attributes; - /** - * Reserved for use by Windows NT. Set value to 0 when a file is - * created and never modify or look at it after that. - */ - uint8_t reservedNT; - /** - * The granularity of the seconds part of creationTime is 2 seconds - * so this field is a count of tenths of a second and its valid - * value range is 0-199 inclusive. (WHG note - seems to be hundredths) - */ - uint8_t creationTimeTenths; - /** Time file was created. */ - uint16_t creationTime; - /** Date file was created. */ - uint16_t creationDate; - /** - * Last access date. Note that there is no last access time, only - * a date. This is the date of last read or write. In the case of - * a write, this should be set to the same date as lastWriteDate. - */ - uint16_t lastAccessDate; - /** - * High word of this entry's first cluster number (always 0 for a - * FAT12 or FAT16 volume). - */ - uint16_t firstClusterHigh; - /** Time of last write. File creation is considered a write. */ - uint16_t lastWriteTime; - /** Date of last write. File creation is considered a write. */ - uint16_t lastWriteDate; - /** Low word of this entry's first cluster number. */ - uint16_t firstClusterLow; - /** 32-bit unsigned holding this file's size in bytes. */ - uint32_t fileSize; -}; -//------------------------------------------------------------------------------ -// Definitions for directory entries -// -/** Type name for directoryEntry */ -typedef struct directoryEntry dir_t; -/** escape for name[0] = 0XE5 */ -uint8_t const DIR_NAME_0XE5 = 0X05; -/** name[0] value for entry that is free after being "deleted" */ -uint8_t const DIR_NAME_DELETED = 0XE5; -/** name[0] value for entry that is free and no allocated entries follow */ -uint8_t const DIR_NAME_FREE = 0X00; -/** file is read-only */ -uint8_t const DIR_ATT_READ_ONLY = 0X01; -/** File should hidden in directory listings */ -uint8_t const DIR_ATT_HIDDEN = 0X02; -/** Entry is for a system file */ -uint8_t const DIR_ATT_SYSTEM = 0X04; -/** Directory entry contains the volume label */ -uint8_t const DIR_ATT_VOLUME_ID = 0X08; -/** Entry is for a directory */ -uint8_t const DIR_ATT_DIRECTORY = 0X10; -/** Old DOS archive bit for backup support */ -uint8_t const DIR_ATT_ARCHIVE = 0X20; -/** Test value for long name entry. Test is - (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ -uint8_t const DIR_ATT_LONG_NAME = 0X0F; -/** Test mask for long name entry */ -uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; -/** defined attribute bits */ -uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; -/** Directory entry is part of a long name */ -static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { - return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; -} -/** Mask for file/subdirectory tests */ -uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); -/** Directory entry is for a file */ -static inline uint8_t DIR_IS_FILE(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; -} -/** Directory entry is for a subdirectory */ -static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; -} -/** Directory entry is for a file or subdirectory */ -static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; -} -#endif // FatStructs_h diff --git a/libraries/Robot_Control/Melody.cpp b/libraries/Robot_Control/Melody.cpp deleted file mode 100644 index 0341c55..0000000 --- a/libraries/Robot_Control/Melody.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#include "ArduinoRobot.h" -#include "SquawkSD.h" -#include "Fat16.h" - - - -SQUAWK_CONSTRUCT_ISR(SQUAWK_PWM_PIN5); - - -void RobotControl::beginSpeaker(uint16_t frequency){ - SquawkSynth::begin(frequency); - SquawkSynth::play(); - osc[2].vol = 0x7F; -} - -void RobotControl::playNote(byte period, word length, char modifier) { - // Modifier . makes note length 2/3 - if(modifier == '.') length = (length * 2) / 3; - // Set up the play frequency, 352800 is [sample_rate]=44100 * [tuning]=8.0 - osc[2].freq = 352800 / period; - // Delay, silence, delay - delay(length); - osc[2].freq = 0; - delay(length); -} - -void RobotControl::playMelody(char* script){ - // Find length of play string - word length = strlen(script); - // Set the default note time - word time = 500; - // Loop through each character in the play string - for(int n = 0; n < length; n++) { - // Fetch the character AFTER the current one - it may contain a modifier - char modifier = script[n + 1]; - // Fetch the current character and branch accordingly - switch(script[n]) { - // Notes - case 'c': playNote(214, time, modifier); break; // Play a C - case 'C': playNote(202, time, modifier); break; // Play a C# - case 'd': playNote(190, time, modifier); break; // Play a D - case 'D': playNote(180, time, modifier); break; // Play a D# - case 'e': playNote(170, time, modifier); break; // Play an F - case 'f': playNote(160, time, modifier); break; // Play an F - case 'F': playNote(151, time, modifier); break; // Play an F# - case 'g': playNote(143, time, modifier); break; // Play a G - case 'G': playNote(135, time, modifier); break; // Play a G# - case 'a': playNote(127, time, modifier); break; // Play an A - case 'A': playNote(120, time, modifier); break; // Play an A# - case 'b': playNote(113, time, modifier); break; // Play a B - // Delay - case '-': playNote(0, time, modifier); break; // Play a quiet note - // Note lengths - case '1': time = 1000; break; // Full note - case '2': time = 500; break; // Half note - case '4': time = 250; break; // Quarter note - case '8': time = 50; break; // Eigth note - // Modifier '.' makes note length 2/3 - - } - } -} - -void RobotControl::beep(int beep_length){ - char scr1[]="8F"; - char scr2[]="8Fe"; - char scr3[]="1F"; - - switch (beep_length) - { - case BEEP_SIMPLE: - default: - playMelody(scr1); - break; - - case BEEP_DOUBLE: - playMelody(scr2); - break; - - case BEEP_LONG: - playMelody(scr3); - } - -} - -void RobotControl::tempoWrite(int tempo){ - SquawkSynthSD::tempo(tempo); -} -void RobotControl::tuneWrite(float tune){ - SquawkSynthSD::tune(tune); -} - -void RobotControl::playFile(char* filename){ - melody.open(filename,O_READ); - SquawkSynthSD::play(melody); -} - -void RobotControl::stopPlayFile(){ - melody.close(); -} \ No newline at end of file diff --git a/libraries/Robot_Control/Motors.cpp b/libraries/Robot_Control/Motors.cpp deleted file mode 100644 index 9d5e8b0..0000000 --- a/libraries/Robot_Control/Motors.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "ArduinoRobot.h" #include "EasyTransfer2.h" void RobotControl::motorsStop(){ messageOut.writeByte(COMMAND_MOTORS_STOP); messageOut.sendData(); } void RobotControl::motorsWrite(int speedLeft,int speedRight){ messageOut.writeByte(COMMAND_RUN); messageOut.writeInt(speedLeft); messageOut.writeInt(speedRight); messageOut.sendData(); } void RobotControl::motorsWritePct(int speedLeftPct, int speedRightPct){ int16_t speedLeft=255*speedLeftPct; int16_t speedRight=255*speedRightPct; motorsWrite(speedLeft,speedRight); } void RobotControl::pointTo(int angle){ int target=angle; uint8_t speed=80; target=target%360; if(target<0){ target+=360; } int direction=angle; while(1){ if(direction>0){ motorsWrite(speed,-speed);//right delay(10); }else{ motorsWrite(-speed,speed);//left delay(10); } int currentAngle=compassRead(); int diff=target-currentAngle; if(diff<-180) diff += 360; else if(diff> 180) diff -= 360; direction=-diff; if(abs(diff)<5){ motorsWrite(0,0); return; } } } void RobotControl::turn(int angle){ int originalAngle=compassRead(); int target=originalAngle+angle; pointTo(target); /*uint8_t speed=80; target=target%360; if(target<0){ target+=360; } int direction=angle; while(1){ if(direction>0){ motorsWrite(speed,speed);//right delay(10); }else{ motorsWrite(-speed,-speed);//left delay(10); } int currentAngle=compassRead(); int diff=target-currentAngle; if(diff<-180) diff += 360; else if(diff> 180) diff -= 360; direction=-diff; if(abs(diff)<5){ motorsWrite(0,0); return; } }*/ } void RobotControl::moveForward(int speed){ motorsWrite(speed,speed); } void RobotControl::moveBackward(int speed){ motorsWrite(speed,speed); } void RobotControl::turnLeft(int speed){ motorsWrite(speed,255); } void RobotControl::turnRight(int speed){ motorsWrite(255,speed); } /* int RobotControl::getIRrecvResult(){ messageOut.writeByte(COMMAND_GET_IRRECV); messageOut.sendData(); //delay(10); while(!messageIn.receiveData()); if(messageIn.readByte()==COMMAND_GET_IRRECV_RE){ return messageIn.readInt(); } return -1; } */ \ No newline at end of file diff --git a/libraries/Robot_Control/Multiplexer.cpp b/libraries/Robot_Control/Multiplexer.cpp deleted file mode 100644 index 8f7d30e..0000000 --- a/libraries/Robot_Control/Multiplexer.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "Multiplexer.h" - -void Multiplexer::begin(uint8_t* selectors, uint8_t Z, uint8_t length){ - for(uint8_t i=0;iselectors[i]=selectors[i]; - pinMode(selectors[i],OUTPUT); - } - this->length=length; - this->pin_Z=Z; - pinMode(pin_Z,INPUT); -} - -void Multiplexer::selectPin(uint8_t num){ - for(uint8_t i=0;i= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -class Multiplexer{ - public: - void begin(uint8_t* selectors, uint8_t Z, uint8_t length); - void selectPin(uint8_t num); - int getAnalogValue(); - int getAnalogValueAt(uint8_t num); - bool getDigitalValue(); - bool getDigitalValueAt(uint8_t num); - private: - uint8_t selectors[4]; - uint8_t pin_Z; - uint8_t length; -}; - -#endif diff --git a/libraries/Robot_Control/RobotSdCard.cpp b/libraries/Robot_Control/RobotSdCard.cpp deleted file mode 100644 index df833d2..0000000 --- a/libraries/Robot_Control/RobotSdCard.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include - -void RobotControl::beginSD(){ - card.init(); - file.init(&card); - melody.init(&card); -} - -void RobotControl::_enableSD(){ - DDRB = DDRB & 0xDF; //pinMode(CS_LCD,INPUT); - DDRB = DDRB | 0x10; //pinMode(CS_SD,OUTPUT); -} - -/* -void RobotControl::sdTest(){ - file.open("Infor.txt",O_READ); - uint8_t buf[7]; - char n; - while ((n = file.read(buf, sizeof(buf))) > 0) { - for (uint8_t i = 0; i < n; i++) Serial.write(buf[i]); - } -}*/ \ No newline at end of file diff --git a/libraries/Robot_Control/SPI.cpp b/libraries/Robot_Control/SPI.cpp deleted file mode 100644 index 5e48073..0000000 --- a/libraries/Robot_Control/SPI.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#include "pins_arduino.h" -#include "SPI.h" - -SPIClass SPI; - -void SPIClass::begin() { - - // Set SS to high so a connected chip will be "deselected" by default - digitalWrite(SS, HIGH); - - // When the SS pin is set as OUTPUT, it can be used as - // a general purpose output port (it doesn't influence - // SPI operations). - pinMode(SS, OUTPUT); - - // Warning: if the SS pin ever becomes a LOW INPUT then SPI - // automatically switches to Slave, so the data direction of - // the SS pin MUST be kept as OUTPUT. - SPCR |= _BV(MSTR); - SPCR |= _BV(SPE); - - // Set direction register for SCK and MOSI pin. - // MISO pin automatically overrides to INPUT. - // By doing this AFTER enabling SPI, we avoid accidentally - // clocking in a single bit since the lines go directly - // from "input" to SPI control. - // http://code.google.com/p/arduino/issues/detail?id=888 - pinMode(SCK, OUTPUT); - pinMode(MOSI, OUTPUT); -} - - -void SPIClass::end() { - SPCR &= ~_BV(SPE); -} - -void SPIClass::setBitOrder(uint8_t bitOrder) -{ - if(bitOrder == LSBFIRST) { - SPCR |= _BV(DORD); - } else { - SPCR &= ~(_BV(DORD)); - } -} - -void SPIClass::setDataMode(uint8_t mode) -{ - SPCR = (SPCR & ~SPI_MODE_MASK) | mode; -} - -void SPIClass::setClockDivider(uint8_t rate) -{ - SPCR = (SPCR & ~SPI_CLOCK_MASK) | (rate & SPI_CLOCK_MASK); - SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((rate >> 2) & SPI_2XCLOCK_MASK); -} - diff --git a/libraries/Robot_Control/SPI.h b/libraries/Robot_Control/SPI.h deleted file mode 100644 index f647d5c..0000000 --- a/libraries/Robot_Control/SPI.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED - -#include -#include -#include - -#define SPI_CLOCK_DIV4 0x00 -#define SPI_CLOCK_DIV16 0x01 -#define SPI_CLOCK_DIV64 0x02 -#define SPI_CLOCK_DIV128 0x03 -#define SPI_CLOCK_DIV2 0x04 -#define SPI_CLOCK_DIV8 0x05 -#define SPI_CLOCK_DIV32 0x06 -//#define SPI_CLOCK_DIV64 0x07 - -#define SPI_MODE0 0x00 -#define SPI_MODE1 0x04 -#define SPI_MODE2 0x08 -#define SPI_MODE3 0x0C - -#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR -#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR -#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR - -class SPIClass { -public: - inline static byte transfer(byte _data); - - // SPI Configuration methods - - inline static void attachInterrupt(); - inline static void detachInterrupt(); // Default - - static void begin(); // Default - static void end(); - - static void setBitOrder(uint8_t); - static void setDataMode(uint8_t); - static void setClockDivider(uint8_t); -}; - -extern SPIClass SPI; - -byte SPIClass::transfer(byte _data) { - SPDR = _data; - while (!(SPSR & _BV(SPIF))) - ; - return SPDR; -} - -void SPIClass::attachInterrupt() { - SPCR |= _BV(SPIE); -} - -void SPIClass::detachInterrupt() { - SPCR &= ~_BV(SPIE); -} - -#endif diff --git a/libraries/Robot_Control/SdCard.cpp b/libraries/Robot_Control/SdCard.cpp deleted file mode 100644 index fbbd8bc..0000000 --- a/libraries/Robot_Control/SdCard.cpp +++ /dev/null @@ -1,279 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ -#include -#if ARDUINO < 100 -#include -#else // ARDUINO -#include -#endif // ARDUINO -#include -#include -//------------------------------------------------------------------------------ -// r1 status values -uint8_t const R1_READY_STATE = 0; -uint8_t const R1_IDLE_STATE = 1; -// start data token for read or write -uint8_t const DATA_START_BLOCK = 0XFE; -// data response tokens for write block -uint8_t const DATA_RES_MASK = 0X1F; -uint8_t const DATA_RES_ACCEPTED = 0X05; -uint8_t const DATA_RES_CRC_ERROR = 0X0B; -uint8_t const DATA_RES_WRITE_ERROR = 0X0D; -// -// stop compiler from inlining where speed optimization is not required -#define STATIC_NOINLINE static __attribute__((noinline)) -//------------------------------------------------------------------------------ -// SPI static functions -// -// clock byte in -STATIC_NOINLINE uint8_t spiRec(void) { - SPDR = 0xff; - while (!(SPSR & (1 << SPIF))); - return SPDR; -} -// clock byte out -STATIC_NOINLINE void spiSend(uint8_t b) { - SPDR = b; - while (!(SPSR & (1 << SPIF))); -} -//------------------------------------------------------------------------------ -// wait for card to go not busy -// return false if timeout -static uint8_t waitForToken(uint8_t token, uint16_t timeoutMillis) { - uint16_t t0 = millis(); - while (spiRec() != token) { - if (((uint16_t)millis() - t0) > timeoutMillis) return false; - } - return true; -} -//------------------------------------------------------------------------------ -uint8_t SdCard::cardCommand(uint8_t cmd, uint32_t arg) { - uint8_t r1; - - // select card - chipSelectLow(); - - // wait if busy - waitForToken(0XFF, SD_COMMAND_TIMEOUT); - - // send command - spiSend(cmd | 0x40); - - // send argument - for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s); - - // send CRC - must send valid CRC for CMD0 - spiSend(cmd == CMD0 ? 0x95 : 0XFF); - - // wait for not busy - for (uint8_t retry = 0; (0X80 & (r1 = spiRec())) && retry != 0XFF; retry++); - return r1; -} -//------------------------------------------------------------------------------ -uint8_t SdCard::cardAcmd(uint8_t cmd, uint32_t arg) { - cardCommand(CMD55, 0); - return cardCommand(cmd, arg); -} -//============================================================================== -// SdCard member functions -//------------------------------------------------------------------------------ -/** - * Determine the size of a standard SD flash memory card - * \return The number of 512 byte data blocks in the card - */ -uint32_t SdCard::cardSize(void) { - uint16_t c_size; - csd_t csd; - if (!readReg(CMD9, &csd)) return 0; - uint8_t read_bl_len = csd.read_bl_len; - c_size = (csd.c_size_high << 10) | (csd.c_size_mid << 2) | csd.c_size_low; - uint8_t c_size_mult = (csd.c_size_mult_high << 1) | csd.c_size_mult_low; - return (uint32_t)(c_size+1) << (c_size_mult + read_bl_len - 7); -} -//------------------------------------------------------------------------------ -void SdCard::chipSelectHigh(void) { - digitalWrite(chipSelectPin_, HIGH); - // make sure MISO goes high impedance - spiSend(0XFF); -} -//------------------------------------------------------------------------------ -void SdCard::chipSelectLow(void) { - // Enable SPI, Master, clock rate F_CPU/4 - SPCR = (1 << SPE) | (1 << MSTR); - - // Doubled Clock Frequency to F_CPU/2 unless speed_ is nonzero - if (!speed_) SPSR |= (1 << SPI2X); - - digitalWrite(chipSelectPin_, LOW); -} -//------------------------------------------------------------------------------ -void SdCard::error(uint8_t code, uint8_t data) { - errorData = data; - error(code); -} -//------------------------------------------------------------------------------ -void SdCard::error(uint8_t code) { - errorCode = code; - chipSelectHigh(); -} -//------------------------------------------------------------------------------ -/** - * Initialize a SD flash memory card. - * - * \param[in] speed Set SPI Frequency to F_CPU/2 if speed = 0 or F_CPU/4 - * if speed = 1. - * \param[in] chipSelectPin SD chip select pin number. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - * - */ -uint8_t SdCard::init(uint8_t speed, uint8_t chipSelectPin) { - if (speed > 1) { - error(SD_ERROR_SPI_SPEED); - return false; - } - speed_ = speed; - chipSelectPin_ = chipSelectPin; - errorCode = 0; - uint8_t r; - // 16-bit init start time allows over a minute - uint16_t t0 = (uint16_t)millis(); - - pinMode(chipSelectPin_, OUTPUT); - digitalWrite(chipSelectPin_, HIGH); - pinMode(SPI_MISO_PIN, INPUT); - pinMode(SPI_SS_PIN, OUTPUT); - pinMode(SPI_MOSI_PIN, OUTPUT); - pinMode(SPI_SCK_PIN, OUTPUT); - - // Enable SPI, Master, clock rate F_CPU/128 - SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); - - // must supply min of 74 clock cycles with CS high. - for (uint8_t i = 0; i < 10; i++) spiSend(0XFF); - digitalWrite(chipSelectPin_, LOW); - - // command to go idle in SPI mode - while ((r = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { - if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { - error(SD_ERROR_CMD0, r); - return false; - } - } - // start initialization and wait for completed initialization - while ((r = cardAcmd(ACMD41, 0)) != R1_READY_STATE) { - if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { - error(SD_ERROR_ACMD41, r); - return false; - } - } - chipSelectHigh(); - return true; -} -//------------------------------------------------------------------------------ -/** - * Reads a 512 byte block from a storage device. - * - * \param[in] blockNumber Logical block to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - */ -uint8_t SdCard::readBlock(uint32_t blockNumber, uint8_t* dst) { - if (cardCommand(CMD17, blockNumber << 9)) { - error(SD_ERROR_CMD17); - return false; - } - return readTransfer(dst, 512); -} -//------------------------------------------------------------------------------ -uint8_t SdCard::readReg(uint8_t cmd, void* buf) { - uint8_t* dst = reinterpret_cast(buf); - if (cardCommand(cmd, 0)) { - chipSelectHigh(); - return false; - } - return readTransfer(dst, 16); -} -//------------------------------------------------------------------------------ -uint8_t SdCard::readTransfer(uint8_t* dst, uint16_t count) { - // wait for start of data - if (!waitForToken(DATA_START_BLOCK, SD_READ_TIMEOUT)) { - error(SD_ERROR_READ_TIMEOUT); - } - // start first spi transfer - SPDR = 0XFF; - for (uint16_t i = 0; i < count; i++) { - while (!(SPSR & (1 << SPIF))); - dst[i] = SPDR; - SPDR = 0XFF; - } - // wait for first CRC byte - while (!(SPSR & (1 << SPIF))); - spiRec(); // second CRC byte - chipSelectHigh(); - return true; -} -//------------------------------------------------------------------------------ -/** - * Writes a 512 byte block to a storage device. - * - * \param[in] blockNumber Logical block to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. - */ -uint8_t SdCard::writeBlock(uint32_t blockNumber, const uint8_t* src) { - uint32_t address = blockNumber << 9; -#if SD_PROTECT_BLOCK_ZERO - // don't allow write to first block - if (address == 0) { - error(SD_ERROR_BLOCK_ZERO_WRITE); - return false; - } -#endif // SD_PROTECT_BLOCK_ZERO - if (cardCommand(CMD24, address)) { - error(SD_ERROR_CMD24); - return false; - } - // optimize write loop - SPDR = DATA_START_BLOCK; - for (uint16_t i = 0; i < 512; i++) { - while (!(SPSR & (1 << SPIF))); - SPDR = src[i]; - } - while (!(SPSR & (1 << SPIF))); // wait for last data byte - spiSend(0xFF); // dummy crc - spiSend(0xFF); // dummy crc - - // get write response - uint8_t r1 = spiRec(); - if ((r1 & DATA_RES_MASK) != DATA_RES_ACCEPTED) { - error(SD_ERROR_WRITE_RESPONSE, r1); - return false; - } - // wait for card to complete write programming - if (!waitForToken(0XFF, SD_WRITE_TIMEOUT)) { - error(SD_ERROR_WRITE_TIMEOUT); - } - chipSelectHigh(); - return true; -} diff --git a/libraries/Robot_Control/SdCard.h b/libraries/Robot_Control/SdCard.h deleted file mode 100644 index c03e6ab..0000000 --- a/libraries/Robot_Control/SdCard.h +++ /dev/null @@ -1,192 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ -#ifndef SdCard_h -#define SdCard_h - /** - * \file - * SdCard class - */ -#include -//------------------------------------------------------------------------------ -// Warning only SD_CHIP_SELECT_PIN, the SD card select pin, may be redefined. -// define hardware SPI pins -#if defined(__AVR_ATmega168__)\ -||defined(__AVR_ATmega168P__)\ -||defined(__AVR_ATmega328P__) -// 168 and 328 Arduinos -/** Slave Select pin */ -uint8_t const SPI_SS_PIN = 10; -/** Master Out Slave In pin */ -uint8_t const SPI_MOSI_PIN = 11; -/** Master In Slave Out pin */ -uint8_t const SPI_MISO_PIN = 12; -/** Serial Clock */ -uint8_t const SPI_SCK_PIN = 13; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega1280__)\ -|| defined(__AVR_ATmega2560__) -// pins for Arduino Mega -uint8_t const SPI_SS_PIN = 53; -uint8_t const SPI_MOSI_PIN = 51; -uint8_t const SPI_MISO_PIN = 50; -uint8_t const SPI_SCK_PIN = 52; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega644P__)\ -|| defined(__AVR_ATmega644__)\ -|| defined(__AVR_ATmega1284P__) -// pins for Sanguino -uint8_t const SPI_SS_PIN = 4; -uint8_t const SPI_MOSI_PIN = 5; -uint8_t const SPI_MISO_PIN = 6; -uint8_t const SPI_SCK_PIN = 7; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega32U4__) -// pins for Teensy 2.0 -uint8_t const SPI_SS_PIN = 8; -uint8_t const SPI_MOSI_PIN = 16; -uint8_t const SPI_MISO_PIN = 14; -uint8_t const SPI_SCK_PIN = 15; -//------------------------------------------------------------------------------ -#elif defined(__AVR_AT90USB646__)\ -|| defined(__AVR_AT90USB1286__) -// pins for Teensy++ 1.0 & 2.0 -uint8_t const SPI_SS_PIN = 20; -uint8_t const SPI_MOSI_PIN = 22; -uint8_t const SPI_MISO_PIN = 23; -uint8_t const SPI_SCK_PIN = 21; -//------------------------------------------------------------------------------ -#else // SPI pins -#error unknown CPU -#endif // SPI pins -//------------------------------------------------------------------------------ -/** - * SD Chip Select pin - * - * Warning if this pin is redefined the hardware SS pin will be enabled - * as an output by init(). An avr processor will not function as an SPI - * master unless SS is set to output mode. - * - * For example to set SD_CHIP_SELECT_PIN to 8 for the SparkFun microSD shield: - * uint8_t const SD_CHIP_SELECT_PIN = 8; - * - * The default chip select pin for the SD card is SS. - */ -uint8_t const SD_CHIP_SELECT_PIN = SPI_SS_PIN; -//------------------------------------------------------------------------------ -/** command timeout ms */ -uint16_t const SD_COMMAND_TIMEOUT = 300; -/** init timeout ms */ -uint16_t const SD_INIT_TIMEOUT = 2000; -/** read timeout ms */ -uint16_t const SD_READ_TIMEOUT = 300; -/** write timeout ms */ -uint16_t const SD_WRITE_TIMEOUT = 600; -//------------------------------------------------------------------------------ -// error codes -/** Card did not go into SPI mode */ -uint8_t const SD_ERROR_CMD0 = 1; -/** Card did not go ready */ -uint8_t const SD_ERROR_ACMD41 = 2; -/** Write command not accepted */ -uint8_t const SD_ERROR_CMD24 = 3; -/** Read command not accepted */ -uint8_t const SD_ERROR_CMD17 = 4; -/** timeout waiting for read data */ -uint8_t const SD_ERROR_READ_TIMEOUT = 5; -/** write error occurred */ -uint8_t const SD_ERROR_WRITE_RESPONSE = 6; -/** timeout waiting for write status */ -uint8_t const SD_ERROR_WRITE_TIMEOUT = 7; -/** attempt to write block zero */ -uint8_t const SD_ERROR_BLOCK_ZERO_WRITE = 8; -/** card returned an error to a CMD13 status check after a write */ -uint8_t const SD_ERROR_WRITE_PROGRAMMING = 9; -/** invalid SPI speed in init() call */ -uint8_t const SD_ERROR_SPI_SPEED = 10; -//------------------------------------------------------------------------------ -// SD command codes -/** SEND OPERATING CONDITIONS */ -uint8_t const ACMD41 = 0X29; -/** GO_IDLE_STATE - init card in spi mode if CS low */ -uint8_t const CMD0 = 0X00; -/** SEND_CSD - Card Specific Data */ -uint8_t const CMD9 = 0X09; -/** SEND_CID - Card IDentification */ -uint8_t const CMD10 = 0X0A; -/** SEND_STATUS - read the card status register */ -uint8_t const CMD13 = 0X0D; -/** READ_BLOCK */ -uint8_t const CMD17 = 0X11; -/** WRITE_BLOCK */ -uint8_t const CMD24 = 0X18; -/** APP_CMD - escape for application specific command */ -uint8_t const CMD55 = 0X37; -//------------------------------------------------------------------------------ -/** - * \class SdCard - * \brief Hardware access class for SD flash cards - * - * Supports raw access to a standard SD flash memory card. - * - */ -class SdCard { - public: - /** Code for a SD error. See SdCard.h for definitions. */ - uint8_t errorCode; - /** Data that may be helpful in determining the cause of an error */ - uint8_t errorData; - uint32_t cardSize(void); - /** - * Initialize an SD flash memory card with default clock rate and chip - * select pin. See SdCard::init(uint8_t sckRateID, uint8_t chipSelectPin). - */ - uint8_t init(void) { - return init(0, SD_CHIP_SELECT_PIN); - } - /** - * Initialize an SD flash memory card with the selected SPI clock rate - * and the default SD chip select pin. - * See SdCard::init(uint8_t slow, uint8_t chipSelectPin). - */ - uint8_t init(uint8_t speed) { - return init(speed, SD_CHIP_SELECT_PIN); - } - uint8_t init(uint8_t speed, uint8_t chipselectPin); - uint8_t readBlock(uint32_t block, uint8_t* dst); - /** Read the CID register which contains info about the card. - * This includes Manufacturer ID, OEM ID, product name, version, - * serial number, and manufacturing date. */ - uint8_t readCID(cid_t* cid) { - return readReg(CMD10, cid); - } - uint8_t writeBlock(uint32_t block, const uint8_t* src); - private: - uint8_t cardAcmd(uint8_t cmd, uint32_t arg); - uint8_t cardCommand(uint8_t cmd, uint32_t arg); - uint8_t chipSelectPin_; - uint8_t speed_; - void chipSelectHigh(void); - void chipSelectLow(void); - void error(uint8_t code, uint8_t data); - void error(uint8_t code); - uint8_t readReg(uint8_t cmd, void* buf); - uint8_t readTransfer(uint8_t* dst, uint16_t count); -}; -#endif // SdCard_h diff --git a/libraries/Robot_Control/SdInfo.h b/libraries/Robot_Control/SdInfo.h deleted file mode 100644 index 4c82e0b..0000000 --- a/libraries/Robot_Control/SdInfo.h +++ /dev/null @@ -1,117 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * . - */ -#ifndef SdInfo_h -#define SdInfo_h -#include -// Based on the document: -// -// SD Specifications -// Part 1 -// Physical Layer -// Simplified Specification -// Version 2.00 -// September 25, 2006 -// -// www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf -// -// Card IDentification (CID) register -typedef struct CID { - // byte 0 - uint8_t mid; // Manufacturer ID - // byte 1-2 - char oid[2]; // OEM/Application ID - // byte 3-7 - char pnm[5]; // Product name - // byte 8 - unsigned prv_m : 4; // Product revision n.m - unsigned prv_n : 4; - // byte 9-12 - uint32_t psn; // Product serial number - // byte 13 - unsigned mdt_year_high : 4; // Manufacturing date - unsigned reserved : 4; - // byte 14 - unsigned mdt_month : 4; - unsigned mdt_year_low :4; - // byte 15 - unsigned always1 : 1; - unsigned crc : 7; -}cid_t; -// Card-Specific Data register -typedef struct CSD { - // byte 0 - unsigned reserved1 : 6; - unsigned csd_ver : 2; - // byte 1 - uint8_t taac; - // byte 2 - uint8_t nsac; - // byte 3 - uint8_t tran_speed; - // byte 4 - uint8_t ccc_high; - // byte 5 - unsigned read_bl_len : 4; - unsigned ccc_low : 4; - // byte 6 - unsigned c_size_high : 2; - unsigned reserved2 : 2; - unsigned dsr_imp : 1; - unsigned read_blk_misalign :1; - unsigned write_blk_misalign : 1; - unsigned read_bl_partial : 1; - // byte 7 - uint8_t c_size_mid; - // byte 8 - unsigned vdd_r_curr_max : 3; - unsigned vdd_r_curr_min : 3; - unsigned c_size_low :2; - // byte 9 - unsigned c_size_mult_high : 2; - unsigned vdd_w_cur_max : 3; - unsigned vdd_w_curr_min : 3; - // byte 10 - unsigned sector_size_high : 6; - unsigned erase_blk_en : 1; - unsigned c_size_mult_low : 1; - // byte 11 - unsigned wp_grp_size : 7; - unsigned sector_size_low : 1; - // byte 12 - unsigned write_bl_len_high : 2; - unsigned r2w_factor : 3; - unsigned reserved3 : 2; - unsigned wp_grp_enable : 1; - // byte 13 - unsigned reserved4 : 5; - unsigned write_partial : 1; - unsigned write_bl_len_low : 2; - // byte 14 - unsigned reserved5: 2; - unsigned file_format : 2; - unsigned tmp_write_protect : 1; - unsigned perm_write_protect : 1; - unsigned copy : 1; - unsigned file_format_grp : 1; - // byte 15 - unsigned always1 : 1; - unsigned crc : 7; -}csd_t; -#endif // SdInfo_h diff --git a/libraries/Robot_Control/Sensors.cpp b/libraries/Robot_Control/Sensors.cpp deleted file mode 100644 index b651c28..0000000 --- a/libraries/Robot_Control/Sensors.cpp +++ /dev/null @@ -1,274 +0,0 @@ -#include "ArduinoRobot.h" -#include "Multiplexer.h" -#include "Wire.h" -bool RobotControl::digitalRead(uint8_t port){ - uint8_t type=_getTypeCode(port); - switch(type){ - case TYPE_TOP_TK: - return _digitalReadTopMux(port); - break; - case TYPE_TOP_TKD: - return _digitalReadTopPin(port); - break; - case TYPE_BOTTOM_TK: - return _requestDigitalRead(port); - break; - } -} -int RobotControl::analogRead(uint8_t port){ - uint8_t type=_getTypeCode(port); - switch(type){ - case TYPE_TOP_TK: - return _analogReadTopMux(port); - break; - case TYPE_TOP_TKD: - return _analogReadTopPin(port); - break; - case TYPE_BOTTOM_TK: - return _requestAnalogRead(port); - break; - } -} -void RobotControl::digitalWrite(uint8_t port, bool value){ - uint8_t type=_getTypeCode(port); - switch(type){ - case TYPE_TOP_TK: - //Top TKs can't use digitalWrite? - break; - case TYPE_TOP_TKD: - _digitalWriteTopPin(port, value); - break; - case TYPE_BOTTOM_TK: - _requestDigitalWrite(port, value); - break; - } -} -void RobotControl::analogWrite(uint8_t port, uint8_t value){ - if(port==TKD4) - ::analogWrite(port,value); -} - -uint8_t RobotControl::_getTypeCode(uint8_t port){ - switch(port){ - case TK0: - case TK1: - case TK2: - case TK3: - case TK4: - case TK5: - case TK6: - case TK7: - return TYPE_TOP_TK; - break; - - case TKD0: - case TKD1: - case TKD2: - case TKD3: - case TKD4: - case TKD5: - case LED1: - return TYPE_TOP_TKD; - break; - - case B_TK1: - case B_TK2: - case B_TK3: - case B_TK4: - return TYPE_BOTTOM_TK; - break; - } -} -uint8_t RobotControl::_portToTopMux(uint8_t port){ - switch(port){ - case TK0: - return 0; - case TK1: - return 1; - case TK2: - return 2; - case TK3: - return 3; - case TK4: - return 4; - case TK5: - return 5; - case TK6: - return 6; - case TK7: - return 7; - } -} -uint8_t RobotControl::_topDPortToAPort(uint8_t port){ - switch(port){ - case TKD0: - return A1; - case TKD1: - return A2; - case TKD2: - return A3; - case TKD3: - return A4; - case TKD4: - return A7; - case TKD5: - return A11; - } -} -int* RobotControl::parseMBDPort(uint8_t port){ - //Serial.println(port); - switch(port){ - case B_TK1: - return &motorBoardData._B_TK1; - case B_TK2: - return &motorBoardData._B_TK2; - case B_TK3: - return &motorBoardData._B_TK3; - case B_TK4: - return &motorBoardData._B_TK4; - - /* - case B_IR0: - return &motorBoardData._B_IR0; - case B_IR1: - return &motorBoardData._B_IR1; - case B_IR2: - return &motorBoardData._B_IR2; - case B_IR3: - return &motorBoardData._B_IR3; - case B_IR4: - return &motorBoardData._B_IR4;*/ - } -} -int RobotControl::get_motorBoardData(uint8_t port){ - return *parseMBDPort(port); -} -void RobotControl::set_motorBoardData(uint8_t port, int data){ - *parseMBDPort(port)=data; -} - -bool RobotControl::_digitalReadTopMux(uint8_t port){ - uint8_t num=_portToTopMux(port); - return Multiplexer::getDigitalValueAt(num); -} - -int RobotControl::_analogReadTopMux(uint8_t port){ - uint8_t num=_portToTopMux(port); - return Multiplexer::getAnalogValueAt(num); -} - -bool RobotControl::_digitalReadTopPin(uint8_t port){ - return ::digitalRead(port); -} -int RobotControl::_analogReadTopPin(uint8_t port){ - uint8_t aPin=_topDPortToAPort(port); - return ::analogRead(aPin); -} -void RobotControl::_digitalWriteTopPin(uint8_t port, bool value){ - ::digitalWrite(port, value); -} - -bool RobotControl::_requestDigitalRead(uint8_t port){ - messageOut.writeByte(COMMAND_DIGITAL_READ); - messageOut.writeByte(port);//B_TK1 - B_TK4 - messageOut.sendData(); - delay(10); - if(messageIn.receiveData()){ - //Serial.println("*************"); - uint8_t cmd=messageIn.readByte(); - //Serial.print("cmd: "); - //Serial.println(cmd); - if(!(cmd==COMMAND_DIGITAL_READ_RE)) - return false; - - uint8_t pt=messageIn.readByte(); //Bottom TK port codename - //Serial.print("pt: "); - //Serial.println(pt); - set_motorBoardData(pt,messageIn.readByte()); - return get_motorBoardData(port); - } -} -int RobotControl::_requestAnalogRead(uint8_t port){ - messageOut.writeByte(COMMAND_ANALOG_READ); - messageOut.writeByte(port);//B_TK1 - B_TK4 - messageOut.sendData(); - delay(10); - if(messageIn.receiveData()){ - uint8_t cmd=messageIn.readByte(); - //Serial.println("*************"); - //Serial.print("cmd: "); - //Serial.println(cmd); - if(!(cmd==COMMAND_ANALOG_READ_RE)) - return false; - - uint8_t pt=messageIn.readByte(); - //Serial.print("pt: "); - //Serial.println(pt); - set_motorBoardData(pt,messageIn.readInt()); - return get_motorBoardData(port); - } -} -void RobotControl::_requestDigitalWrite(uint8_t selector, uint8_t value){ - messageOut.writeByte(COMMAND_DIGITAL_WRITE); - messageOut.writeByte(selector);//B_TK1 - B_TK4 - messageOut.writeByte(value); - messageOut.sendData(); -} - - - - - -void RobotControl::updateIR(){ - messageOut.writeByte(COMMAND_READ_IR); - messageOut.sendData(); - delay(10); - if(messageIn.receiveData()){ - if(messageIn.readByte()==COMMAND_READ_IR_RE){ - for(int i=0;i<5;i++){ - IRarray[i]=messageIn.readInt(); - } - } - } -} - -int RobotControl::knobRead(){ - return ::analogRead(POT); -} - -int RobotControl::trimRead(){ - messageOut.writeByte(COMMAND_READ_TRIM); - messageOut.sendData(); - delay(10); - if(messageIn.receiveData()){ - uint8_t cmd=messageIn.readByte(); - if(!(cmd==COMMAND_READ_TRIM_RE)) - return false; - - uint16_t pt=messageIn.readInt(); - return pt; - } -} - -uint16_t RobotControl::compassRead(){ - return Compass::getReading(); -} - -/* -void RobotControl::beginUR(uint8_t pinTrigger, uint8_t pinEcho){ - pinTrigger_UR=pinTrigger; - pinEcho_UR=pinEcho; - - pinMode(pinEcho_UR, INPUT); - pinMode(pinTrigger_UR, OUTPUT); -} -uint16_t RobotControl::getDistance(){ - digitalWrite(pinTrigger_UR, LOW); // Set the trigger pin to low for 2uS - delayMicroseconds(2); - digitalWrite(pinTrigger_UR, HIGH); // Send a 10uS high to trigger ranging - delayMicroseconds(10); - digitalWrite(pinTrigger_UR, LOW); // Send pin low again - uint16_t distance = pulseIn(pinEcho_UR, HIGH); // Read in times pulse - distance= distance/58; // Calculate distance from time of pulse - return distance; -}*/ \ No newline at end of file diff --git a/libraries/Robot_Control/Squawk.cpp b/libraries/Robot_Control/Squawk.cpp deleted file mode 100644 index 5b39ebe..0000000 --- a/libraries/Robot_Control/Squawk.cpp +++ /dev/null @@ -1,601 +0,0 @@ -// Squawk Soft-Synthesizer Library for Arduino -// -// Davey Taylor 2013 -// d.taylor@arduino.cc - -#include "Squawk.h" - -// Period range, used for clamping -#define PERIOD_MIN 28 -#define PERIOD_MAX 3424 - -// Convenience macros -#define LO4(V) ((V) & 0x0F) -#define HI4(V) (((V) & 0xF0) >> 4) -#define MIN(A, B) ((A) < (B) ? (A) : (B)) -#define MAX(A, B) ((A) > (B) ? (A) : (B)) -#define FREQ(PERIOD) (tuning_long / (PERIOD)) - -// SquawkStream class for PROGMEM data -class StreamROM : public SquawkStream { - private: - uint8_t *p_start; - uint8_t *p_cursor; - public: - StreamROM(const uint8_t *p_rom = NULL) { p_start = p_cursor = (uint8_t*)p_rom; } - uint8_t read() { return pgm_read_byte(p_cursor++); } - void seek(size_t offset) { p_cursor = p_start + offset; } -}; - -// Oscillator memory -typedef struct { - uint8_t fxp; - uint8_t offset; - uint8_t mode; -} pto_t; - -// Deconstructed cell -typedef struct { - uint8_t fxc, fxp, ixp; -} cel_t; - -// Effect memory -typedef struct { - int8_t volume; - uint8_t port_speed; - uint16_t port_target; - bool glissando; - pto_t vibr; - pto_t trem; - uint16_t period; - uint8_t param; -} fxm_t; - -// Locals -static uint8_t order_count; -static uint8_t order[64]; -static uint8_t speed; -static uint8_t tick; -static uint8_t ix_row; -static uint8_t ix_order; -static uint8_t ix_nextrow; -static uint8_t ix_nextorder; -static uint8_t row_delay; -static fxm_t fxm[4]; -static cel_t cel[4]; -static uint32_t tuning_long; -static uint16_t sample_rate; -static float tuning = 1.0; -static uint16_t tick_rate = 50; - -static SquawkStream *stream; -static uint16_t stream_base; -static StreamROM rom; - -// Imports -extern intptr_t squawk_register; -extern uint16_t cia; - -// Exports -osc_t osc[4]; -uint8_t pcm = 128; - -// ProTracker period tables -uint16_t period_tbl[84] PROGMEM = { - 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1814, - 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 907, - 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, - 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, - 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, - 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, - 53, 50, 47, 45, 42, 40, 37, 35, 33, 31, 30, 28, -}; - -// ProTracker sine table -int8_t sine_tbl[32] PROGMEM = { - 0x00, 0x0C, 0x18, 0x25, 0x30, 0x3C, 0x47, 0x51, 0x5A, 0x62, 0x6A, 0x70, 0x76, 0x7A, 0x7D, 0x7F, - 0x7F, 0x7F, 0x7D, 0x7A, 0x76, 0x70, 0x6A, 0x62, 0x5A, 0x51, 0x47, 0x3C, 0x30, 0x25, 0x18, 0x0C, -}; - -// Squawk object -SquawkSynth Squawk; - -// Look up or generate waveform for ProTracker vibrato/tremolo oscillator -static int8_t do_osc(pto_t *p_osc) { - int8_t sample = 0; - int16_t mul; - switch(p_osc->mode & 0x03) { - case 0: // Sine - sample = pgm_read_byte(&sine_tbl[(p_osc->offset) & 0x1F]); - if(p_osc->offset & 0x20) sample = -sample; - break; - case 1: // Square - sample = (p_osc->offset & 0x20) ? 127 : -128; - break; - case 2: // Saw - sample = -(p_osc->offset << 2); - break; - case 3: // Noise (random) - sample = rand(); - break; - } - mul = sample * LO4(p_osc->fxp); - p_osc->offset = (p_osc->offset + HI4(p_osc->fxp)); - return mul >> 6; -} - -// Calculates and returns arpeggio period -// Essentially finds period of current note + halftones -static inline uint16_t arpeggio(uint8_t ch, uint8_t halftones) { - uint8_t n; - for(n = 0; n != 47; n++) { - if(fxm[ch].period >= pgm_read_word(&period_tbl[n])) break; - } - return pgm_read_word(&period_tbl[MIN(n + halftones, 47)]); -} - -// Calculates and returns glissando period -// Essentially snaps a sliding frequency to the closest note -static inline uint16_t glissando(uint8_t ch) { - uint8_t n; - uint16_t period_h, period_l; - for(n = 0; n != 47; n++) { - period_l = pgm_read_word(&period_tbl[n]); - period_h = pgm_read_word(&period_tbl[n + 1]); - if(fxm[ch].period < period_l && fxm[ch].period >= period_h) { - if(period_l - fxm[ch].period <= fxm[ch].period - period_h) { - period_h = period_l; - } - break; - } - } - return period_h; -} - -// Tunes Squawk to a different frequency -void SquawkSynth::tune(float new_tuning) { - tuning = new_tuning; - tuning_long = (long)(((double)3669213184.0 / (double)sample_rate) * (double)tuning); - -} - -// Sets tempo -void SquawkSynth::tempo(uint16_t new_tempo) { - tick_rate = new_tempo; - cia = sample_rate / tick_rate; // not atomic? -} - -// Initializes Squawk -// Sets up the selected port, and the sample grinding ISR -void SquawkSynth::begin(uint16_t hz) { - word isr_rr; - - sample_rate = hz; - tuning_long = (long)(((double)3669213184.0 / (double)sample_rate) * (double)tuning); - cia = sample_rate / tick_rate; - - if(squawk_register == (intptr_t)&OCR0A) { - // Squawk uses PWM on OCR0A/PD5(ATMega328/168)/PB7(ATMega32U4) -#ifdef __AVR_ATmega32U4__ - DDRB |= 0b10000000; // TODO: FAIL on 32U4 -#else - DDRD |= 0b01000000; -#endif - TCCR0A = 0b10000011; // Fast-PWM 8-bit - TCCR0B = 0b00000001; // 62500Hz - OCR0A = 0x7F; - } else if(squawk_register == (intptr_t)&OCR0B) { - // Squawk uses PWM on OCR0B/PC5(ATMega328/168)/PD0(ATMega32U4) -#ifdef __AVR_ATmega32U4__ - DDRD |= 0b00000001; -#else - DDRD |= 0b00100000; -#endif // Set timer mode to - TCCR0A = 0b00100011; // Fast-PWM 8-bit - TCCR0B = 0b00000001; // 62500Hz - OCR0B = 0x7F; -#ifdef OCR2A - } else if(squawk_register == (intptr_t)&OCR2A) { - // Squawk uses PWM on OCR2A/PB3 - DDRB |= 0b00001000; // Set timer mode to - TCCR2A = 0b10000011; // Fast-PWM 8-bit - TCCR2B = 0b00000001; // 62500Hz - OCR2A = 0x7F; -#endif -#ifdef OCR2B - } else if(squawk_register == (intptr_t)&OCR2B) { - // Squawk uses PWM on OCR2B/PD3 - DDRD |= 0b00001000; // Set timer mode to - TCCR2A = 0b00100011; // Fast-PWM 8-bit - TCCR2B = 0b00000001; // 62500Hz - OCR2B = 0x7F; -#endif -#ifdef OCR3AL - } else if(squawk_register == (intptr_t)&OCR3AL) { - // Squawk uses PWM on OCR3AL/PC6 - DDRC |= 0b01000000; // Set timer mode to - TCCR3A = 0b10000001; // Fast-PWM 8-bit - TCCR3B = 0b00001001; // 62500Hz - OCR3AH = 0x00; - OCR3AL = 0x7F; -#endif - } else if(squawk_register == (intptr_t)&SPDR) { - // NOT YET SUPPORTED - // Squawk uses external DAC via SPI - // TODO: Configure SPI - // TODO: Needs SS toggle in sample grinder - } else if(squawk_register == (intptr_t)&PORTB) { - // NOT YET SUPPORTED - // Squawk uses resistor ladder on PORTB - // TODO: Needs shift right in sample grinder - DDRB = 0b11111111; - } else if(squawk_register == (intptr_t)&PORTC) { - // NOT YET SUPPORTED - // Squawk uses resistor ladder on PORTC - // TODO: Needs shift right in sample grinder - DDRC = 0b11111111; - } - - // Seed LFSR (needed for noise) - osc[3].freq = 0x2000; - - // Set up ISR to run at sample_rate (may not be exact) - isr_rr = F_CPU / sample_rate; - TCCR1A = 0b00000000; // Set timer mode - TCCR1B = 0b00001001; - OCR1AH = isr_rr >> 8; // Set freq - OCR1AL = isr_rr & 0xFF; -} - -// Decrunches a 9 byte row into a useful data -static void decrunch_row() { - uint8_t data; - - // Initial decrunch - stream->seek(stream_base + ((order[ix_order] << 6) + ix_row) * 9); - data = stream->read(); cel[0].fxc = data << 0x04; - cel[1].fxc = data & 0xF0; - data = stream->read(); cel[0].fxp = data; - data = stream->read(); cel[1].fxp = data; - data = stream->read(); cel[2].fxc = data << 0x04; - cel[3].fxc = data >> 0x04; - data = stream->read(); cel[2].fxp = data; - data = stream->read(); cel[3].fxp = data; - data = stream->read(); cel[0].ixp = data; - data = stream->read(); cel[1].ixp = data; - data = stream->read(); cel[2].ixp = data; - - // Decrunch extended effects - if(cel[0].fxc == 0xE0) { cel[0].fxc |= cel[0].fxp >> 4; cel[0].fxp &= 0x0F; } - if(cel[1].fxc == 0xE0) { cel[1].fxc |= cel[1].fxp >> 4; cel[1].fxp &= 0x0F; } - if(cel[2].fxc == 0xE0) { cel[2].fxc |= cel[2].fxp >> 4; cel[2].fxp &= 0x0F; } - - // Decrunch cell 3 ghetto-style - cel[3].ixp = ((cel[3].fxp & 0x80) ? 0x00 : 0x7F) | ((cel[3].fxp & 0x40) ? 0x80 : 0x00); - cel[3].fxp &= 0x3F; - switch(cel[3].fxc) { - case 0x02: - case 0x03: if(cel[3].fxc & 0x01) cel[3].fxp |= 0x40; cel[3].fxp = (cel[3].fxp >> 4) | (cel[3].fxp << 4); cel[3].fxc = 0x70; break; - case 0x01: if(cel[3].fxp & 0x08) cel[3].fxp = (cel[3].fxp & 0x07) << 4; cel[3].fxc = 0xA0; break; - case 0x04: cel[3].fxc = 0xC0; break; - case 0x05: cel[3].fxc = 0xB0; break; - case 0x06: cel[3].fxc = 0xD0; break; - case 0x07: cel[3].fxc = 0xF0; break; - case 0x08: cel[3].fxc = 0xE7; break; - case 0x09: cel[3].fxc = 0xE9; break; - case 0x0A: cel[3].fxc = (cel[3].fxp & 0x08) ? 0xEA : 0xEB; cel[3].fxp &= 0x07; break; - case 0x0B: cel[3].fxc = (cel[3].fxp & 0x10) ? 0xED : 0xEC; cel[3].fxp &= 0x0F; break; - case 0x0C: cel[3].fxc = 0xEE; break; - } - - // Apply generic effect parameter memory - uint8_t ch; - cel_t *p_cel = cel; - fxm_t *p_fxm = fxm; - for(ch = 0; ch != 4; ch++) { - uint8_t fx = p_cel->fxc; - if(fx == 0x10 || fx == 0x20 || fx == 0xE1 || fx == 0xE2 || fx == 0x50 || fx == 0x60 || fx == 0xA0) { - if(p_cel->fxp) { - p_fxm->param = p_cel->fxp; - } else { - p_cel->fxp = p_fxm->param; - } - } - p_cel++; p_fxm++; - } -} - -// Resets playback -static void playroutine_reset() { - memset(fxm, 0, sizeof(fxm)); - tick = 0; - ix_row = 0; - ix_order = 0; - ix_nextrow = 0xFF; - ix_nextorder = 0xFF; - row_delay = 0; - speed = 6; - decrunch_row(); -} - -// Start grinding samples -void SquawkSynth::play() { - TIMSK1 = 1 << OCIE1A; // Enable interrupt -} - -// Load a melody stream and start grinding samples -void SquawkSynth::play(SquawkStream *melody) { - uint8_t n; - pause(); - stream = melody; - stream->seek(0); - n = stream->read(); - if(n == 'S') { - // Squawk SD file - stream->seek(4); - stream_base = stream->read() << 8; - stream_base |= stream->read(); - stream_base += 6; - } else { - // Squawk ROM array - stream_base = 1; - } - stream->seek(stream_base); - order_count = stream->read(); - if(order_count <= 64) { - stream_base += order_count + 1; - for(n = 0; n < order_count; n++) order[n] = stream->read(); - playroutine_reset(); - play(); - } else { - order_count = 0; - } -} - -// Load a melody in PROGMEM and start grinding samples -void SquawkSynth::play(const uint8_t *melody) { - pause(); - rom = StreamROM(melody); - play(&rom); -} - -// Pause playback -void SquawkSynth::pause() { - TIMSK1 = 0; // Disable interrupt -} - -// Stop playing, unload melody -void SquawkSynth::stop() { - pause(); - order_count = 0; // Unload melody -} - -// Progress module by one tick -void squawk_playroutine() { - static bool lockout = false; - - if(!order_count) return; - - // Protect from re-entry via ISR - cli(); - if(lockout) { - sei(); - return; - } - lockout = true; - sei(); - - // Handle row delay - if(row_delay) { - if(tick == 0) row_delay--; - // Advance tick - if(++tick == speed) tick = 0; - } else { - - // Quick pointer access - fxm_t *p_fxm = fxm; - osc_t *p_osc = osc; - cel_t *p_cel = cel; - - // Temps - uint8_t ch, fx, fxp; - bool pattern_jump = false; - uint8_t ix_period; - - for(ch = 0; ch != 4; ch++) { - uint8_t temp; - - // Local register copy - fx = p_cel->fxc; - fxp = p_cel->fxp; - ix_period = p_cel->ixp; - - // If first tick - if(tick == (fx == 0xED ? fxp : 0)) { - - // Reset volume - if(ix_period & 0x80) p_osc->vol = p_fxm->volume = 0x20; - - if((ix_period & 0x7F) != 0x7F) { - - // Reset oscillators (unless continous flag set) - if((p_fxm->vibr.mode & 0x4) == 0x0) p_fxm->vibr.offset = 0; - if((p_fxm->trem.mode & 0x4) == 0x0) p_fxm->trem.offset = 0; - - // Cell has note - if(fx == 0x30 || fx == 0x50) { - - // Tone-portamento effect setup - p_fxm->port_target = pgm_read_word(&period_tbl[ix_period & 0x7F]); - } else { - - // Set required effect memory parameters - p_fxm->period = pgm_read_word(&period_tbl[ix_period & 0x7F]); - - // Start note - if(ch != 3) p_osc->freq = FREQ(p_fxm->period); - - } - } - - // Effects processed when tick = 0 - switch(fx) { - case 0x30: // Portamento - if(fxp) p_fxm->port_speed = fxp; - break; - case 0xB0: // Jump to pattern - ix_nextorder = (fxp >= order_count ? 0x00 : fxp); - ix_nextrow = 0; - pattern_jump = true; - break; - case 0xC0: // Set volume - p_osc->vol = p_fxm->volume = MIN(fxp, 0x20); - break; - case 0xD0: // Jump to row - if(!pattern_jump) ix_nextorder = ((ix_order + 1) >= order_count ? 0x00 : ix_order + 1); - pattern_jump = true; - ix_nextrow = (fxp > 63 ? 0 : fxp); - break; - case 0xF0: // Set speed, BPM(CIA) not supported - if(fxp <= 0x20) speed = fxp; - break; - case 0x40: // Vibrato - if(fxp) p_fxm->vibr.fxp = fxp; - break; - case 0x70: // Tremolo - if(fxp) p_fxm->trem.fxp = fxp; - break; - case 0xE1: // Fine slide up - if(ch != 3) { - p_fxm->period = MAX(p_fxm->period - fxp, PERIOD_MIN); - p_osc->freq = FREQ(p_fxm->period); - } - break; - case 0xE2: // Fine slide down - if(ch != 3) { - p_fxm->period = MIN(p_fxm->period + fxp, PERIOD_MAX); - p_osc->freq = FREQ(p_fxm->period); - } - break; - case 0xE3: // Glissando control - p_fxm->glissando = (fxp != 0); - break; - case 0xE4: // Set vibrato waveform - p_fxm->vibr.mode = fxp; - break; - case 0xE7: // Set tremolo waveform - p_fxm->trem.mode = fxp; - break; - case 0xEA: // Fine volume slide up - p_osc->vol = p_fxm->volume = MIN(p_fxm->volume + fxp, 0x20); - break; - case 0xEB: // Fine volume slide down - p_osc->vol = p_fxm->volume = MAX(p_fxm->volume - fxp, 0); - break; - case 0xEE: // Delay - row_delay = fxp; - break; - } - } else { - - // Effects processed when tick > 0 - switch(fx) { - case 0x10: // Slide up - if(ch != 3) { - p_fxm->period = MAX(p_fxm->period - fxp, PERIOD_MIN); - p_osc->freq = FREQ(p_fxm->period); - } - break; - case 0x20: // Slide down - if(ch != 3) { - p_fxm->period = MIN(p_fxm->period + fxp, PERIOD_MAX); - p_osc->freq = FREQ(p_fxm->period); - } - break; -/* - // Just feels... ugly - case 0xE9: // Retrigger note - temp = tick; while(temp >= fxp) temp -= fxp; - if(!temp) { - if(ch == 3) { - p_osc->freq = p_osc->phase = 0x2000; - } else { - p_osc->phase = 0; - } - } - break; -*/ - case 0xEC: // Note cut - if(fxp == tick) p_osc->vol = 0x00; - break; - default: // Multi-effect processing - - // Portamento - if(ch != 3 && (fx == 0x30 || fx == 0x50)) { - if(p_fxm->period < p_fxm->port_target) p_fxm->period = MIN(p_fxm->period + p_fxm->port_speed, p_fxm->port_target); - else p_fxm->period = MAX(p_fxm->period - p_fxm->port_speed, p_fxm->port_target); - if(p_fxm->glissando) p_osc->freq = FREQ(glissando(ch)); - else p_osc->freq = FREQ(p_fxm->period); - } - - // Volume slide - if(fx == 0x50 || fx == 0x60 || fx == 0xA0) { - if((fxp & 0xF0) == 0) p_fxm->volume -= (LO4(fxp)); - if((fxp & 0x0F) == 0) p_fxm->volume += (HI4(fxp)); - p_osc->vol = p_fxm->volume = MAX(MIN(p_fxm->volume, 0x20), 0); - } - } - } - - // Normal play and arpeggio - if(fx == 0x00) { - if(ch != 3) { - temp = tick; while(temp > 2) temp -= 2; - if(temp == 0) { - - // Reset - p_osc->freq = FREQ(p_fxm->period); - } else if(fxp) { - - // Arpeggio - p_osc->freq = FREQ(arpeggio(ch, (temp == 1 ? HI4(fxp) : LO4(fxp)))); - } - } - } else if(fx == 0x40 || fx == 0x60) { - - // Vibrato - if(ch != 3) p_osc->freq = FREQ((p_fxm->period + do_osc(&p_fxm->vibr))); - } else if(fx == 0x70) { - int8_t trem = p_fxm->volume + do_osc(&p_fxm->trem); - p_osc->vol = MAX(MIN(trem, 0x20), 0); - } - - // Next channel - p_fxm++; p_cel++; p_osc++; - } - - // Advance tick - if(++tick == speed) tick = 0; - - // Advance playback - if(tick == 0) { - if(++ix_row == 64) { - ix_row = 0; - if(++ix_order >= order_count) ix_order = 0; - } - // Forced order/row - if( ix_nextorder != 0xFF ) { - ix_order = ix_nextorder; - ix_nextorder = 0xFF; - } - if( ix_nextrow != 0xFF ) { - ix_row = ix_nextrow; - ix_nextrow = 0xFF; - } - decrunch_row(); - } - - } - - lockout = false; -} \ No newline at end of file diff --git a/libraries/Robot_Control/Squawk.h b/libraries/Robot_Control/Squawk.h deleted file mode 100644 index 3481acf..0000000 --- a/libraries/Robot_Control/Squawk.h +++ /dev/null @@ -1,265 +0,0 @@ -// Squawk Soft-Synthesizer Library for Arduino -// -// Davey Taylor 2013 -// d.taylor@arduino.cc - -#ifndef _SQUAWK_H_ -#define _SQUAWK_H_ -#include -#include -#include "Arduino.h" - -#define Melody const uint8_t PROGMEM - -class SquawkStream { - public: - virtual ~SquawkStream() = 0; - virtual uint8_t read() = 0; - virtual void seek(size_t offset) = 0; -}; -inline SquawkStream::~SquawkStream() { } - -class SquawkSynth { - -protected: - // Load and play specified melody - void play(SquawkStream *melody); - -public: - SquawkSynth() {}; - - // Initialize Squawk to generate samples at sample_rate Hz - void begin(uint16_t sample_rate); - - // Load and play specified melody - // melody needs to point to PROGMEM data - void play(const uint8_t *melody); - - // Resume currently loaded melody (or enable direct osc manipulation by sketch) - void play(); - - // Pause playback - void pause(); - - // Stop playback (unloads song) - void stop(); - - // Tune Squawk to a different frequency - default is 1.0 - void tune(float tuning); - - // Change the tempo - default is 50 - void tempo(uint16_t tempo); -}; - -extern SquawkSynth Squawk; - -// oscillator structure -typedef struct { - uint8_t vol; - uint16_t freq; - uint16_t phase; -} osc_t; - -typedef osc_t Oscillator; - -// oscillator memory -extern osc_t osc[4]; -extern uint8_t pcm; -// channel 0 is pulse wave @ 25% duty -// channel 1 is square wave -// channel 2 is triangle wave -// channel 3 is noise - -// For channel 3, freq is used as part of its LFSR and should not be changed. -// LFSR: Linear feedback shift register, a method of producing a -// pseudo-random bit sequence, used to generate nasty noise. - -#ifdef __AVR_ATmega32U4__ -// Supported configurations for ATmega32U4 -#define SQUAWK_PWM_PIN5 OCR3AL -#define SQUAWK_PWM_PIN11 OCR0A -#define SQUAWK_PWM_PIN3 OCR0B -/* -// NOT SUPPORTED YET -#define SQUAWK_PWM_PIN6 OCR4D -#define SQUAWK_PWM_PIN9 OCR4B -#define SQUAWK_PWM_PIN10 OCR4B -*/ -#endif - -#ifdef __AVR_ATmega168__ -// Supported configurations for ATmega168 -#define SQUAWK_PWM_PIN6 OCR0A -#define SQUAWK_PWM_PIN5 OCR0B -#define SQUAWK_PWM_PIN11 OCR2A -#define SQUAWK_PWM_PIN3 OCR2B -#endif - -#ifdef __AVR_ATmega328P__ -// Supported configurations for ATmega328P -#define SQUAWK_PWM_PIN6 OCR0A -#define SQUAWK_PWM_PIN5 OCR0B -#define SQUAWK_PWM_PIN11 OCR2A -#define SQUAWK_PWM_PIN3 OCR2B -#endif - -/* -// NOT SUPPORTED YET -#define SQUAWK_SPI SPDR -#define SQUAWK_RLD_PORTB PORTB -#define SQUAWK_RLD_PORTC PORTC -*/ - -extern void squawk_playroutine() asm("squawk_playroutine"); - -// SAMPLE GRINDER -// generates samples and updates oscillators -// uses 132 cycles (not counting playroutine) -// ~1/3 CPU @ 44kHz on 16MHz -#define SQUAWK_CONSTRUCT_ISR(TARGET_REGISTER) \ -uint16_t cia, cia_count; \ -intptr_t squawk_register = (intptr_t)&TARGET_REGISTER; \ -ISR(TIMER1_COMPA_vect, ISR_NAKED) { \ - asm volatile( \ - "push r2 " "\n\t" \ - "in r2, __SREG__ " "\n\t" \ - "push r18 " "\n\t" \ - "push r27 " "\n\t" \ - "push r26 " "\n\t" \ - "push r0 " "\n\t" \ - "push r1 " "\n\t" \ -\ - "lds r18, osc+2*%[mul]+%[fre] " "\n\t" \ - "lds r0, osc+2*%[mul]+%[pha] " "\n\t" \ - "add r0, r18 " "\n\t" \ - "sts osc+2*%[mul]+%[pha], r0 " "\n\t" \ - "lds r18, osc+2*%[mul]+%[fre]+1" "\n\t" \ - "lds r1, osc+2*%[mul]+%[pha]+1" "\n\t" \ - "adc r1, r18 " "\n\t" \ - "sts osc+2*%[mul]+%[pha]+1, r1 " "\n\t" \ -\ - "mov r27, r1 " "\n\t" \ - "sbrc r27, 7 " "\n\t" \ - "com r27 " "\n\t" \ - "lsl r27 " "\n\t" \ - "lds r26, osc+2*%[mul]+%[vol] " "\n\t" \ - "subi r27, 128 " "\n\t" \ - "muls r27, r26 " "\n\t" \ - "lsl r1 " "\n\t" \ - "mov r26, r1 " "\n\t" \ -\ - "lds r18, osc+0*%[mul]+%[fre] " "\n\t" \ - "lds r0, osc+0*%[mul]+%[pha] " "\n\t" \ - "add r0, r18 " "\n\t" \ - "sts osc+0*%[mul]+%[pha], r0 " "\n\t" \ - "lds r18, osc+0*%[mul]+%[fre]+1" "\n\t" \ - "lds r1, osc+0*%[mul]+%[pha]+1" "\n\t" \ - "adc r1, r18 " "\n\t" \ - "sts osc+0*%[mul]+%[pha]+1, r1 " "\n\t" \ -\ - "mov r18, r1 " "\n\t" \ - "lsl r18 " "\n\t" \ - "and r18, r1 " "\n\t" \ - "lds r27, osc+0*%[mul]+%[vol] " "\n\t" \ - "sbrc r18, 7 " "\n\t" \ - "neg r27 " "\n\t" \ - "add r26, r27 " "\n\t" \ -\ - "lds r18, osc+1*%[mul]+%[fre] " "\n\t" \ - "lds r0, osc+1*%[mul]+%[pha] " "\n\t" \ - "add r0, r18 " "\n\t" \ - "sts osc+1*%[mul]+%[pha], r0 " "\n\t" \ - "lds r18, osc+1*%[mul]+%[fre]+1" "\n\t" \ - "lds r1, osc+1*%[mul]+%[pha]+1" "\n\t" \ - "adc r1, r18 " "\n\t" \ - "sts osc+1*%[mul]+%[pha]+1, r1 " "\n\t" \ -\ - "lds r27, osc+1*%[mul]+%[vol] " "\n\t" \ - "sbrc r1, 7 " "\n\t" \ - "neg r27 " "\n\t" \ - "add r26, r27 " "\n\t" \ -\ - "ldi r27, 1 " "\n\t" \ - "lds r0, osc+3*%[mul]+%[fre] " "\n\t" \ - "lds r1, osc+3*%[mul]+%[fre]+1" "\n\t" \ - "add r0, r0 " "\n\t" \ - "adc r1, r1 " "\n\t" \ - "sbrc r1, 7 " "\n\t" \ - "eor r0, r27 " "\n\t" \ - "sbrc r1, 6 " "\n\t" \ - "eor r0, r27 " "\n\t" \ - "sts osc+3*%[mul]+%[fre], r0 " "\n\t" \ - "sts osc+3*%[mul]+%[fre]+1, r1 " "\n\t" \ -\ - "lds r27, osc+3*%[mul]+%[vol] " "\n\t" \ - "sbrc r1, 7 " "\n\t" \ - "neg r27 " "\n\t" \ - "add r26, r27 " "\n\t" \ -\ - "lds r27, pcm " "\n\t" \ - "add r26, r27 " "\n\t" \ - "sts %[reg], r26 " "\n\t" \ -\ - "lds r27, cia_count+1 " "\n\t" \ - "lds r26, cia_count " "\n\t" \ - "sbiw r26, 1 " "\n\t" \ - "breq call_playroutine " "\n\t" \ - "sts cia_count+1, r27 " "\n\t" \ - "sts cia_count, r26 " "\n\t" \ - "pop r1 " "\n\t" \ - "pop r0 " "\n\t" \ - "pop r26 " "\n\t" \ - "pop r27 " "\n\t" \ - "pop r18 " "\n\t" \ - "out __SREG__, r2 " "\n\t" \ - "pop r2 " "\n\t" \ - "reti " "\n\t" \ - "call_playroutine: " "\n\t" \ -\ - "lds r27, cia+1 " "\n\t" \ - "lds r26, cia " "\n\t" \ - "sts cia_count+1, r27 " "\n\t" \ - "sts cia_count, r26 " "\n\t" \ -\ - "sei " "\n\t" \ - "push r19 " "\n\t" \ - "push r20 " "\n\t" \ - "push r21 " "\n\t" \ - "push r22 " "\n\t" \ - "push r23 " "\n\t" \ - "push r24 " "\n\t" \ - "push r25 " "\n\t" \ - "push r30 " "\n\t" \ - "push r31 " "\n\t" \ -\ - "clr r1 " "\n\t" \ - "call squawk_playroutine " "\n\t" \ -\ - "pop r31 " "\n\t" \ - "pop r30 " "\n\t" \ - "pop r25 " "\n\t" \ - "pop r24 " "\n\t" \ - "pop r23 " "\n\t" \ - "pop r22 " "\n\t" \ - "pop r21 " "\n\t" \ - "pop r20 " "\n\t" \ - "pop r19 " "\n\t" \ -\ - "pop r1 " "\n\t" \ - "pop r0 " "\n\t" \ - "pop r26 " "\n\t" \ - "pop r27 " "\n\t" \ - "pop r18 " "\n\t" \ - "out __SREG__, r2 " "\n\t" \ - "pop r2 " "\n\t" \ - "reti " "\n\t" \ - : \ - : [reg] "M" _SFR_MEM_ADDR(TARGET_REGISTER), \ - [mul] "M" (sizeof(Oscillator)), \ - [pha] "M" (offsetof(Oscillator, phase)), \ - [fre] "M" (offsetof(Oscillator, freq)), \ - [vol] "M" (offsetof(Oscillator, vol)) \ - ); \ -} - -#endif \ No newline at end of file diff --git a/libraries/Robot_Control/SquawkSD.cpp b/libraries/Robot_Control/SquawkSD.cpp deleted file mode 100644 index 3c97ef4..0000000 --- a/libraries/Robot_Control/SquawkSD.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include - -SquawkSynthSD SquawkSD; - -class StreamFile : public SquawkStream { - private: - Fat16 f; - public: - StreamFile(Fat16 file = Fat16()) { f = file; } - uint8_t read() { return f.read(); } - void seek(size_t offset) { f.seekSet(offset); } -}; - -static StreamFile file; - -extern uint16_t period_tbl[84] PROGMEM; - -void SquawkSynthSD::play(Fat16 melody) { - SquawkSynth::pause(); - file = StreamFile(melody); - SquawkSynth::play(&file); -} - -/* -void SquawkSynthSD::convert(Fat16 in, Fat16 out) { - unsigned int n; - uint8_t patterns = 0, order_count; - unsigned int ptn, row, chn; - uint8_t temp; - - uint8_t fxc[4], fxp[4], note[4], sample[4]; - uint16_t period; - - out.write('S'); // ID - out.write('Q'); - out.write('M'); - out.write('1'); - out.write((uint8_t)0); // No meta data - out.write((uint8_t)0); - - // Write order list, count patterns - in.seek(0x3B6); - order_count = in.read(); - out.write(order_count); - in.seek(0x3B8); - for(n = 0; n < order_count; n++) { - temp = in.read(); - if(temp >= patterns) patterns = temp + 1; - out.write(temp); - } - - // Write patterns - in.seek(0x43C); - for(ptn = 0; ptn < patterns; ptn++) { - for(row = 0; row < 64; row++) { - for(chn = 0; chn < 4; chn++) { - - // Basic extraction - temp = in.read(); // sample.msb and period.msb - period = (temp & 0x0F) << 8; - sample[chn] = temp & 0xF0; - period |= in.read(); // period.lsb - temp = in.read(); // sample.lsb and effect - sample[chn] |= temp >> 4; - fxc[chn] = (temp & 0x0F) << 4; - fxp[chn] = in.read(); // parameters - if(fxc[chn] == 0xE0) { - fxc[chn] |= fxp[chn] >> 4; // extended parameters - fxp[chn] &= 0x0F; - } - - #define DIF(A, B) ((A) > (B) ? ((int32_t)(A) - (int32_t)(B)) : ((int32_t)(B) - (int32_t)(A))) - // Find closest matching period - if(period == 0) { - note[chn] = 0x7F; - } else { - int16_t best = DIF(period, pgm_read_word(&period_tbl[0])); - note[chn] = 0; - for(n = 0; n < sizeof(period_tbl) / sizeof(uint16_t); n++) { - if(DIF(period, pgm_read_word(&period_tbl[n])) < best) { - note[chn] = n; - best = DIF(period, pgm_read_word(&period_tbl[n])); - } - } - } - - // Crunch volume/decimal commands - if(fxc[chn] == 0x50 || fxc[chn] == 0x60 || fxc[chn] == 0xA0) { - fxp[chn] = (fxp[chn] >> 1) & 0x77; - } else if(fxc[chn] == 0x70) { - fxp[chn] = (fxp[chn] & 0xF0) | ((fxp[chn] & 0x0F) >> 1); - } else if(fxc[chn] == 0xC0 || fxc[chn] == 0xEA || fxc[chn] == 0xEB) { - fxp[chn] >>= 1; - } else if(fxc[chn] == 0xD0) { - fxp[chn] = ((fxp[chn] >> 4) * 10) | (fxp[chn] & 0x0F); - } - - // Re-nibblify - it's a word! - if(chn != 3) { - if((fxc[chn] & 0xF0) == 0xE0) fxp[chn] |= fxc[chn] << 4; - fxc[chn] >>= 4; - } - - } - - // Ghetto crunch the last channel to save a byte - switch(fxc[3]) { - case 0x50: case 0x60: case 0xA0: - fxc[3] = 0x1; - if((fxp[3] >> 4) >= (fxp[3] & 0x0F)) { - fxp[3] = 0x80 + ((fxp[3] >> 4) - (fxp[3] & 0x0F)); - } else { - fxp[3] = ((fxp[3] & 0x0F) - (fxp[3] >> 4)); - } - break; - case 0x70: - fxc[3] = (fxp[3] & 0x4) ? 0x3 : 0x2; - fxp[3] = (fxp[3] >> 4) | ((fxp[3] & 0x03) << 4); - break; - case 0xC0: - fxc[3] = 0x4; - fxp[3] &= 0x1F; - break; - case 0xB0: - fxc[3] = 0x5; - fxp[3] &= 0x1F; - break; - case 0xD0: - fxc[3] = 0x6; - if(fxp[3] > 63) fxp[3] = 0; - break; - case 0xF0: - if(fxp[3] > 0x20) { - fxc[3] = 0x0; - fxp[3] = 0x00; - } else { - fxc[3] = 0x7; - } - break; - case 0xE7: - fxc[3] = 0x8; - break; - case 0xE9: - fxc[3] = 0x9; - break; - case 0xEA: - fxc[3] = 0xA; - fxp[3] |= 0x08; - break; - case 0xEB: - fxc[3] = 0xA; - break; - case 0xEC: - fxc[3] = 0xB; - break; - case 0xED: - fxc[3] = 0xB; - fxp[3] |= 0x10; - break; - case 0xEE: - fxc[3] = 0xC; - break; - default: - fxc[3] = 0; - fxp[3] = 0; - } - if(note[3] != 0x7F) fxp[3] |= 0x80; - if(sample[3]) fxp[3] |= 0x40; - - // Write out - out.write((fxc[0]) | fxc[1] << 4); - out.write(fxp[0]); - out.write(fxp[1]); - out.write((fxc[2]) | fxc[3] << 4); - out.write(fxp[2]); - out.write(fxp[3]); - out.write(note[0] | (sample[0] == 0 ? 0x00 : 0x80)); - out.write(note[1] | (sample[1] == 0 ? 0x00 : 0x80)); - out.write(note[2] | (sample[2] == 0 ? 0x00 : 0x80)); - } - } -}*/ \ No newline at end of file diff --git a/libraries/Robot_Control/SquawkSD.h b/libraries/Robot_Control/SquawkSD.h deleted file mode 100644 index 89d46a5..0000000 --- a/libraries/Robot_Control/SquawkSD.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef _SQUAWKSD_H_ -#define _SQUAWKSD_H_ -#include -#include "Fat16.h" - -class SquawkSynthSD : public SquawkSynth { - private: - Fat16 f; - public: - inline void play() { Squawk.play(); }; - void play(Fat16 file); - //void convert(Fat16 in, Fat16 out); -}; - -extern SquawkSynthSD SquawkSD; - -#endif \ No newline at end of file diff --git a/libraries/Robot_Control/Wire.cpp b/libraries/Robot_Control/Wire.cpp deleted file mode 100644 index 4e7a17c..0000000 --- a/libraries/Robot_Control/Wire.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* - TwoWire.cpp - TWI/I2C library for Wiring & Arduino - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts -*/ - -extern "C" { - #include - #include - #include - #include "twi.h" -} - -#include "Wire.h" - -// Initialize Class Variables ////////////////////////////////////////////////// - -uint8_t TwoWire::rxBuffer[BUFFER_LENGTH]; -uint8_t TwoWire::rxBufferIndex = 0; -uint8_t TwoWire::rxBufferLength = 0; - -uint8_t TwoWire::txAddress = 0; -uint8_t TwoWire::txBuffer[BUFFER_LENGTH]; -uint8_t TwoWire::txBufferIndex = 0; -uint8_t TwoWire::txBufferLength = 0; - -uint8_t TwoWire::transmitting = 0; -void (*TwoWire::user_onRequest)(void); -void (*TwoWire::user_onReceive)(int); - -// Constructors //////////////////////////////////////////////////////////////// - -TwoWire::TwoWire() -{ -} - -// Public Methods ////////////////////////////////////////////////////////////// - -void TwoWire::begin(void) -{ - rxBufferIndex = 0; - rxBufferLength = 0; - - txBufferIndex = 0; - txBufferLength = 0; - - twi_init(); -} - -void TwoWire::begin(uint8_t address) -{ - twi_setAddress(address); - twi_attachSlaveTxEvent(onRequestService); - twi_attachSlaveRxEvent(onReceiveService); - begin(); -} - -void TwoWire::begin(int address) -{ - begin((uint8_t)address); -} - -uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop) -{ - // clamp to buffer length - if(quantity > BUFFER_LENGTH){ - quantity = BUFFER_LENGTH; - } - // perform blocking read into buffer - uint8_t read = twi_readFrom(address, rxBuffer, quantity, sendStop); - // set rx buffer iterator vars - rxBufferIndex = 0; - rxBufferLength = read; - - return read; -} - -uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity) -{ - return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true); -} - -uint8_t TwoWire::requestFrom(int address, int quantity) -{ - return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true); -} - -uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop) -{ - return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)sendStop); -} - -void TwoWire::beginTransmission(uint8_t address) -{ - // indicate that we are transmitting - transmitting = 1; - // set address of targeted slave - txAddress = address; - // reset tx buffer iterator vars - txBufferIndex = 0; - txBufferLength = 0; -} - -void TwoWire::beginTransmission(int address) -{ - beginTransmission((uint8_t)address); -} - -// -// Originally, 'endTransmission' was an f(void) function. -// It has been modified to take one parameter indicating -// whether or not a STOP should be performed on the bus. -// Calling endTransmission(false) allows a sketch to -// perform a repeated start. -// -// WARNING: Nothing in the library keeps track of whether -// the bus tenure has been properly ended with a STOP. It -// is very possible to leave the bus in a hung state if -// no call to endTransmission(true) is made. Some I2C -// devices will behave oddly if they do not see a STOP. -// -uint8_t TwoWire::endTransmission(uint8_t sendStop) -{ - // transmit buffer (blocking) - int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1, sendStop); - // reset tx buffer iterator vars - txBufferIndex = 0; - txBufferLength = 0; - // indicate that we are done transmitting - transmitting = 0; - return ret; -} - -// This provides backwards compatibility with the original -// definition, and expected behaviour, of endTransmission -// -uint8_t TwoWire::endTransmission(void) -{ - return endTransmission(true); -} - -// must be called in: -// slave tx event callback -// or after beginTransmission(address) -size_t TwoWire::write(uint8_t data) -{ - if(transmitting){ - // in master transmitter mode - // don't bother if buffer is full - if(txBufferLength >= BUFFER_LENGTH){ - setWriteError(); - return 0; - } - // put byte in tx buffer - txBuffer[txBufferIndex] = data; - ++txBufferIndex; - // update amount in buffer - txBufferLength = txBufferIndex; - }else{ - // in slave send mode - // reply to master - twi_transmit(&data, 1); - } - return 1; -} - -// must be called in: -// slave tx event callback -// or after beginTransmission(address) -size_t TwoWire::write(const uint8_t *data, size_t quantity) -{ - if(transmitting){ - // in master transmitter mode - for(size_t i = 0; i < quantity; ++i){ - write(data[i]); - } - }else{ - // in slave send mode - // reply to master - twi_transmit(data, quantity); - } - return quantity; -} - -// must be called in: -// slave rx event callback -// or after requestFrom(address, numBytes) -int TwoWire::available(void) -{ - return rxBufferLength - rxBufferIndex; -} - -// must be called in: -// slave rx event callback -// or after requestFrom(address, numBytes) -int TwoWire::read(void) -{ - int value = -1; - - // get each successive byte on each call - if(rxBufferIndex < rxBufferLength){ - value = rxBuffer[rxBufferIndex]; - ++rxBufferIndex; - } - - return value; -} - -// must be called in: -// slave rx event callback -// or after requestFrom(address, numBytes) -int TwoWire::peek(void) -{ - int value = -1; - - if(rxBufferIndex < rxBufferLength){ - value = rxBuffer[rxBufferIndex]; - } - - return value; -} - -void TwoWire::flush(void) -{ - // XXX: to be implemented. -} - -// behind the scenes function that is called when data is received -void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes) -{ - // don't bother if user hasn't registered a callback - if(!user_onReceive){ - return; - } - // don't bother if rx buffer is in use by a master requestFrom() op - // i know this drops data, but it allows for slight stupidity - // meaning, they may not have read all the master requestFrom() data yet - if(rxBufferIndex < rxBufferLength){ - return; - } - // copy twi rx buffer into local read buffer - // this enables new reads to happen in parallel - for(uint8_t i = 0; i < numBytes; ++i){ - rxBuffer[i] = inBytes[i]; - } - // set rx iterator vars - rxBufferIndex = 0; - rxBufferLength = numBytes; - // alert user program - user_onReceive(numBytes); -} - -// behind the scenes function that is called when data is requested -void TwoWire::onRequestService(void) -{ - // don't bother if user hasn't registered a callback - if(!user_onRequest){ - return; - } - // reset tx buffer iterator vars - // !!! this will kill any pending pre-master sendTo() activity - txBufferIndex = 0; - txBufferLength = 0; - // alert user program - user_onRequest(); -} - -// sets function called on slave write -void TwoWire::onReceive( void (*function)(int) ) -{ - user_onReceive = function; -} - -// sets function called on slave read -void TwoWire::onRequest( void (*function)(void) ) -{ - user_onRequest = function; -} - -// Preinstantiate Objects ////////////////////////////////////////////////////// - -TwoWire Wire = TwoWire(); - diff --git a/libraries/Robot_Control/Wire.h b/libraries/Robot_Control/Wire.h deleted file mode 100644 index a93d0f5..0000000 --- a/libraries/Robot_Control/Wire.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - TwoWire.h - TWI/I2C library for Arduino & Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts -*/ - -#ifndef TwoWire_h -#define TwoWire_h - -#include -#include "Stream.h" - -#define BUFFER_LENGTH 32 - -class TwoWire : public Stream -{ - private: - static uint8_t rxBuffer[]; - static uint8_t rxBufferIndex; - static uint8_t rxBufferLength; - - static uint8_t txAddress; - static uint8_t txBuffer[]; - static uint8_t txBufferIndex; - static uint8_t txBufferLength; - - static uint8_t transmitting; - static void (*user_onRequest)(void); - static void (*user_onReceive)(int); - static void onRequestService(void); - static void onReceiveService(uint8_t*, int); - public: - TwoWire(); - void begin(); - void begin(uint8_t); - void begin(int); - void beginTransmission(uint8_t); - void beginTransmission(int); - uint8_t endTransmission(void); - uint8_t endTransmission(uint8_t); - uint8_t requestFrom(uint8_t, uint8_t); - uint8_t requestFrom(uint8_t, uint8_t, uint8_t); - uint8_t requestFrom(int, int); - uint8_t requestFrom(int, int, int); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *, size_t); - virtual int available(void); - virtual int read(void); - virtual int peek(void); - virtual void flush(void); - void onReceive( void (*)(int) ); - void onRequest( void (*)(void) ); - - inline size_t write(unsigned long n) { return write((uint8_t)n); } - inline size_t write(long n) { return write((uint8_t)n); } - inline size_t write(unsigned int n) { return write((uint8_t)n); } - inline size_t write(int n) { return write((uint8_t)n); } - using Print::write; -}; - -extern TwoWire Wire; - -#endif - diff --git a/libraries/Robot_Control/communication.cpp b/libraries/Robot_Control/communication.cpp deleted file mode 100644 index eaf5346..0000000 --- a/libraries/Robot_Control/communication.cpp +++ /dev/null @@ -1 +0,0 @@ -#include bool RobotControl::isActionDone(){ if(messageIn.receiveData()){ if(messageIn.readByte()==COMMAND_ACTION_DONE){ return true; } } return false; } void RobotControl::pauseMode(uint8_t onOff){ messageOut.writeByte(COMMAND_PAUSE_MODE); if(onOff){ messageOut.writeByte(true); }else{ messageOut.writeByte(false); } messageOut.sendData(); } void RobotControl::lineFollowConfig(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime){ messageOut.writeByte(COMMAND_LINE_FOLLOW_CONFIG); messageOut.writeByte(KP); messageOut.writeByte(KD); messageOut.writeByte(robotSpeed); messageOut.writeByte(intergrationTime); messageOut.sendData(); } \ No newline at end of file diff --git a/libraries/Robot_Control/examples/explore/R01_Logo/R01_Logo.ino b/libraries/Robot_Control/examples/explore/R01_Logo/R01_Logo.ino deleted file mode 100644 index 794479e..0000000 --- a/libraries/Robot_Control/examples/explore/R01_Logo/R01_Logo.ino +++ /dev/null @@ -1,134 +0,0 @@ -/* Robot Logo - - This sketch demonstrates basic movement of the Robot. - When the sketch starts, press the on-board buttons to tell - the robot how to move. Pressing the middle button will - save the pattern, and the robot will follow accordingly. - You can record up to 20 commands. The robot will move for - one second per command. - - This example uses images on an SD card. It looks for - files named "lg0.bmp" and "lg1.bmp" and draws them on the - screen. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include // include the robot library - -int commands[20]; // array for storing commands - -void setup() { - // initialize the Robot, SD card, and display - Robot.begin(); - Robot.beginTFT(); - Robot.beginSD(); - - // draw "lg0.bmp" and "lg1.bmp" on the screen - Robot.displayLogos(); -} - -void loop() { - - Robot.drawBMP("intro.bmp", 0, 0); //display background image - - iniCommands(); // remove commands from the array - addCommands(); // add commands to the array - - delay(1000); // wait for a second - - executeCommands(); // follow orders - - Robot.stroke(0,0,0); - Robot.text("Done!", 5, 103); // write some text to the display - delay(1500); // wait for a moment -} - -// empty the commands array -void iniCommands() { - for(int i=0; i<20; i++) - commands[i]=-1; -} - -// add commands to the array -void addCommands() { - Robot.stroke(0,0,0); - // display text on the screen - Robot.text("1. Press buttons to\n add commands.\n\n 2. Middle to finish.", 5, 5); - - // read the buttons' state - for(int i=0; i<20;) { //max 20 commands - int key = Robot.keyboardRead(); - if(key == BUTTON_MIDDLE) { //finish input - break; - }else if(key == BUTTON_NONE) { //if no button is pressed - continue; - } - commands[i] = key; // save the button to the array - PrintCommandI(i, 46); // print the command on the screen - delay(100); - i++; - } -} - -// run through the array and move the robot -void executeCommands() { - // print status to the screen - Robot.text("Excuting...",5,70); - - // read through the array and move accordingly - for(int i=0; i<20; i++) { - switch(commands[i]) { - case BUTTON_LEFT: - Robot.turn(-90); - break; - case BUTTON_RIGHT: - Robot.turn(90); - break; - case BUTTON_UP: - Robot.motorsWrite(255, 255); - break; - case BUTTON_DOWN: - Robot.motorsWrite(-255, -255); - break; - case BUTTON_NONE: - return; - } - // print the current command to the screen - Robot.stroke(255,0,0); - PrintCommandI(i, 86); - delay(1000); - - // stop moving for a second - Robot.motorsStop(); - delay(1000); - } -} - -// convert the button press to a single character -char keyToChar(int key) { - switch(key) { - case BUTTON_LEFT: - return '<'; - case BUTTON_RIGHT: - return '>'; - case BUTTON_UP: - return '^'; - case BUTTON_DOWN: - return 'v'; - } -} - -// display a command -void PrintCommandI(int i, int originY) { - Robot.text(keyToChar(commands[i]), i%14*8+5, i/14*10+originY); -} - diff --git a/libraries/Robot_Control/examples/explore/R02_Line_Follow/R02_Line_Follow.ino b/libraries/Robot_Control/examples/explore/R02_Line_Follow/R02_Line_Follow.ino deleted file mode 100644 index 58de253..0000000 --- a/libraries/Robot_Control/examples/explore/R02_Line_Follow/R02_Line_Follow.ino +++ /dev/null @@ -1,73 +0,0 @@ -/* Robot Line Follow - - This sketch demonstrates the line following capabilities - of the Arduino Robot. On the floor, place some black - electrical tape along the path you wish the robot to follow. - To indicate a stopping point, place another piece of tape - perpendicular to the path. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include // include the robot library - -long timerOrigin; // used for counting elapsed time - -void setup() { - // initialize the Robot, SD card, display, and speaker - Robot.begin(); - Robot.beginTFT(); - Robot.beginSD(); - Robot.beginSpeaker(); - - // show the logots on the TFT screen - Robot.displayLogos(); - - Robot.drawBMP("lf.bmp", 0, 0); // display background image - - Robot.playFile("chase.sqm"); // play a song from the SD card - - // add the instructions - Robot.text("Line Following\n\n place the robot on\n the track and \n see it run", 5, 5); - Robot.text("Press the middle\n button to start...", 5, 61); - Robot.waitContinue(); - - // These are some general values that work for line following - // uncomment one or the other to see the different behaviors of the robot - // Robot.lineFollowConfig(11, 5, 50, 10); - Robot.lineFollowConfig(14, 9, 50, 10); - - //set the motor board into line-follow mode - Robot.setMode(MODE_LINE_FOLLOW); - - // start - Robot.fill(255, 255, 255); - Robot.stroke(255, 255, 255); - Robot.rect(0, 0, 128, 80); // erase the previous text - Robot.stroke(0, 0, 0); - Robot.text("Start", 5, 5); - - Robot.stroke(0, 0, 0); // choose color for the text - Robot.text("Time passed:", 5, 21); // write some text to the screen - - timerOrigin=millis(); // keep track of the elapsed time - - while(!Robot.isActionDone()) { //wait for the finish signal - Robot.debugPrint(millis()-timerOrigin, 5, 29); // show how much time has passed - } - - Robot.stroke(0, 0, 0); - Robot.text("Done!", 5, 45); -} -void loop() { - //nothing here, the program only runs once. Reset the robot - //to do it again! -} diff --git a/libraries/Robot_Control/examples/explore/R03_Disco_Bot/R03_Disco_Bot.ino b/libraries/Robot_Control/examples/explore/R03_Disco_Bot/R03_Disco_Bot.ino deleted file mode 100644 index 3574b01..0000000 --- a/libraries/Robot_Control/examples/explore/R03_Disco_Bot/R03_Disco_Bot.ino +++ /dev/null @@ -1,179 +0,0 @@ -/* Disco Bot - - This sketch shows you how to use the melody playing - feature of the robot, with some really cool 8-bit music. - Music will play when the robot is turned on, and it - will show you some dance moves. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include // include the robot library - -/* Dancing steps: - S: stop - L: turn left - R: turn right - F: go forward - B: go backwards - - The number after each command determines how long - each step lasts. Each number is 1/2 second long. - - The "\0" indicates end of string -*/ -char danceScript[] = "S4L1R1S2F1B1S1\0"; - -int currentScript = 0; // what step are we at - -int currentSong = 0; // keep track of the current song -static const int SONGS_COUNT = 3; // number of songs - -// an array to hold the songs -char musics[][11] = { - "melody.sqm", - "menu.sqm", - "chase.sqm", -}; - -// variables for non-blocking delay -long waitFrom; -long waitTime = 0; - -void setup() { - // initialize the Robot, SD card, display, and speaker - Robot.begin(); - Robot.beginSpeaker(); - Robot.beginSD(); - Robot.beginTFT(); - - // draw "lg0.bmp" and "lg1.bmp" on the screen - Robot.displayLogos(); - - // Print instructions to the screen - Robot.text("1. Use left and\n right key to switch\n song", 5, 5); - Robot.text("2. Put robot on the\n ground to dance", 5, 33); - - // wait for a few soconds - delay(3000); - - setInterface(); // display the current song - play(0); //play the first song in the array - - resetWait(); //Initialize non-blocking delay -} - -void loop() { - // read the butttons on the robot - int key = Robot.keyboardRead(); - - // Right/left buttons play next/previous song - switch(key) { - case BUTTON_UP: - case BUTTON_LEFT: - play(-1); //play previous song - break; - case BUTTON_DOWN: - case BUTTON_RIGHT: - play(1); //play next song - break; - } - - // dance! - runScript(); -} - -// Dancing function -void runScript() { - if(!waiting()) { // if the previous instructions have finished - // get the next 2 commands (direction and duration) - parseCommand(danceScript[currentScript], danceScript[currentScript+1]); - currentScript += 2; - if(danceScript[currentScript] == '\0') // at the end of the array - currentScript = 0; // start again at the beginning - } -} - -// instead of delay, use this timer -boolean waiting() { - if(millis()-waitFrom >= waitTime) - return false; - else - return true; -} - -// how long to wait -void wait(long t) { - resetWait(); - waitTime = t; -} - -// reset the timer -void resetWait() { - waitFrom = millis(); -} - -// read the direction and dirstion of the steps -void parseCommand(char dir, char duration) { - //convert the scripts to action - switch(dir) { - case 'L': - Robot.motorsWrite(-255, 255); - break; - case 'R': - Robot.motorsWrite(255, -255); - break; - case 'F': - Robot.motorsWrite(255, 255); - break; - case 'B': - Robot.motorsWrite(-255, -255); - break; - case 'S': - Robot.motorsStop(); - break; - } - //You can change "500" to change the pace of dancing - wait(500*(duration-'0')); -} - -// display the song -void setInterface() { - Robot.clearScreen(); - Robot.stroke(0, 0, 0); - Robot.text(musics[0], 0, 0); -} - -// display the next song -void select(int seq, boolean onOff) { - if(onOff){//select - Robot.stroke(0, 0, 0); - Robot.text(musics[seq], 0, 0); - }else{//deselect - Robot.stroke(255, 255, 255); - Robot.text(musics[seq], 0, 0); - } -} - -// play the slected song -void play(int seq) { - select(currentSong, false); - if(currentSong <= 0 && seq == -1) { //previous of 1st song? - currentSong = SONGS_COUNT-1; //go to last song - } else if(currentSong >= SONGS_COUNT-1 && seq == 1) { //next of last? - currentSong = 0; //go to 1st song - } else { - currentSong += seq; //next song - } - Robot.stopPlayFile(); - Robot.playFile(musics[currentSong]); - select(currentSong, true); //display the current song -} diff --git a/libraries/Robot_Control/examples/explore/R04_Compass/R04_Compass.ino b/libraries/Robot_Control/examples/explore/R04_Compass/R04_Compass.ino deleted file mode 100644 index a7a7315..0000000 --- a/libraries/Robot_Control/examples/explore/R04_Compass/R04_Compass.ino +++ /dev/null @@ -1,70 +0,0 @@ -/* Robot Compass - - The robot has an on-board compass module, with - which it can tell the direction the robot is - facing. This sketch will make sure the robot - goes towards a certain direction. - - Beware, magnets will interfere with the compass - readings. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -// include the robot library -#include - -int speedLeft; -int speedRight; -int compassValue; -int direc = 180; //Direction the robot is heading - -void setup() { - // initialize the modules - Robot.begin(); - Robot.beginTFT(); - Robot.beginSD(); - Robot.displayLogos(); -} - -void loop() { - // read the compass orientation - compassValue = Robot.compassRead(); - - // how many degrees are we off - int diff = compassValue-direc; - - // modify degress - if(diff > 180) - diff = -360+diff; - else if(diff < -180) - diff = 360+diff; - - // Make the robot turn to its proper orientation - diff = map(diff, -180, 180, -255, 255); - - if(diff > 0) { - // keep the right wheel spinning, - // change the speed of the left wheel - speedLeft = 255-diff; - speedRight = 255; - } else { - // keep the right left spinning, - // change the speed of the left wheel - speedLeft = 255; - speedRight = 255+diff; - } - // write out to the motors - Robot.motorsWrite(speedLeft, speedRight); - - // draw the orientation on the screen - Robot.drawCompass(compassValue); -} diff --git a/libraries/Robot_Control/examples/explore/R05_Inputs/R05_Inputs.ino b/libraries/Robot_Control/examples/explore/R05_Inputs/R05_Inputs.ino deleted file mode 100644 index 1359f8d..0000000 --- a/libraries/Robot_Control/examples/explore/R05_Inputs/R05_Inputs.ino +++ /dev/null @@ -1,166 +0,0 @@ -/* Robot Inputs - - This sketch shows you how to use the on-board - potentiometer and buttons as inputs. - - Turning the potentiometer draws a clock-shaped - circle. The up and down buttons change the pitch, - while the left and right buttons change the tempo. - The middle button resets tempo and pitch. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -// default tempo and pitch of the music -int tempo = 60; -int pitch = 1000; - -void setup() { - // initialize the Robot, SD card, speaker, and display - Robot.begin(); - Robot.beginTFT(); - Robot.beginSpeaker(); - Robot.beginSD(); - - // draw "lg0.bmp" and "lg1.bmp" on the screen - Robot.displayLogos(); - - // play a sound file - Robot.playFile("Melody.sqm"); -} - -void loop() { - // check the value of the buttons - keyDown(Robot.keyboardRead()); - - // check the value of the pot - drawKnob(Robot.knobRead()); -} - -// Draw the basic interface -void renderUI() { - //fill the buttons blank - Robot.fill(255, 255, 255); - Robot.rect(53, 58, 13, 13); // left - Robot.rect(93, 58, 13, 13); // right - Robot.rect(73, 38, 13, 13); // up - Robot.circle(79, 64, 6); // middle - Robot.rect(73, 78, 13, 13); // down - Robot.circle(26, 116, 18); // knob - - //draw the vertical bargraph - int fullPart=map(pitch, 200, 2000, 0, 58); //length of filled bargraph - Robot.fill(255, 255, 255); - Robot.rect(21, 30, 13, 58-fullPart); - Robot.fill(0, 0, 255); - Robot.rect(21, 88-fullPart, 13, fullPart); //58-fullPart+30 - - //draw the horizontal bargraph - fullPart = map(tempo, 20, 100, 0, 58); // length of filled bargraph - Robot.fill(255, 190, 0); - Robot.rect(53, 110, fullPart, 13); - Robot.fill(255, 255, 255); - Robot.rect(53+fullPart, 110, 58-fullPart, 13); -} - -void keyDown(int keyCode) { - // use a static int so it is persistent over time - static int oldKey; - switch(keyCode) { - case BUTTON_LEFT: - //left button pressed, reduces tempo - tempo -= 5; - if(tempo < 20) tempo = 20; //lowest tempo 20 - Robot.fill(255,190,0); - - Robot.rect(53, 58, 13, 13); - break; - case BUTTON_RIGHT: - //right button pressed, increases tempo - tempo += 5; - if(tempo > 100) tempo = 100; //highest tempo 100 - Robot.fill(255,190,0); - Robot.rect(93, 58, 13, 13); - break; - case BUTTON_UP: - //up button pressed, increases pitch - pitch += 120; - if(pitch > 2000) pitch = 2000; - Robot.fill(0, 0, 255); - - Robot.rect(73, 38, 13, 13); - break; - case BUTTON_DOWN: - //down button pressed, reduces pitch - pitch -= 120; - if(pitch < 200){ - pitch = 200; - } - Robot.fill(0, 0, 255); - - Robot.rect(73, 78, 13, 13); - break; - case BUTTON_MIDDLE: - //middle button pressed, resets tempo and pitch - tempo = 60; - pitch = 1000; - Robot.fill(160,160,160); - - Robot.circle(79, 64, 6); - break; - case BUTTON_NONE: - //Only when the keys are released(thus BUTTON_NONE is - //encountered the first time), the interface will be - //re-drawn. - if(oldKey != BUTTON_NONE){ - renderUI(); - } - break; - } - if(oldKey != keyCode) { - // change the song's tempo - Robot.tempoWrite(tempo); - // change the song's pitch - Robot.tuneWrite(float(pitch/1000.0)); - } - oldKey = keyCode; -} - -void drawKnob(int val) { - static int x = 0, y = 0, val_old = 0; - // radian number, -3.14 to 3.14 - float ang = map(val, 0, 1023, -PI*1000, PI*1000) / 1000.0; - - // erase the old line - if (val_old != val) { - Robot.stroke(255, 255, 255); - Robot.line(26, 116, x, y); - } - - // the following lines avoid a glitch in the TFT library - // that seems to appear when drawing a vertical line - if (val < 1011 && val > 265 || val < 253) { - //a bit math for drawing the hand inside the clock - x = 16*sin(ang)+26; - y = 16*cos(ang)+116; - } - if (val > 265 && val < 253) { - x = 10; y = 116; - } - if (val >= 1011) { - x = 27; y = 100; - } - Robot.stroke(0, 0, 0); - Robot.line(26, 116, x, y); - val_old = val; -} diff --git a/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/R06_Wheel_Calibration.ino b/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/R06_Wheel_Calibration.ino deleted file mode 100644 index c571b3a..0000000 --- a/libraries/Robot_Control/examples/explore/R06_Wheel_Calibration/R06_Wheel_Calibration.ino +++ /dev/null @@ -1,103 +0,0 @@ -/* 6 Wheel Calibration - - Use this sketch to calibrate the wheels in your robot. - Your robot should drive as straight as possible when - putting both motors at the same speed. - - Run the software and follow the on-screen instructions. - Use the trimmer on the motor board to make sure the - robot is working at its best! - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include // inport the robot librsry -// import the utility library -// a description of its funtionality is below -#include - -// arrays to hold the text for instructions -char script1[] ="Wheel Calibration"; -char script2[] ="1. Put Robot on a\n flat surface"; -char script3[] ="2. Adjust speed with the knob on top"; -char script4[] ="3. If robot goes\n straight, it's done"; -char script5[] ="4. Use screwdriver\n on the bottom trim"; -char script6[] ="- Robot turns left,\n screw it clockwise;"; -char script7[] ="- Turns right, screw it ct-colockwise;"; -char script8[] ="5. Repeat 4 until\n going straight"; - -int speedRobot; //robot speed -int calibrationValue; //value for calibrate difference between wheels - -void setup(){ - //necessary initialization sequence - Robot.begin(); - Robot.beginTFT(); - Robot.beginSD(); - - // left and top margin for displaying text - // see below for a description of this - textManager.setMargin(5,5); - // write all instructions at once - writeAllscript(); - -} -void loop(){ - //Control the robot's speed with knob on top - int speedRobot=map(Robot.knobRead(),0,1023,-255,255); - Robot.motorsWrite(speedRobot,speedRobot); - - //read value of the pot on motor baord,to clibrate the wheels - int calibrationValue=map(Robot.trimRead(),0,1023,-30,30); - // print the values to the screen - Robot.debugPrint(calibrationValue,110,145); - delay(40); - -} - -void writeAllscript(){ - //prints 8 scripts one after another - textManager.writeText(0,0,script1); - textManager.writeText(1,0,script2); - textManager.writeText(3,0,script3); - textManager.writeText(5,0,script4); - textManager.writeText(7,0,script5); - textManager.writeText(9,0,script6); - textManager.writeText(11,0,script7); - textManager.writeText(13,0,script8); -} - -/** -textManager mostly contains helper functions for -R06_Wheel_Calibration and R01_Hello_User. - - textManager.setMargin(margin_left, margin_top): - Configure the left and top margin for text - display. The margins will be used by - textManager.writeText(). - Parameters: - margin_left, margin_top: int, the margin values - from the top and left side of the screen. - Returns: - none - - textManager.writeText(line,column,text): - Display text on the specific line and column. - It's different from Robot.text() which - uses pixels for positioning the text. - Parameters: - line:int, which line is the text displayed. Each line - is 10px high. - column:int, which column is the text displayed. Each - column is 8px wide. - text:a char array(string) of the text to be displayed. - Returns: - none -*/ diff --git a/libraries/Robot_Control/examples/explore/R07_Runaway_Robot/R07_Runaway_Robot.ino b/libraries/Robot_Control/examples/explore/R07_Runaway_Robot/R07_Runaway_Robot.ino deleted file mode 100644 index 9832d29..0000000 --- a/libraries/Robot_Control/examples/explore/R07_Runaway_Robot/R07_Runaway_Robot.ino +++ /dev/null @@ -1,78 +0,0 @@ -/* Runaway Robot - - Play tag with your robot! With an ultrasonic - distance sensor, it's capable of detecting and avoiding - obstacles, never bumping into walls again! - - You'll need to attach an untrasonic range finder to TK1. - - Circuit: - * Arduino Robot - * US range finder like Maxbotix EZ10, with analog output - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -// include the robot library -#include - -int sensorPin = TK1; // pin is used by the sensor - -void setup() { - // initialize the Robot, SD card, and display - Serial.begin(9600); - Robot.begin(); - Robot.beginTFT(); - Robot.beginSD(); - Robot.displayLogos(); - - // draw a face on the LCD screen - setFace(true); -} - -void loop() { - // If the robot is blocked, turn until free - while(getDistance() < 40) { // If an obstacle is less than 20cm away - setFace(false); //shows an unhappy face - Robot.motorsStop(); // stop the motors - delay(1000); // wait for a moment - Robot.turn(90); // turn to the right and try again - setFace(true); // happy face - } - // if there are no objects in the way, keep moving - Robot.motorsWrite(255, 255); - delay(100); -} - -// return the distance in cm -float getDistance() { - // read the value from the sensor - int sensorValue = Robot.analogRead(sensorPin); - //Convert the sensor input to cm. - float distance_cm = sensorValue*1.27; - return distance_cm; -} - -// make a happy or sad face -void setFace(boolean onOff) { - if(onOff) { - // if true show a happy face - Robot.background(0, 0, 255); - Robot.setCursor(44, 60); - Robot.stroke(0, 255, 0); - Robot.setTextSize(4); - Robot.print(":)"); - }else{ - // if false show an upset face - Robot.background(255, 0, 0); - Robot.setCursor(44, 60); - Robot.stroke(0, 255, 0); - Robot.setTextSize(4); - Robot.print("X("); - } -} diff --git a/libraries/Robot_Control/examples/explore/R08_Remote_Control/R08_Remote_Control.ino b/libraries/Robot_Control/examples/explore/R08_Remote_Control/R08_Remote_Control.ino deleted file mode 100644 index fda21cb..0000000 --- a/libraries/Robot_Control/examples/explore/R08_Remote_Control/R08_Remote_Control.ino +++ /dev/null @@ -1,123 +0,0 @@ -/* 08 Remote Control - - ******************* - *** - ***This example code is in an experimental state. - ***You are welcome to try this with your robot, - ***and no harm will come to it. We will provide a - ***detailed description of an updated version of this - ***in a future update - *** - *** For this example to work you need: - *** - *** - download and install the IR-Remote library by Ken Shirriff - *** to be found at https://github.com/shirriff/Arduino-IRremote - *** - get a Sony remote control - *** - *** This example will be updated soon, come back to the Robot - *** page on the Arduino server for updates!! - *** - ******************* - - If you connect a IR receiver to the robot, - you can control it like you control a TV set. - Using a Sony compatiable remote control, - map some buttons to different actions. - You can make the robot move around without - even touching it! - - Circuit: - * Arduino Robot - * Connect the IRreceiver to TDK2 - * Sony compatible remote control - - based on the IRremote library - by Ken Shirriff - http://arcfn.com - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -// include the necessary libraries -#include -#include - -// Define a few commands from your remote control -#define IR_CODE_FORWARD 0x2C9B -#define IR_CODE_BACKWARDS 0x6C9B -#define IR_CODE_TURN_LEFT 0xD4B8F -#define IR_CODE_TURN_RIGHT 0x34B8F - -int RECV_PIN = TKD2; // the pin the IR receiver is connected to -IRrecv irrecv(RECV_PIN); // an instance of the IR receiver object -decode_results results; // container for received IR codes - -void setup() { - // initialize the Robot, SD card, display, and speaker - Robot.begin(); - Robot.beginTFT(); - Robot.beginSD(); - - // print some text to the screen - Robot.stroke(0, 0, 0); - Robot.text("Remote Control code:", 5, 5); - Robot.text("Command:", 5, 26); - irrecv.enableIRIn(); // Start the receiver -} - -void loop() { - // if there is an IR command, process it - if (irrecv.decode(&results)) { - processResult(); - irrecv.resume(); // resume receiver - } -} - -void processResult() { - unsigned long res = results.value; - // print the value to the screen - Robot.debugPrint(res, 5, 15); - - if(res == IR_CODE_FORWARD || res == IR_CODE_BACKWARDS || res == IR_CODE_TURN_LEFT || res == IR_CODE_TURN_RIGHT) { - Robot.fill(255, 255, 255); - Robot.stroke(255, 255, 255); - - Robot.rect(5, 36, 55, 10); - } - switch(results.value){ - case IR_CODE_FORWARD: - Robot.stroke(0, 0, 0); - Robot.text("Forward", 5, 36); - Robot.motorsWrite(255, 255); - delay(300); - Robot.motorsStop(); - break; - case IR_CODE_BACKWARDS: - Robot.stroke(0, 0, 0); - Robot.text("Backwards", 5, 36); - Robot.motorsWrite(-255, -255); - delay(300); - Robot.motorsStop(); - break; - case IR_CODE_TURN_LEFT: - Robot.stroke(0, 0, 0); - Robot.text("Left", 5, 36); - Robot.motorsWrite(-255, 255); - delay(100); - Robot.motorsStop(); - break; - case IR_CODE_TURN_RIGHT: - Robot.stroke(0, 0, 0); - Robot.text("Right", 5, 36); - Robot.motorsWrite(255, -255); - delay(100); - Robot.motorsStop(); - break; - } -} - diff --git a/libraries/Robot_Control/examples/explore/R09_Picture_Browser/R09_Picture_Browser.ino b/libraries/Robot_Control/examples/explore/R09_Picture_Browser/R09_Picture_Browser.ino deleted file mode 100644 index a43348c..0000000 --- a/libraries/Robot_Control/examples/explore/R09_Picture_Browser/R09_Picture_Browser.ino +++ /dev/null @@ -1,159 +0,0 @@ -/* Picture Browser - - You can make your own gallery/picture show with the - Robot. Put some pictures on the SD card, start the - sketch, they will diplay on the screen. - - Use the left/right buttons to navigate through the - previous and next images. - - Press up or down to enter a mode where you change - the pictures by rotating the robot. - - You can add your own pictures onto the SD card, and - view them in the Robot's gallery! - - Pictures must be uncompressed BMP, 24-bit color depth, - 160 pixels wide, and 128 pixels tall. - - They should be named as "picN.bmp". Replace 'N' with a - number between 0 and 9. - - The current code only supports 10 pictures. How would you - improve it to handle more? - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include // include the robot library - -const int NUM_PICS = 4; //Total number of pictures in Gallery - -// name the modes -const int CONTROL_MODE_KEY = 0; -const int CONTROL_MODE_COMPASS = 1; - -char buffer[] = "pic1.bmp"; // current file name -int i = 1; // Current gallery sequence counter -int mode = 0; // Current mode - -// text to display on screen -char modeNames[][9] = { "keyboard", "tilt " }; - -void setup() { - // initialize the Robot, SD card, display, and speaker - Robot.beginSD(); - Robot.beginTFT(); - Robot.begin(); - - // draw "lg0.bmp" and "lg1.bmp" on the screen - Robot.displayLogos(); - - // draw init3.bmp from the SD card on the screen - Robot.drawBMP("init3.bmp", 0, 0); - - // display instructions - Robot.stroke(0, 0, 0); - Robot.text("The gallery\n\n has 2 modes, in\n keyboard mode, L/R\n key for switching\n pictures, U/D key\n for changing modes", 5, 5); - delay(6000); - Robot.clearScreen(); - Robot.drawBMP("pb.bmp", 0, 0); - Robot.text("In tilt mode,\n quickly tilt the\n robot to switch\n pictures", 5, 5); - delay(4000); -} - -void loop() { - buffer[3] = '0'+i;// change filename of the img to be displayed - Robot.drawBMP(buffer, 0, 0); // draw the file on the screen - // change control modes - switch(mode) { - case CONTROL_MODE_COMPASS: - compassControl(3); - break; - case CONTROL_MODE_KEY: - keyboardControl(); - break; - } - delay(200); -} - -void keyboardControl() { - //Use buttons to control the gallery - while(true) { - int keyPressed = Robot.keyboardRead(); // read the button values - switch(keyPressed) { - case BUTTON_LEFT: // display previous picture - if(--i < 1) i = NUM_PICS; - return; - case BUTTON_MIDDLE: // do nothing - case BUTTON_RIGHT: // display next picture - if(++i > NUM_PICS) i = 1; - return; - case BUTTON_UP: // change mode - changeMode(-1); - return; - case BUTTON_DOWN: // change mode - changeMode(1); - return; - } - } -} - -// if controlling by the compass -void compassControl(int change) { - // Rotate the robot to change the pictures - while(true) { - // read the value of the compass - int oldV = Robot.compassRead(); - - //get the change of angle - int diff = Robot.compassRead()-oldV; - if(diff > 180) diff -= 360; - else if(diff < -180) diff += 360; - - if(abs(diff) > change) { - if(++i > NUM_PICS) i = 1; - return; - } - - // chage modes, if buttons are pressed - int keyPressed = Robot.keyboardRead(); - switch(keyPressed) { - case BUTTON_UP: - changeMode(-1); - return; - case BUTTON_DOWN: - changeMode(1); - return; - } - delay(10); - } -} - -// Change the control mode and display it on the LCD -void changeMode(int changeDir) { - // alternate modes - mode += changeDir; - if(mode < 0) { - mode = 1; - } else if(mode > 1) - mode=0; - - // display the mode on screen - Robot.fill(255, 255, 255); - Robot.stroke(255, 255, 255); - Robot.rect(0, 0, 128, 12); - Robot.stroke(0, 0, 0); - Robot.text("Control:", 2, 2); - Robot.text(modeNames[mode], 52, 2); - delay(1000); -} - diff --git a/libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino b/libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino deleted file mode 100644 index 48044db..0000000 --- a/libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino +++ /dev/null @@ -1,124 +0,0 @@ -/* Robot Rescue - - In this example, the robot enters the line following mode and - plays some music until it reaches its target. Once it finds the - target, it pushes it out of the track. It then returns to the - track and looks for a second target. - - You can make the robot push as many objects as you want to, just - add more to calls to the rescue function or even move that code - into the loop. - - Circuit: - * Arduino Robot - * some objects for the robot to push - * a line-following circuit - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include // include the robot library - -void setup(){ - // initialize the Robot, SD card, display, and speaker - Robot.begin(); - Robot.beginTFT(); - Robot.beginSD(); - Robot.beginSpeaker(); - - // draw "lg0.bmp" and "lg1.bmp" on the screen - Robot.displayLogos(); - - // display the line following instructional image from the SD card - Robot.drawBMP("lf.bmp", 0, 0); - - // play the chase music file - Robot.playFile("chase.sqm"); - - // add the instructions - Robot.text("Rescue\n\n place the robot on\n the rescue track\n pushing the\n obstacles away", 5, 5); - Robot.text("Press the middle\n button to start...", 5, 61); - Robot.waitContinue(); - - // start - Robot.fill(255, 255, 255); - Robot.stroke(255, 255, 255); - Robot.rect(0, 0, 128, 80); // erase the previous text - Robot.stroke(0, 0, 0); - Robot.text("Start", 5, 5); - - // use this to calibrate the line following algorithm - // uncomment one or the other to see the different behaviors of the robot - // Robot.lineFollowConfig(11, 5, 50, 10); - Robot.lineFollowConfig(14, 9, 50, 10); - - // run the rescue sequence - rescueSequence(); - Robot.text("Found obstacle", 5, 12); - // find the track again - goToNext(); - Robot.text("Found track", 5, 19); - // run the rescue sequence a second time - rescueSequence(); - Robot.text("Found obstacle", 5, 26); - - // here you could go on ... - - // write status on the screen - Robot.stroke(0, 0, 0); - Robot.text("Done!", 5, 25); -} - -void loop(){ - //nothing here, the program only runs once. -} - -// run the sequence -void rescueSequence(){ - //set the motor board into line-follow mode - Robot.setMode(MODE_LINE_FOLLOW); - - while(!Robot.isActionDone()){ // wait until it is no longer following the line - } - delay(1000); - - // do the rescue operation - doRescue(); - delay(1000); -} - -void doRescue(){ - // Reached the endline, engage the target - Robot.motorsWrite(200,200); - delay(250); - Robot.motorsStop(); - delay(1000); - - // Turn the robot - Robot.turn(90); - Robot.motorsStop(); - delay(1000); - - // Move forward - Robot.motorsWrite(200,200); - delay(500); - Robot.motorsStop(); - delay(1000); - - // move backwards, leave the target - Robot.motorsWrite(-200,-200); - delay(500); - Robot.motorsStop(); -} - -void goToNext(){ - // Turn the robot - Robot.turn(-90); - Robot.motorsStop(); - delay(1000); -} diff --git a/libraries/Robot_Control/examples/explore/R11_Hello_User/R11_Hello_User.ino b/libraries/Robot_Control/examples/explore/R11_Hello_User/R11_Hello_User.ino deleted file mode 100644 index 90fbfff..0000000 --- a/libraries/Robot_Control/examples/explore/R11_Hello_User/R11_Hello_User.ino +++ /dev/null @@ -1,181 +0,0 @@ -/* Hello User - - Hello User! This sketch is the first thing you see - when starting this robot. It gives you a warm welcome, - showing you some of the really amazing abilities of - the robot, and make itself really personal to you. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include // include the robot library -// include the utility function for ths sketch -// see the details below -#include - -char buffer[20];//for storing user name - -void setup(){ - //necessary initialization sequence - Robot.begin(); - Robot.beginTFT(); - Robot.beginSpeaker(32000); - Robot.beginSD(); - - // show the logos from the SD card - Robot.displayLogos(); - - // play the music file - Robot.playFile("menu.sqm"); - - // clear the screen - Robot.clearScreen(); - - // From now on, display different slides of - // text/pictures in sequence. The so-called - // scripts are strings of text stored in the - // robot's memory - - // these functions are explained below - - //Script 6 - textManager.writeScript(5, 4, 0); - textManager.writeScript(9, 10, 0); - Robot.waitContinue(); - delay(500); - Robot.clearScreen(); - - //Script 7 - textManager.writeScript(6, 4, 0); - textManager.writeScript(9, 10, 0); - Robot.waitContinue(); - delay(500); - Robot.clearScreen(); - - //Script 8 - // this function enables sound and images at once - textManager.showPicture("init2.bmp", 0, 0); - - textManager.writeScript(7, 2, 0); - textManager.writeScript(9, 7, 0); - Robot.waitContinue(); - delay(500); - Robot.clearScreen(); - - //Script 9 - textManager.showPicture("init3.bmp", 0, 0); - textManager.writeScript(8, 2, 0); - textManager.writeScript(9, 7, 0); - Robot.waitContinue(); - delay(500); - Robot.clearScreen(); - - //Script 11 - textManager.writeScript(10, 4, 0); - textManager.writeScript(9, 10, 0); - Robot.waitContinue(); - delay(500); - Robot.clearScreen(); - - //Input screen - textManager.writeScript(0, 1, 1); - textManager.input(3, 1, USERNAME); - - textManager.writeScript(1, 5, 1); - textManager.input(7, 1, ROBOTNAME); - - delay(1000); - Robot.clearScreen(); - - //last screen - textManager.showPicture("init4.bmp", 0, 0); - textManager.writeText(1, 2, "Hello"); - Robot.userNameRead(buffer); - textManager.writeText(3, 2, buffer); - - textManager.writeScript(4,10,0); - - Robot.waitContinue(BUTTON_LEFT); - Robot.waitContinue(BUTTON_RIGHT); - textManager.showPicture("kt1.bmp", 0, 0); -} - -void loop(){ - // do nothing here -} - - -/** -textManager mostly contains helper functions for -R06_Wheel_Calibration and R01_Hello_User. - -The ones used in this example: - textManager.setMargin(margin_left, margin_top): - Configure the left and top margin for text - display. The margins will be used for - textManager.writeText(). - Parameters: - margin_left, margin_top: the margin values - from the top and left side of the screen. - Returns: - none - - textManager.writeScript(script_number,line,column): - Display a script of Hello User example. - Parameters: - script_number: an int value representing the - script to be displayed. - line, column: in which line,column is the script - displayed. Same as writeText(). - Returns: - none - - textManager.input(line,column,codename): - Print an input indicator(">") in the line and column, - dispaly and receive input from a virtual keyboard, - and save the value into EEPROM represented by codename - Parameters: - line,column: int values represents where the input - starts. Same as wirteText(). - codename: either USERNAME,ROBOTNAME,CITYNAME or - COUNTRYNAME. You can call Robot.userNameRead(), - robotNameRead(),cityNameRead() or countryNameRead() - to access the values later. - Returns: - none; - - textManager.writeText(line,column,text): - Display text on the specific line and column. - It's different from Robot.text() as the later - uses pixels for positioning the text. - Parameters: - line:in which line is the text displayed. Each line - is 10px high. - column:in which column is the text displayed. Each - column is 8px wide. - text:a char array(string) of the text to be displayed. - Returns: - none - - textManager.showPicture(filename, x, y): - It has the same functionality as Robot.drawPicture(), - while fixing the conflict between drawPicture() and - sound playing. Using Robot.drawPicture(), it'll have - glitches when playing sound at the same time. Using - showPicture(), it'll stop sound when displaying - picture, so preventing the problem. - Parameters: - filename:string, name of the bmp file in sd - x,y: int values, position of the picture - Returns: - none - -*/ diff --git a/libraries/Robot_Control/examples/learn/AllIOPorts/AllIOPorts.ino b/libraries/Robot_Control/examples/learn/AllIOPorts/AllIOPorts.ino deleted file mode 100644 index 3520214..0000000 --- a/libraries/Robot_Control/examples/learn/AllIOPorts/AllIOPorts.ino +++ /dev/null @@ -1,149 +0,0 @@ -/* - All IO Ports - - This example goes through all the IO ports on your robot and - reads/writes from/to them. Uncomment the different lines inside - the loop to test the different possibilities. - - The TK inputs on the Control Board are multiplexed and therefore - it is not recommended to use them as outputs. The TKD pins on the - Control Board as well as the TK pins on the Motor Board go directly - to the microcontroller and therefore can be used both as inputs - and outputs. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -// use arrays to store the names of the pins to be read -uint8_t arr[] = { TK0, TK1, TK2, TK3, TK4, TK5, TK6, TK7 }; -uint8_t arr2[] = { TKD0, TKD1, TKD2, TKD3, TKD4, TKD5 }; -uint8_t arr3[] = { B_TK1, B_TK2, B_TK3, B_TK4 }; - -void setup(){ - // initialize the robot - Robot.begin(); - - // open the serial port to send the information of what you are reading - Serial.begin(9600); -} - -void loop(){ - // read all the TK inputs at the Motor Board as analog - analogReadB_TKs(); - - // read all the TK inputs at the Motor Board as digital - //digitalReadB_TKs(); - - // read all the TK inputs at the Control Board as analog - //analogReadTKs(); - - // read all the TK inputs at the Control Board as digital - //digitalReadTKs(); - - // read all the TKD inputs at the Control Board as analog - //analogReadTKDs(); - - // read all the TKD inputs at the Control Board as digital - //digitalReadTKDs(); - - // write all the TK outputs at the Motor Board as digital - //digitalWriteB_TKs(); - - // write all the TKD outputs at the Control Board as digital - //digitalWriteTKDs(); - delay(5); -} - -// read all TK inputs on the Control Board as analog inputs -void analogReadTKs() { - for(int i=0;i<8;i++) { - Serial.print(Robot.analogRead(arr[i])); - Serial.print(","); - } - Serial.println(""); -} - -// read all TK inputs on the Control Board as digital inputs -void digitalReadTKs() { - for(int i=0;i<8;i++) { - Serial.print(Robot.digitalRead(arr[i])); - Serial.print(","); - } - Serial.println(""); -} - -// read all TKD inputs on the Control Board as analog inputs -void analogReadTKDs() { - for(int i=0; i<6; i++) { - Serial.print(Robot.analogRead(arr2[i])); - Serial.print(","); - } - Serial.println(""); -} - -// read all TKD inputs on the Control Board as digital inputs -void digitalReadTKDs() { - for(int i=0; i<6; i++) { - Serial.print(Robot.digitalRead(arr2[i])); - Serial.print(","); - } - Serial.println(""); -} - -// write all TKD outputs on the Control Board as digital outputs -void digitalWriteTKDs() { - // turn all the pins on - for(int i=0; i<6; i++) { - Robot.digitalWrite(arr2[i], HIGH); - } - delay(500); - - // turn all the pins off - for(int i=0; i<6; i++){ - Robot.digitalWrite(arr2[i], LOW); - } - delay(500); -} - -// write all TK outputs on the Motor Board as digital outputs -void digitalWriteB_TKs() { - // turn all the pins on - for(int i=0; i<4; i++) { - Robot.digitalWrite(arr3[i], HIGH); - } - delay(500); - - // turn all the pins off - for(int i=0; i<4; i++) { - Robot.digitalWrite(arr3[i], LOW); - } - delay(500); -} - -// read all TK inputs on the Motor Board as analog inputs -void analogReadB_TKs() { - for(int i=0; i<4; i++) { - Serial.print(Robot.analogRead(arr3[i])); - Serial.print(","); - } - Serial.println(""); -} - -// read all TKD inputs on the Motor Board as digital inputs -void digitalReadB_TKs() { - for(int i=0; i<4; i++) { - Serial.print(Robot.digitalRead(arr3[i])); - Serial.print(","); - } - Serial.println(""); -} diff --git a/libraries/Robot_Control/examples/learn/Beep/Beep.ino b/libraries/Robot_Control/examples/learn/Beep/Beep.ino deleted file mode 100644 index 1a78673..0000000 --- a/libraries/Robot_Control/examples/learn/Beep/Beep.ino +++ /dev/null @@ -1,39 +0,0 @@ -/* - Beep - - Test different pre-configured beeps on - the robot's speaker. - - Possible beeps are: - - BEEP_SIMPLE - - BEEP_DOUBLE - - BEEP_LONG - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the sound speaker - Robot.beginSpeaker(); -} -void loop() { - Robot.beep(BEEP_SIMPLE); - delay(1000); - Robot.beep(BEEP_DOUBLE); - delay(1000); - Robot.beep(BEEP_LONG); - delay(1000); -} diff --git a/libraries/Robot_Control/examples/learn/CleanEEPROM/CleanEEPROM.ino b/libraries/Robot_Control/examples/learn/CleanEEPROM/CleanEEPROM.ino deleted file mode 100644 index ae14bdd..0000000 --- a/libraries/Robot_Control/examples/learn/CleanEEPROM/CleanEEPROM.ino +++ /dev/null @@ -1,41 +0,0 @@ -/* - Clean EEPROM - - This example erases the user information stored on the - external EEPROM memory chip on your robot. - - BEWARE, this will erase the following information: - - your name - - your robots name given by you - - your city and country if you configured them via software - - EEPROMs shouldn't be rewritten too often, therefore the - code runs only during setup and not inside loop. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup(){ - // initialize the robot - Robot.begin(); - - // write empty strings for the different fields - Robot.userNameWrite(""); - Robot.robotNameWrite(""); - Robot.cityNameWrite(""); - Robot.countryNameWrite(""); -} - -void loop(){ - // do nothing -} diff --git a/libraries/Robot_Control/examples/learn/Compass/Compass.ino b/libraries/Robot_Control/examples/learn/Compass/Compass.ino deleted file mode 100644 index 4170ab7..0000000 --- a/libraries/Robot_Control/examples/learn/Compass/Compass.ino +++ /dev/null @@ -1,41 +0,0 @@ -/* - Compass - - Try the compass both on the robot's TFT - and through the serial port. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the robot's screen - Robot.beginTFT(); - - // initialize the serial port - Serial.begin(9600); -} - -void loop() { - // read the compass - int compass = Robot.compassRead(); - - // print out the sensor's value - Serial.println(compass); - - // show the value on the robot's screen - Robot.drawCompass(compass); -} - diff --git a/libraries/Robot_Control/examples/learn/IRArray/IRArray.ino b/libraries/Robot_Control/examples/learn/IRArray/IRArray.ino deleted file mode 100644 index 36b4acf..0000000 --- a/libraries/Robot_Control/examples/learn/IRArray/IRArray.ino +++ /dev/null @@ -1,44 +0,0 @@ -/* - IR array - - Read the analog value of the IR sensors at the - bottom of the robot. The also-called line following - sensors are a series of pairs of IR sender/receiver - used to detect how dark it is underneath the robot. - - The information coming from the sensor array is stored - into the Robot.IRarray[] and updated using the Robot.updateIR() - method. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup(){ - // initialize the robot - Robot.begin(); - - // initialize the serial port - Serial.begin(9600); -} - -void loop(){ - // store the sensor information into the array - Robot.updateIR(); - - // iterate the array and print the data to the Serial port - for(int i=0; i<5; i++){ - Serial.print(Robot.IRarray[i]); - Serial.print(" "); - } - Serial.println(""); -} diff --git a/libraries/Robot_Control/examples/learn/LCDDebugPrint/LCDDebugPrint.ino b/libraries/Robot_Control/examples/learn/LCDDebugPrint/LCDDebugPrint.ino deleted file mode 100644 index 0078b77..0000000 --- a/libraries/Robot_Control/examples/learn/LCDDebugPrint/LCDDebugPrint.ino +++ /dev/null @@ -1,37 +0,0 @@ -/* - LCD Debug Print - - Use the Robot's library function debugPrint() to - quickly send a sensor reading to the robot's creen. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -int value; - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the screen - Robot.beginTFT(); -} -void loop(){ - // read a value - value = analogRead(A4); - - // send the value to the screen - Robot.debugPrint(value); - - delay(40); -} diff --git a/libraries/Robot_Control/examples/learn/LCDPrint/LCDPrint.ino b/libraries/Robot_Control/examples/learn/LCDPrint/LCDPrint.ino deleted file mode 100644 index d34168c..0000000 --- a/libraries/Robot_Control/examples/learn/LCDPrint/LCDPrint.ino +++ /dev/null @@ -1,44 +0,0 @@ -/* - LCD Print - - Print the reading from a sensor to the screen. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -int value; - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the robot's screen - Robot.beginLCD(); -} - -void loop() { - // read a analog port - value=Robot.analogRead(TK4); - - // write the sensor value on the screen - Robot.fill(0, 255, 0); - Robot.textSize(1); - Robot.text(value, 0, 0); - - delay(500); - - // erase the previous text on the screen - Robot.fill(255, 255, 255); - Robot.textSize(1); - Robot.text(value, 0, 0); -} diff --git a/libraries/Robot_Control/examples/learn/LCDWriteText/LCDWriteText.ino b/libraries/Robot_Control/examples/learn/LCDWriteText/LCDWriteText.ino deleted file mode 100644 index e34a7d2..0000000 --- a/libraries/Robot_Control/examples/learn/LCDWriteText/LCDWriteText.ino +++ /dev/null @@ -1,41 +0,0 @@ -/* - LCD Write Text - - Use the Robot's library function text() to - print out text to the robot's screen. Take - into account that you need to erase the - information before continuing writing. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the screen - Robot.beginTFT(); -} -void loop() { - Robot.stroke(0, 0, 0); // choose the color black - Robot.text("Hello World", 0, 0); // print the text - delay(2000); - Robot.stroke(255, 255, 255); // choose the color white - Robot.text("Hello World", 0, 0); // writing text in the same color as the BG erases the text! - - Robot.stroke(0, 0, 0); // choose the color black - Robot.text("I am a robot", 0, 0); // print the text - delay(3000); - Robot.stroke(255, 255, 255); // choose the color black - Robot.text("I am a robot", 0, 0); // print the text -} diff --git a/libraries/Robot_Control/examples/learn/LineFollowWithPause/LineFollowWithPause.ino b/libraries/Robot_Control/examples/learn/LineFollowWithPause/LineFollowWithPause.ino deleted file mode 100644 index a3d3fc0..0000000 --- a/libraries/Robot_Control/examples/learn/LineFollowWithPause/LineFollowWithPause.ino +++ /dev/null @@ -1,49 +0,0 @@ -/* - Line Following with Pause - - As the robot has two processors, one to command the motors and one to - take care of the screen and user input, it is possible to write - programs that put one part of the robot to do something and get the - other half to control it. - - This example shows how the Control Board assigns the Motor one to - follow a line, but asks it to stop every 3 seconds. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the screen - Robot.beginTFT(); - - // get some time to place the robot on the ground - delay(3000); - - // set the robot in line following mode - Robot.setMode(MODE_LINE_FOLLOW); -} - -void loop() { - // tell the robot to take a break and stop - Robot.pauseMode(true); - Robot.debugPrint('p'); - delay(3000); - - // tell the robot to move on - Robot.pauseMode(false); - Robot.debugPrint('>'); - delay(3000); -} diff --git a/libraries/Robot_Control/examples/learn/Melody/Melody.ino b/libraries/Robot_Control/examples/learn/Melody/Melody.ino deleted file mode 100644 index 6c049a7..0000000 --- a/libraries/Robot_Control/examples/learn/Melody/Melody.ino +++ /dev/null @@ -1,62 +0,0 @@ -/* - Melody - - Plays a melody stored in a string. - - The notes and durations are encoded as follows: - - NOTES: - c play "C" - C play "#C" - d play "D" - D play "#D" - e play "E" - f play "F" - F play "#F" - g play "G" - G play "#G" - a play "A" - A play "#A" - b play "B" - - silence - - DURATIONS: - 1 Set as full note - 2 Set as half note - 4 Set as quarter note - 8 Set as eigth note - - SPECIAL NOTATION: - . Make the previous note 3/4 the length - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - - This code uses the Squawk sound library designed by STG. For - more information about it check: http://github.com/stg/squawk - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the sound library - Robot.beginSpeaker(); -} - -void loop() { - // array containing the melody - char aTinyMelody[] = "8eF-FFga4b.a.g.F.8beee-d2e.1-"; - - // play the melody - Robot.playMelody(aTinyMelody); -} diff --git a/libraries/Robot_Control/examples/learn/MotorTest/MotorTest.ino b/libraries/Robot_Control/examples/learn/MotorTest/MotorTest.ino deleted file mode 100644 index baaaf06..0000000 --- a/libraries/Robot_Control/examples/learn/MotorTest/MotorTest.ino +++ /dev/null @@ -1,41 +0,0 @@ -/* - Motor Test - - Just see if the robot can move and turn. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); -} - -void loop() { - Robot.motorsWrite(255,255); // move forward - delay(2000); - Robot.motorsStop(); // fast stop - delay(1000); - Robot.motorsWrite(-255,-255); // backward - delay(1000); - Robot.motorsWrite(0,0); // slow stop - delay(1000); - Robot.motorsWrite(-255,255); // turn left - delay(2000); - Robot.motorsStop(); // fast stop - delay(1000); - Robot.motorsWrite(255,-255); // turn right - delay(2000); - Robot.motorsStop(); // fast stop - delay(1000); -} diff --git a/libraries/Robot_Control/examples/learn/SpeedByPotentiometer/SpeedByPotentiometer.ino b/libraries/Robot_Control/examples/learn/SpeedByPotentiometer/SpeedByPotentiometer.ino deleted file mode 100644 index e97f48d..0000000 --- a/libraries/Robot_Control/examples/learn/SpeedByPotentiometer/SpeedByPotentiometer.ino +++ /dev/null @@ -1,39 +0,0 @@ -/* - Speed by Potentiometer - - Control the robot's speed using the on-board - potentiometer. The speed will be printed on - the TFT screen. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); - - // initialize the screen - Robot.beginTFT(); -} - -void loop() { - // read the value of the potentiometer - int val=map(Robot.knobRead(), 0, 1023, -255, 255); - - // print the value to the TFT screen - Robot.debugPrint(val); - - // set the same speed on both of the robot's wheels - Robot.motorsWrite(val,val); - delay(10); -} diff --git a/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino b/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino deleted file mode 100644 index 543c06c..0000000 --- a/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino +++ /dev/null @@ -1,32 +0,0 @@ -/* - Turn Test - - Check if the robot turns a certain amount of degrees. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); -} - -void loop(){ - Robot.turn(50); //turn 50 degrees to the right - Robot.motorsStop(); - delay(1000); - - Robot.turn(-100); //turn 100 degrees to the left - Robot.motorsStop(); - delay(1000); -} diff --git a/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino.orig b/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino.orig deleted file mode 100644 index 4e3624f..0000000 --- a/libraries/Robot_Control/examples/learn/TurnTest/TurnTest.ino.orig +++ /dev/null @@ -1,37 +0,0 @@ -/* - Turn Test - - Check if the robot turns a certain amount of degrees. - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the robot - Robot.begin(); -} - -<<<<<<< HEAD -void loop() { - Robot.turn(50); //turn 50 degrees to the right -======= -void loop(){ - Robot.turn(50);//turn 50 degrees to the right - Robot.motorsStop(); ->>>>>>> f062f704463222e83390b4a954e211f0f7e6e66f - delay(1000); - - Robot.turn(-100);//turn 100 degrees to the left - Robot.motorsStop(); - delay(1000); -} diff --git a/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino b/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino deleted file mode 100644 index 5bbc0e5..0000000 --- a/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino +++ /dev/null @@ -1,38 +0,0 @@ -/* - Keyboard Test - - Check how the robot's keyboard works. This example - sends the data about the key pressed through the - serial port. - - All the buttons on the Control Board are tied up to a - single analog input pin, in this way it is possible to multiplex a - whole series of buttons on one single pin. - - It is possible to recalibrate the thresholds of the buttons using - the Robot.keyboardCalibrate() function, that takes a 5 ints long - array as parameter - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -void setup() { - // initialize the serial port - Serial.begin(9600); -} - -void loop() { - // print out the keyboard readings - Serial.println(Robot.keyboardRead()); - delay(100); -} diff --git a/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino.orig b/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino.orig deleted file mode 100644 index 6ee6c05..0000000 --- a/libraries/Robot_Control/examples/learn/keyboardTest/keyboardTest.ino.orig +++ /dev/null @@ -1,49 +0,0 @@ -/* - Keyboard Test - - Check how the robot's keyboard works. This example - sends the data about the key pressed through the - serial port. - - All the buttons on the Control Board are tied up to a - single analog input pin, in this way it is possible to multiplex a - whole series of buttons on one single pin. - - It is possible to recalibrate the thresholds of the buttons using - the Robot.keyboardCalibrate() function, that takes a 5 ints long - array as parameter - - Circuit: - * Arduino Robot - - created 1 May 2013 - by X. Yang - modified 12 May 2013 - by D. Cuartielles - - This example is in the public domain - */ - -#include - -<<<<<<< HEAD -// it is possible to use an array to calibrate -//int vals[] = { 0, 133, 305, 481, 724 }; - -void setup() { - // initialize the serial port - Serial.begin(9600); - - // calibrate the keyboard - //Robot.keyboardCalibrate(vals);//For the new robot only. -======= -void setup(){ - Serial.begin(9600); ->>>>>>> f062f704463222e83390b4a954e211f0f7e6e66f -} - -void loop() { - // print out the keyboard readings - Serial.println(Robot.keyboardRead()); - delay(100); -} diff --git a/libraries/Robot_Control/glcdfont.c b/libraries/Robot_Control/glcdfont.c deleted file mode 100644 index abc3631..0000000 --- a/libraries/Robot_Control/glcdfont.c +++ /dev/null @@ -1,266 +0,0 @@ -#include -#include - -#ifndef FONT5X7_H -#define FONT5X7_H - -// standard ascii 5x7 font - -static unsigned char font[] PROGMEM = { - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, - 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, - 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, - 0x18, 0x3C, 0x7E, 0x3C, 0x18, - 0x1C, 0x57, 0x7D, 0x57, 0x1C, - 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, - 0x00, 0x18, 0x3C, 0x18, 0x00, - 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, - 0x00, 0x18, 0x24, 0x18, 0x00, - 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, - 0x30, 0x48, 0x3A, 0x06, 0x0E, - 0x26, 0x29, 0x79, 0x29, 0x26, - 0x40, 0x7F, 0x05, 0x05, 0x07, - 0x40, 0x7F, 0x05, 0x25, 0x3F, - 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, - 0x7F, 0x3E, 0x1C, 0x1C, 0x08, - 0x08, 0x1C, 0x1C, 0x3E, 0x7F, - 0x14, 0x22, 0x7F, 0x22, 0x14, - 0x5F, 0x5F, 0x00, 0x5F, 0x5F, - 0x06, 0x09, 0x7F, 0x01, 0x7F, - 0x00, 0x66, 0x89, 0x95, 0x6A, - 0x60, 0x60, 0x60, 0x60, 0x60, - 0x94, 0xA2, 0xFF, 0xA2, 0x94, - 0x08, 0x04, 0x7E, 0x04, 0x08, - 0x10, 0x20, 0x7E, 0x20, 0x10, - 0x08, 0x08, 0x2A, 0x1C, 0x08, - 0x08, 0x1C, 0x2A, 0x08, 0x08, - 0x1E, 0x10, 0x10, 0x10, 0x10, - 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, - 0x30, 0x38, 0x3E, 0x38, 0x30, - 0x06, 0x0E, 0x3E, 0x0E, 0x06, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x5F, 0x00, 0x00, - 0x00, 0x07, 0x00, 0x07, 0x00, - 0x14, 0x7F, 0x14, 0x7F, 0x14, - 0x24, 0x2A, 0x7F, 0x2A, 0x12, - 0x23, 0x13, 0x08, 0x64, 0x62, - 0x36, 0x49, 0x56, 0x20, 0x50, - 0x00, 0x08, 0x07, 0x03, 0x00, - 0x00, 0x1C, 0x22, 0x41, 0x00, - 0x00, 0x41, 0x22, 0x1C, 0x00, - 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, - 0x08, 0x08, 0x3E, 0x08, 0x08, - 0x00, 0x80, 0x70, 0x30, 0x00, - 0x08, 0x08, 0x08, 0x08, 0x08, - 0x00, 0x00, 0x60, 0x60, 0x00, - 0x20, 0x10, 0x08, 0x04, 0x02, - 0x3E, 0x51, 0x49, 0x45, 0x3E, - 0x00, 0x42, 0x7F, 0x40, 0x00, - 0x72, 0x49, 0x49, 0x49, 0x46, - 0x21, 0x41, 0x49, 0x4D, 0x33, - 0x18, 0x14, 0x12, 0x7F, 0x10, - 0x27, 0x45, 0x45, 0x45, 0x39, - 0x3C, 0x4A, 0x49, 0x49, 0x31, - 0x41, 0x21, 0x11, 0x09, 0x07, - 0x36, 0x49, 0x49, 0x49, 0x36, - 0x46, 0x49, 0x49, 0x29, 0x1E, - 0x00, 0x00, 0x14, 0x00, 0x00, - 0x00, 0x40, 0x34, 0x00, 0x00, - 0x00, 0x08, 0x14, 0x22, 0x41, - 0x14, 0x14, 0x14, 0x14, 0x14, - 0x00, 0x41, 0x22, 0x14, 0x08, - 0x02, 0x01, 0x59, 0x09, 0x06, - 0x3E, 0x41, 0x5D, 0x59, 0x4E, - 0x7C, 0x12, 0x11, 0x12, 0x7C, - 0x7F, 0x49, 0x49, 0x49, 0x36, - 0x3E, 0x41, 0x41, 0x41, 0x22, - 0x7F, 0x41, 0x41, 0x41, 0x3E, - 0x7F, 0x49, 0x49, 0x49, 0x41, - 0x7F, 0x09, 0x09, 0x09, 0x01, - 0x3E, 0x41, 0x41, 0x51, 0x73, - 0x7F, 0x08, 0x08, 0x08, 0x7F, - 0x00, 0x41, 0x7F, 0x41, 0x00, - 0x20, 0x40, 0x41, 0x3F, 0x01, - 0x7F, 0x08, 0x14, 0x22, 0x41, - 0x7F, 0x40, 0x40, 0x40, 0x40, - 0x7F, 0x02, 0x1C, 0x02, 0x7F, - 0x7F, 0x04, 0x08, 0x10, 0x7F, - 0x3E, 0x41, 0x41, 0x41, 0x3E, - 0x7F, 0x09, 0x09, 0x09, 0x06, - 0x3E, 0x41, 0x51, 0x21, 0x5E, - 0x7F, 0x09, 0x19, 0x29, 0x46, - 0x26, 0x49, 0x49, 0x49, 0x32, - 0x03, 0x01, 0x7F, 0x01, 0x03, - 0x3F, 0x40, 0x40, 0x40, 0x3F, - 0x1F, 0x20, 0x40, 0x20, 0x1F, - 0x3F, 0x40, 0x38, 0x40, 0x3F, - 0x63, 0x14, 0x08, 0x14, 0x63, - 0x03, 0x04, 0x78, 0x04, 0x03, - 0x61, 0x59, 0x49, 0x4D, 0x43, - 0x00, 0x7F, 0x41, 0x41, 0x41, - 0x02, 0x04, 0x08, 0x10, 0x20, - 0x00, 0x41, 0x41, 0x41, 0x7F, - 0x04, 0x02, 0x01, 0x02, 0x04, - 0x40, 0x40, 0x40, 0x40, 0x40, - 0x00, 0x03, 0x07, 0x08, 0x00, - 0x20, 0x54, 0x54, 0x78, 0x40, - 0x7F, 0x28, 0x44, 0x44, 0x38, - 0x38, 0x44, 0x44, 0x44, 0x28, - 0x38, 0x44, 0x44, 0x28, 0x7F, - 0x38, 0x54, 0x54, 0x54, 0x18, - 0x00, 0x08, 0x7E, 0x09, 0x02, - 0x18, 0xA4, 0xA4, 0x9C, 0x78, - 0x7F, 0x08, 0x04, 0x04, 0x78, - 0x00, 0x44, 0x7D, 0x40, 0x00, - 0x20, 0x40, 0x40, 0x3D, 0x00, - 0x7F, 0x10, 0x28, 0x44, 0x00, - 0x00, 0x41, 0x7F, 0x40, 0x00, - 0x7C, 0x04, 0x78, 0x04, 0x78, - 0x7C, 0x08, 0x04, 0x04, 0x78, - 0x38, 0x44, 0x44, 0x44, 0x38, - 0xFC, 0x18, 0x24, 0x24, 0x18, - 0x18, 0x24, 0x24, 0x18, 0xFC, - 0x7C, 0x08, 0x04, 0x04, 0x08, - 0x48, 0x54, 0x54, 0x54, 0x24, - 0x04, 0x04, 0x3F, 0x44, 0x24, - 0x3C, 0x40, 0x40, 0x20, 0x7C, - 0x1C, 0x20, 0x40, 0x20, 0x1C, - 0x3C, 0x40, 0x30, 0x40, 0x3C, - 0x44, 0x28, 0x10, 0x28, 0x44, - 0x4C, 0x90, 0x90, 0x90, 0x7C, - 0x44, 0x64, 0x54, 0x4C, 0x44, - 0x00, 0x08, 0x36, 0x41, 0x00, - 0x00, 0x00, 0x77, 0x00, 0x00, - 0x00, 0x41, 0x36, 0x08, 0x00, - 0x02, 0x01, 0x02, 0x04, 0x02, - 0x3C, 0x26, 0x23, 0x26, 0x3C, - 0x1E, 0xA1, 0xA1, 0x61, 0x12, - 0x3A, 0x40, 0x40, 0x20, 0x7A, - 0x38, 0x54, 0x54, 0x55, 0x59, - 0x21, 0x55, 0x55, 0x79, 0x41, - 0x21, 0x54, 0x54, 0x78, 0x41, - 0x21, 0x55, 0x54, 0x78, 0x40, - 0x20, 0x54, 0x55, 0x79, 0x40, - 0x0C, 0x1E, 0x52, 0x72, 0x12, - 0x39, 0x55, 0x55, 0x55, 0x59, - 0x39, 0x54, 0x54, 0x54, 0x59, - 0x39, 0x55, 0x54, 0x54, 0x58, - 0x00, 0x00, 0x45, 0x7C, 0x41, - 0x00, 0x02, 0x45, 0x7D, 0x42, - 0x00, 0x01, 0x45, 0x7C, 0x40, - 0xF0, 0x29, 0x24, 0x29, 0xF0, - 0xF0, 0x28, 0x25, 0x28, 0xF0, - 0x7C, 0x54, 0x55, 0x45, 0x00, - 0x20, 0x54, 0x54, 0x7C, 0x54, - 0x7C, 0x0A, 0x09, 0x7F, 0x49, - 0x32, 0x49, 0x49, 0x49, 0x32, - 0x32, 0x48, 0x48, 0x48, 0x32, - 0x32, 0x4A, 0x48, 0x48, 0x30, - 0x3A, 0x41, 0x41, 0x21, 0x7A, - 0x3A, 0x42, 0x40, 0x20, 0x78, - 0x00, 0x9D, 0xA0, 0xA0, 0x7D, - 0x39, 0x44, 0x44, 0x44, 0x39, - 0x3D, 0x40, 0x40, 0x40, 0x3D, - 0x3C, 0x24, 0xFF, 0x24, 0x24, - 0x48, 0x7E, 0x49, 0x43, 0x66, - 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, - 0xFF, 0x09, 0x29, 0xF6, 0x20, - 0xC0, 0x88, 0x7E, 0x09, 0x03, - 0x20, 0x54, 0x54, 0x79, 0x41, - 0x00, 0x00, 0x44, 0x7D, 0x41, - 0x30, 0x48, 0x48, 0x4A, 0x32, - 0x38, 0x40, 0x40, 0x22, 0x7A, - 0x00, 0x7A, 0x0A, 0x0A, 0x72, - 0x7D, 0x0D, 0x19, 0x31, 0x7D, - 0x26, 0x29, 0x29, 0x2F, 0x28, - 0x26, 0x29, 0x29, 0x29, 0x26, - 0x30, 0x48, 0x4D, 0x40, 0x20, - 0x38, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x38, - 0x2F, 0x10, 0xC8, 0xAC, 0xBA, - 0x2F, 0x10, 0x28, 0x34, 0xFA, - 0x00, 0x00, 0x7B, 0x00, 0x00, - 0x08, 0x14, 0x2A, 0x14, 0x22, - 0x22, 0x14, 0x2A, 0x14, 0x08, - 0xAA, 0x00, 0x55, 0x00, 0xAA, - 0xAA, 0x55, 0xAA, 0x55, 0xAA, - 0x00, 0x00, 0x00, 0xFF, 0x00, - 0x10, 0x10, 0x10, 0xFF, 0x00, - 0x14, 0x14, 0x14, 0xFF, 0x00, - 0x10, 0x10, 0xFF, 0x00, 0xFF, - 0x10, 0x10, 0xF0, 0x10, 0xF0, - 0x14, 0x14, 0x14, 0xFC, 0x00, - 0x14, 0x14, 0xF7, 0x00, 0xFF, - 0x00, 0x00, 0xFF, 0x00, 0xFF, - 0x14, 0x14, 0xF4, 0x04, 0xFC, - 0x14, 0x14, 0x17, 0x10, 0x1F, - 0x10, 0x10, 0x1F, 0x10, 0x1F, - 0x14, 0x14, 0x14, 0x1F, 0x00, - 0x10, 0x10, 0x10, 0xF0, 0x00, - 0x00, 0x00, 0x00, 0x1F, 0x10, - 0x10, 0x10, 0x10, 0x1F, 0x10, - 0x10, 0x10, 0x10, 0xF0, 0x10, - 0x00, 0x00, 0x00, 0xFF, 0x10, - 0x10, 0x10, 0x10, 0x10, 0x10, - 0x10, 0x10, 0x10, 0xFF, 0x10, - 0x00, 0x00, 0x00, 0xFF, 0x14, - 0x00, 0x00, 0xFF, 0x00, 0xFF, - 0x00, 0x00, 0x1F, 0x10, 0x17, - 0x00, 0x00, 0xFC, 0x04, 0xF4, - 0x14, 0x14, 0x17, 0x10, 0x17, - 0x14, 0x14, 0xF4, 0x04, 0xF4, - 0x00, 0x00, 0xFF, 0x00, 0xF7, - 0x14, 0x14, 0x14, 0x14, 0x14, - 0x14, 0x14, 0xF7, 0x00, 0xF7, - 0x14, 0x14, 0x14, 0x17, 0x14, - 0x10, 0x10, 0x1F, 0x10, 0x1F, - 0x14, 0x14, 0x14, 0xF4, 0x14, - 0x10, 0x10, 0xF0, 0x10, 0xF0, - 0x00, 0x00, 0x1F, 0x10, 0x1F, - 0x00, 0x00, 0x00, 0x1F, 0x14, - 0x00, 0x00, 0x00, 0xFC, 0x14, - 0x00, 0x00, 0xF0, 0x10, 0xF0, - 0x10, 0x10, 0xFF, 0x10, 0xFF, - 0x14, 0x14, 0x14, 0xFF, 0x14, - 0x10, 0x10, 0x10, 0x1F, 0x00, - 0x00, 0x00, 0x00, 0xF0, 0x10, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, - 0xFF, 0xFF, 0xFF, 0x00, 0x00, - 0x00, 0x00, 0x00, 0xFF, 0xFF, - 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, - 0x38, 0x44, 0x44, 0x38, 0x44, - 0x7C, 0x2A, 0x2A, 0x3E, 0x14, - 0x7E, 0x02, 0x02, 0x06, 0x06, - 0x02, 0x7E, 0x02, 0x7E, 0x02, - 0x63, 0x55, 0x49, 0x41, 0x63, - 0x38, 0x44, 0x44, 0x3C, 0x04, - 0x40, 0x7E, 0x20, 0x1E, 0x20, - 0x06, 0x02, 0x7E, 0x02, 0x02, - 0x99, 0xA5, 0xE7, 0xA5, 0x99, - 0x1C, 0x2A, 0x49, 0x2A, 0x1C, - 0x4C, 0x72, 0x01, 0x72, 0x4C, - 0x30, 0x4A, 0x4D, 0x4D, 0x30, - 0x30, 0x48, 0x78, 0x48, 0x30, - 0xBC, 0x62, 0x5A, 0x46, 0x3D, - 0x3E, 0x49, 0x49, 0x49, 0x00, - 0x7E, 0x01, 0x01, 0x01, 0x7E, - 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, - 0x44, 0x44, 0x5F, 0x44, 0x44, - 0x40, 0x51, 0x4A, 0x44, 0x40, - 0x40, 0x44, 0x4A, 0x51, 0x40, - 0x00, 0x00, 0xFF, 0x01, 0x03, - 0xE0, 0x80, 0xFF, 0x00, 0x00, - 0x08, 0x08, 0x6B, 0x6B, 0x08, - 0x36, 0x12, 0x36, 0x24, 0x36, - 0x06, 0x0F, 0x09, 0x0F, 0x06, - 0x00, 0x00, 0x18, 0x18, 0x00, - 0x00, 0x00, 0x10, 0x10, 0x00, - 0x30, 0x40, 0xFF, 0x01, 0x01, - 0x00, 0x1F, 0x01, 0x01, 0x1E, - 0x00, 0x19, 0x1D, 0x17, 0x12, - 0x00, 0x3C, 0x3C, 0x3C, 0x3C, - 0x00, 0x00, 0x00, 0x00, 0x00, -}; -#endif diff --git a/libraries/Robot_Control/helper.cpp b/libraries/Robot_Control/helper.cpp deleted file mode 100644 index a7a956a..0000000 --- a/libraries/Robot_Control/helper.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "ArduinoRobot.h" - -void RobotControl::drawBase(){ - Arduino_LCD::drawCircle(64,80,50,foreGround); - Arduino_LCD::drawLine(64,30,64,20,foreGround); -} -void RobotControl::drawDire(int16_t dire){ - static uint8_t x_old; - static uint8_t y_old; - static uint8_t x_t_old; - static uint8_t y_t_old; - - uint8_t x=60*sin(dire/360.0*6.28)+64; - uint8_t x_t=40*sin(dire/360.0*6.28)+64; - uint8_t y=60*cos(dire/360.0*6.28)+80; - uint8_t y_t=40*cos(dire/360.0*6.28)+80; - - Arduino_LCD::drawLine(x_t_old,y_t_old,x_old,y_old,backGround); - Arduino_LCD::drawLine(x_t,y_t,x,y,RED); - - x_old=x; - y_old=y; - x_t_old=x_t; - y_t_old=y_t; -} - -void RobotControl::drawCompass(uint16_t value){ - drawBase(); - drawDire(value); - debugPrint(value,57,76); -} - -//display logos -void RobotControl::displayLogos(){ - _drawBMP("lg0.bmp",0,0); - delay(2000); - _drawBMP("lg1.bmp",0,0); - delay(2000); - clearScreen(); -} - -//wait for a button to be pressed -void RobotControl::waitContinue(uint8_t key){ - while(!(Robot.keyboardRead()==key)); -} diff --git a/libraries/Robot_Control/information.cpp b/libraries/Robot_Control/information.cpp deleted file mode 100644 index c36e9ce..0000000 --- a/libraries/Robot_Control/information.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/*#include -//0 - 319: pic array, - -//320 - 337 username, -#define ADDRESS_USERNAME 320 -//338 - 355 robotname, -#define ADDRESS_ROBOTNAME 338 -//356 - 373 cityname, -#define ADDRESS_CITYNAME 356 - //374- 391 countryname, -#define ADDRESS_COUNTRYNAME 374 -//508-511 robot info -#define ADDRESS_ROBOTINFO 508 - - -void RobotControl::getMyName(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_USERNAME,(uint8_t*)container,18); -} -void RobotControl::getRobotName(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_ROBOTNAME,(uint8_t*)container,18); -} -void RobotControl::getMyCity(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_CITYNAME,(uint8_t*)container,18); -} -void RobotControl::getMyCountry(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_COUNTRYNAME,(uint8_t*)container,18); -} - -void RobotControl::setMyName(char* text){ - EEPROM_I2C::writePage(ADDRESS_USERNAME,(uint8_t*)text,18); -} -void RobotControl::setRobotName(char* text){ - EEPROM_I2C::writePage(ADDRESS_ROBOTNAME,(uint8_t*)text,18); -} -void RobotControl::setMyCity(char* text){ - EEPROM_I2C::writePage(ADDRESS_CITYNAME,(uint8_t*)text,18); -} -void RobotControl::setMyCountry(char* text){ - EEPROM_I2C::writePage(ADDRESS_COUNTRYNAME,(uint8_t*)text,18); -} -*/ \ No newline at end of file diff --git a/libraries/Robot_Control/keyboard.cpp b/libraries/Robot_Control/keyboard.cpp deleted file mode 100644 index 7e647bb..0000000 --- a/libraries/Robot_Control/keyboard.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "ArduinoRobot.h" - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif -int pul_min[]={0,133,319,494,732}; -int pul_max[]={10,153,339,514,752}; -/*int pul_min[]={0,123,295,471,714}; -int pul_max[]={0,143,315,491,734};*/ -/* -int pul_min[]={0,133,319,494,732}; -int pul_max[]={10,153,339,514,752}; -*/ -void sort(int* v); - -void RobotControl::keyboardCalibrate(int *vals){ - for(int i=0;i<5;i++){ - pul_min[i]=vals[i]-10; - pul_max[i]=vals[i]+10; - } -} -int8_t RobotControl::keyboardRead(void) -{ - - int lectura_pul; - int8_t conta_pul=0; - static int anterior=0; - - lectura_pul = this->averageAnalogInput(KEY); - - while ((conta_pul < NUMBER_BUTTONS) && !(lectura_pul >= pul_min[conta_pul] && lectura_pul <= pul_max[conta_pul])) - conta_pul++; - - if (conta_pul >= NUMBER_BUTTONS) - conta_pul = -1; - else - delay(100); - - return conta_pul; -} - -int RobotControl::averageAnalogInput(int pinNum) -{ - int vals[5]; - for(int i=0;i<5;i++){ - for(int j=i;j<5;j++){ - vals[j]=::analogRead(pinNum); - } - sort(vals); - } - return vals[0]; -} -void sort(int* v){ - int tmp; - for(int i=0;i<4;i++) - for(int j=i+1;j<5;j++) - if(v[j]foreGround=foreGround; - this->backGround=backGround; -} -void RobotControl::_enableLCD(){ - DDRB = DDRB & 0xEF; //pinMode(CS_SD,INPUT); - DDRB = DDRB | 0x20; //pinMode(CS_LCD,OUTPUT); -} -/*void RobotControl::_setErase(uint8_t posX, uint8_t posY){ - Arduino_LCD::setCursor(posX,posY); - Arduino_LCD::setTextColor(backGround); - Arduino_LCD::setTextSize(1); -} -void RobotControl::_setWrite(uint8_t posX, uint8_t posY){ - Arduino_LCD::setCursor(posX,posY); - Arduino_LCD::setTextColor(foreGround); - Arduino_LCD::setTextSize(1); -}*/ -/* -void RobotControl::text(int value, uint8_t posX, uint8_t posY, bool EW){ - if(EW) - _setWrite(posX,posY); - else - _setErase(posX,posY); - Arduino_LCD::print(value); -} -void RobotControl::text(long value, uint8_t posX, uint8_t posY, bool EW){ - if(EW) - _setWrite(posX,posY); - else - _setErase(posX,posY); - Arduino_LCD::print(value); -} -void RobotControl::text(char* value, uint8_t posX, uint8_t posY, bool EW){ - if(EW) - _setWrite(posX,posY); - else - _setErase(posX,posY); - Arduino_LCD::print(value); -} -void RobotControl::text(char value, uint8_t posX, uint8_t posY, bool EW){ - if(EW) - _setWrite(posX,posY); - else - _setErase(posX,posY); - Arduino_LCD::print(value); -} -*/ - -void RobotControl::debugPrint(long value, uint8_t x, uint8_t y){ - static long oldVal=0; - Arduino_LCD::stroke(backGround); - text(oldVal,x,y); - Arduino_LCD::stroke(foreGround); - text(value,x,y); - oldVal=value; -} - -void RobotControl::clearScreen(){ - Arduino_LCD::fillScreen(backGround); -} - -void RobotControl::drawBMP(char* filename, uint8_t x, uint8_t y){ - /*for(int j=0;j= screenWidth) || (y >= screenHeight)) return; - - // Crop area to be loaded - if((x+width-1) >= screenWidth) width = screenWidth - x; - if((y+height-1) >= screenHeight) height = screenHeight - y; - - // Set TFT address window to clipped image bounds - Arduino_LCD::setAddrWindow(x, y, x+width-1, y+height-1); - - // launch the reading command - _drawBMP_EEPROM(iconOffset, width, height); -} - -// Draw BMP from SD card through the filename -void RobotControl::_drawBMP(char* filename, uint8_t posX, uint8_t posY){ - uint8_t bmpWidth, bmpHeight; // W+H in pixels - uint8_t bmpDepth; // Bit depth (currently must be 24) - uint32_t bmpImageoffset; // Start of image data in file - uint32_t rowSize; // Not always = bmpWidth; may have padding - uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) - uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer - bool goodBmp = false; // Set to true on valid header parse - bool flip = true; // BMP is stored bottom-to-top - uint8_t w, h, row, col; - uint8_t r, g, b; - uint32_t pos = 0; - - // Open requested file on SD card - if ((file.open(filename,O_READ)) == NULL) { - return; - } - - // Parse BMP header - if(read16(file) == 0x4D42) { // BMP signature - read32(file);//uint32_t aux = read32(file); - (void)read32(file); // Read & ignore creator bytes - bmpImageoffset = read32(file); // Start of image data - - // Read DIB header - (void)read32(file);//aux = read32(file); - bmpWidth = read32(file); - bmpHeight = read32(file); - - if(read16(file) == 1) { // # planes -- must be '1' - bmpDepth = read16(file); // bits per pixel - if((bmpDepth == 24) && (read32(file) == 0)) { // 0 = uncompressed - goodBmp = true; // Supported BMP format -- proceed! - - // BMP rows are padded (if needed) to 4-byte boundary - rowSize = (bmpWidth * 3 + 3) & ~3; - - // If bmpHeight is negative, image is in top-down order. - // This is not canon but has been observed in the wild. - if(bmpHeight < 0) { - bmpHeight = -bmpHeight; - flip = false; - } - - // Crop area to be loaded - w = bmpWidth; - h = bmpHeight; - - // Start drawing - //_enableLCD(); - Arduino_LCD::setAddrWindow(posX, posY, posX+bmpWidth-1, posY+bmpHeight-1); - - for (row=0; row= sizeof(sdbuffer)) { // Indeed - //_enableSD(); - file.read(sdbuffer, sizeof(sdbuffer)); - buffidx = 0; // Set index to beginning - //_enableLCD(); - } - // Convert pixel from BMP to TFT format, push to display - b = sdbuffer[buffidx++]; - g = sdbuffer[buffidx++]; - r = sdbuffer[buffidx++]; - - int color = Arduino_LCD::Color565(r,g,b); - - Arduino_LCD::pushColor(color); - } // end pixel - } // end scanline - //_enableSD(); - } // end goodBmp*/ - } - } - file.close(); - //_enableLCD(); -} -uint16_t read16(Fat16& f) { - uint16_t result; - f.read(&result,sizeof(result)); - return result; -} -uint32_t read32(Fat16& f) { - uint32_t result; - f.read(&result,sizeof(result)); - return result; -} -/* -uint16_t color565(uint8_t r, uint8_t g, uint8_t b) { - return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); -}*/ - - -void RobotControl::_drawBMP_EEPROM(uint16_t address, uint8_t width, uint8_t height){ - uint16_t u16retVal = 0; - EEPROM_I2C::_beginTransmission(address); - EEPROM_I2C::_endTransmission(); - /*Wire.beginTransmission(DEVICEADDRESS); - Wire.write( (address >> 8) & 0xFF ); - Wire.write( (address >> 0) & 0xFF ); - Wire.endTransmission();*/ - - long s = width * height ; - for(long j = 0; j < (long) s >> 4; j++) { // divided by 32, times 2 - Wire.requestFrom(DEVICEADDRESS, 32); - for(int i = 0; i < 32; i+=2) { - u16retVal = Wire.read(); - u16retVal = (u16retVal << 8) + Wire.read(); - Arduino_LCD::pushColor(u16retVal); - } - } - -} -void RobotControl::beginBMPFromEEPROM(){ - _eeprom_bmp=(EEPROM_BMP*)malloc(NUM_EEPROM_BMP*sizeof(EEPROM_BMP)); - EEPROM_I2C::_beginTransmission(0); - EEPROM_I2C::_endTransmission(); - - for(uint8_t j=0;j -#include -#include "VirtualKeyboard.h" -#include "RobotTextManager.h" -#include "scripts_Hello_User.h" - -const int TextManager::lineHeight=10; -const int TextManager::charWidth=6; - - -void TextManager::setMargin(int margin_left,int margin_top){ - this->margin_left=margin_left; - this->margin_top=margin_top; -} -int TextManager::getLin(int lineNum){ - return lineNum*lineHeight+margin_top; -} - -int TextManager::getCol(int colNum){ - return colNum*charWidth+margin_left; -} - -void TextManager::writeText(int lineNum, int colNum, char* txt, bool onOff){ - if(!onOff) - Robot.setTextColor(WHITE); - - Robot.setCursor(getCol(colNum),getLin(lineNum)); - Robot.print(txt); - - Robot.setTextColor(BLACK); -} - -void TextManager::drawInput(bool onOff){ - if(!onOff) - Robot.setTextColor(WHITE); - - Robot.setCursor(getCol(inputCol),getLin(inputLin)+1); - Robot.print('_'); - - Robot.setTextColor(BLACK); - -} - -void TextManager::mvInput(int dire){ - drawInput(0); - if(dire<0){ - if(inputPos>0){ - inputPos--; - inputCol--; - } - }else{ - if(inputPos<16){ - inputPos++; - inputCol++; - } - } - drawInput(1); -} - -char TextManager::selectLetter(){ - static int oldVal; - char val=map(Robot.knobRead(),0,1023,32,125); - if(val==oldVal){ - return 0; //No changes - }else{ - oldVal=val; - return val; //Current letter - } -} - -void TextManager::refreshCurrentLetter(char letter){ - if(letter){ - writeText(inputLin,inputCol,inputPool+inputPos,false);//erase - inputPool[inputPos]=letter; - writeText(inputLin,inputCol,inputPool+inputPos,true);//write - } -} - - -void TextManager::getInput(int lin, int col){ - writeText(lin,col,">"); //Input indicator - - writeText(lin, col+1, inputPool); - - inputLin=lin; //Ini input cursor - inputCol=col+1; - inputPos=0; - drawInput(true); - - Vkey.display(100);//Vkey is a object of VirtualKeyboard class - - while(true){ - switch(Robot.keyboardRead()){ - case BUTTON_LEFT: - //Robot.beep(BEEP_SIMPLE); - mvInput(-1); - break; - case BUTTON_RIGHT: - //Robot.beep(BEEP_SIMPLE); - mvInput(1); - break; - case BUTTON_MIDDLE: - //Robot.beep(BEEP_DOUBLE); - char selection=Vkey.getSelection(); - if(selection!='\0'){ - refreshCurrentLetter(selection); - mvInput(1); - }else{ - drawInput(false); - return; - } - } - Vkey.run(); - delay(10); - } -} -void TextManager::setInputPool(int code){ - switch(code){ - case USERNAME: - Robot.userNameRead(inputPool); - break; - case ROBOTNAME: - Robot.robotNameRead(inputPool); - break; - case CITYNAME: - Robot.cityNameRead(inputPool); - break; - case COUNTRYNAME: - Robot.countryNameRead(inputPool); - break; - } - for(int i=0;i<18;i++){ - if(inputPool[i]=='\0'){ - for(int j=i;j<18;j++){ - inputPool[j]='\0'; - } - break; - } - } -} -void TextManager::pushInput(int code){ - switch(code){ - case USERNAME: - Robot.userNameWrite(inputPool); - break; - case ROBOTNAME: - Robot.robotNameWrite(inputPool); - break; - case CITYNAME: - Robot.cityNameWrite(inputPool); - break; - case COUNTRYNAME: - Robot.countryNameWrite(inputPool); - break; - } - for(int i=0;i<18;i++){ - inputPool[i]='\0'; - } -} -void TextManager::input(int lin,int col, int code){ - setInputPool(code); - getInput(lin,col); - pushInput(code); -} - -void TextManager::showPicture(char * filename, int posX, int posY){ - Robot.pause(); - Robot._drawBMP(filename,posX,posY); - Robot.play(); -} - -void TextManager::getPGMtext(int seq){ - //It takes a string from program space, and fill it - //in the buffer - //if(in hello user example){ - if(true){ - strcpy_P(PGMbuffer,(char*)pgm_read_word(&(::scripts_Hello_User[seq]))); - } -} - -void TextManager::writeScript(int seq, int line, int col){ - //print a string from program space to a specific line, - //column on the LCD - - //first fill the buffer with text from program space - getPGMtext(seq); - //then print it to the screen - textManager.writeText(line,col,PGMbuffer); -} - - -TextManager textManager=TextManager(); diff --git a/libraries/Robot_Control/utility/RobotTextManager.h b/libraries/Robot_Control/utility/RobotTextManager.h deleted file mode 100644 index 6c0b7bd..0000000 --- a/libraries/Robot_Control/utility/RobotTextManager.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef ROBOTTEXTMANAGER_H -#define ROBOTTEXTMANAGER_H - -#define USERNAME 0 -#define ROBOTNAME 1 -#define CITYNAME 2 -#define COUNTRYNAME 3 -#define EMPTY 4 - -class TextManager{ - //The TextManager class is a collection of features specific for Hello - //User example. - // - //- It includes solution for setting text position based on - // line/column. The original Robot.text(), or the more low level - // print() function can only set text position on pixels from left, - // top. - // - //- The process of accepting input with the virtual keyboard, saving - // into or reading from EEPROM is delt with here. - // - //- A workflow for stop the music while displaying image. Trouble - // will happen otherwise. - - public: - //add some margin to the text, left side only atm. - void setMargin(int margin_left,int margin_top); - - //print text based on line, column. - void writeText(int lineNum, int colNum, char* txt, bool onOff=true); - - //print a script from the scripts library - void writeScript(int seq, int line, int col); - - //The whole process of getting input - void input(int lin,int col, int code); - //Print a cursor and virtual keyboard on screen, and save the user's input - void getInput(int lin, int col); - //Get user name, robot name, city name or country name from EEPROM - //and store in the input pool. - void setInputPool(int code); - //save user input to EEPROM - void pushInput(int code); - - //Replaces Robot.drawPicture(), as this one solves collision between - //image and music - void showPicture(char * filename, int posX, int posY); - - private: - int margin_left,margin_top; - int getLin(int lineNum); //Convert line to pixels from top - int getCol(int colNum); //Convert line to pixels from left - - static const int lineHeight;//8+2=10 - static const int charWidth;//5+1=6 - - int inputPos; - int inputLin; - int inputCol; - - void drawInput(bool onOff); - void mvInput(int dire); - - char selectLetter(); - void refreshCurrentLetter(char letter); - - void getPGMtext(int seq); - - char PGMbuffer[85]; //the buffer for storing strings - char inputPool[18]; -}; - -//a trick for removing the need of creating an object of TextManager. -//So you can call me.somefunction() directly in the sketch. -extern TextManager textManager; - -#endif diff --git a/libraries/Robot_Control/utility/VirtualKeyboard.cpp b/libraries/Robot_Control/utility/VirtualKeyboard.cpp deleted file mode 100644 index ad73c75..0000000 --- a/libraries/Robot_Control/utility/VirtualKeyboard.cpp +++ /dev/null @@ -1,127 +0,0 @@ -#include "VirtualKeyboard.h" - -int VirtualKeyboard::getColLin(int val){ - uint8_t col,lin; - lin=val/10; - col=val%10; // saving 36 bytes :( - /*if(0<=val && 9>=val){ - col=val; - lin=0; - }else if(10<=val && 19>=val){ - col=val-10; - lin=1; - }else if(20<=val && 29>=val){ - col=val-20; - lin=2; - }else if(30<=val && 39>=val){ - col=val-30; - lin=3; - }*/ - return (col<<8)+lin; //Put col and lin in one int -} -void VirtualKeyboard::run(){ -/** visually select a letter on the keyboard -* The selection boarder is 1px higher than the character, -* 1px on the bottom, 2px to the left and 2px to the right. -* -*/ - if(!onOff)return; - //Serial.println(onOff); - static int oldColLin=0; - uint8_t val=map(Robot.knobRead(),0,1023,0,38); - if(val==38)val=37; //The last value is jumpy when using batteries - int colLin=getColLin(val); - - if(oldColLin!=colLin){ - uint8_t x=(oldColLin>>8 & 0xFF)*11+10;//col*11+1+9 - uint8_t y=(oldColLin & 0xFF)*11+1+top;//lin*11+1+top - uint8_t w=9; - if(oldColLin==1795) //last item "Enter", col=7 lin=3 - w=33; //(5+1)*6-1+2+2 charWidth=5, charMargin=1, count("Enter")=6, lastItem_MarginRight=0, marginLeft==marginRight=2 - Robot.drawRect(x,y,w,9,hideColor); - - - x=(colLin>>8 & 0xFF)*11+10; - y=(colLin & 0xFF)*11+1+top; - w=9; - if(colLin==1795) //last item "Enter", col=7 lin=3 - w=33; //(5+1)*6-1+2+2 charWidth=5, charMargin=1, count("Enter")=6, lastItem_MarginRight=0, marginLeft==marginRight=2 - Robot.drawRect(x,y,w,9,showColor); - oldColLin=colLin; - } -} - -char VirtualKeyboard::getSelection(){ - if(!onOff)return -1; - - uint8_t val=map(Robot.knobRead(),0,1023,0,38); - if(0<=val && 9>=val) - val='0'+val; - else if(10<=val && 35>=val) - val='A'+val-10; - else if(val==36) - val=' '; - else if(val>=37) - val='\0'; - - return val; -} -void VirtualKeyboard::hide(){ - onOff=false; - Robot.fillRect(0,top,128,44,hideColor);//11*4 -} - -void VirtualKeyboard::display(uint8_t top, uint16_t showColor, uint16_t hideColor){ -/** Display the keyboard at y position of top -* formular: -* When text size is 1, one character is 5*7 -* margin-left==margin-right==3, -* margin-top==margin-bottom==2, -* keyWidth=5+3+3==11, -* keyHeight=7+2+2==11, -* keyboard-margin-left=keyboard-margin-right==9 -* so character-x=11*col+9+3=11*col+12 -* character-y=11*lin+2+top -* -**/ - this->top=top; - this->onOff=true; - - this->showColor=showColor; - this->hideColor=hideColor; - - for(uint8_t i=0;i<36;i++){ - Robot.setCursor(i%10*11+12,2+top+i/10*11); - if(i<10) - Robot.print(char('0'+i)); - else - Robot.print(char(55+i));//'A'-10=55 - }//for saving 58 bytes :( - - /*for(int i=0;i<10;i++){ - Robot.setCursor(i*11+12,2+top);//11*0+2+top - Robot.print(char('0'+i));//line_1: 0-9 - } - for(int i=0;i<10;i++){ - Robot.setCursor(i*11+12,13+top);//11*1+2+top - Robot.print(char('A'+i));//line_2: A-J - } - for(int i=0;i<10;i++){ - Robot.setCursor(i*11+12,24+top);//11*2+2+top - Robot.print(char('K'+i));//line_3: K-T - } - for(int i=0;i<6;i++){ - Robot.setCursor(i*11+12,35+top);//11*3+2+top - Robot.print(char('U'+i));//line_4: U-Z - }*/ - //space and enter at the end of the last line. - Robot.setCursor(78,35+top);//6*11+12=78 - Robot.print('_');//_ - - Robot.setCursor(89,35+top);//7*11+12=89 - Robot.print("Enter");//enter -} - - - -VirtualKeyboard Vkey=VirtualKeyboard(); \ No newline at end of file diff --git a/libraries/Robot_Control/utility/VirtualKeyboard.h b/libraries/Robot_Control/utility/VirtualKeyboard.h deleted file mode 100644 index 273edb7..0000000 --- a/libraries/Robot_Control/utility/VirtualKeyboard.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef VIRTUAL_KEYBOARD_H -#define VIRTUAL_KEYBOARD_H - -#include -#include - -class VirtualKeyboard{ - public: - //void begin(); - void display(uint8_t top, uint16_t showColor=BLACK, uint16_t hideColor=WHITE); - void hide(); - - char getSelection(); - void run(); - - private: - uint8_t top; - bool onOff; - - uint16_t showColor; - uint16_t hideColor; - - int getColLin(int val); - -}; - -extern VirtualKeyboard Vkey; -#endif \ No newline at end of file diff --git a/libraries/Robot_Control/utility/scripts_Hello_User.h b/libraries/Robot_Control/utility/scripts_Hello_User.h deleted file mode 100644 index 29f085f..0000000 --- a/libraries/Robot_Control/utility/scripts_Hello_User.h +++ /dev/null @@ -1,51 +0,0 @@ -#include - -//an advanced trick for storing strings inside the program space -//as the ram of Arduino is very tiny, keeping too many string in it -//can kill the program - -prog_char hello_user_script1[] PROGMEM="What's your name?"; -prog_char hello_user_script2[] PROGMEM="Give me a name!"; -prog_char hello_user_script3[] PROGMEM="And the country?"; -prog_char hello_user_script4[] PROGMEM="The city you're in?"; -prog_char hello_user_script5[] PROGMEM=" Plug me to\n\n your computer\n\n and start coding!"; - -prog_char hello_user_script6[] PROGMEM=" Hello User!\n\n It's me, your robot\n\n I'm alive! <3"; -prog_char hello_user_script7[] PROGMEM=" First I need some\n\n input from you!"; -prog_char hello_user_script8[] PROGMEM=" Use the knob\n\n to select letters"; -prog_char hello_user_script9[] PROGMEM=" Use L/R button\n\n to move the cursor,\n\n middle to confirm"; -prog_char hello_user_script10[] PROGMEM=" Press middle key\n to continue..."; -prog_char hello_user_script11[] PROGMEM=" Choose \"enter\" to\n\n finish the input"; - -PROGMEM const char *scripts_Hello_User[]={ - hello_user_script1, - hello_user_script2, - hello_user_script3, - hello_user_script4, - hello_user_script5, - hello_user_script6, - hello_user_script7, - hello_user_script8, - hello_user_script9, - hello_user_script10, - hello_user_script11, -}; - -/* -void getPGMtext(int seq){ - //It takes a string from program space, and fill it - //in the buffer - strcpy_P(buffer,(char*)pgm_read_word(&(scripts[seq]))); -} - -void writeScript(int seq, int line, int col){ - //print a string from program space to a specific line, - //column on the LCD - - //first fill the buffer with text from program space - getPGMtext(seq); - //then print it to the screen - textManager.writeText(line,col,buffer); -} - -*/ \ No newline at end of file diff --git a/libraries/Robot_Control/utility/twi.c b/libraries/Robot_Control/utility/twi.c deleted file mode 100644 index 6b2db3c..0000000 --- a/libraries/Robot_Control/utility/twi.c +++ /dev/null @@ -1,527 +0,0 @@ -/* - twi.c - TWI/I2C library for Wiring & Arduino - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts -*/ - -#include -#include -#include -#include -#include -#include -#include "Arduino.h" // for digitalWrite - -#ifndef cbi -#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) -#endif - -#ifndef sbi -#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) -#endif - -#include "pins_arduino.h" -#include "twi.h" - -static volatile uint8_t twi_state; -static volatile uint8_t twi_slarw; -static volatile uint8_t twi_sendStop; // should the transaction end with a stop -static volatile uint8_t twi_inRepStart; // in the middle of a repeated start - -static void (*twi_onSlaveTransmit)(void); -static void (*twi_onSlaveReceive)(uint8_t*, int); - -static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH]; -static volatile uint8_t twi_masterBufferIndex; -static volatile uint8_t twi_masterBufferLength; - -static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH]; -static volatile uint8_t twi_txBufferIndex; -static volatile uint8_t twi_txBufferLength; - -static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH]; -static volatile uint8_t twi_rxBufferIndex; - -static volatile uint8_t twi_error; - -/* - * Function twi_init - * Desc readys twi pins and sets twi bitrate - * Input none - * Output none - */ -void twi_init(void) -{ - // initialize state - twi_state = TWI_READY; - twi_sendStop = true; // default value - twi_inRepStart = false; - - // activate internal pullups for twi. - digitalWrite(SDA, 1); - digitalWrite(SCL, 1); - - // initialize twi prescaler and bit rate - cbi(TWSR, TWPS0); - cbi(TWSR, TWPS1); - TWBR = ((F_CPU / TWI_FREQ) - 16) / 2; - - /* twi bit rate formula from atmega128 manual pg 204 - SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR)) - note: TWBR should be 10 or higher for master mode - It is 72 for a 16mhz Wiring board with 100kHz TWI */ - - // enable twi module, acks, and twi interrupt - TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA); -} - -/* - * Function twi_slaveInit - * Desc sets slave address and enables interrupt - * Input none - * Output none - */ -void twi_setAddress(uint8_t address) -{ - // set twi slave address (skip over TWGCE bit) - TWAR = address << 1; -} - -/* - * Function twi_readFrom - * Desc attempts to become twi bus master and read a - * series of bytes from a device on the bus - * Input address: 7bit i2c device address - * data: pointer to byte array - * length: number of bytes to read into array - * sendStop: Boolean indicating whether to send a stop at the end - * Output number of bytes read - */ -uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length, uint8_t sendStop) -{ - uint8_t i; - - // ensure data will fit into buffer - if(TWI_BUFFER_LENGTH < length){ - return 0; - } - - // wait until twi is ready, become master receiver - while(TWI_READY != twi_state){ - continue; - } - twi_state = TWI_MRX; - twi_sendStop = sendStop; - // reset error state (0xFF.. no error occured) - twi_error = 0xFF; - - // initialize buffer iteration vars - twi_masterBufferIndex = 0; - twi_masterBufferLength = length-1; // This is not intuitive, read on... - // On receive, the previously configured ACK/NACK setting is transmitted in - // response to the received byte before the interrupt is signalled. - // Therefor we must actually set NACK when the _next_ to last byte is - // received, causing that NACK to be sent in response to receiving the last - // expected byte of data. - - // build sla+w, slave device address + w bit - twi_slarw = TW_READ; - twi_slarw |= address << 1; - - if (true == twi_inRepStart) { - // if we're in the repeated start state, then we've already sent the start, - // (@@@ we hope), and the TWI statemachine is just waiting for the address byte. - // We need to remove ourselves from the repeated start state before we enable interrupts, - // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning - // up. Also, don't enable the START interrupt. There may be one pending from the - // repeated start that we sent outselves, and that would really confuse things. - twi_inRepStart = false; // remember, we're dealing with an ASYNC ISR - TWDR = twi_slarw; - TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE); // enable INTs, but not START - } - else - // send start condition - TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA); - - // wait for read operation to complete - while(TWI_MRX == twi_state){ - continue; - } - - if (twi_masterBufferIndex < length) - length = twi_masterBufferIndex; - - // copy twi buffer to data - for(i = 0; i < length; ++i){ - data[i] = twi_masterBuffer[i]; - } - - return length; -} - -/* - * Function twi_writeTo - * Desc attempts to become twi bus master and write a - * series of bytes to a device on the bus - * Input address: 7bit i2c device address - * data: pointer to byte array - * length: number of bytes in array - * wait: boolean indicating to wait for write or not - * sendStop: boolean indicating whether or not to send a stop at the end - * Output 0 .. success - * 1 .. length to long for buffer - * 2 .. address send, NACK received - * 3 .. data send, NACK received - * 4 .. other twi error (lost bus arbitration, bus error, ..) - */ -uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait, uint8_t sendStop) -{ - uint8_t i; - - // ensure data will fit into buffer - if(TWI_BUFFER_LENGTH < length){ - return 1; - } - - // wait until twi is ready, become master transmitter - while(TWI_READY != twi_state){ - continue; - } - twi_state = TWI_MTX; - twi_sendStop = sendStop; - // reset error state (0xFF.. no error occured) - twi_error = 0xFF; - - // initialize buffer iteration vars - twi_masterBufferIndex = 0; - twi_masterBufferLength = length; - - // copy data to twi buffer - for(i = 0; i < length; ++i){ - twi_masterBuffer[i] = data[i]; - } - - // build sla+w, slave device address + w bit - twi_slarw = TW_WRITE; - twi_slarw |= address << 1; - - // if we're in a repeated start, then we've already sent the START - // in the ISR. Don't do it again. - // - if (true == twi_inRepStart) { - // if we're in the repeated start state, then we've already sent the start, - // (@@@ we hope), and the TWI statemachine is just waiting for the address byte. - // We need to remove ourselves from the repeated start state before we enable interrupts, - // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning - // up. Also, don't enable the START interrupt. There may be one pending from the - // repeated start that we sent outselves, and that would really confuse things. - twi_inRepStart = false; // remember, we're dealing with an ASYNC ISR - TWDR = twi_slarw; - TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE); // enable INTs, but not START - } - else - // send start condition - TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA); // enable INTs - - // wait for write operation to complete - while(wait && (TWI_MTX == twi_state)){ - continue; - } - - if (twi_error == 0xFF) - return 0; // success - else if (twi_error == TW_MT_SLA_NACK) - return 2; // error: address send, nack received - else if (twi_error == TW_MT_DATA_NACK) - return 3; // error: data send, nack received - else - return 4; // other twi error -} - -/* - * Function twi_transmit - * Desc fills slave tx buffer with data - * must be called in slave tx event callback - * Input data: pointer to byte array - * length: number of bytes in array - * Output 1 length too long for buffer - * 2 not slave transmitter - * 0 ok - */ -uint8_t twi_transmit(const uint8_t* data, uint8_t length) -{ - uint8_t i; - - // ensure data will fit into buffer - if(TWI_BUFFER_LENGTH < length){ - return 1; - } - - // ensure we are currently a slave transmitter - if(TWI_STX != twi_state){ - return 2; - } - - // set length and copy data into tx buffer - twi_txBufferLength = length; - for(i = 0; i < length; ++i){ - twi_txBuffer[i] = data[i]; - } - - return 0; -} - -/* - * Function twi_attachSlaveRxEvent - * Desc sets function called before a slave read operation - * Input function: callback function to use - * Output none - */ -void twi_attachSlaveRxEvent( void (*function)(uint8_t*, int) ) -{ - twi_onSlaveReceive = function; -} - -/* - * Function twi_attachSlaveTxEvent - * Desc sets function called before a slave write operation - * Input function: callback function to use - * Output none - */ -void twi_attachSlaveTxEvent( void (*function)(void) ) -{ - twi_onSlaveTransmit = function; -} - -/* - * Function twi_reply - * Desc sends byte or readys receive line - * Input ack: byte indicating to ack or to nack - * Output none - */ -void twi_reply(uint8_t ack) -{ - // transmit master read ready signal, with or without ack - if(ack){ - TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA); - }else{ - TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT); - } -} - -/* - * Function twi_stop - * Desc relinquishes bus master status - * Input none - * Output none - */ -void twi_stop(void) -{ - // send stop condition - TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO); - - // wait for stop condition to be exectued on bus - // TWINT is not set after a stop condition! - while(TWCR & _BV(TWSTO)){ - continue; - } - - // update twi state - twi_state = TWI_READY; -} - -/* - * Function twi_releaseBus - * Desc releases bus control - * Input none - * Output none - */ -void twi_releaseBus(void) -{ - // release bus - TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT); - - // update twi state - twi_state = TWI_READY; -} - -SIGNAL(TWI_vect) -{ - switch(TW_STATUS){ - // All Master - case TW_START: // sent start condition - case TW_REP_START: // sent repeated start condition - // copy device address and r/w bit to output register and ack - TWDR = twi_slarw; - twi_reply(1); - break; - - // Master Transmitter - case TW_MT_SLA_ACK: // slave receiver acked address - case TW_MT_DATA_ACK: // slave receiver acked data - // if there is data to send, send it, otherwise stop - if(twi_masterBufferIndex < twi_masterBufferLength){ - // copy data to output register and ack - TWDR = twi_masterBuffer[twi_masterBufferIndex++]; - twi_reply(1); - }else{ - if (twi_sendStop) - twi_stop(); - else { - twi_inRepStart = true; // we're gonna send the START - // don't enable the interrupt. We'll generate the start, but we - // avoid handling the interrupt until we're in the next transaction, - // at the point where we would normally issue the start. - TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ; - twi_state = TWI_READY; - } - } - break; - case TW_MT_SLA_NACK: // address sent, nack received - twi_error = TW_MT_SLA_NACK; - twi_stop(); - break; - case TW_MT_DATA_NACK: // data sent, nack received - twi_error = TW_MT_DATA_NACK; - twi_stop(); - break; - case TW_MT_ARB_LOST: // lost bus arbitration - twi_error = TW_MT_ARB_LOST; - twi_releaseBus(); - break; - - // Master Receiver - case TW_MR_DATA_ACK: // data received, ack sent - // put byte into buffer - twi_masterBuffer[twi_masterBufferIndex++] = TWDR; - case TW_MR_SLA_ACK: // address sent, ack received - // ack if more bytes are expected, otherwise nack - if(twi_masterBufferIndex < twi_masterBufferLength){ - twi_reply(1); - }else{ - twi_reply(0); - } - break; - case TW_MR_DATA_NACK: // data received, nack sent - // put final byte into buffer - twi_masterBuffer[twi_masterBufferIndex++] = TWDR; - if (twi_sendStop) - twi_stop(); - else { - twi_inRepStart = true; // we're gonna send the START - // don't enable the interrupt. We'll generate the start, but we - // avoid handling the interrupt until we're in the next transaction, - // at the point where we would normally issue the start. - TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ; - twi_state = TWI_READY; - } - break; - case TW_MR_SLA_NACK: // address sent, nack received - twi_stop(); - break; - // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case - - // Slave Receiver - case TW_SR_SLA_ACK: // addressed, returned ack - case TW_SR_GCALL_ACK: // addressed generally, returned ack - case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack - case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack - // enter slave receiver mode - twi_state = TWI_SRX; - // indicate that rx buffer can be overwritten and ack - twi_rxBufferIndex = 0; - twi_reply(1); - break; - case TW_SR_DATA_ACK: // data received, returned ack - case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack - // if there is still room in the rx buffer - if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){ - // put byte in buffer and ack - twi_rxBuffer[twi_rxBufferIndex++] = TWDR; - twi_reply(1); - }else{ - // otherwise nack - twi_reply(0); - } - break; - case TW_SR_STOP: // stop or repeated start condition received - // put a null char after data if there's room - if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){ - twi_rxBuffer[twi_rxBufferIndex] = '\0'; - } - // sends ack and stops interface for clock stretching - twi_stop(); - // callback to user defined callback - twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex); - // since we submit rx buffer to "wire" library, we can reset it - twi_rxBufferIndex = 0; - // ack future responses and leave slave receiver state - twi_releaseBus(); - break; - case TW_SR_DATA_NACK: // data received, returned nack - case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack - // nack back at master - twi_reply(0); - break; - - // Slave Transmitter - case TW_ST_SLA_ACK: // addressed, returned ack - case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack - // enter slave transmitter mode - twi_state = TWI_STX; - // ready the tx buffer index for iteration - twi_txBufferIndex = 0; - // set tx buffer length to be zero, to verify if user changes it - twi_txBufferLength = 0; - // request for txBuffer to be filled and length to be set - // note: user must call twi_transmit(bytes, length) to do this - twi_onSlaveTransmit(); - // if they didn't change buffer & length, initialize it - if(0 == twi_txBufferLength){ - twi_txBufferLength = 1; - twi_txBuffer[0] = 0x00; - } - // transmit first byte from buffer, fall - case TW_ST_DATA_ACK: // byte sent, ack returned - // copy data to output register - TWDR = twi_txBuffer[twi_txBufferIndex++]; - // if there is more to send, ack, otherwise nack - if(twi_txBufferIndex < twi_txBufferLength){ - twi_reply(1); - }else{ - twi_reply(0); - } - break; - case TW_ST_DATA_NACK: // received nack, we are done - case TW_ST_LAST_DATA: // received ack, but we are done already! - // ack future responses - twi_reply(1); - // leave slave receiver state - twi_state = TWI_READY; - break; - - // All - case TW_NO_INFO: // no state information - break; - case TW_BUS_ERROR: // bus error, illegal stop/start - twi_error = TW_BUS_ERROR; - twi_stop(); - break; - } -} - diff --git a/libraries/Robot_Control/utility/twi.h b/libraries/Robot_Control/utility/twi.h deleted file mode 100644 index 6526593..0000000 --- a/libraries/Robot_Control/utility/twi.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - twi.h - TWI/I2C library for Wiring & Arduino - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef twi_h -#define twi_h - - #include - - //#define ATMEGA8 - - #ifndef TWI_FREQ - #define TWI_FREQ 100000L - #endif - - #ifndef TWI_BUFFER_LENGTH - #define TWI_BUFFER_LENGTH 32 - #endif - - #define TWI_READY 0 - #define TWI_MRX 1 - #define TWI_MTX 2 - #define TWI_SRX 3 - #define TWI_STX 4 - - void twi_init(void); - void twi_setAddress(uint8_t); - uint8_t twi_readFrom(uint8_t, uint8_t*, uint8_t, uint8_t); - uint8_t twi_writeTo(uint8_t, uint8_t*, uint8_t, uint8_t, uint8_t); - uint8_t twi_transmit(const uint8_t*, uint8_t); - void twi_attachSlaveRxEvent( void (*)(uint8_t*, int) ); - void twi_attachSlaveTxEvent( void (*)(void) ); - void twi_reply(uint8_t); - void twi_stop(void); - void twi_releaseBus(void); - -#endif - diff --git a/libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp b/libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp deleted file mode 100644 index 7740a06..0000000 --- a/libraries/Robot_Motor/ArduinoRobotMotorBoard.cpp +++ /dev/null @@ -1,265 +0,0 @@ -#include "ArduinoRobotMotorBoard.h" -#include "EasyTransfer2.h" -#include "Multiplexer.h" -#include "LineFollow.h" - -RobotMotorBoard::RobotMotorBoard(){ - //LineFollow::LineFollow(); -} -/*void RobotMotorBoard::beginIRReceiver(){ - IRrecv::enableIRIn(); -}*/ -void RobotMotorBoard::begin(){ - //initialze communication - Serial1.begin(9600); - messageIn.begin(&Serial1); - messageOut.begin(&Serial1); - - //init MUX - uint8_t MuxPins[]={MUXA,MUXB,MUXC}; - this->IRs.begin(MuxPins,MUX_IN,3); - pinMode(MUXI,INPUT); - digitalWrite(MUXI,LOW); - - isPaused=false; -} - -void RobotMotorBoard::process(){ - if(isPaused)return;//skip process if the mode is paused - - if(mode==MODE_SIMPLE){ - //Serial.println("s"); - //do nothing? Simple mode is just about getting commands - }else if(mode==MODE_LINE_FOLLOW){ - //do line following stuff here. - LineFollow::runLineFollow(); - }else if(mode==MODE_ADJUST_MOTOR){ - //Serial.println('a'); - //motorAdjustment=analogRead(POT); - //setSpeed(255,255); - //delay(100); - } -} -void RobotMotorBoard::pauseMode(bool onOff){ - if(onOff){ - isPaused=true; - }else{ - isPaused=false; - } - stopCurrentActions(); - -} -void RobotMotorBoard::parseCommand(){ - uint8_t modeName; - uint8_t codename; - int value; - int speedL; - int speedR; - if(this->messageIn.receiveData()){ - //Serial.println("data received"); - uint8_t command=messageIn.readByte(); - //Serial.println(command); - switch(command){ - case COMMAND_SWITCH_MODE: - modeName=messageIn.readByte(); - setMode(modeName); - break; - case COMMAND_RUN: - if(mode==MODE_LINE_FOLLOW)break;//in follow line mode, the motor does not follow commands - speedL=messageIn.readInt(); - speedR=messageIn.readInt(); - motorsWrite(speedL,speedR); - break; - case COMMAND_MOTORS_STOP: - motorsStop(); - break; - case COMMAND_ANALOG_WRITE: - codename=messageIn.readByte(); - value=messageIn.readInt(); - _analogWrite(codename,value); - break; - case COMMAND_DIGITAL_WRITE: - codename=messageIn.readByte(); - value=messageIn.readByte(); - _digitalWrite(codename,value); - break; - case COMMAND_ANALOG_READ: - codename=messageIn.readByte(); - _analogRead(codename); - break; - case COMMAND_DIGITAL_READ: - codename=messageIn.readByte(); - _digitalRead(codename); - break; - case COMMAND_READ_IR: - _readIR(); - break; - case COMMAND_READ_TRIM: - _readTrim(); - break; - case COMMAND_PAUSE_MODE: - pauseMode(messageIn.readByte());//onOff state - break; - case COMMAND_LINE_FOLLOW_CONFIG: - LineFollow::config( - messageIn.readByte(), //KP - messageIn.readByte(), //KD - messageIn.readByte(), //robotSpeed - messageIn.readByte() //IntegrationTime - ); - break; - } - } - //delay(5); -} -uint8_t RobotMotorBoard::parseCodename(uint8_t codename){ - switch(codename){ - case B_TK1: - return TK1; - case B_TK2: - return TK2; - case B_TK3: - return TK3; - case B_TK4: - return TK4; - } -} -uint8_t RobotMotorBoard::codenameToAPin(uint8_t codename){ - switch(codename){ - case B_TK1: - return A0; - case B_TK2: - return A1; - case B_TK3: - return A6; - case B_TK4: - return A11; - } -} - -void RobotMotorBoard::setMode(uint8_t mode){ - if(mode==MODE_LINE_FOLLOW){ - LineFollow::calibIRs(); - } - /*if(mode==SET_MOTOR_ADJUSTMENT){ - save_motor_adjustment_to_EEPROM(); - } - */ - /*if(mode==MODE_IR_CONTROL){ - beginIRReceiver(); - }*/ - this->mode=mode; - //stopCurrentActions();//If line following, this should stop the motors -} - -void RobotMotorBoard::stopCurrentActions(){ - motorsStop(); - //motorsWrite(0,0); -} - -void RobotMotorBoard::motorsWrite(int speedL, int speedR){ - /*Serial.print(speedL); - Serial.print(" "); - Serial.println(speedR);*/ - //motor adjustment, using percentage - _refreshMotorAdjustment(); - - if(motorAdjustment<0){ - speedR*=(1+motorAdjustment); - }else{ - speedL*=(1-motorAdjustment); - } - - if(speedL>0){ - analogWrite(IN_A1,speedL); - analogWrite(IN_A2,0); - }else{ - analogWrite(IN_A1,0); - analogWrite(IN_A2,-speedL); - } - - if(speedR>0){ - analogWrite(IN_B1,speedR); - analogWrite(IN_B2,0); - }else{ - analogWrite(IN_B1,0); - analogWrite(IN_B2,-speedR); - } -} -void RobotMotorBoard::motorsWritePct(int speedLpct, int speedRpct){ - //speedLpct, speedRpct ranges from -100 to 100 - motorsWrite(speedLpct*2.55,speedRpct*2.55); -} -void RobotMotorBoard::motorsStop(){ - analogWrite(IN_A1,255); - analogWrite(IN_A2,255); - - analogWrite(IN_B1,255); - analogWrite(IN_B2,255); -} - - -/* -* -* -* Input and Output ports -* -* -*/ -void RobotMotorBoard::_digitalWrite(uint8_t codename,bool value){ - uint8_t pin=parseCodename(codename); - digitalWrite(pin,value); -} -void RobotMotorBoard::_analogWrite(uint8_t codename,int value){ - //There's no PWM available on motor board -} -void RobotMotorBoard::_digitalRead(uint8_t codename){ - uint8_t pin=parseCodename(codename); - bool value=digitalRead(pin); - messageOut.writeByte(COMMAND_DIGITAL_READ_RE); - messageOut.writeByte(codename); - messageOut.writeByte(value); - messageOut.sendData(); -} -void RobotMotorBoard::_analogRead(uint8_t codename){ - uint8_t pin=codenameToAPin(codename); - int value=analogRead(pin); - messageOut.writeByte(COMMAND_ANALOG_READ_RE); - messageOut.writeByte(codename); - messageOut.writeInt(value); - messageOut.sendData(); -} -int RobotMotorBoard::IRread(uint8_t num){ - IRs.selectPin(num-1); //To make consistant with the pins labeled on the board - return IRs.getAnalogValue(); -} - -void RobotMotorBoard::_readIR(){ - //Serial.println("readIR"); - int value; - messageOut.writeByte(COMMAND_READ_IR_RE); - for(int i=1;i<6;i++){ - value=IRread(i); - messageOut.writeInt(value); - } - messageOut.sendData(); -} - -void RobotMotorBoard::_readTrim(){ - int value=analogRead(TRIM); - messageOut.writeByte(COMMAND_READ_TRIM_RE); - messageOut.writeInt(value); - messageOut.sendData(); -} - -void RobotMotorBoard::_refreshMotorAdjustment(){ - motorAdjustment=map(analogRead(TRIM),0,1023,-30,30)/100.0; -} - -void RobotMotorBoard::reportActionDone(){ - setMode(MODE_SIMPLE); - messageOut.writeByte(COMMAND_ACTION_DONE); - messageOut.sendData(); -} - -RobotMotorBoard RobotMotor=RobotMotorBoard(); \ No newline at end of file diff --git a/libraries/Robot_Motor/ArduinoRobotMotorBoard.h b/libraries/Robot_Motor/ArduinoRobotMotorBoard.h deleted file mode 100644 index c1004c4..0000000 --- a/libraries/Robot_Motor/ArduinoRobotMotorBoard.h +++ /dev/null @@ -1,125 +0,0 @@ -#ifndef ArduinoRobot_h -#define ArduinoRobot_h - -#include "EasyTransfer2.h" -#include "Multiplexer.h" -#include "LineFollow.h" -//#include "IRremote.h" - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -//Command code -#define COMMAND_SWITCH_MODE 0 -#define COMMAND_RUN 10 -#define COMMAND_MOTORS_STOP 11 -#define COMMAND_ANALOG_WRITE 20 -#define COMMAND_DIGITAL_WRITE 30 -#define COMMAND_ANALOG_READ 40 -#define COMMAND_ANALOG_READ_RE 41 -#define COMMAND_DIGITAL_READ 50 -#define COMMAND_DIGITAL_READ_RE 51 -#define COMMAND_READ_IR 60 -#define COMMAND_READ_IR_RE 61 -#define COMMAND_ACTION_DONE 70 -#define COMMAND_READ_TRIM 80 -#define COMMAND_READ_TRIM_RE 81 -#define COMMAND_PAUSE_MODE 90 -#define COMMAND_LINE_FOLLOW_CONFIG 100 - - -//component codename -#define CN_LEFT_MOTOR 0 -#define CN_RIGHT_MOTOR 1 -#define CN_IR 2 - -//motor board modes -#define MODE_SIMPLE 0 -#define MODE_LINE_FOLLOW 1 -#define MODE_ADJUST_MOTOR 2 -#define MODE_IR_CONTROL 3 - -//bottom TKs, just for communication purpose -#define B_TK1 201 -#define B_TK2 202 -#define B_TK3 203 -#define B_TK4 204 - -/* -A message structure will be: -switch mode (2): - byte COMMAND_SWITCH_MODE, byte mode -run (5): - byte COMMAND_RUN, int speedL, int speedR -analogWrite (3): - byte COMMAND_ANALOG_WRITE, byte codename, byte value; -digitalWrite (3): - byte COMMAND_DIGITAL_WRITE, byte codename, byte value; -analogRead (2): - byte COMMAND_ANALOG_READ, byte codename; -analogRead _return_ (4): - byte COMMAND_ANALOG_READ_RE, byte codename, int value; -digitalRead (2): - byte COMMAND_DIGITAL_READ, byte codename; -digitalRead _return_ (4): - byte COMMAND_DIGITAL_READ_RE, byte codename, int value; -read IR (1): - byte COMMAND_READ_IR; -read IR _return_ (9): - byte COMMAND_READ_IR_RE, int valueA, int valueB, int valueC, int valueD; - - -*/ - -class RobotMotorBoard:public LineFollow{ - public: - RobotMotorBoard(); - void begin(); - - void process(); - - void parseCommand(); - - int IRread(uint8_t num); - - void setMode(uint8_t mode); - void pauseMode(bool onOff); - - void motorsWrite(int speedL, int speedR); - void motorsWritePct(int speedLpct, int speedRpct);//write motor values in percentage - void motorsStop(); - private: - float motorAdjustment;//-1.0 ~ 1.0, whether left is lowered or right is lowered - - //convert codename to actual pins - uint8_t parseCodename(uint8_t codename); - uint8_t codenameToAPin(uint8_t codename); - - void stopCurrentActions(); - //void sendCommand(byte command,byte codename,int value); - - void _analogWrite(uint8_t codename, int value); - void _digitalWrite(uint8_t codename, bool value); - void _analogRead(uint8_t codename); - void _digitalRead(uint8_t codename); - void _readIR(); - void _readTrim(); - - void _refreshMotorAdjustment(); - - Multiplexer IRs; - uint8_t mode; - uint8_t isPaused; - EasyTransfer2 messageIn; - EasyTransfer2 messageOut; - - //Line Following - void reportActionDone(); -}; - -extern RobotMotorBoard RobotMotor; - -#endif \ No newline at end of file diff --git a/libraries/Robot_Motor/EasyTransfer2.cpp b/libraries/Robot_Motor/EasyTransfer2.cpp deleted file mode 100644 index 24427cc..0000000 --- a/libraries/Robot_Motor/EasyTransfer2.cpp +++ /dev/null @@ -1,152 +0,0 @@ -#include "EasyTransfer2.h" - - - - -//Captures address and size of struct -void EasyTransfer2::begin(HardwareSerial *theSerial){ - _serial = theSerial; - - //dynamic creation of rx parsing buffer in RAM - //rx_buffer = (uint8_t*) malloc(size); - - resetData(); -} - -void EasyTransfer2::writeByte(uint8_t dat){ - if(position<20) - data[position++]=dat; - size++; -} -void EasyTransfer2::writeInt(int dat){ - if(position<19){ - data[position++]=dat>>8; - data[position++]=dat; - size+=2; - } -} -uint8_t EasyTransfer2::readByte(){ - if(position>=size)return 0; - return data[position++]; -} -int EasyTransfer2::readInt(){ - if(position+1>=size)return 0; - int dat_1=data[position++]<<8; - int dat_2=data[position++]; - int dat= dat_1 | dat_2; - return dat; -} - -void EasyTransfer2::resetData(){ - for(int i=0;i<20;i++){ - data[i]=0; - } - size=0; - position=0; -} - -//Sends out struct in binary, with header, length info and checksum -void EasyTransfer2::sendData(){ - uint8_t CS = size; - _serial->write(0x06); - _serial->write(0x85); - _serial->write(size); - for(int i = 0; iwrite(*(data+i)); - //Serial.print(*(data+i)); - //Serial.print(","); - } - //Serial.println(""); - _serial->write(CS); - - resetData(); -} - -boolean EasyTransfer2::receiveData(){ - - //start off by looking for the header bytes. If they were already found in a previous call, skip it. - if(rx_len == 0){ - //this size check may be redundant due to the size check below, but for now I'll leave it the way it is. - if(_serial->available() >= 3){ - //this will block until a 0x06 is found or buffer size becomes less then 3. - while(_serial->read() != 0x06) { - //This will trash any preamble junk in the serial buffer - //but we need to make sure there is enough in the buffer to process while we trash the rest - //if the buffer becomes too empty, we will escape and try again on the next call - if(_serial->available() < 3) - return false; - } - //Serial.println("head"); - if (_serial->read() == 0x85){ - rx_len = _serial->read(); - //Serial.print("rx_len:"); - //Serial.println(rx_len); - resetData(); - - //make sure the binary structs on both Arduinos are the same size. - /*if(rx_len != size){ - rx_len = 0; - return false; - }*/ - } - } - //Serial.println("nothing"); - } - - //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned. - if(rx_len != 0){ - - while(_serial->available() && rx_array_inx <= rx_len){ - data[rx_array_inx++] = _serial->read(); - } - - if(rx_len == (rx_array_inx-1)){ - //seem to have got whole message - //last uint8_t is CS - calc_CS = rx_len; - //Serial.print("len:"); - //Serial.println(rx_len); - for (int i = 0; i -* -*This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. -*To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or -*send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. -******************************************************************/ -#ifndef EasyTransfer2_h -#define EasyTransfer2_h - - -//make it a little prettier on the front end. -#define details(name) (byte*)&name,sizeof(name) - -//Not neccessary, but just in case. -#if ARDUINO > 22 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif -#include "HardwareSerial.h" -//#include -#include -#include -#include -#include - -class EasyTransfer2 { -public: -void begin(HardwareSerial *theSerial); -//void begin(uint8_t *, uint8_t, NewSoftSerial *theSerial); -void sendData(); -boolean receiveData(); - -void writeByte(uint8_t dat); -void writeInt(int dat); -uint8_t readByte(); -int readInt(); - - -private: -HardwareSerial *_serial; - -void resetData(); - -uint8_t data[20]; //data storage, for both read and send -uint8_t position; -uint8_t size; //size of data in bytes. Both for read and send -//uint8_t * address; //address of struct -//uint8_t size; //size of struct -//uint8_t * rx_buffer; //address for temporary storage and parsing buffer -//uint8_t rx_buffer[20]; -uint8_t rx_array_inx; //index for RX parsing buffer -uint8_t rx_len; //RX packet length according to the packet -uint8_t calc_CS; //calculated Chacksum -}; - - - -#endif \ No newline at end of file diff --git a/libraries/Robot_Motor/LineFollow.h b/libraries/Robot_Motor/LineFollow.h deleted file mode 100644 index 608d573..0000000 --- a/libraries/Robot_Motor/LineFollow.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef LINE_FOLLOW_H -#define LINE_FOLLOW_H - -#if ARDUINO >= 100 - #include "Arduino.h" -#else - #include "WProgram.h" -#endif - -class LineFollow{ - public: - LineFollow(); - - void calibIRs(); - void runLineFollow(); - void config(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime); - - //These are all pure virtual functions, pure VF needs pure specifier "=0" - //virtual void motorsWrite(int speedL, int speedR)=0; - virtual void motorsWritePct(int speedLpct, int speedRpct)=0; - virtual void motorsStop()=0; - virtual int IRread(uint8_t num)=0; - protected: - virtual void reportActionDone()=0; - - private: - void doCalibration(int speedPct, int time); - void ajusta_niveles(); - - uint8_t KP; - uint8_t KD; - uint8_t robotSpeed; //percentage - uint8_t intergrationTime; - - int lectura_sensor[5], last_error, acu; - int sensor_blanco[5]; - int sensor_negro[5]; -}; - -#endif \ No newline at end of file diff --git a/libraries/Robot_Motor/Multiplexer.cpp b/libraries/Robot_Motor/Multiplexer.cpp deleted file mode 100644 index c0fdd86..0000000 --- a/libraries/Robot_Motor/Multiplexer.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "Multiplexer.h" - -void Multiplexer::begin(uint8_t* selectors, uint8_t Z, uint8_t length){ - for(uint8_t i=0;iselectors[i]=selectors[i]; - pinMode(selectors[i],OUTPUT); - } - this->length=length; - this->pin_Z=Z; - pinMode(pin_Z,INPUT); -} - -void Multiplexer::selectPin(uint8_t num){ - for(uint8_t i=0;i= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -class Multiplexer{ - public: - void begin(uint8_t* selectors, uint8_t Z, uint8_t length); - void selectPin(uint8_t num); - int getAnalogValue(); - int getAnalogValueAt(uint8_t num); - bool getDigitalValue(); - bool getDigitalValueAt(uint8_t num); - private: - uint8_t selectors[4]; - uint8_t pin_Z; - uint8_t length; -}; - -#endif diff --git a/libraries/Robot_Motor/examples/Robot_IR_Array_Test/Robot_IR_Array_Test.ino b/libraries/Robot_Motor/examples/Robot_IR_Array_Test/Robot_IR_Array_Test.ino deleted file mode 100644 index e201fd9..0000000 --- a/libraries/Robot_Motor/examples/Robot_IR_Array_Test/Robot_IR_Array_Test.ino +++ /dev/null @@ -1,26 +0,0 @@ -/* Motor Board IR Array Test - - This example of the Arduno robot's motor board returns the - values read fron the 5 infrared sendors on the bottom of - the robot. - -*/ -// include the motor board header -#include - -String bar; // string for storing the informaton - -void setup(){ - // start serial communication - Serial.begin(9600); - // initialize the library - RobotMotor.begin(); -} -void loop(){ - bar=String(""); // empty the string - // read the sensors and add them to the string - bar=bar+RobotMotor.readIR(0)+' '+RobotMotor.readIR(1)+' '+RobotMotor.readIR(2)+' '+RobotMotor.readIR(3)+' '+RobotMotor.readIR(4); - // print out the values - Serial.println(bar); - delay(100); -} diff --git a/libraries/Robot_Motor/examples/Robot_Motor_Core/Robot_Motor_Core.ino b/libraries/Robot_Motor/examples/Robot_Motor_Core/Robot_Motor_Core.ino deleted file mode 100644 index f74f30a..0000000 --- a/libraries/Robot_Motor/examples/Robot_Motor_Core/Robot_Motor_Core.ino +++ /dev/null @@ -1,18 +0,0 @@ -/* Motor Core - - This code for the Arduino Robot's motor board - is the stock firmware. program the motor board with - this sketch whenever you want to return the motor - board to its default state. - -*/ - -#include - -void setup(){ - RobotMotor.begin(); -} -void loop(){ - RobotMotor.parseCommand(); - RobotMotor.process(); -} diff --git a/libraries/Robot_Motor/lineFollow.cpp b/libraries/Robot_Motor/lineFollow.cpp deleted file mode 100644 index d6ebed8..0000000 --- a/libraries/Robot_Motor/lineFollow.cpp +++ /dev/null @@ -1,152 +0,0 @@ -//#include -#include "LineFollow.h" - -//#define KP 19 //0.1 units -//#define KD 14 -//#define ROBOT_SPEED 100 //percentage - -//#define KP 11 -//#define KD 5 -//#define ROBOT_SPEED 50 - -//#define INTEGRATION_TIME 10 //En ms - -/*uint8_t KP=11; -uint8_t KD=5; -uint8_t robotSpeed=50; //percentage -uint8_t intergrationTime=10;*/ - -#define NIVEL_PARA_LINEA 50 - -/*int lectura_sensor[5], last_error=0, acu=0; - -//Estos son los arrays que hay que rellenar con los valores de los sensores -//de suelo sobre blanco y negro. -int sensor_blanco[]={ - 0,0,0,0,0}; -int sensor_negro[]={ - 1023,1023,1023,1023,1023}; -*/ -//unsigned long time; - -//void mueve_robot(int vel_izq, int vel_der); -//void para_robot(); -//void doCalibration(int speedPct, int time); -//void ajusta_niveles(); //calibrate values - -LineFollow::LineFollow(){ - /*KP=11; - KD=5; - robotSpeed=50; //percentage - intergrationTime=10;*/ - config(11,5,50,10); - - for(int i=0;i<5;i++){ - sensor_blanco[i]=0; - sensor_negro[i]=1023; - } -} - -void LineFollow::config(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime){ - this->KP=KP; - this->KD=KD; - this->robotSpeed=robotSpeed; - this->intergrationTime=intergrationTime; - /*Serial.print("LFC: "); - Serial.print(KP); - Serial.print(' '); - Serial.print(KD); - Serial.print(' '); - Serial.print(robotSpeed); - Serial.print(' '); - Serial.println(intergrationTime);*/ - -} -void LineFollow::calibIRs(){ - static bool isInited=false;//So only init once - if(isInited)return ; - - delay(1000); - - doCalibration(30,500); - doCalibration(-30,800); - doCalibration(30,500); - - delay(1000); - isInited=true; -} - -void LineFollow::runLineFollow(){ - for(int count=0; count<5; count++) - { - lectura_sensor[count]=map(IRread(count),sensor_negro[count],sensor_blanco[count],0,127); - acu+=lectura_sensor[count]; - } - - //Serial.println(millis()); - if (acu > NIVEL_PARA_LINEA) - { - acu/=5; - - int error = ((lectura_sensor[0]<<6)+(lectura_sensor[1]<<5)-(lectura_sensor[3]<<5)-(lectura_sensor[4]<<6))/acu; - - error = constrain(error,-100,100); - - //Calculamos la correcion de velocidad mediante un filtro PD - int vel = (error * KP)/10 + (error-last_error)*KD; - - last_error = error; - - //Corregimos la velocidad de avance con el error de salida del filtro PD - int motor_left = constrain((robotSpeed + vel),-100,100); - int motor_right =constrain((robotSpeed - vel),-100,100); - - //Movemos el robot - //motorsWritePct(motor_left,motor_right); - motorsWritePct(motor_left,motor_right); - - //Esperamos un poquito a que el robot reaccione - delay(intergrationTime); - } - else - { - //Hemos encontrado una linea negra - //perpendicular a nuestro camino - //paramos el robot - motorsStop(); - - //y detenemos la ejecución del programa - //while(true); - reportActionDone(); - //setMode(MODE_SIMPLE); - } -} - - -void LineFollow::doCalibration(int speedPct, int time){ - motorsWritePct(speedPct, -speedPct); - unsigned long beginTime = millis(); - while((millis()-beginTime) sensor_blanco[count]) - sensor_blanco[count]=lectura; - - if (lectura < sensor_negro[count]) - sensor_negro[count]=lectura; - } -} - - - - - - diff --git a/libraries/SPI/SPI.cpp b/libraries/SPI/SPI.cpp deleted file mode 100644 index 5e48073..0000000 --- a/libraries/SPI/SPI.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#include "pins_arduino.h" -#include "SPI.h" - -SPIClass SPI; - -void SPIClass::begin() { - - // Set SS to high so a connected chip will be "deselected" by default - digitalWrite(SS, HIGH); - - // When the SS pin is set as OUTPUT, it can be used as - // a general purpose output port (it doesn't influence - // SPI operations). - pinMode(SS, OUTPUT); - - // Warning: if the SS pin ever becomes a LOW INPUT then SPI - // automatically switches to Slave, so the data direction of - // the SS pin MUST be kept as OUTPUT. - SPCR |= _BV(MSTR); - SPCR |= _BV(SPE); - - // Set direction register for SCK and MOSI pin. - // MISO pin automatically overrides to INPUT. - // By doing this AFTER enabling SPI, we avoid accidentally - // clocking in a single bit since the lines go directly - // from "input" to SPI control. - // http://code.google.com/p/arduino/issues/detail?id=888 - pinMode(SCK, OUTPUT); - pinMode(MOSI, OUTPUT); -} - - -void SPIClass::end() { - SPCR &= ~_BV(SPE); -} - -void SPIClass::setBitOrder(uint8_t bitOrder) -{ - if(bitOrder == LSBFIRST) { - SPCR |= _BV(DORD); - } else { - SPCR &= ~(_BV(DORD)); - } -} - -void SPIClass::setDataMode(uint8_t mode) -{ - SPCR = (SPCR & ~SPI_MODE_MASK) | mode; -} - -void SPIClass::setClockDivider(uint8_t rate) -{ - SPCR = (SPCR & ~SPI_CLOCK_MASK) | (rate & SPI_CLOCK_MASK); - SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((rate >> 2) & SPI_2XCLOCK_MASK); -} - diff --git a/libraries/SPI/SPI.h b/libraries/SPI/SPI.h deleted file mode 100644 index f647d5c..0000000 --- a/libraries/SPI/SPI.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED - -#include -#include -#include - -#define SPI_CLOCK_DIV4 0x00 -#define SPI_CLOCK_DIV16 0x01 -#define SPI_CLOCK_DIV64 0x02 -#define SPI_CLOCK_DIV128 0x03 -#define SPI_CLOCK_DIV2 0x04 -#define SPI_CLOCK_DIV8 0x05 -#define SPI_CLOCK_DIV32 0x06 -//#define SPI_CLOCK_DIV64 0x07 - -#define SPI_MODE0 0x00 -#define SPI_MODE1 0x04 -#define SPI_MODE2 0x08 -#define SPI_MODE3 0x0C - -#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR -#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR -#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR - -class SPIClass { -public: - inline static byte transfer(byte _data); - - // SPI Configuration methods - - inline static void attachInterrupt(); - inline static void detachInterrupt(); // Default - - static void begin(); // Default - static void end(); - - static void setBitOrder(uint8_t); - static void setDataMode(uint8_t); - static void setClockDivider(uint8_t); -}; - -extern SPIClass SPI; - -byte SPIClass::transfer(byte _data) { - SPDR = _data; - while (!(SPSR & _BV(SPIF))) - ; - return SPDR; -} - -void SPIClass::attachInterrupt() { - SPCR |= _BV(SPIE); -} - -void SPIClass::detachInterrupt() { - SPCR &= ~_BV(SPIE); -} - -#endif diff --git a/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino b/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino deleted file mode 100644 index 9d77a42..0000000 --- a/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino +++ /dev/null @@ -1,143 +0,0 @@ -/* - SCP1000 Barometric Pressure Sensor Display - - Shows the output of a Barometric Pressure Sensor on a - Uses the SPI library. For details on the sensor, see: - http://www.sparkfun.com/commerce/product_info.php?products_id=8161 - http://www.vti.fi/en/support/obsolete_products/pressure_sensors/ - - This sketch adapted from Nathan Seidle's SCP1000 example for PIC: - http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip - - Circuit: - SCP1000 sensor attached to pins 6, 7, 10 - 13: - DRDY: pin 6 - CSB: pin 7 - MOSI: pin 11 - MISO: pin 12 - SCK: pin 13 - - created 31 July 2010 - modified 14 August 2010 - by Tom Igoe - */ - -// the sensor communicates using SPI, so include the library: -#include - -//Sensor's memory register addresses: -const int PRESSURE = 0x1F; //3 most significant bits of pressure -const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure -const int TEMPERATURE = 0x21; //16 bit temperature reading -const byte READ = 0b11111100; // SCP1000's read command -const byte WRITE = 0b00000010; // SCP1000's write command - -// pins used for the connection with the sensor -// the other you need are controlled by the SPI library): -const int dataReadyPin = 6; -const int chipSelectPin = 7; - -void setup() { - Serial.begin(9600); - - // start the SPI library: - SPI.begin(); - - // initalize the data ready and chip select pins: - pinMode(dataReadyPin, INPUT); - pinMode(chipSelectPin, OUTPUT); - - //Configure SCP1000 for low noise configuration: - writeRegister(0x02, 0x2D); - writeRegister(0x01, 0x03); - writeRegister(0x03, 0x02); - // give the sensor time to set up: - delay(100); -} - -void loop() { - //Select High Resolution Mode - writeRegister(0x03, 0x0A); - - // don't do anything until the data ready pin is high: - if (digitalRead(dataReadyPin) == HIGH) { - //Read the temperature data - int tempData = readRegister(0x21, 2); - - // convert the temperature to celsius and display it: - float realTemp = (float)tempData / 20.0; - Serial.print("Temp[C]="); - Serial.print(realTemp); - - - //Read the pressure data highest 3 bits: - byte pressure_data_high = readRegister(0x1F, 1); - pressure_data_high &= 0b00000111; //you only needs bits 2 to 0 - - //Read the pressure data lower 16 bits: - unsigned int pressure_data_low = readRegister(0x20, 2); - //combine the two parts into one 19-bit number: - long pressure = ((pressure_data_high << 16) | pressure_data_low)/4; - - // display the temperature: - Serial.println("\tPressure [Pa]=" + String(pressure)); - } -} - -//Read from or write to register from the SCP1000: -unsigned int readRegister(byte thisRegister, int bytesToRead ) { - byte inByte = 0; // incoming byte from the SPI - unsigned int result = 0; // result to return - Serial.print(thisRegister, BIN); - Serial.print("\t"); - // SCP1000 expects the register name in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the address and the command into one byte - byte dataToSend = thisRegister & READ; - Serial.println(thisRegister, BIN); - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - // send the device the register you want to read: - SPI.transfer(dataToSend); - // send a value of 0 to read the first byte returned: - result = SPI.transfer(0x00); - // decrement the number of bytes left to read: - bytesToRead--; - // if you still have another byte to read: - if (bytesToRead > 0) { - // shift the first byte left, then get the second byte: - result = result << 8; - inByte = SPI.transfer(0x00); - // combine the byte you just got with the previous one: - result = result | inByte; - // decrement the number of bytes left to read: - bytesToRead--; - } - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); - // return the result: - return(result); -} - - -//Sends a write command to SCP1000 - -void writeRegister(byte thisRegister, byte thisValue) { - - // SCP1000 expects the register address in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the register address and the command into one byte: - byte dataToSend = thisRegister | WRITE; - - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - - SPI.transfer(dataToSend); //Send register location - SPI.transfer(thisValue); //Send value to record into register - - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); -} - diff --git a/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.ino b/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.ino deleted file mode 100644 index 9c9c9b6..0000000 --- a/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.ino +++ /dev/null @@ -1,143 +0,0 @@ -/* - SCP1000 Barometric Pressure Sensor Display - - Shows the output of a Barometric Pressure Sensor on a - Uses the SPI library. For details on the sensor, see: - http://www.sparkfun.com/commerce/product_info.php?products_id=8161 - http://www.vti.fi/en/support/obsolete_products/pressure_sensors/ - - This sketch adapted from Nathan Seidle's SCP1000 example for PIC: - http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip - - Circuit: - SCP1000 sensor attached to pins 6, 7, 10 - 13: - DRDY: pin 6 - CSB: pin 7 - MOSI: pin 11 - MISO: pin 12 - SCK: pin 13 - - created 31 July 2010 - modified 14 August 2010 - by Tom Igoe - */ - -// the sensor communicates using SPI, so include the library: -#include - -//Sensor's memory register addresses: -const int PRESSURE = 0x1F; //3 most significant bits of pressure -const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure -const int TEMPERATURE = 0x21; //16 bit temperature reading -cont byte READ = 0b00000000; // SCP1000's read command -const byte WRITE = 0b00000010; // SCP1000's write command -// pins used for the connection with the sensor -// the other you need are controlled by the SPI library): -const int dataReadyPin = 6; -const int chipSelectPin = 7; - -void setup() { - Serial.begin(9600); - - // start the SPI library: - SPI.begin(); - - // initalize the data ready and chip select pins: - pinMode(dataReadyPin, INPUT); - pinMode(chipSelectPin, OUTPUT); - - //Configure SCP1000 for low noise configuration: - writeRegister(0x02, 0x2D); - writeRegister(0x01, 0x03); - writeRegister(0x03, 0x02); - // give the sensor time to set up: - delay(100); -} - -void loop() { - //Select High Resolution Mode - writeRegister(0x03, 0x0A); - - // don't do anything until the data ready pin is high: - if (digitalRead(dataReadyPin) == HIGH) { - //Read the temperature data - int tempData = readRegister(0x21, 2); - - // convert the temperature to celsius and display it: - float realTemp = (float)tempData / 20.0; - Serial.print("Temp[C]="); - Serial.print(realTemp); - - - //Read the pressure data highest 3 bits: - byte pressure_data_high = readRegister(0x1F, 1); - pressure_data_high &= 0b00000111; //you only needs bits 2 to 0 - - //Read the pressure data lower 16 bits: - unsigned int pressure_data_low = readRegister(0x20, 2); - //combine the two parts into one 19-bit number: - long pressure = ((pressure_data_high << 16) | pressure_data_low)/4; - - // display the temperature: - Serial.println("\tPressure [Pa]=" + String(pressure)); - } -} - -//Read from or write to register from the SCP1000: -unsigned int readRegister(byte thisRegister, int bytesToRead ) { - byte inByte = 0; // incoming byte from the SPI - unsigned int result = 0; // result to return - - // SCP1000 expects the register name in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the address and the command into one byte - dataToSend = thisRegister & READ; - - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - // send the device the register you want to read: - SPI.transfer(dataToSend); - // send a value of 0 to read the first byte returned: - result = SPI.transfer(0x00); - // decrement the number of bytes left to read: - bytesToRead--; - // if you still have another byte to read: - if (bytesToRead > 0) { - // shift the first byte left, then get the second byte: - result = result << 8; - inByte = SPI.transfer(0x00); - // combine the byte you just got with the previous one: - result = result | inByte; - // decrement the number of bytes left to read: - bytesToRead--; - } - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); - // return the result: - return(result); -} - - -//Sends a write command to SCP1000 - -void writeRegister(byte thisRegister, byte thisValue) { - - // SCP1000 expects the register address in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the register address and the command into one byte: - dataToSend = thisRegister | WRITE; - - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - - SPI.transfer(dataToSend); //Send register location - SPI.transfer(thisValue); //Send value to record into register - - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); -} - - - diff --git a/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino b/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino deleted file mode 100644 index adf93a2..0000000 --- a/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino +++ /dev/null @@ -1,71 +0,0 @@ -/* - Digital Pot Control - - This example controls an Analog Devices AD5206 digital potentiometer. - The AD5206 has 6 potentiometer channels. Each channel's pins are labeled - A - connect this to voltage - W - this is the pot's wiper, which changes when you set it - B - connect this to ground. - - The AD5206 is SPI-compatible,and to command it, you send two bytes, - one with the channel number (0 - 5) and one with the resistance value for the - channel (0 - 255). - - The circuit: - * All A pins of AD5206 connected to +5V - * All B pins of AD5206 connected to ground - * An LED and a 220-ohm resisor in series connected from each W pin to ground - * CS - to digital pin 10 (SS pin) - * SDI - to digital pin 11 (MOSI pin) - * CLK - to digital pin 13 (SCK pin) - - created 10 Aug 2010 - by Tom Igoe - - Thanks to Heather Dewey-Hagborg for the original tutorial, 2005 - -*/ - - -// inslude the SPI library: -#include - - -// set pin 10 as the slave select for the digital pot: -const int slaveSelectPin = 10; - -void setup() { - // set the slaveSelectPin as an output: - pinMode (slaveSelectPin, OUTPUT); - // initialize SPI: - SPI.begin(); -} - -void loop() { - // go through the six channels of the digital pot: - for (int channel = 0; channel < 6; channel++) { - // change the resistance on this channel from min to max: - for (int level = 0; level < 255; level++) { - digitalPotWrite(channel, level); - delay(10); - } - // wait a second at the top: - delay(100); - // change the resistance on this channel from max to min: - for (int level = 0; level < 255; level++) { - digitalPotWrite(channel, 255 - level); - delay(10); - } - } - -} - -void digitalPotWrite(int address, int value) { - // take the SS pin low to select the chip: - digitalWrite(slaveSelectPin,LOW); - // send in the address and value via SPI: - SPI.transfer(address); - SPI.transfer(value); - // take the SS pin high to de-select the chip: - digitalWrite(slaveSelectPin,HIGH); -} diff --git a/libraries/SPI/keywords.txt b/libraries/SPI/keywords.txt deleted file mode 100644 index fa76165..0000000 --- a/libraries/SPI/keywords.txt +++ /dev/null @@ -1,36 +0,0 @@ -####################################### -# Syntax Coloring Map SPI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -SPI KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -begin KEYWORD2 -end KEYWORD2 -transfer KEYWORD2 -setBitOrder KEYWORD2 -setDataMode KEYWORD2 -setClockDivider KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### -SPI_CLOCK_DIV4 LITERAL1 -SPI_CLOCK_DIV16 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_CLOCK_DIV128 LITERAL1 -SPI_CLOCK_DIV2 LITERAL1 -SPI_CLOCK_DIV8 LITERAL1 -SPI_CLOCK_DIV32 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_MODE0 LITERAL1 -SPI_MODE1 LITERAL1 -SPI_MODE2 LITERAL1 -SPI_MODE3 LITERAL1 \ No newline at end of file -- cgit v1.2.3-18-g5258 From 21ca174dbe051346c94c857c39dff08c96fb5939 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Wed, 3 Jul 2013 22:55:18 +0200 Subject: GSM library to the new format and some strings adaptations --- libraries/GSM/GSM.h | 68 --- libraries/GSM/GSM3CircularBuffer.cpp | 319 ----------- libraries/GSM/GSM3CircularBuffer.h | 205 -------- libraries/GSM/GSM3MobileAccessProvider.cpp | 3 - libraries/GSM/GSM3MobileAccessProvider.h | 68 --- libraries/GSM/GSM3MobileCellManagement.cpp | 1 - libraries/GSM/GSM3MobileCellManagement.h | 53 -- libraries/GSM/GSM3MobileClientProvider.cpp | 3 - libraries/GSM/GSM3MobileClientProvider.h | 156 ------ libraries/GSM/GSM3MobileClientService.cpp | 260 --------- libraries/GSM/GSM3MobileClientService.h | 162 ------ libraries/GSM/GSM3MobileDataNetworkProvider.cpp | 3 - libraries/GSM/GSM3MobileDataNetworkProvider.h | 62 --- libraries/GSM/GSM3MobileMockupProvider.cpp | 191 ------- libraries/GSM/GSM3MobileMockupProvider.h | 255 --------- libraries/GSM/GSM3MobileNetworkProvider.cpp | 72 --- libraries/GSM/GSM3MobileNetworkProvider.h | 136 ----- libraries/GSM/GSM3MobileNetworkRegistry.cpp | 51 -- libraries/GSM/GSM3MobileNetworkRegistry.h | 63 --- libraries/GSM/GSM3MobileSMSProvider.cpp | 3 - libraries/GSM/GSM3MobileSMSProvider.h | 91 ---- libraries/GSM/GSM3MobileServerProvider.cpp | 5 - libraries/GSM/GSM3MobileServerProvider.h | 95 ---- libraries/GSM/GSM3MobileServerService.cpp | 159 ------ libraries/GSM/GSM3MobileServerService.h | 124 ----- libraries/GSM/GSM3MobileVoiceProvider.cpp | 4 - libraries/GSM/GSM3MobileVoiceProvider.h | 90 ---- libraries/GSM/GSM3SMSService.cpp | 126 ----- libraries/GSM/GSM3SMSService.h | 110 ---- libraries/GSM/GSM3ShieldV1.cpp | 96 ---- libraries/GSM/GSM3ShieldV1.h | 137 ----- libraries/GSM/GSM3ShieldV1AccessProvider.cpp | 296 ----------- libraries/GSM/GSM3ShieldV1AccessProvider.h | 116 ---- libraries/GSM/GSM3ShieldV1BandManagement.cpp | 67 --- libraries/GSM/GSM3ShieldV1BandManagement.h | 96 ---- libraries/GSM/GSM3ShieldV1BaseProvider.cpp | 27 - libraries/GSM/GSM3ShieldV1BaseProvider.h | 73 --- libraries/GSM/GSM3ShieldV1CellManagement.cpp | 168 ------ libraries/GSM/GSM3ShieldV1CellManagement.h | 92 ---- libraries/GSM/GSM3ShieldV1ClientProvider.cpp | 294 ----------- libraries/GSM/GSM3ShieldV1ClientProvider.h | 181 ------- libraries/GSM/GSM3ShieldV1DataNetworkProvider.cpp | 363 ------------- libraries/GSM/GSM3ShieldV1DataNetworkProvider.h | 140 ----- libraries/GSM/GSM3ShieldV1DirectModemProvider.cpp | 143 ----- libraries/GSM/GSM3ShieldV1DirectModemProvider.h | 118 ----- libraries/GSM/GSM3ShieldV1ModemCore.cpp | 198 ------- libraries/GSM/GSM3ShieldV1ModemCore.h | 260 --------- libraries/GSM/GSM3ShieldV1ModemVerification.cpp | 79 --- libraries/GSM/GSM3ShieldV1ModemVerification.h | 64 --- libraries/GSM/GSM3ShieldV1MultiClientProvider.cpp | 583 --------------------- libraries/GSM/GSM3ShieldV1MultiClientProvider.h | 202 ------- libraries/GSM/GSM3ShieldV1MultiServerProvider.cpp | 357 ------------- libraries/GSM/GSM3ShieldV1MultiServerProvider.h | 136 ----- libraries/GSM/GSM3ShieldV1PinManagement.cpp | 201 ------- libraries/GSM/GSM3ShieldV1PinManagement.h | 103 ---- libraries/GSM/GSM3ShieldV1SMSProvider.cpp | 293 ----------- libraries/GSM/GSM3ShieldV1SMSProvider.h | 130 ----- libraries/GSM/GSM3ShieldV1ScanNetworks.cpp | 126 ----- libraries/GSM/GSM3ShieldV1ScanNetworks.h | 75 --- libraries/GSM/GSM3ShieldV1ServerProvider.cpp | 205 -------- libraries/GSM/GSM3ShieldV1ServerProvider.h | 126 ----- libraries/GSM/GSM3ShieldV1VoiceProvider.cpp | 215 -------- libraries/GSM/GSM3ShieldV1VoiceProvider.h | 137 ----- libraries/GSM/GSM3SoftSerial.cpp | 537 ------------------- libraries/GSM/GSM3SoftSerial.h | 174 ------ libraries/GSM/GSM3VoiceCallService.cpp | 144 ----- libraries/GSM/GSM3VoiceCallService.h | 102 ---- libraries/GSM/License.txt | 166 ------ .../examples/GSMPachubeClient/GSMPachubeClient.ino | 186 ------- .../GSMPachubeClientString.ino | 167 ------ .../examples/GsmTwitterClient/GsmTwitterClient.ino | 162 ------ .../GSM/examples/GsmWebClient/GsmWebClient.ino | 109 ---- .../GSM/examples/GsmWebServer/GsmWebServer.ino | 118 ----- .../GSM/examples/MakeVoiceCall/MakeVoiceCall.ino | 116 ---- libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino | 98 ---- .../examples/ReceiveVoiceCall/ReceiveVoiceCall.ino | 105 ---- libraries/GSM/examples/SendSMS/SendSMS.ino | 110 ---- .../Tools/BandManagement/BandManagement.ino | 120 ----- .../Tools/GsmScanNetworks/GsmScanNetworks.ino | 95 ---- .../examples/Tools/PinManagement/PinManagement.ino | 168 ------ libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino | 204 ------- .../GSM/examples/Tools/TestModem/TestModem.ino | 77 --- .../examples/Tools/TestWebServer/TestWebServer.ino | 85 --- libraries/GSM/keywords.txt | 72 --- 84 files changed, 11950 deletions(-) delete mode 100644 libraries/GSM/GSM.h delete mode 100644 libraries/GSM/GSM3CircularBuffer.cpp delete mode 100644 libraries/GSM/GSM3CircularBuffer.h delete mode 100644 libraries/GSM/GSM3MobileAccessProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileAccessProvider.h delete mode 100644 libraries/GSM/GSM3MobileCellManagement.cpp delete mode 100644 libraries/GSM/GSM3MobileCellManagement.h delete mode 100644 libraries/GSM/GSM3MobileClientProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileClientProvider.h delete mode 100644 libraries/GSM/GSM3MobileClientService.cpp delete mode 100644 libraries/GSM/GSM3MobileClientService.h delete mode 100644 libraries/GSM/GSM3MobileDataNetworkProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileDataNetworkProvider.h delete mode 100644 libraries/GSM/GSM3MobileMockupProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileMockupProvider.h delete mode 100644 libraries/GSM/GSM3MobileNetworkProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileNetworkProvider.h delete mode 100644 libraries/GSM/GSM3MobileNetworkRegistry.cpp delete mode 100644 libraries/GSM/GSM3MobileNetworkRegistry.h delete mode 100644 libraries/GSM/GSM3MobileSMSProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileSMSProvider.h delete mode 100644 libraries/GSM/GSM3MobileServerProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileServerProvider.h delete mode 100644 libraries/GSM/GSM3MobileServerService.cpp delete mode 100644 libraries/GSM/GSM3MobileServerService.h delete mode 100644 libraries/GSM/GSM3MobileVoiceProvider.cpp delete mode 100644 libraries/GSM/GSM3MobileVoiceProvider.h delete mode 100644 libraries/GSM/GSM3SMSService.cpp delete mode 100644 libraries/GSM/GSM3SMSService.h delete mode 100644 libraries/GSM/GSM3ShieldV1.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1.h delete mode 100644 libraries/GSM/GSM3ShieldV1AccessProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1AccessProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1BandManagement.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1BandManagement.h delete mode 100644 libraries/GSM/GSM3ShieldV1BaseProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1BaseProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1CellManagement.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1CellManagement.h delete mode 100644 libraries/GSM/GSM3ShieldV1ClientProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1ClientProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1DataNetworkProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1DataNetworkProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1DirectModemProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1DirectModemProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1ModemCore.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1ModemCore.h delete mode 100644 libraries/GSM/GSM3ShieldV1ModemVerification.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1ModemVerification.h delete mode 100644 libraries/GSM/GSM3ShieldV1MultiClientProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1MultiClientProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1MultiServerProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1MultiServerProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1PinManagement.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1PinManagement.h delete mode 100644 libraries/GSM/GSM3ShieldV1SMSProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1SMSProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1ScanNetworks.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1ScanNetworks.h delete mode 100644 libraries/GSM/GSM3ShieldV1ServerProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1ServerProvider.h delete mode 100644 libraries/GSM/GSM3ShieldV1VoiceProvider.cpp delete mode 100644 libraries/GSM/GSM3ShieldV1VoiceProvider.h delete mode 100644 libraries/GSM/GSM3SoftSerial.cpp delete mode 100644 libraries/GSM/GSM3SoftSerial.h delete mode 100644 libraries/GSM/GSM3VoiceCallService.cpp delete mode 100644 libraries/GSM/GSM3VoiceCallService.h delete mode 100644 libraries/GSM/License.txt delete mode 100644 libraries/GSM/examples/GSMPachubeClient/GSMPachubeClient.ino delete mode 100644 libraries/GSM/examples/GSMPachubeClientString/GSMPachubeClientString.ino delete mode 100644 libraries/GSM/examples/GsmTwitterClient/GsmTwitterClient.ino delete mode 100644 libraries/GSM/examples/GsmWebClient/GsmWebClient.ino delete mode 100644 libraries/GSM/examples/GsmWebServer/GsmWebServer.ino delete mode 100644 libraries/GSM/examples/MakeVoiceCall/MakeVoiceCall.ino delete mode 100644 libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino delete mode 100644 libraries/GSM/examples/ReceiveVoiceCall/ReceiveVoiceCall.ino delete mode 100644 libraries/GSM/examples/SendSMS/SendSMS.ino delete mode 100644 libraries/GSM/examples/Tools/BandManagement/BandManagement.ino delete mode 100644 libraries/GSM/examples/Tools/GsmScanNetworks/GsmScanNetworks.ino delete mode 100644 libraries/GSM/examples/Tools/PinManagement/PinManagement.ino delete mode 100644 libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino delete mode 100644 libraries/GSM/examples/Tools/TestModem/TestModem.ino delete mode 100644 libraries/GSM/examples/Tools/TestWebServer/TestWebServer.ino delete mode 100644 libraries/GSM/keywords.txt diff --git a/libraries/GSM/GSM.h b/libraries/GSM/GSM.h deleted file mode 100644 index ec2bf6a..0000000 --- a/libraries/GSM/GSM.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3SIMPLIFIERFILE_ -#define _GSM3SIMPLIFIERFILE_ - -// This file simplifies the use of the GSM3 library -// First we include everything. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define GSM GSM3ShieldV1AccessProvider -#define GPRS GSM3ShieldV1DataNetworkProvider -#define GSMClient GSM3MobileClientService -#define GSMServer GSM3MobileServerService -#define GSMVoiceCall GSM3VoiceCallService -#define GSM_SMS GSM3SMSService - -#define GSMPIN GSM3ShieldV1PinManagement -#define GSMModem GSM3ShieldV1ModemVerification -#define GSMCell GSM3CellManagement -#define GSMBand GSM3ShieldV1BandManagement -#define GSMScanner GSM3ShieldV1ScanNetworks - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3CircularBuffer.cpp b/libraries/GSM/GSM3CircularBuffer.cpp deleted file mode 100644 index e64c571..0000000 --- a/libraries/GSM/GSM3CircularBuffer.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include "GSM3CircularBuffer.h" -#include - -GSM3CircularBuffer::GSM3CircularBuffer(GSM3CircularBufferManager* mgr) -{ - head=0; - tail=0; - cbm=mgr; -} - -int GSM3CircularBuffer::write(char c) -{ - byte aux=(tail+1)& __BUFFERMASK__; - if(aux!=head) - { - theBuffer[tail]=c; - // Lets put an extra zero at the end, so we can - // read chains as we like. - // This is not exactly perfect, we are always 1+ behind the head - theBuffer[aux]=0; - tail=aux; - return 1; - } - return 0; -} - -char GSM3CircularBuffer::read() -{ - char res; - if(head!=tail) - { - res=theBuffer[head]; - head=(head+1)& __BUFFERMASK__; - //if(cbm) - // cbm->spaceAvailable(); - return res; - } - else - { - return 0; - } -} - -char GSM3CircularBuffer::peek(int increment) -{ - char res; - byte num_aux; - - if (tail>head) num_aux = tail-head; - else num_aux = 128 - head + tail; - - if(increment < num_aux) - { - res=theBuffer[head]; - return res; - } - else - { - return 0; - } -} - -void GSM3CircularBufferManager::spaceAvailable(){return;}; - -void GSM3CircularBuffer::flush() -{ - head=tail; -} - -char* GSM3CircularBuffer::nextString() -{ - while(head!=tail) - { - head=(head+1) & __BUFFERMASK__; - if(theBuffer[head]==0) - { - head=(head+1) & __BUFFERMASK__; - return (char*)theBuffer+head; - } - } - return 0; -} - - -bool GSM3CircularBuffer::locate(const char* reference) -{ - - return locate(reference, head, tail, 0, 0); -} - -bool GSM3CircularBuffer::chopUntil(const char* reference, bool movetotheend, bool usehead) -{ - byte from, to; - - if(locate(reference, head, tail, &from, &to)) - { - if(usehead) - { - if(movetotheend) - head=(to+1) & __BUFFERMASK__; - else - head=from; - } - else - { - if(movetotheend) - tail=(to+1) & __BUFFERMASK__; - else - tail=from; - } - return true; - } - else - { - return false; - } -} - -bool GSM3CircularBuffer::locate(const char* reference, byte thishead, byte thistail, byte* from, byte* to) -{ - int refcursor=0; - bool into=false; - byte b2, binit; - bool possible=1; - - if(reference[0]==0) - return true; - - for(byte b1=thishead; b1!=thistail;b1=(b1+1)& __BUFFERMASK__) - { - possible = 1; - b2 = b1; - while (possible&&(b2!=thistail)) - { - if(theBuffer[b2]==reference[refcursor]) - { - if(!into) - binit=b2; - into=true; - refcursor++; - if(reference[refcursor]==0) - { - if(from) - *from=binit; - if(to) - *to=b2; - return true; - } - } - else if (into==true) - { - possible = 0; - into=false; - refcursor=0; - } - b2=(b2+1)& __BUFFERMASK__; - } - } - return false; -} - -bool GSM3CircularBuffer::extractSubstring(const char* from, const char* to, char* buffer, int bufsize) -{ - byte t1; - byte h2; - byte b; - int i; - -//DEBUG -//Serial.println("Beginning extractSubstring"); -//Serial.print("head,tail=");Serial.print(int(head));Serial.print(",");Serial.println(int(tail)); - - if(!locate(from, head, tail, 0, &t1)) - return false; - -//DEBUG -//Serial.println("Located chain from."); - - t1++; //To point the next. - if(!locate(to, t1, tail, &h2, 0)) - return false; - -//DEBUG -//Serial.println("Located chain to."); -/*Serial.print("t1=");Serial.println(int(t1)); -Serial.print("h2=");Serial.println(int(h2));*/ - - - for(i=0,b=t1;i='0')&&(c<='9')) - { - anyfound=true; - res=(res*10)+(int)c-48; - } - else - { - if(negative) - res=(-1)*res; - return res; - } - } - if(negative) - res=(-1)*res; - return res; -} - -void GSM3CircularBuffer::debugBuffer() -{ - byte h1=head; - byte t1=tail; - Serial.println(); - Serial.print(h1); - Serial.print(" "); - Serial.print(t1); - Serial.print('>'); - for(byte b=h1; b!=t1; b=(b+1)& __BUFFERMASK__) - printCharDebug(theBuffer[b]); - Serial.println(); -} - -void GSM3CircularBuffer::printCharDebug(uint8_t c) -{ - if((c>31)&&(c<127)) - Serial.print((char)c); - else - { - Serial.print('%'); - Serial.print(c); - Serial.print('%'); - } -} - -bool GSM3CircularBuffer::retrieveBuffer(char* buffer, int bufsize, int& SizeWritten) -{ - byte b; - int i; - - /*for(i=0,b=head;i -#include - -#ifndef byte -#define byte uint8_t -#endif - -// These values have to be interrelated -// To-Do: may we have just one? (BUFFERMASK) -#define __BUFFERSIZE__ 128 -#define __BUFFERMASK__ 0x7F - -class GSM3CircularBufferManager -{ - public: - - /** If there is spaceAvailable in the buffer, lets send a XON - */ - virtual void spaceAvailable(); -}; - -class GSM3CircularBuffer -{ - private: - // Buffer pointers. - // head=tail means buffer empty - // tail=head-1 means buffer full - // tail=head+1 means just one char (pointed by head) - // REMEMBER. head can be moved only by the main program - // REMEMBER. tail can be moved only by the other thread (interrupts) - // REMEMBER. head and tail can move only FORWARD - volatile byte head; // First written one - volatile byte tail; // Last written one. - - GSM3CircularBufferManager* cbm; // Circular buffer manager - - // The buffer - volatile byte theBuffer[__BUFFERSIZE__]; - - /** Checks if a substring exists in the buffer - @param reference Substring - @param thishead Head - @param thistail Tail - @param from Initial byte position - @param to Final byte position - @return true if exists, in otherwise return false - */ - bool locate(const char* reference, byte thishead, byte thistail, byte* from=0, byte* to=0); - - public: - - /** Constructor - @param mgr Circular buffer manager - */ - GSM3CircularBuffer(GSM3CircularBufferManager* mgr=0); - - // TO-DO.Check if this formule runs too at the buffer limit - - /** Get available bytes in circular buffer - @return available bytes - */ - inline byte availableBytes(){ return ((head-(tail+1))&__BUFFERMASK__);}; - - /** Stored bytes in circular buffer - @return stored bytes - */ - inline byte storedBytes(){ return ((tail-head)&__BUFFERMASK__);}; - - /** Write a character in circular buffer - @param c Character - @return 1 if successful - */ - int write(char c); - - /** Returns a character and moves the pointer - @return character - */ - char read(); - - /** Returns a character but does not move the pointer. - @param increment Increment - @return character - */ - char peek(int increment); - - /** Returns a pointer to the head of the buffer - @return buffer with pointer in head - */ - inline char* firstString(){return (char*)theBuffer+head;}; - - /** Go forward one string - @return buffer with one string advance - */ - char* nextString(); - - /** Flush circular buffer - */ - void flush(); - - /** Get tail - @return tail - */ - inline byte getTail(){return tail;}; - - /** Get head - @return head - */ - inline byte getHead(){return head;}; - - // Only can be executed from the interrupt! - /** Delete circular buffer to the end - @param from Initial byte position - */ - inline void deleteToTheEnd(byte from){tail=from;}; - - /** Checks if a substring exists in the buffer - move=0, dont move, =1,put head at the beginning of the string, =2, put head at the end - @param reference - @return true if exists, in otherwise return false - */ - bool locate(const char* reference); - - /** Locates reference. If found, moves head (or tail) to the beginning (or end) - @param reference - @param movetotheend - @param head - @return true if successful - */ - bool chopUntil(const char* reference, bool movetotheend, bool head=true); - - /** Reads an integer from the head. Stops with first non blank, non number character - @return integer from the head - */ - int readInt(); - - // Caveat: copies the first bytes until buffer is full - - /** Extract a substring from circular buffer - @param from Initial byte position - @param to Final byte position - @param buffer Buffer for copy substring - @param bufsize Buffer size - @return true if successful, false if substring does not exists - */ - bool extractSubstring(const char* from, const char* to, char* buffer, int bufsize); - - /** Retrieve all the contents of buffer from head to tail - @param buffer - @param bufsize - @param SizeWritten - @return true if successful - */ - bool retrieveBuffer(char* buffer, int bufsize, int& SizeWritten); - - /** Debug function to print the buffer after receiving data from the modem. - */ - void debugBuffer(); - - /** Utility: dump character if printable, else, put in %x% - @param c Character - */ - static void printCharDebug(uint8_t c); - - -}; - - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileAccessProvider.cpp b/libraries/GSM/GSM3MobileAccessProvider.cpp deleted file mode 100644 index 02d1080..0000000 --- a/libraries/GSM/GSM3MobileAccessProvider.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include - -GSM3MobileAccessProvider* theGSM3MobileAccessProvider; \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileAccessProvider.h b/libraries/GSM/GSM3MobileAccessProvider.h deleted file mode 100644 index 21ecd1b..0000000 --- a/libraries/GSM/GSM3MobileAccessProvider.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILEACCESSPROVIDER_ -#define _GSM3MOBILEACCESSPROVIDER_ - -enum GSM3_NetworkStatus_t { ERROR, IDLE, CONNECTING, GSM_READY, GPRS_READY, TRANSPARENT_CONNECTED}; - -class GSM3MobileAccessProvider -{ - public: - // Access functions - //Configuration functions. - /** Establish GSM connection - @param pin PIN code - @param restart Determines if hardware restart - @param synchronous Determines sync mode - @return If synchronous, GSM3_NetworkStatus_t. If asynchronous, returns 0. - */ - virtual inline GSM3_NetworkStatus_t begin(char* pin=0,bool restart=true, bool synchronous=true)=0; - - /** Check network access status - @return 1 if Alive, 0 if down - */ - virtual inline int isAccessAlive()=0; - - /** Shutdown the modem (power off really) - @return true if successful - */ - virtual inline bool shutdown()=0; - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - virtual int ready()=0; -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileCellManagement.cpp b/libraries/GSM/GSM3MobileCellManagement.cpp deleted file mode 100644 index 1db20b9..0000000 --- a/libraries/GSM/GSM3MobileCellManagement.cpp +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileCellManagement.h b/libraries/GSM/GSM3MobileCellManagement.h deleted file mode 100644 index 035dfee..0000000 --- a/libraries/GSM/GSM3MobileCellManagement.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILECELLMANAGEMENT_ -#define _GSM3MOBILECELLMANAGEMENT_ - -#include - -class GSM3MobileCellManagement -{ - public: - - virtual inline int getLocation() {return 0;}; - - virtual inline int getICCID() {return 0;}; - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - virtual int ready()=0; -}; - -#endif diff --git a/libraries/GSM/GSM3MobileClientProvider.cpp b/libraries/GSM/GSM3MobileClientProvider.cpp deleted file mode 100644 index 3636a75..0000000 --- a/libraries/GSM/GSM3MobileClientProvider.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include - -GSM3MobileClientProvider* theGSM3MobileClientProvider; \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileClientProvider.h b/libraries/GSM/GSM3MobileClientProvider.h deleted file mode 100644 index a771ff4..0000000 --- a/libraries/GSM/GSM3MobileClientProvider.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_MOBILECLIENTPROVIDER__ -#define __GSM3_MOBILECLIENTPROVIDER__ - -#include -#include - -class GSM3MobileClientProvider -{ - protected: - - uint8_t sockets; - - public: - - /** Constructor */ - GSM3MobileClientProvider(){}; - - /** Minimum socket - @return socket - */ - virtual inline int minSocket()=0; - - /** Maximum socket - @return socket - */ - virtual inline int maxSocket()=0; - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - virtual int ready()=0; - - /** Get status socket client - @param socket Socket - @return 1 if connected - */ - virtual bool getStatusSocketClient(uint8_t socket)=0; - - // Socket management - - /** Get socket - @param socket Socket - @return socket - */ - virtual int getSocket(int socket=-1)=0; - - /** Release socket - @param socket Socket - */ - virtual void releaseSocket(int socket)=0; - - // Client socket functions - - /** Connect to a server via TCP connection - @param server Server name or IP address in a String - @param port Port - @param id_socket Socket - @return 0 if command running, 1 if success, otherwise error - */ - virtual int connectTCPClient(const char* server, int port, int id_socket)=0; - - /** Connect to a server (by IP address) via TCP connection - @param add IP address in IPAddress format - @param port Port - @param id_socket Socket - @return 0 if command running, 1 if success, otherwise error - */ - virtual int connectTCPClient(IPAddress add, int port, int id_socket)=0; - - /** Begin writing through a socket - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - virtual void beginWriteSocket(bool client1Server0, int id_socket)=0; - - /** Write through a socket. MUST go after beginWriteSocket() - @param c character to be written - */ - virtual void writeSocket(uint8_t c)=0; - - /** Write through a socket. MUST go after beginWriteSocket() - @param buf characters to be written (final 0 will not be written) - */ - virtual void writeSocket(const char* buf)=0; - - /** Finish current writing - */ - virtual void endWriteSocket()=0; - - /** Check if there are data to be read in socket. - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if there are data available, 4 if no data, otherwise error - */ - virtual int availableSocket(bool client, int id_socket)=0; - - /** Read data (get a character) available in socket - @return character - */ - virtual int readSocket()=0; - - /** Flush socket - */ - virtual void flushSocket()=0; - - /** Get a character but will not advance the buffer head - @return character - */ - virtual int peekSocket()=0; - - /** Close a socket - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Socket - @return 0 if command running, 1 if success, otherwise error - */ - virtual int disconnectTCP(bool client1Server0, int idsocket)=0; - -}; - -extern GSM3MobileClientProvider* theGSM3MobileClientProvider; - -#endif diff --git a/libraries/GSM/GSM3MobileClientService.cpp b/libraries/GSM/GSM3MobileClientService.cpp deleted file mode 100644 index a913f54..0000000 --- a/libraries/GSM/GSM3MobileClientService.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include -#include - -// While there is only a shield (ShieldV1) we will include it by default -#include -GSM3ShieldV1ClientProvider theShieldV1ClientProvider; - - -#define GSM3MOBILECLIENTSERVICE_CLIENT 0x01 // 1: This side is Client. 0: This side is Server -#define GSM3MOBILECLIENTSERVICE_WRITING 0x02 // 1: TRUE 0: FALSE -#define GSM3MOBILECLIENTSERVICE_SYNCH 0x04 // 1: TRUE, compatible with other clients 0: FALSE - -#define __TOUTBEGINWRITE__ 10000 - - -GSM3MobileClientService::GSM3MobileClientService(bool synch) -{ - flags = GSM3MOBILECLIENTSERVICE_CLIENT; - if(synch) - flags |= GSM3MOBILECLIENTSERVICE_SYNCH; - mySocket=255; -} - -GSM3MobileClientService::GSM3MobileClientService(int socket, bool synch) -{ - // We are creating a socket on an existing, occupied one. - flags=0; - if(synch) - flags |= GSM3MOBILECLIENTSERVICE_SYNCH; - mySocket=socket; - theGSM3MobileClientProvider->getSocket(socket); - -} - -// Returns 0 if last command is still executing -// 1 if success -// >1 if error -int GSM3MobileClientService::ready() -{ - return theGSM3MobileClientProvider->ready(); -} - -int GSM3MobileClientService::connect(IPAddress add, uint16_t port) -{ - if(theGSM3MobileClientProvider==0) - return 2; - - // TODO: ask for the socket id - mySocket=theGSM3MobileClientProvider->getSocket(); - - if(mySocket<0) - return 2; - - int res=theGSM3MobileClientProvider->connectTCPClient(add, port, mySocket); - if(flags & GSM3MOBILECLIENTSERVICE_SYNCH) - res=waitForAnswer(); - - return res; -}; - -int GSM3MobileClientService::connect(const char *host, uint16_t port) -{ - - if(theGSM3MobileClientProvider==0) - return 2; - // TODO: ask for the socket id - mySocket=theGSM3MobileClientProvider->getSocket(); - - if(mySocket<0) - return 2; - - int res=theGSM3MobileClientProvider->connectTCPClient(host, port, mySocket); - if(flags & GSM3MOBILECLIENTSERVICE_SYNCH) - res=waitForAnswer(); - - return res; -} - -int GSM3MobileClientService::waitForAnswer() -{ - unsigned long m; - m=millis(); - int res; - - while(((millis()-m)< __TOUTBEGINWRITE__ )&&(ready()==0)) - delay(100); - - res=ready(); - - // If we get something different from a 1, we are having a problem - if(res!=1) - res=0; - - return res; -} - -void GSM3MobileClientService::beginWrite(bool sync) -{ - flags |= GSM3MOBILECLIENTSERVICE_WRITING; - theGSM3MobileClientProvider->beginWriteSocket(flags & GSM3MOBILECLIENTSERVICE_CLIENT, mySocket); - if(sync) - waitForAnswer(); -} - -size_t GSM3MobileClientService::write(uint8_t c) -{ - if(!(flags & GSM3MOBILECLIENTSERVICE_WRITING)) - beginWrite(true); - theGSM3MobileClientProvider->writeSocket(c); - return 1; -} - -size_t GSM3MobileClientService::write(const uint8_t* buf) -{ - if(!(flags & GSM3MOBILECLIENTSERVICE_WRITING)) - beginWrite(true); - theGSM3MobileClientProvider->writeSocket((const char*)(buf)); - return strlen((const char*)buf); -} - -size_t GSM3MobileClientService::write(const uint8_t* buf, size_t sz) -{ - if(!(flags & GSM3MOBILECLIENTSERVICE_WRITING)) - beginWrite(true); - for(int i=0;iwriteSocket(buf[i]); - return sz; -} - -void GSM3MobileClientService::endWrite(bool sync) -{ - flags ^= GSM3MOBILECLIENTSERVICE_WRITING; - theGSM3MobileClientProvider->endWriteSocket(); - if(sync) - waitForAnswer(); -} - -uint8_t GSM3MobileClientService::connected() -{ - if(mySocket==255) - return 0; - return theGSM3MobileClientProvider->getStatusSocketClient(mySocket); -} - -GSM3MobileClientService::operator bool() -{ - return connected()==1; -}; - -int GSM3MobileClientService::available() -{ - int res; - - // Even if not connected, we are looking for available data - - if(flags & GSM3MOBILECLIENTSERVICE_WRITING) - endWrite(true); - - res=theGSM3MobileClientProvider->availableSocket(flags & GSM3MOBILECLIENTSERVICE_CLIENT,mySocket); - if(flags & GSM3MOBILECLIENTSERVICE_SYNCH) - res=waitForAnswer(); - - return res; -} - -int GSM3MobileClientService::read(uint8_t *buf, size_t size) -{ - int i; - uint8_t c; - - for(i=0;ireadSocket(flags & GSM3MOBILECLIENTSERVICE_CLIENT, (char *)(buf), size, mySocket); - - return res; -*/ -} - -int GSM3MobileClientService::read() -{ - if(flags & GSM3MOBILECLIENTSERVICE_WRITING) - endWrite(true); - int c=theGSM3MobileClientProvider->readSocket(); - return c; -} - -int GSM3MobileClientService::peek() -{ - if(flags & GSM3MOBILECLIENTSERVICE_WRITING) - endWrite(true); - return theGSM3MobileClientProvider->peekSocket(/*mySocket, false*/); -} - -void GSM3MobileClientService::flush() -{ - if(flags & GSM3MOBILECLIENTSERVICE_WRITING) - endWrite(true); - theGSM3MobileClientProvider->flushSocket(/*mySocket*/); - if(flags & GSM3MOBILECLIENTSERVICE_SYNCH) - waitForAnswer(); - -} - -void GSM3MobileClientService::stop() -{ - if(flags & GSM3MOBILECLIENTSERVICE_WRITING) - endWrite(true); - theGSM3MobileClientProvider->disconnectTCP(flags & GSM3MOBILECLIENTSERVICE_CLIENT, mySocket); - theGSM3MobileClientProvider->releaseSocket(mySocket); - mySocket = 0; - if(flags & GSM3MOBILECLIENTSERVICE_SYNCH) - waitForAnswer(); -} - diff --git a/libraries/GSM/GSM3MobileClientService.h b/libraries/GSM/GSM3MobileClientService.h deleted file mode 100644 index 5a36a97..0000000 --- a/libraries/GSM/GSM3MobileClientService.h +++ /dev/null @@ -1,162 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILECLIENTSERVICE_ -#define _GSM3MOBILECLIENTSERVICE_ - -#include -#include - - -class GSM3MobileClientService : public Client -{ - private: - - uint8_t mySocket; - uint8_t flags; - - /** Blocks waiting for an answer - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int waitForAnswer(); - - public: - - /** Constructor - @param synch Sync mode - */ - GSM3MobileClientService(bool synch=true); - - /** Constructor - @param socket Socket - @param synch Sync mode - */ - GSM3MobileClientService(int socket, bool synch); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(); - - // we take this function out as IPAddress is complex to bring to - // version 1. - /** Connect to server by IP address - @param (IPAddress) - @param (uint16_t) - @return returns 0 if last command is still executing, 1 success, 2 if there are no resources - */ - inline int connect(IPAddress, uint16_t); - - /** Connect to server by hostname - @param host Hostname - @param port Port - @return returns 0 if last command is still executing, 1 success, 2 if there are no resources - */ - int connect(const char *host, uint16_t port); - - /** Initialize write in request - @param sync Sync mode - */ - void beginWrite(bool sync=false); - - /** Write a character in request - @param c Character - @return size - */ - size_t write(uint8_t c); - - /** Write a characters buffer in request - @param buf Buffer - @return buffer size - */ - size_t write(const uint8_t *buf); - - /** Write a characters buffer with size in request - @param (uint8_t*) Buffer - @param (size_t) Buffer size - @return buffer size - */ - size_t write(const uint8_t*, size_t); - - /** Finish write request - @param sync Sync mode - */ - void endWrite(bool sync=false); - - /** Check if connected to server - @return 1 if connected - */ - uint8_t connected(); - - operator bool(); - - /** Read from response buffer and copy size specified to buffer - @param buf Buffer - @param size Buffer size - @return bytes read - */ - int read(uint8_t *buf, size_t size); - - /** Read a character from response buffer - @return character - */ - int read(); - - /** Check if exists a response available - @return 1 if exists, 0 if not exists - */ - int available(); - - /** Read a character from response buffer but does not move the pointer. - @return character - */ - int peek(); - - /** Flush response buffer - */ - void flush(); - - /** Stop client - */ - void stop(); - - /** Get socket - @return socket - */ - inline int getSocket(){return (int)mySocket;}; - - -}; - - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileDataNetworkProvider.cpp b/libraries/GSM/GSM3MobileDataNetworkProvider.cpp deleted file mode 100644 index 538f6d4..0000000 --- a/libraries/GSM/GSM3MobileDataNetworkProvider.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include - -// GSM3MobileDataNetworkProvider* theGSM3MobileDataNetworkProvider; \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileDataNetworkProvider.h b/libraries/GSM/GSM3MobileDataNetworkProvider.h deleted file mode 100644 index bffd381..0000000 --- a/libraries/GSM/GSM3MobileDataNetworkProvider.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILEDATANETWORKPROVIDER_ -#define _GSM3MOBILEDATANETWORKPROVIDER_ - -#include - -// This class is not really useful, but serves as a guideline for programmers -// We keep it but it should never be linked -class GSM3MobileDataNetworkProvider -{ - public: - - /** Attach to GPRS/GSM network - @param networkId APN GPRS - @param user Username - @param pass Password - @return connection status - */ - virtual GSM3_NetworkStatus_t networkAttach(char* networId, char* user, char* pass)=0; - - /** Detach GPRS/GSM network - @return connection status - */ - virtual GSM3_NetworkStatus_t networkDetach()=0; - -}; - -extern GSM3MobileDataNetworkProvider* theGSM3MobileDataNetworkProvider; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileMockupProvider.cpp b/libraries/GSM/GSM3MobileMockupProvider.cpp deleted file mode 100644 index b39ee26..0000000 --- a/libraries/GSM/GSM3MobileMockupProvider.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include -#include -#include - - -GSM3MobileMockupProvider::GSM3MobileMockupProvider() -{ - lineStatus=IDLE; - msgExample="Hello#World"; - msgIndex=0; -}; - -int GSM3MobileMockupProvider::begin(char* pin) -{ - Serial.println("GSM3MobileMockupProvider::begin()"); - return 0; -}; - -int GSM3MobileMockupProvider::ready() -{ - Serial.println("GSM3MobileMockupProvider::ready()"); - return 1; -}; - -int GSM3MobileMockupProvider::beginSMS(const char* number) -{ - Serial.println("SM3MobileMockupProvider::beginSMS()"); - return 0; -}; - -void GSM3MobileMockupProvider::writeSMS(char c) -{ - Serial.print(c); -}; - -int GSM3MobileMockupProvider::endSMS() -{ - Serial.println("GSM3MobileMockupProvider::endSMS()"); -}; - -int GSM3MobileMockupProvider::availableSMS() -{ - Serial.println("GSM3MobileMockupProvider::availableSMS()"); - return 120; -}; - -int GSM3MobileMockupProvider::peek() -{ - return (int)'H'; -}; - -int GSM3MobileMockupProvider::remoteSMSNumber(char* number, int nlength) -{ - if(nlength>=13) - strcpy(number, "+34630538546"); - return 12; -}; - - -void GSM3MobileMockupProvider::flushSMS() -{ - Serial.println("GSM3MobileMockupProvider::flushSMS()"); -}; - -int GSM3MobileMockupProvider::readSMS() -{ - if(msgExample[msgIndex]==0) - { - msgIndex=0; - return 0; - } - else - { - msgIndex++; - return msgExample[msgIndex-1]; - }; -}; - -int GSM3MobileMockupProvider::connectTCPClient(const char* server, int port, int id_socket) -{ - Serial.println("GSM3MobileMockupProvider::connectTCPClient()"); - Serial.print(server);Serial.print(":");Serial.print(port);Serial.print("-");Serial.println(id_socket); -} - -void GSM3MobileMockupProvider::writeSocket(const uint8_t *buf, size_t size, int id_socket) -{ - int i; - for(i=0;i=minSocket())&&(socket<=maxSocket())) - return 1; - else - return 0; -}; -*/ - -int GSM3MobileMockupProvider::readSocket(uint8_t *buf, size_t size, int idsocket) -{ - int i; - int l=strlen(msgExample); - for(i=0;(i12)) - strcpy("192.168.1.1", localIP); - return 1; -}; - -bool GSM3MobileMockupProvider::getSocketModemStatus(uint8_t s) -{ - // Feeling lazy - return true; -} - diff --git a/libraries/GSM/GSM3MobileMockupProvider.h b/libraries/GSM/GSM3MobileMockupProvider.h deleted file mode 100644 index 59eee41..0000000 --- a/libraries/GSM/GSM3MobileMockupProvider.h +++ /dev/null @@ -1,255 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILEMOCKUPPROVIDER_ -#define _GSM3MOBILEMOCKUPPROVIDER_ - -#include -#include - -class GSM3MobileMockupProvider: public GSM3MobileNetworkProvider -{ - private: - // Introducing this status is quite "heavy". But something like this should - // be added to ShieldV1. Or not. - // Note, in ShieldV1 there is no "RECEIVINGSMS" status. - enum GSM3_modemlinest_e { IDLE, WAITINGANSWER, SENDINGSMS}; - GSM3_modemlinest_e lineStatus; - char* msgExample; - int msgIndex; - - public: - - /** Minimum socket - @return 1 - */ - inline int minSocket(){return 1;}; - - /** Maximum socket - @return 8 - */ - inline int maxSocket(){return 8;}; - - /** Constructor */ - GSM3MobileMockupProvider(); - - /** Get network status - @return network status - */ - inline GSM3_NetworkStatus_t getStatus(){return ERROR;}; - - /** Get voice call status - @return call status - */ - inline GSM3_voiceCall_st getvoiceCallStatus(){return IDLE_CALL;}; - - /** Get last command status - @return Returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(); - inline void closeCommand(int code){}; - - //Configuration functions. - - /** Begin connection - @param pin PIN code - @return - */ - int begin(char* pin=0); - - /** Check if is modem alive - @return 0 - */ - inline int isModemAlive(){return 0;}; - - /** Shutdown the modem (power off really) - @return true if successful - */ - inline bool shutdown(){return false;}; - - //Call functions - - /** Launch a voice call - @param number Phone number to be called - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - inline int voiceCall(const char* number){return 0;}; - - /** Answer a voice call - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - inline int answerCall(){return 0;}; - - /** Hang a voice call - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - inline int hangCall(){return 0;}; - - /** Retrieve phone number of caller - @param buffer Buffer for copy phone number - @param bufsize Buffer size - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - inline int retrieveCallingNumber(char* buffer, int*& bufsize){return 0;}; - - // SMS functions - - /** Begin a SMS to send it - @param number Destination - @return error command if it exists - */ - int beginSMS(const char* number); - - /** End SMS - @return error command if it exists - */ - int endSMS(); - - /** Check if SMS available and prepare it to be read - @return error command if it exists - */ - int availableSMS(); - - /** Read a byte but do not advance the buffer header (circular buffer) - @return character - */ - int peek(); - - /** Delete the SMS from Modem memory and proccess answer - */ - void flushSMS(); - - /** Read sender number phone - @param number Buffer for save number phone - @param nlength Buffer length - @return 1 success, >1 error - */ - int remoteSMSNumber(char* number, int nlength); - - /** Read one char for SMS buffer (advance circular buffer) - @return character - */ - int readSMS(); - - /** Write a SMS character by character - @param c Character - */ - void writeSMS(char c); - - // Socket functions - - /** Connect to a remote TCP server - @param server String with IP or server name - @param port Remote port number - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - int connectTCPClient(const char* server, int port, int id_socket); - - // Attention to parameter rewriting in ShieldV1 - /** Write buffer information into a socket - @param buf Buffer - @param size Buffer size - @param idsocket Socket - */ - void writeSocket(const uint8_t *buf, size_t size, int idsocket); - - // ShieldV1 will have two reading mechanisms: - // Mechanism 1: Call AT+QIRD for size bytes. Put them in the circular buffer, - // fill buf. Take care to xon/xoff effect, as we may copy just a part of the - // incoming bytes. - /** Read socket and put information in a buffer - @param buf Buffer - @param size Buffer size - @param idsocket Socket - @return - */ - int readSocket(uint8_t *buf, size_t size, int idsocket); - - // Mechanism 2 in ShieldV1: - // When called "available()" or "read()" reuse readSocket code to execute - // QIRD SYNCHRONOUSLY. Ask the modem for 1500 bytes but do not copy them anywhere, - // leave data in the circular buffer. Put buffer head at the start of received data. - // Peek() will get a character but will not advance the buffer head. - // Read() will get one character. XON/XOFF will take care of buffer filling - // If Read() gets to the end of the QIRD response, execute again QIRD SYNCHRONOUSLY - // If the user executes flush(), execute read() until there is nothing more to read() - // (the modem gives no way to empty the socket of incoming data) - - /** Check if there are data to be read in socket. - @param idsocket Local socket number - @return 0 if command running, 1 if there are data available, 4 if no data, otherwise error - */ - int availableSocket(int idsocket); - - /** Read data (get a character) available in socket - @param idsocket Socket - @param advance Determines if advance the buffer head - @return character - */ - int readSocket(int idsocket, bool advance=true); - - /** Flush socket - @param idsocket Socket - */ - void flushSocket(int idsocket); - - // This is the same in ShieldV1 - /** Close a socket - @param idsocket Socket - @return 0 if command running, 1 if success, otherwise error - */ - int disconnectTCP(int idsocket); - - // TCP Server. Attention. Changing the int*&. We'll receive a buffer for the IP - // If the pointer ins NULL just forget it - // I think that opening a server does not occupy a socket. Is that true? - /** Establish a TCP connection - @param port Port - @param localIP IP address - @param localIPlength IP address size in characters - @return command error if exists - */ - int connectTCPServer(int port, char* localIP, int* localIPlength); - - // Modem sockets status. Return TRUE if the modem thinks the socket is occupied. - // This should be detected through an unrequisited response - /** Get modem status - @param s Socket - @return modem status (true if connected) - */ - bool getSocketModemStatus(uint8_t s); - - -}; -#endif diff --git a/libraries/GSM/GSM3MobileNetworkProvider.cpp b/libraries/GSM/GSM3MobileNetworkProvider.cpp deleted file mode 100644 index a8a91c2..0000000 --- a/libraries/GSM/GSM3MobileNetworkProvider.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include - -GSM3MobileNetworkProvider* theProvider; - -GSM3MobileNetworkProvider::GSM3MobileNetworkProvider() -{ - socketsAsServer=0x0000; -}; - - -int GSM3MobileNetworkProvider::getNewOccupiedSocketAsServer() -{ - int i; - for(i=minSocketAsServer(); i<=maxSocketAsServer(); i++) - { - if ((!(socketsAsServer&(0x0001< -#include -#include -#include - -class GSM3MobileNetworkProvider -{ - private: - - /** Restart hardware - @return 1 if successful - */ - int HWrestart(); - - uint16_t socketsAsServer; // Server socket - - /** Get modem status - @param s Socket - @return modem status (true if connected) - */ - virtual inline bool getSocketAsServerModemStatus(int s){return false;}; - - public: - - /** minSocketAsServer - @return 0 - */ - virtual inline int minSocketAsServer(){return 0;}; - - /** maxSocketAsServer - @return 0 - */ - virtual inline int maxSocketAsServer(){return 0;}; - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - virtual int ready()=0; - - /** Constructor */ - GSM3MobileNetworkProvider(); - - /** Get network status - @return network status - */ - virtual inline GSM3_NetworkStatus_t getStatus(){return ERROR;}; - - /** Get socket client status - @param socket Socket - @return 1 if connected, 0 otherwise - */ - bool getStatusSocketClient(uint8_t socket); - - /** Close a AT command - @param code Close code - */ - virtual inline void closeCommand(int code){}; - - /** Establish a TCP connection - @param port Port - @param localIP IP address - @param localIPlength IP address size in characters - @return command error if exists - */ - virtual inline int connectTCPServer(int port, char* localIP, int localIPlength){return 0;}; - - /** Get local IP address - @param LocalIP Buffer for save IP address - @param LocalIPlength Buffer size - */ - virtual inline int getIP(char* LocalIP, int LocalIPlength){return 0;}; - - /** Get new occupied socket - @return -1 if no new socket has been occupied - */ - int getNewOccupiedSocketAsServer(); - - /** Get socket status as server - @param socket Socket to get status - @return socket status - */ - bool getStatusSocketAsServer(uint8_t socket); - - /** Close a socket - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - int disconnectTCP(bool client1Server0, int idsocket){return 1;}; - - /** Release socket - @param socket Socket - */ - void releaseSocket(int socket){}; - -}; - -extern GSM3MobileNetworkProvider* theProvider; - -#endif diff --git a/libraries/GSM/GSM3MobileNetworkRegistry.cpp b/libraries/GSM/GSM3MobileNetworkRegistry.cpp deleted file mode 100644 index 5e22f3a..0000000 --- a/libraries/GSM/GSM3MobileNetworkRegistry.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include - -GSM3MobileNetworkRegistry::GSM3MobileNetworkRegistry() -{ - theProvider=0; -}; - -void GSM3MobileNetworkRegistry::registerMobileNetworkProvider(GSM3MobileNetworkProvider* provider) -{ - theProvider=provider; -} - -GSM3MobileNetworkProvider* GSM3MobileNetworkRegistry::getMobileNetworkProvider() -{ - return theProvider; -} - -GSM3MobileNetworkRegistry theMobileNetworkRegistry; diff --git a/libraries/GSM/GSM3MobileNetworkRegistry.h b/libraries/GSM/GSM3MobileNetworkRegistry.h deleted file mode 100644 index de43977..0000000 --- a/libraries/GSM/GSM3MobileNetworkRegistry.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILENETWORKREGISTRY_ -#define _GSM3MOBILENETWORKREGISTRY_ -#include - -class GSM3MobileNetworkRegistry -{ - private: - - GSM3MobileNetworkProvider* theProvider; // Network provider - - public: - - /** Constructor */ - GSM3MobileNetworkRegistry(); - - /** Register in mobile network provider - @param provider Provider - */ - void registerMobileNetworkProvider(GSM3MobileNetworkProvider* provider); - - /** Returns network provider object pointer - @return mobile network provider - */ - GSM3MobileNetworkProvider* getMobileNetworkProvider(); - -}; - -extern GSM3MobileNetworkRegistry theMobileNetworkRegistry; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileSMSProvider.cpp b/libraries/GSM/GSM3MobileSMSProvider.cpp deleted file mode 100644 index b536330..0000000 --- a/libraries/GSM/GSM3MobileSMSProvider.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include - -GSM3MobileSMSProvider* theGSM3SMSProvider; diff --git a/libraries/GSM/GSM3MobileSMSProvider.h b/libraries/GSM/GSM3MobileSMSProvider.h deleted file mode 100644 index aa72711..0000000 --- a/libraries/GSM/GSM3MobileSMSProvider.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILESMSPROVIDER_ -#define _GSM3MOBILESMSPROVIDER_ - -class GSM3MobileSMSProvider -{ - public: - - /** Begin a SMS to send it - @param to Destination - @return error command if it exists - */ - virtual inline int beginSMS(const char* to){return 0;}; - - /** Write a SMS character by character - @param c Character - */ - virtual inline void writeSMS(const char c){}; - - /** End SMS - @return error command if it exists - */ - virtual inline int endSMS(){return 0;}; - - /** Check if SMS available and prepare it to be read - @return number of bytes in a received SMS - */ - virtual inline int availableSMS(){return 0;}; - - /** Read a byte but do not advance the buffer header (circular buffer) - @return character - */ - virtual inline int peekSMS(){return 0;}; - - /** Delete the SMS from Modem memory and proccess answer - */ - virtual inline void flushSMS(){return;}; - - /** Read sender number phone - @param number Buffer for save number phone - @param nlength Buffer length - @return 1 success, >1 error - */ - virtual inline int remoteSMSNumber(char* number, int nlength){return 0;}; - - /** Read one char for SMS buffer (advance circular buffer) - @return character - */ - virtual inline int readSMS(){return 0;}; - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - virtual int ready()=0; -}; - -extern GSM3MobileSMSProvider* theGSM3SMSProvider; - -#endif diff --git a/libraries/GSM/GSM3MobileServerProvider.cpp b/libraries/GSM/GSM3MobileServerProvider.cpp deleted file mode 100644 index 4739ac7..0000000 --- a/libraries/GSM/GSM3MobileServerProvider.cpp +++ /dev/null @@ -1,5 +0,0 @@ - #include - - GSM3MobileServerProvider* theGSM3MobileServerProvider; - - \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileServerProvider.h b/libraries/GSM/GSM3MobileServerProvider.h deleted file mode 100644 index e4eb9c5..0000000 --- a/libraries/GSM/GSM3MobileServerProvider.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_MOBILESERVERPROVIDER__ -#define __GSM3_MOBILESERVERPROVIDER__ - - -#include -#include -#include - - -class GSM3MobileServerProvider -{ - /** Get socket status - @param s Socket - @return modem status (true if connected) - */ - virtual bool getSocketAsServerModemStatus(int s)=0; - - public: - - /** minSocketAsServer - @return socket - */ - virtual int minSocketAsServer()=0; - - /** maxSocketAsServer - @return socket - */ - virtual int maxSocketAsServer()=0; - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - virtual int ready()=0; - - /** Constructor */ - GSM3MobileServerProvider(){}; - - /** Connect server to TCP port - @param port TCP port - @return command error if exists - */ - virtual int connectTCPServer(int port)=0; - //virtual int getIP(char* LocalIP, int LocalIPlength)=0; - - /** Get new occupied socket as server - @return return -1 if no new socket has been occupied - */ - virtual int getNewOccupiedSocketAsServer()=0; - - /** Get socket status - @param socket Socket - @return socket status (true if connected) - */ - virtual bool getStatusSocketAsServer(uint8_t socket)=0; - - // virtual int disconnectTCP(bool client1Server0, int idsocket)=0; - -}; - -extern GSM3MobileServerProvider* theGSM3MobileServerProvider; - -#endif diff --git a/libraries/GSM/GSM3MobileServerService.cpp b/libraries/GSM/GSM3MobileServerService.cpp deleted file mode 100644 index bf76cfc..0000000 --- a/libraries/GSM/GSM3MobileServerService.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include -#include - - -#define __TOUTSERVER__ 10000 -#define BUFFERSIZETWEET 100 - -#define GSM3MOBILESERVERSERVICE_SYNCH 0x01 // 1: TRUE, compatible with other clients 0: FALSE - -// While there is only a shield (ShieldV1) we will include it by default -#include -GSM3ShieldV1ServerProvider theShieldV1ServerProvider; - - -GSM3MobileServerService::GSM3MobileServerService(uint8_t port, bool synch) -{ - mySocket=0; - _port=port; - flags = 0; - - // If synchronous - if(synch) - flags |= GSM3MOBILESERVERSERVICE_SYNCH; -} - -// Returns 0 if last command is still executing -// 1 if success -// >1 if error -int GSM3MobileServerService::ready() -{ - return theGSM3MobileServerProvider->ready(); -} - -void GSM3MobileServerService::begin() -{ - if(theGSM3MobileServerProvider==0) - return; - theGSM3MobileServerProvider->connectTCPServer(_port); - - if(flags & GSM3MOBILESERVERSERVICE_SYNCH) - waitForAnswer(); -} - -GSM3MobileClientService GSM3MobileServerService::available(bool synch) -{ - int newSocket; - // In case we are debugging, we'll need to force a look at the buffer - ready(); - - newSocket=theGSM3MobileServerProvider->getNewOccupiedSocketAsServer(); - - // Instatiate new client. If we are synch, the client is synchronous/blocking - GSM3MobileClientService client((uint8_t)(newSocket), (flags & GSM3MOBILESERVERSERVICE_SYNCH)); - - return client; -} - -size_t GSM3MobileServerService::write(uint8_t c) -{ -// Adapt to the new, lean implementation -// theGSM3MobileServerProvider->writeSocket(c); - return 1; -} - -void GSM3MobileServerService::beginWrite() -{ -// Adapt to the new, lean implementation -// theGSM3MobileServerProvider->beginWriteSocket(local1Remote0, mySocket); -} - -size_t GSM3MobileServerService::write(const uint8_t* buf) -{ -// Adapt to the new, lean implementation -// theGSM3MobileServerProvider->writeSocket((const char*)(buf)); - return strlen((const char*)buf); -} - -size_t GSM3MobileServerService::write(const uint8_t* buf, size_t sz) -{ -// Adapt to the new, lean implementation -// theGSM3MobileServerProvider->writeSocket((const char*)(buf)); -} - -void GSM3MobileServerService::endWrite() -{ -// Adapt to the new, lean implementation -// theGSM3MobileServerProvider->endWriteSocket(); -} - -void GSM3MobileServerService::stop() -{ - - // Review, should be the server? - theGSM3MobileClientProvider->disconnectTCP(local1Remote0, mySocket); - if(flags & GSM3MOBILESERVERSERVICE_SYNCH) - waitForAnswer(); - theGSM3MobileClientProvider->releaseSocket(mySocket); - mySocket = -1; -} - - -/*int GSM3MobileServerService::getIP(char* LocalIP, int LocalIPlength) -{ - return theGSM3MobileServerProvider->getIP(LocalIP, LocalIPlength); -}*/ - -int GSM3MobileServerService::waitForAnswer() -{ - unsigned long m; - m=millis(); - int res; - - while(((millis()-m)< __TOUTSERVER__ )&&(ready()==0)) - delay(10); - - res=ready(); - - // If we get something different from a 1, we are having a problem - if(res!=1) - res=0; - - return res; -} - - diff --git a/libraries/GSM/GSM3MobileServerService.h b/libraries/GSM/GSM3MobileServerService.h deleted file mode 100644 index 12165ee..0000000 --- a/libraries/GSM/GSM3MobileServerService.h +++ /dev/null @@ -1,124 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILESERVERSERVICE_ -#define _GSM3MOBILESERVERSERVICE_ - -#include -#include -#include - -class GSM3MobileServerService : public Server -{ - private: - - uint8_t _port; // Port - uint8_t mySocket; // Actual socket - uint8_t flags; - bool local1Remote0; - - /** Internal utility, used in synchronous calls - @return operation result, 1 if success, 0 otherwise - */ - int waitForAnswer(); - - public: - - /** Constructor - @param port Port - @param synch True if the server acts synchronously - */ - GSM3MobileServerService(uint8_t port, bool synch=true); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(); - - /** Initialize server - */ - void begin(); - - /** Check if there is an incoming client request - @param synch If true, the returned client is synchronous or - blocking. - @return Client if successful, else error - */ - GSM3MobileClientService available(bool synch=true); - - // Just to keep in line with Ethernet. - // Write to every open socket... - //void write(uint8_t); - //void write(const uint8_t *buf, size_t size); - - /** Begin write in socket - */ - void beginWrite(); - - /** Write character in socket - @param c Character - @return size - */ - size_t write(uint8_t c); - - /** Write buffer in socket - @param buf Buffer - @return size - */ - size_t write(const uint8_t *buf); - - /** Write buffer in socket with size - @param buf Buffer - @param sz Buffer size - @return size - */ - size_t write(const uint8_t *buf, size_t sz); - - /** End write in socket - */ - void endWrite(); - - /** Stop server - */ - void stop(); - - // we take this function out as IPAddress is complex to bring to - // version 1. - // inline int connect(IPAddress ip, uint16_t port){return 0;}; - // Returns 2 if there are no resources - //int getIP(char* LocalIP, int LocalIPlength); - -}; - - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3MobileVoiceProvider.cpp b/libraries/GSM/GSM3MobileVoiceProvider.cpp deleted file mode 100644 index 7af4e8f..0000000 --- a/libraries/GSM/GSM3MobileVoiceProvider.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include - - -GSM3MobileVoiceProvider* theGSM3MobileVoiceProvider; diff --git a/libraries/GSM/GSM3MobileVoiceProvider.h b/libraries/GSM/GSM3MobileVoiceProvider.h deleted file mode 100644 index 2091a1b..0000000 --- a/libraries/GSM/GSM3MobileVoiceProvider.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3MOBILEVOICEPROVIDER_ -#define _GSM3MOBILEVOICEPROVIDER_ - -enum GSM3_voiceCall_st { IDLE_CALL, CALLING, RECEIVINGCALL, TALKING}; - -class GSM3MobileVoiceProvider -{ - public: - - /** Initialize the object relating it to the general infrastructure - @param - @return void - */ - virtual void initialize(){}; - - /** Launch a voice call - @param number Phone number to be called - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - virtual int voiceCall(const char* number)=0; - - /** Answer a voice call - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - virtual int answerCall()=0; - - /** Hang a voice call - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - virtual int hangCall()=0; - - /** Retrieve phone number of caller - @param buffer Buffer for copy phone number - @param bufsize Buffer size - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - virtual int retrieveCallingNumber(char* buffer, int bufsize)=0; - - /** Returns voice call status - @return voice call status - */ - virtual GSM3_voiceCall_st getvoiceCallStatus()=0; - - /** Set voice call status - @param status New status for voice call - */ - virtual void setvoiceCallStatus(GSM3_voiceCall_st status)=0; - - /** Get last command status - @return Returns 0 if last command is still executing, 1 success, >1 error - */ - virtual int ready()=0; -}; - -extern GSM3MobileVoiceProvider* theGSM3MobileVoiceProvider; - -#endif diff --git a/libraries/GSM/GSM3SMSService.cpp b/libraries/GSM/GSM3SMSService.cpp deleted file mode 100644 index 378dc2c..0000000 --- a/libraries/GSM/GSM3SMSService.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include -#include - -// While there is only a shield (ShieldV1) we will include it by default -#include -GSM3ShieldV1SMSProvider theShieldV1SMSProvider; - -#define GSM3SMSSERVICE_SYNCH 0x01 // 1: synchronous 0: asynchronous -#define __TOUT__ 10000 - - -GSM3SMSService::GSM3SMSService(bool synch) -{ - if(synch) - flags |= GSM3SMSSERVICE_SYNCH; -} - -// Returns 0 if last command is still executing -// 1 if success -// >1 if error -int GSM3SMSService::ready() -{ - return theGSM3SMSProvider->ready(); -} - -int GSM3SMSService::beginSMS(const char *number) -{ - return waitForAnswerIfNeeded(theGSM3SMSProvider->beginSMS(number)); -}; - -int GSM3SMSService::endSMS() -{ - return waitForAnswerIfNeeded(theGSM3SMSProvider->endSMS()); -}; - -size_t GSM3SMSService::write(uint8_t c) -{ - theGSM3SMSProvider->writeSMS(c); - return 1; -} - -void GSM3SMSService::flush() -{ - theGSM3SMSProvider->flushSMS(); - waitForAnswerIfNeeded(1); -}; - -int GSM3SMSService::available() -{ - return waitForAnswerIfNeeded(theGSM3SMSProvider->availableSMS()); -}; - -int GSM3SMSService::remoteNumber(char* number, int nlength) -{ - return theGSM3SMSProvider->remoteSMSNumber(number, nlength); - -} - -int GSM3SMSService::read() -{ - return theGSM3SMSProvider->readSMS(); -}; -int GSM3SMSService::peek() -{ - return theGSM3SMSProvider->peekSMS(); -}; - -int GSM3SMSService::waitForAnswerIfNeeded(int returnvalue) -{ - // If synchronous - if(flags & GSM3SMSSERVICE_SYNCH ) - { - unsigned long m; - m=millis(); - // Wait for __TOUT__ - while(((millis()-m)< __TOUT__ )&&(ready()==0)) - delay(100); - // If everything was OK, return 1 - // else (timeout or error codes) return 0; - if(ready()==1) - return 1; - else - return 0; - } - // If not synchronous just kick ahead the coming result - return ready(); -} - - - - - diff --git a/libraries/GSM/GSM3SMSService.h b/libraries/GSM/GSM3SMSService.h deleted file mode 100644 index 878be11..0000000 --- a/libraries/GSM/GSM3SMSService.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3SMSSERVICE_ -#define _GSM3SMSSERVICE_ - -#include -#include - -class GSM3SMSService : public Stream -{ - private: - - uint8_t flags; - - /** Makes synchronous the functions, if needed - @param returnvalue Return value - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int waitForAnswerIfNeeded(int returnvalue); - - public: - - /** Constructor - @param synch Determines sync mode - */ - GSM3SMSService(bool synch=true); - - /** Write a character in SMS message - @param c Character - @return size - */ - size_t write(uint8_t c); - - /** Begin a SMS to send it - @param to Destination - @return error command if it exists - */ - int beginSMS(const char* to); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(); - - /** End SMS - @return error command if it exists - */ - int endSMS(); - - /** Check if SMS available and prepare it to be read - @return number of bytes in a received SMS - */ - int available(); - - /** Read sender number phone - @param number Buffer for save number phone - @param nlength Buffer length - @return 1 success, >1 error - */ - int remoteNumber(char* number, int nlength); - - /** Read one char for SMS buffer (advance circular buffer) - @return byte - */ - int read(); - - /** Read a byte but do not advance the buffer header (circular buffer) - @return byte - */ - int peek(); - - /** Delete the SMS from Modem memory and proccess answer - */ - void flush(); - -}; - - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1.cpp b/libraries/GSM/GSM3ShieldV1.cpp deleted file mode 100644 index d594874..0000000 --- a/libraries/GSM/GSM3ShieldV1.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include -#include - -#define __RESETPIN__ 7 -#define __TOUTLOCALCOMS__ 500 -#define __TOUTSHUTDOWN__ 5000 -#define __TOUTMODEMCONFIGURATION__ 5000//equivalent to 30000 because of time in interrupt routine. -#define __TOUTAT__ 1000 -#define __TOUTSMS__ 7000 -#define __TOUTCALL__ 15000 -#define __TOUTGPRS__ 10000 -#define __NCLIENTS_MAX__ 3 - -//Constructor. -GSM3ShieldV1::GSM3ShieldV1(bool db) -{ - theGSM3ShieldV1ModemCore.setCommandCounter(1); - socketsAccepted=0; - theGSM3ShieldV1ModemCore.registerUMProvider(this); - theProvider=this; -} - -//Response management. -void GSM3ShieldV1::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case NONE: - theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from); - break; - - } -} - -//Function for 2 sec delay inside an interruption. -void GSM3ShieldV1::delayInsideInterrupt2seg() -{ - for (int k=0;k<40;k++) theGSM3ShieldV1ModemCore.gss.tunedDelay(50000); -} - -///////////////////////////////////////////////////////UNSOLICITED RESULT CODE (URC) FUNCTIONS/////////////////////////////////////////////////////////////////// - -//URC recognize. -bool GSM3ShieldV1::recognizeUnsolicitedEvent(byte oldTail) -{ - -int nlength; -char auxLocate [15]; - //POWER DOWN. - prepareAuxLocate(PSTR("POWER DOWN"), auxLocate); - if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate)) - { - theGSM3ShieldV1ModemCore.gss.cb.flush(); - return true; - } - - - return false; -} - - - diff --git a/libraries/GSM/GSM3ShieldV1.h b/libraries/GSM/GSM3ShieldV1.h deleted file mode 100644 index db52f7b..0000000 --- a/libraries/GSM/GSM3ShieldV1.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_SHIELDV1__ -#define __GSM3_SHIELDV1__ - -#include -#include -#include -#include - - -class GSM3ShieldV1 : public GSM3MobileNetworkProvider, public GSM3ShieldV1BaseProvider -{ - // General code, for modem management - private: - - /** Delay inside an interrupt (2 seconds) - */ - void delayInsideInterrupt2seg(); - - // Code for SMS Service - private: - - - long commandMillis; - bool commandSent; - - const char* pinConfig; //PIN. - char* accessPoint; //APN. - char* userName; //User. - char* passw; //Password. - const char* remoteID; //Server. - - char* dataSocket; //Data socket. - int local_Port; //Local Port. - char* local_IP; //Local IP. - int local_IP_Length; //Local IP length. - - - int socketDataSize; //Size of socket data to be read. - int socketDataSizeWritten; //Number of socket data written in buffer not to overflow the buffer - - int socketsAccepted; //Status for remote clients accepted of closed. - - public: - - /** Constructor **/ - GSM3ShieldV1(bool debug=false); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - /** Parse modem response - @param rsp Returns true if expected response exists - @param string1 Substring expected in response - @param string2 Second substring expected in response - @return true if parsed successful - */ - bool genericParse_rsp2(bool& rsp, char* string1, char* string2); - - /** Recognize URC - @param oldTail - @return true if successful - */ - bool recognizeUnsolicitedEvent(byte oldTail); - - /** Receive answer - @return true if successful - */ - bool answerReceived(); - - /** Receive socket - @param id_socket Socket ID - @return true if successful - */ - bool socketReceived(int id_socket); - - /** Update active ID sockets - @param active Active sockets - @param ID Id for update - */ - void update_activeIDsockets (bool active, int ID); - - /** Assign ID to socket - @param ID Id to assign to socket - @return true if successful - */ - bool assignIDsocket (int& ID); - - /** Close data socket - @return true if successful - */ - bool closedDataSocket(); //Flag closed current data socket. - - //bool writeIncomingCalls(char* bufferForCallerId) If isn't zero, doesn't wait calls -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1AccessProvider.cpp b/libraries/GSM/GSM3ShieldV1AccessProvider.cpp deleted file mode 100644 index 67ae755..0000000 --- a/libraries/GSM/GSM3ShieldV1AccessProvider.cpp +++ /dev/null @@ -1,296 +0,0 @@ -#include -#include - -#define __RESETPIN__ 7 -#define __TOUTSHUTDOWN__ 5000 -#define __TOUTMODEMCONFIGURATION__ 5000//equivalent to 30000 because of time in interrupt routine. -#define __TOUTAT__ 1000 - -char _command_AT[] PROGMEM = "AT"; -char _command_CGREG[] PROGMEM = "AT+CGREG?"; - - -GSM3ShieldV1AccessProvider::GSM3ShieldV1AccessProvider(bool debug) -{ - theGSM3ShieldV1ModemCore.setDebug(debug); - -} - -void GSM3ShieldV1AccessProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case MODEMCONFIG: - ModemConfigurationContinue(); - break; - case ALIVETEST: - isModemAliveContinue(); - break; - } -} - -///////////////////////////////////////////////////////CONFIGURATION FUNCTIONS/////////////////////////////////////////////////////////////////// - -// Begin -// Restart or start the modem -// May be synchronous -GSM3_NetworkStatus_t GSM3ShieldV1AccessProvider::begin(char* pin, bool restart, bool synchronous) -{ - pinMode(__RESETPIN__, OUTPUT); - - // If asked for modem restart, restart - if (restart) - HWrestart(); - else - HWstart(); - - theGSM3ShieldV1ModemCore.gss.begin(9600); - // Launch modem configuration commands - ModemConfiguration(pin); - // If synchronous, wait till ModemConfiguration is over - if(synchronous) - { - // if we shorten this delay, the command fails - while(ready()==0) - delay(1000); - } - return getStatus(); -} - -//HWrestart. -int GSM3ShieldV1AccessProvider::HWrestart() -{ - - theGSM3ShieldV1ModemCore.setStatus(IDLE); - digitalWrite(__RESETPIN__, HIGH); - delay(12000); - digitalWrite(__RESETPIN__, LOW); - delay(1000); - return 1; //configandwait(pin); -} - -//HWrestart. -int GSM3ShieldV1AccessProvider::HWstart() -{ - - theGSM3ShieldV1ModemCore.setStatus(IDLE); - digitalWrite(__RESETPIN__, HIGH); - delay(2000); - digitalWrite(__RESETPIN__, LOW); - //delay(1000); - - return 1; //configandwait(pin); -} - -//Initial configuration main function. -int GSM3ShieldV1AccessProvider::ModemConfiguration(char* pin) -{ - theGSM3ShieldV1ModemCore.setPhoneNumber(pin); - theGSM3ShieldV1ModemCore.openCommand(this,MODEMCONFIG); - theGSM3ShieldV1ModemCore.setStatus(CONNECTING); - ModemConfigurationContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Initial configuration continue function. -void GSM3ShieldV1AccessProvider::ModemConfigurationContinue() -{ - bool resp; - - // 1: Send AT - // 2: Wait AT OK and SetPin or CGREG - // 3: Wait Pin OK and CGREG - // 4: Wait CGREG and Flow SW control or CGREG - // 5: Wait IFC OK and SMS Text Mode - // 6: Wait SMS text Mode OK and Calling line identification - // 7: Wait Calling Line Id OK and Echo off - // 8: Wait for OK and COLP command for connecting line identification. - // 9: Wait for OK. - int ct=theGSM3ShieldV1ModemCore.getCommandCounter(); - if(ct==1) - { - // Launch AT - theGSM3ShieldV1ModemCore.setCommandCounter(2); - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_AT); - } - else if(ct==2) - { - // Wait for AT - OK. - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - // OK received - if(theGSM3ShieldV1ModemCore.getPhoneNumber() && (theGSM3ShieldV1ModemCore.getPhoneNumber()[0]!=0)) - { - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CPIN="), false); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - theGSM3ShieldV1ModemCore.genericCommand_rqc(theGSM3ShieldV1ModemCore.getPhoneNumber()); - } - else - { - //DEBUG - //Serial.println("AT+CGREG?"); - theGSM3ShieldV1ModemCore.setCommandCounter(4); - theGSM3ShieldV1ModemCore.takeMilliseconds(); - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGREG); - } - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==3) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - theGSM3ShieldV1ModemCore.setCommandCounter(4); - theGSM3ShieldV1ModemCore.takeMilliseconds(); - theGSM3ShieldV1ModemCore.delayInsideInterrupt(2000); - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGREG); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==4) - { - char auxLocate1 [12]; - char auxLocate2 [12]; - prepareAuxLocate(PSTR("+CGREG: 0,1"), auxLocate1); - prepareAuxLocate(PSTR("+CGREG: 0,5"), auxLocate2); - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, auxLocate1, auxLocate2)) - { - if(resp) - { - theGSM3ShieldV1ModemCore.setCommandCounter(5); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+IFC=1,1")); - } - else - { - // If not, launch command again - if(theGSM3ShieldV1ModemCore.takeMilliseconds() > __TOUTMODEMCONFIGURATION__) - { - theGSM3ShieldV1ModemCore.closeCommand(3); - } - else - { - theGSM3ShieldV1ModemCore.delayInsideInterrupt(2000); - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGREG); - } - } - } - } - else if(ct==5) - { - // 5: Wait IFC OK - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - //Delay for SW flow control being active. - theGSM3ShieldV1ModemCore.delayInsideInterrupt(2000); - // 9: SMS Text Mode - theGSM3ShieldV1ModemCore.setCommandCounter(6); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGF=1")); - } - } - else if(ct==6) - { - // 6: Wait SMS text Mode OK - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - //Calling line identification - theGSM3ShieldV1ModemCore.setCommandCounter(7); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CLIP=1")); - } - } - else if(ct==7) - { - // 7: Wait Calling Line Id OK - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Echo off - theGSM3ShieldV1ModemCore.setCommandCounter(8); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATE0")); - } - } - else if(ct==8) - { - // 8: Wait ATEO OK, send COLP - // In Arduino Mega, attention, take away the COLP step - // It looks as we can only have 8 steps - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - theGSM3ShieldV1ModemCore.setCommandCounter(9); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+COLP=1")); - } - } - else if(ct==9) - { - // 9: Wait ATCOLP OK - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if (resp) - { - theGSM3ShieldV1ModemCore.setStatus(GSM_READY); - theGSM3ShieldV1ModemCore.closeCommand(1); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } -} - -//Alive Test main function. -int GSM3ShieldV1AccessProvider::isAccessAlive() -{ - theGSM3ShieldV1ModemCore.setCommandError(0); - theGSM3ShieldV1ModemCore.setCommandCounter(1); - theGSM3ShieldV1ModemCore.openCommand(this,ALIVETEST); - isModemAliveContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Alive Test continue function. -void GSM3ShieldV1AccessProvider::isModemAliveContinue() -{ -bool rsp; -switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_AT); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(rsp)) - { - if (rsp) theGSM3ShieldV1ModemCore.closeCommand(1); - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Shutdown. -bool GSM3ShieldV1AccessProvider::shutdown() -{ - unsigned long m; - bool resp; - char auxLocate [18]; - - // It makes no sense to have an asynchronous shutdown - pinMode(__RESETPIN__, OUTPUT); - digitalWrite(__RESETPIN__, HIGH); - delay(1500); - digitalWrite(__RESETPIN__, LOW); - theGSM3ShieldV1ModemCore.setStatus(IDLE); - theGSM3ShieldV1ModemCore.gss.close(); - - m=millis(); - prepareAuxLocate(PSTR("POWER DOWN"), auxLocate); - while((millis()-m) < __TOUTSHUTDOWN__) - { - delay(1); - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, auxLocate)) - return resp; - } - return false; -} - diff --git a/libraries/GSM/GSM3ShieldV1AccessProvider.h b/libraries/GSM/GSM3ShieldV1AccessProvider.h deleted file mode 100644 index 1ddcc8c..0000000 --- a/libraries/GSM/GSM3ShieldV1AccessProvider.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3SHIELDV1ACCESSPROVIDER_ -#define _GSM3SHIELDV1ACCESSPROVIDER_ - -#include -#include -#include - -class GSM3ShieldV1AccessProvider : public GSM3MobileAccessProvider, public GSM3ShieldV1BaseProvider -{ - private: - - /** Initialize main modem configuration - @param pin PIN code - @return command error if exists - */ - int ModemConfiguration(char* pin); - - /** Continue to modem configuration function - */ - void ModemConfigurationContinue(); - - /** Continue to check if modem alive function - */ - void isModemAliveContinue(); - - - public: - - /** Constructor - @param debug Determines debug mode - */ - - GSM3ShieldV1AccessProvider(bool debug=false); - - /** Start the GSM/GPRS modem, attaching to the GSM network - @param pin SIM PIN number (4 digits in a string, example: "1234"). If - NULL the SIM has no configured PIN. - @param restart Restart the modem. Default is TRUE. The modem receives - a signal through the Ctrl/D7 pin. If it is shut down, it will - start-up. If it is running, it will restart. Takes up to 10 - seconds - @param synchronous If TRUE the call only returns after the Start is complete - or fails. If FALSE the call will return inmediately. You have - to call repeatedly ready() until you get a result. Default is TRUE. - @return If synchronous, GSM3_NetworkStatus_t. If asynchronous, returns 0. - */ - GSM3_NetworkStatus_t begin(char* pin=0,bool restart=true, bool synchronous=true); - - /** Check network access status - @return 1 if Alive, 0 if down - */ - int isAccessAlive(); - - /** Shutdown the modem (power off really) - @return true if successful - */ - bool shutdown(); - - /** Returns 0 if last command is still executing - @return 1 if success, >1 if error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - /** Returns modem status - @return modem network status - */ - inline GSM3_NetworkStatus_t getStatus(){return theGSM3ShieldV1ModemCore.getStatus();}; - - void manageResponse(byte from, byte to); - - /** Restart the modem (will shut down if running) - @return 1 if success, >1 if error - */ - int HWrestart(); - - /** Start the modem (will not shut down if running) - @return 1 if success, >1 if error - */ - int HWstart(); - -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1BandManagement.cpp b/libraries/GSM/GSM3ShieldV1BandManagement.cpp deleted file mode 100644 index 94dec9a..0000000 --- a/libraries/GSM/GSM3ShieldV1BandManagement.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include - -GSM3ShieldV1BandManagement::GSM3ShieldV1BandManagement(bool trace): modem(trace) -{ - quectelStrings[UNDEFINED]=""; - quectelStrings[EGSM_MODE]="\"EGSM_MODE\""; - quectelStrings[DCS_MODE]="\"DCS_MODE\""; - quectelStrings[PCS_MODE]="\"PCS_MODE\""; - quectelStrings[EGSM_DCS_MODE]="\"EGSM_DCS_MODE\""; - quectelStrings[GSM850_PCS_MODE]="\"GSM850_PCS_MODE\""; - quectelStrings[GSM850_EGSM_DCS_PCS_MODE]="\"GSM850_EGSM_DCS_PCS_MODE\""; -} - -GSM3_NetworkStatus_t GSM3ShieldV1BandManagement::begin() -{ - // check modem response - modem.begin(); - - // reset hardware - modem.restartModem(); - - return IDLE; -} - -String GSM3ShieldV1BandManagement::getBand() -{ - String modemResponse=modem.writeModemCommand("AT+QBAND?", 2000); - - for(GSM3GSMBand i=GSM850_EGSM_DCS_PCS_MODE;i>UNDEFINED;i=(GSM3GSMBand)((int)i-1)) - { - if(modemResponse.indexOf(quectelStrings[i])>=0) - return quectelStrings[i]; - } - - Serial.print("Unrecognized modem answer:"); - Serial.println(modemResponse); - - return ""; -} - -bool GSM3ShieldV1BandManagement::setBand(String band) -{ - String command; - String modemResponse; - bool found=false; - - command="AT+QBAND="; - for(GSM3GSMBand i=EGSM_MODE;((i<=GSM850_EGSM_DCS_PCS_MODE)&&(!found));i=(GSM3GSMBand)((int)i+1)) - { - String aux=quectelStrings[i]; - if(aux.indexOf(band)>=0) - { - command+=aux; - found=true; - } - } - - if(!found) - return false; - // Quad-band takes an awful lot of time - modemResponse=modem.writeModemCommand(command, 15000); - - if(modemResponse.indexOf("QBAND")>=0) - return true; - else - return false; -} \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1BandManagement.h b/libraries/GSM/GSM3ShieldV1BandManagement.h deleted file mode 100644 index 919d4ad..0000000 --- a/libraries/GSM/GSM3ShieldV1BandManagement.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3SHIELDV1BANDMANAGEMENT__ -#define __GSM3SHIELDV1BANDMANAGEMENT__ - -// This class executes band management functions for the ShieldV1 -#include - -#define NUMBEROFBANDS 7 -#define GSM_MODE_UNDEFINED "UNDEFINED" -#define GSM_MODE_EGSM "EGSM_MODE" -#define GSM_MODE_DCS "DCS_MODE" -#define GSM_MODE_PCS "PCS_MODE" -#define GSM_MODE_EGSM_DCS "EGSM_DCS_MODE" -#define GSM_MODE_GSM850_PCS "GSM850_PCS_MODE" -#define GSM_MODE_GSM850_EGSM_DCS_PCS "GSM850_EGSM_DCS_PCS_MODE" - -typedef enum GSM3GSMBand {UNDEFINED, EGSM_MODE, DCS_MODE, PCS_MODE, EGSM_DCS_MODE, GSM850_PCS_MODE, GSM850_EGSM_DCS_PCS_MODE}; - -// -// These are the bands and scopes: -// -// E-GSM(900) -// DCS(1800) -// PCS(1900) -// E-GSM(900)+DCS(1800) ex: Europe -// GSM(850)+PCS(1900) Ex: USA, South Am. -// GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900) - -class GSM3ShieldV1BandManagement -{ - private: - - GSM3ShieldV1DirectModemProvider modem; // Direct access to modem - - char* quectelStrings[NUMBEROFBANDS];// = {"\"EGSM_MODE\"", "\"DCS_MODE\"", "\"PCS_MODE\"", - //"\"EGSM_DCS_MODE\"", "\"GSM850_PCS_MODE\"", - //"\"GSM850_EGSM_DCS_PCS_MODE\""}; - - - public: - - /** Constructor - @param trace If true, dumps all AT dialogue to Serial - */ - GSM3ShieldV1BandManagement(bool trace=false); - - /** Forces modem hardware restart, so we begin from scratch - @return always returns IDLE status - */ - GSM3_NetworkStatus_t begin(); - - /** Get current modem work band - @return current modem work band - */ - String getBand(); - - /** Changes the modem operating band - @param band Desired new band - @return true if success, false otherwise - */ - bool setBand(String band); - -}; -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1BaseProvider.cpp b/libraries/GSM/GSM3ShieldV1BaseProvider.cpp deleted file mode 100644 index d63967b..0000000 --- a/libraries/GSM/GSM3ShieldV1BaseProvider.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include -#include -#include - -// Returns 0 if last command is still executing -// 1 if success -// >1 if error -int GSM3ShieldV1BaseProvider::ready() -{ - theGSM3ShieldV1ModemCore.manageReceivedData(); - - return theGSM3ShieldV1ModemCore.getCommandError(); -}; - -void GSM3ShieldV1BaseProvider::prepareAuxLocate(PROGMEM prog_char str[], char auxLocate[]) -{ - int i=0; - char c; - - do - { - c=pgm_read_byte_near(str + i); - auxLocate[i]=c; - i++; - } while (c!=0); -} - diff --git a/libraries/GSM/GSM3ShieldV1BaseProvider.h b/libraries/GSM/GSM3ShieldV1BaseProvider.h deleted file mode 100644 index 802d46c..0000000 --- a/libraries/GSM/GSM3ShieldV1BaseProvider.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3SHIELDV1BASEPROVIDER_ -#define _GSM3SHIELDV1BASEPROVIDER_ - -#include - -enum GSM3_commandType_e { XON, NONE, MODEMCONFIG, ALIVETEST, BEGINSMS, ENDSMS, AVAILABLESMS, FLUSHSMS, - VOICECALL, ANSWERCALL, HANGCALL, RETRIEVECALLINGNUMBER, - ATTACHGPRS, DETACHGPRS, CONNECTTCPCLIENT, DISCONNECTTCP, BEGINWRITESOCKET, ENDWRITESOCKET, - AVAILABLESOCKET, FLUSHSOCKET, CONNECTSERVER, GETIP, GETCONNECTSTATUS, GETLOCATION, GETICCID}; - -class GSM3ShieldV1BaseProvider -{ - public: - - /** Get last command status - @return Returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(); - - /** This function locates strings from PROGMEM in the buffer - @param str PROGMEN - @param auxLocate Buffer where to locate strings - */ - void prepareAuxLocate(PROGMEM prog_char str[], char auxLocate[]); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - virtual void manageResponse(byte from, byte to); - - /** Recognize URC - @param from - @return true if successful (default: false) - */ - virtual bool recognizeUnsolicitedEvent(byte from){return false;}; - -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1CellManagement.cpp b/libraries/GSM/GSM3ShieldV1CellManagement.cpp deleted file mode 100644 index 2af91ab..0000000 --- a/libraries/GSM/GSM3ShieldV1CellManagement.cpp +++ /dev/null @@ -1,168 +0,0 @@ -#include - -GSM3ShieldV1CellManagement::GSM3ShieldV1CellManagement() -{ -} - -bool GSM3ShieldV1CellManagement::parseQCCID_available(bool& rsp) -{ - char c; - bool iccidFound = false; - int i = 0; - - while(((c = theGSM3ShieldV1ModemCore.theBuffer().read()) != 0) & (i < 19)) - { - if((c < 58) & (c > 47)) - iccidFound = true; - - if(iccidFound) - { - bufferICCID[i] = c; - i++; - } - } - bufferICCID[i]=0; - - return true; -} - -bool GSM3ShieldV1CellManagement::parseQENG_available(bool& rsp) -{ - char c; - char location[50] = ""; - int i = 0; - - if (!(theGSM3ShieldV1ModemCore.theBuffer().chopUntil("+QENG: ", true))) - rsp = false; - else - rsp = true; - - if (!(theGSM3ShieldV1ModemCore.theBuffer().chopUntil("+QENG:", true))) - rsp = false; - else - rsp = true; - - while(((c = theGSM3ShieldV1ModemCore.theBuffer().read()) != 0) & (i < 50)) - { - location[i] = c; - i++; - } - location[i]=0; - - char* res_tok = strtok(location, ","); - res_tok=strtok(NULL, ","); - strcpy(countryCode, res_tok); - res_tok=strtok(NULL, ","); - strcpy(networkCode, res_tok); - res_tok=strtok(NULL, ","); - strcpy(locationArea, res_tok); - res_tok=strtok(NULL, ","); - strcpy(cellId, res_tok); - - return true; -} - -int GSM3ShieldV1CellManagement::getLocation(char *country, char *network, char *area, char *cell) -{ - if((theGSM3ShieldV1ModemCore.getStatus() != GSM_READY) && (theGSM3ShieldV1ModemCore.getStatus() != GPRS_READY)) - return 2; - - countryCode=country; - networkCode=network; - locationArea=area; - cellId=cell; - - theGSM3ShieldV1ModemCore.openCommand(this,GETLOCATION); - getLocationContinue(); - - unsigned long timeOut = millis(); - while(((millis() - timeOut) < 5000) & (ready() == 0)); - - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -void GSM3ShieldV1CellManagement::getLocationContinue() -{ - bool resp; - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.gss.tunedDelay(3000); - delay(3000); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QENG=1"), false); - theGSM3ShieldV1ModemCore.print("\r"); - break; - case 2: - if (theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - theGSM3ShieldV1ModemCore.gss.tunedDelay(3000); - delay(3000); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QENG?"), false); - theGSM3ShieldV1ModemCore.print("\r"); - } - else theGSM3ShieldV1ModemCore.closeCommand(1); - break; - case 3: - if (resp) - { - parseQENG_available(resp); - theGSM3ShieldV1ModemCore.closeCommand(3); - } - else theGSM3ShieldV1ModemCore.closeCommand(2); - break; - } -} - -int GSM3ShieldV1CellManagement::getICCID(char *iccid) -{ - if((theGSM3ShieldV1ModemCore.getStatus() != GSM_READY) && (theGSM3ShieldV1ModemCore.getStatus() != GPRS_READY)) - return 2; - - bufferICCID=iccid; - theGSM3ShieldV1ModemCore.openCommand(this,GETICCID); - getICCIDContinue(); - - unsigned long timeOut = millis(); - while(((millis() - timeOut) < 5000) & (ready() == 0)); - - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -void GSM3ShieldV1CellManagement::getICCIDContinue() -{ - bool resp; - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.setCommandCounter(2); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QCCID"), false); - theGSM3ShieldV1ModemCore.print("\r"); - break; - case 2: - if (theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - parseQCCID_available(resp); - theGSM3ShieldV1ModemCore.closeCommand(2); - } - else theGSM3ShieldV1ModemCore.closeCommand(1); - break; - } -} - -void GSM3ShieldV1CellManagement::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case NONE: - theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from); - break; - case GETLOCATION: - getLocationContinue(); - break; - case GETICCID: - getICCIDContinue(); - break; - } -} \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1CellManagement.h b/libraries/GSM/GSM3ShieldV1CellManagement.h deleted file mode 100644 index 78307da..0000000 --- a/libraries/GSM/GSM3ShieldV1CellManagement.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_SHIELDV1CELLMANAGEMENT__ -#define __GSM3_SHIELDV1CELLMANAGEMENT__ - -#include -#include -#include - -class GSM3ShieldV1CellManagement : public GSM3MobileCellManagement, public GSM3ShieldV1BaseProvider -{ - public: - - /** Constructor - */ - GSM3ShieldV1CellManagement(); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - /** getLocation - @return current cell location - */ - int getLocation(char *country, char *network, char *area, char *cell); - - /** getICCID - */ - int getICCID(char *iccid); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - private: - - char *countryCode; - char *networkCode; - char *locationArea; - char *cellId; - - char *bufferICCID; - - /** Continue to getLocation function - */ - void getLocationContinue(); - - /** Continue to getICCID function - */ - void getICCIDContinue(); - - bool parseQENG_available(bool& rsp); - - bool parseQCCID_available(bool& rsp); - -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1ClientProvider.cpp b/libraries/GSM/GSM3ShieldV1ClientProvider.cpp deleted file mode 100644 index 92d3e85..0000000 --- a/libraries/GSM/GSM3ShieldV1ClientProvider.cpp +++ /dev/null @@ -1,294 +0,0 @@ -#include -#include - -GSM3ShieldV1ClientProvider::GSM3ShieldV1ClientProvider() -{ - theGSM3MobileClientProvider=this; -}; - -//Response management. -void GSM3ShieldV1ClientProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case NONE: - theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from); - break; - case CONNECTTCPCLIENT: - connectTCPClientContinue(); - break; - case FLUSHSOCKET: - flushSocketContinue(); - break; - } -} - -//Connect TCP main function. -int GSM3ShieldV1ClientProvider::connectTCPClient(const char* server, int port, int id_socket) -{ - theGSM3ShieldV1ModemCore.setPort(port); - idSocket = id_socket; - - theGSM3ShieldV1ModemCore.setPhoneNumber((char*)server); - theGSM3ShieldV1ModemCore.openCommand(this,CONNECTTCPCLIENT); - theGSM3ShieldV1ModemCore.registerUMProvider(this); - connectTCPClientContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -int GSM3ShieldV1ClientProvider::connectTCPClient(IPAddress add, int port, int id_socket) -{ - remoteIP=add; - theGSM3ShieldV1ModemCore.setPhoneNumber(0); - return connectTCPClient(0, port, id_socket); -} - -//Connect TCP continue function. -void GSM3ShieldV1ClientProvider::connectTCPClientContinue() -{ - bool resp; - // 0: Dot or DNS notation activation - // 1: Disable SW flow control - // 2: Waiting for IFC OK - // 3: Start-up TCP connection "AT+QIOPEN" - // 4: Wait for connection OK - // 5: Wait for CONNECT - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIDNSIP="), false); - if ((theGSM3ShieldV1ModemCore.getPhoneNumber()!=0)&& - ((*(theGSM3ShieldV1ModemCore.getPhoneNumber())<'0')||((*(theGSM3ShieldV1ModemCore.getPhoneNumber())>'9')))) - { - theGSM3ShieldV1ModemCore.print('1'); - theGSM3ShieldV1ModemCore.print('\r'); - } - else - { - theGSM3ShieldV1ModemCore.print('0'); - theGSM3ShieldV1ModemCore.print('\r'); - } - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - //Response received - if(resp) - { - // AT+QIOPEN - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIOPEN="),false); - theGSM3ShieldV1ModemCore.print("\"TCP\",\""); - if(theGSM3ShieldV1ModemCore.getPhoneNumber()!=0) - { - theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber()); - } - else - { - remoteIP.printTo(theGSM3ShieldV1ModemCore); - } - theGSM3ShieldV1ModemCore.print('"'); - theGSM3ShieldV1ModemCore.print(','); - theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPort()); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - - case 3: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Response received - if(resp) - { - // OK Received - // Great. Go for the next step - theGSM3ShieldV1ModemCore.setCommandCounter(4); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - case 4: - char auxLocate [12]; - prepareAuxLocate(PSTR("CONNECT\r\n"), auxLocate); - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp,auxLocate)) - { - // Response received - if(resp) - { - // Received CONNECT OK - // Great. We're done - theGSM3ShieldV1ModemCore.setStatus(TRANSPARENT_CONNECTED); - theGSM3ShieldV1ModemCore.theBuffer().chopUntil(auxLocate, true); - theGSM3ShieldV1ModemCore.closeCommand(1); - } - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - - } -} - -//Disconnect TCP main function. -int GSM3ShieldV1ClientProvider::disconnectTCP(bool client1Server0, int id_socket) -{ - // id Socket does not really mean anything, in this case we have - // only one socket running - theGSM3ShieldV1ModemCore.openCommand(this,DISCONNECTTCP); - - // If we are not closed, launch the command -//[ZZ] if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED) -// { - delay(1000); - theGSM3ShieldV1ModemCore.print("+++"); - delay(1000); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QICLOSE")); - theGSM3ShieldV1ModemCore.setStatus(GPRS_READY); -// } - // Looks like it runs everytime, so we simply flush to death and go on - do - { - // Empty the local buffer, and tell the modem to XON - // If meanwhile we receive a DISCONNECT we should detect it as URC. - theGSM3ShieldV1ModemCore.theBuffer().flush(); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - // Give some time for the buffer to refill - delay(100); - theGSM3ShieldV1ModemCore.closeCommand(1); - }while(theGSM3ShieldV1ModemCore.theBuffer().storedBytes()>0); - - theGSM3ShieldV1ModemCore.unRegisterUMProvider(this); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - - -//Write socket first chain main function. -void GSM3ShieldV1ClientProvider::beginWriteSocket(bool client1Server0, int id_socket) -{ -} - - -//Write socket next chain function. -void GSM3ShieldV1ClientProvider::writeSocket(const char* buf) -{ - if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED) - theGSM3ShieldV1ModemCore.print(buf); -} - -//Write socket character function. -void GSM3ShieldV1ClientProvider::writeSocket(uint8_t c) -{ - if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED) - theGSM3ShieldV1ModemCore.print((char)c); -} - -//Write socket last chain main function. -void GSM3ShieldV1ClientProvider::endWriteSocket() -{ -} - - -//Available socket main function. -int GSM3ShieldV1ClientProvider::availableSocket(bool client1Server0, int id_socket) -{ - - if(!(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED)) - theGSM3ShieldV1ModemCore.closeCommand(4); - - if(theGSM3ShieldV1ModemCore.theBuffer().storedBytes()) - theGSM3ShieldV1ModemCore.closeCommand(1); - else - theGSM3ShieldV1ModemCore.closeCommand(4); - - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -int GSM3ShieldV1ClientProvider::readSocket() -{ - char charSocket; - - if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==0) - { - return 0; - } - - charSocket = theGSM3ShieldV1ModemCore.theBuffer().read(); - - if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==100) - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - - return charSocket; - -} - -//Read socket main function. -int GSM3ShieldV1ClientProvider::peekSocket() -{ - return theGSM3ShieldV1ModemCore.theBuffer().peek(0); -} - - -//Flush SMS main function. -void GSM3ShieldV1ClientProvider::flushSocket() -{ - theGSM3ShieldV1ModemCore.openCommand(this,FLUSHSOCKET); - - flushSocketContinue(); -} - -//Send SMS continue function. -void GSM3ShieldV1ClientProvider::flushSocketContinue() -{ - // If we have incomed data - if(theGSM3ShieldV1ModemCore.theBuffer().storedBytes()>0) - { - // Empty the local buffer, and tell the modem to XON - // If meanwhile we receive a DISCONNECT we should detect it as URC. - theGSM3ShieldV1ModemCore.theBuffer().flush(); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - } - else - { - //We're done - theGSM3ShieldV1ModemCore.closeCommand(1); - } -} - -// URC recognize. -// Yes, we recognize "closes" in client mode -bool GSM3ShieldV1ClientProvider::recognizeUnsolicitedEvent(byte oldTail) -{ - char auxLocate [12]; - prepareAuxLocate(PSTR("CLOSED"), auxLocate); - - if((theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED) & theGSM3ShieldV1ModemCore.theBuffer().chopUntil(auxLocate, false, false)) - { - theGSM3ShieldV1ModemCore.setStatus(GPRS_READY); - theGSM3ShieldV1ModemCore.unRegisterUMProvider(this); - return true; - } - - return false; -} - -int GSM3ShieldV1ClientProvider::getSocket(int socket) -{ - return 0; -} - -void GSM3ShieldV1ClientProvider::releaseSocket(int socket) -{ - -} - -bool GSM3ShieldV1ClientProvider::getStatusSocketClient(uint8_t socket) -{ - return (theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED); - -}; - - - diff --git a/libraries/GSM/GSM3ShieldV1ClientProvider.h b/libraries/GSM/GSM3ShieldV1ClientProvider.h deleted file mode 100644 index fa2f8b5..0000000 --- a/libraries/GSM/GSM3ShieldV1ClientProvider.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_SHIELDV1CLIENTPROVIDER__ -#define __GSM3_SHIELDV1CLIENTPROVIDER__ - -#include -#include - -class GSM3ShieldV1ClientProvider : public GSM3MobileClientProvider, public GSM3ShieldV1BaseProvider -{ - private: - - int remotePort; //Current operation remote port. - IPAddress remoteIP; // Remote IP address - int idSocket; // Remote ID socket. - - - /** Continue to connect TCP client function - */ - void connectTCPClientContinue(); - - /** Continue to available socket function - */ - void availableSocketContinue(); - - /** Continue to flush socket function - */ - void flushSocketContinue(); - - public: - - /** Constructor */ - GSM3ShieldV1ClientProvider(); - - /** minSocket - @return 0 - */ - int minSocket(){return 0;}; - - /** maxSocket - @return 0 - */ - int maxSocket(){return 0;}; - - /** Connect to a remote TCP server - @param server String with IP or server name - @param port Remote port number - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - int connectTCPClient(const char* server, int port, int id_socket); - - /** Connect to a remote TCP server - @param add Remote IP address - @param port Remote port number - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - int connectTCPClient(IPAddress add, int port, int id_socket); - - /** Begin writing through a socket - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - void beginWriteSocket(bool client1Server0, int id_socket); - - /** Write through a socket. MUST go after beginWriteSocket() - @param buf characters to be written (final 0 will not be written) - */ - void writeSocket(const char* buf); - - /** Write through a socket. MUST go after beginWriteSocket() - @param c character to be written - */ - void writeSocket(uint8_t c); - - /** Finish current writing - */ - void endWriteSocket(); - - /** Check if there are data to be read in socket. - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if there are data available, 4 if no data, otherwise error - */ - int availableSocket(bool client, int id_socket); // With "available" and "readSocket" ask the modem for 1500 bytes. - - /** Read data (get a character) available in socket - @return character - */ - int readSocket(); //If Read() gets to the end of the QIRD response, execute again QIRD SYNCHRONOUSLY - - /** Flush socket - */ - void flushSocket(); - - /** Get a character but will not advance the buffer head - @return character - */ - int peekSocket(); - - /** Close a socket - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Socket - @return 0 if command running, 1 if success, otherwise error - */ - int disconnectTCP(bool client1Server0, int id_socket); - - /** Recognize unsolicited event - @param oldTail - @return true if successful - */ - bool recognizeUnsolicitedEvent(byte from); - - /** Manages modem response - @param from Initial byte position - @param to Final byte position - */ - void manageResponse(byte from, byte to); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - // Client socket management, just to be compatible - // with the Multi option - - /** Get socket - @param socket Socket - @return socket - */ - int getSocket(int socket=-1); - - /** Release socket - @param socket Socket - */ - void releaseSocket(int socket); - - /** Get socket client status - @param socket Socket - @return 1 if connected, 0 otherwise - */ - bool getStatusSocketClient(uint8_t socket); - -}; - - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1DataNetworkProvider.cpp b/libraries/GSM/GSM3ShieldV1DataNetworkProvider.cpp deleted file mode 100644 index aaffdba..0000000 --- a/libraries/GSM/GSM3ShieldV1DataNetworkProvider.cpp +++ /dev/null @@ -1,363 +0,0 @@ -#include -#include - -char _command_CGATT[] PROGMEM = "AT+CGATT="; -char _command_SEPARATOR[] PROGMEM = "\",\""; - -//Attach GPRS main function. -GSM3_NetworkStatus_t GSM3ShieldV1DataNetworkProvider::attachGPRS(char* apn, char* user_name, char* password, bool synchronous) -{ - user = user_name; - passwd = password; - // A sad use of byte reuse - theGSM3ShieldV1ModemCore.setPhoneNumber(apn); - - theGSM3ShieldV1ModemCore.openCommand(this,ATTACHGPRS); - theGSM3ShieldV1ModemCore.setStatus(CONNECTING); - - attachGPRSContinue(); - - // If synchronous, wait till attach is over, or not. - if(synchronous) - { - // if we shorten this delay, the command fails - while(ready()==0) - delay(100); - } - - return theGSM3ShieldV1ModemCore.getStatus(); -} - -//Atthach GPRS continue function. -void GSM3ShieldV1DataNetworkProvider::attachGPRSContinue() -{ - bool resp; - // 1: Attach to GPRS service "AT+CGATT=1" - // 2: Wait attach OK and Set the context 0 as FGCNT "AT+QIFGCNT=0" - // 3: Wait context OK and Set bearer type as GPRS, APN, user name and pasword "AT+QICSGP=1..." - // 4: Wait bearer OK and Enable the function of MUXIP "AT+QIMUX=1" - // 5: Wait for disable MUXIP OK and Set the session mode as non transparent "AT+QIMODE=0" - // 6: Wait for session mode OK and Enable notification when data received "AT+QINDI=1" - // 8: Wait domain name OK and Register the TCP/IP stack "AT+QIREGAPP" - // 9: Wait for Register OK and Activate FGCNT "AT+QIACT" - // 10: Wait for activate OK - - int ct=theGSM3ShieldV1ModemCore.getCommandCounter(); - if(ct==1) - { - //AT+CGATT - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGATT,false); - theGSM3ShieldV1ModemCore.print(1); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - } - else if(ct==2) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - //AT+QIFGCNT - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIFGCNT=0")); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==3) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - // Great. Go for the next step - //DEBUG - //Serial.println("AT+QICSGP."); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QICSGP=1,\""),false); - theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber()); - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_SEPARATOR,false); - theGSM3ShieldV1ModemCore.print(user); - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_SEPARATOR,false); - theGSM3ShieldV1ModemCore.print(passwd); - theGSM3ShieldV1ModemCore.print("\"\r"); - theGSM3ShieldV1ModemCore.setCommandCounter(4); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==4) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - // AT+QIMUX=1 for multisocket - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIMUX=0")); - theGSM3ShieldV1ModemCore.setCommandCounter(5); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==5) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - //AT+QIMODE=0 for multisocket - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIMODE=1")); - theGSM3ShieldV1ModemCore.setCommandCounter(6); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==6) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - // AT+QINDI=1 - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QINDI=1")); - theGSM3ShieldV1ModemCore.setCommandCounter(8); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==8) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - // AT+QIREGAPP - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIREGAPP")); - theGSM3ShieldV1ModemCore.setCommandCounter(9); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==9) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if(resp) - { - // AT+QIACT - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIACT")); - theGSM3ShieldV1ModemCore.setCommandCounter(10); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - else if(ct==10) - { - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if (resp) - { - theGSM3ShieldV1ModemCore.setStatus(GPRS_READY); - theGSM3ShieldV1ModemCore.closeCommand(1); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - } -} - -//Detach GPRS main function. -GSM3_NetworkStatus_t GSM3ShieldV1DataNetworkProvider::detachGPRS(bool synchronous) -{ - theGSM3ShieldV1ModemCore.openCommand(this,DETACHGPRS); - theGSM3ShieldV1ModemCore.setStatus(CONNECTING); - detachGPRSContinue(); - - if(synchronous) - { - while(ready()==0) - delay(1); - } - - return theGSM3ShieldV1ModemCore.getStatus(); -} - -void GSM3ShieldV1DataNetworkProvider::detachGPRSContinue() -{ - bool resp; - // 1: Detach to GPRS service "AT+CGATT=0" - // 2: Wait dettach +PDP DEACT - // 3: Wait for OK - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //AT+CGATT=0 - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGATT,false); - theGSM3ShieldV1ModemCore.print(0); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - char auxLocate[12]; - prepareAuxLocate(PSTR("+PDP DEACT"), auxLocate); - if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate)) - { - if(resp) - { - // Received +PDP DEACT; - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - case 3: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // OK received - if (resp) - { - theGSM3ShieldV1ModemCore.setStatus(GSM_READY); - theGSM3ShieldV1ModemCore.closeCommand(1); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//QILOCIP parse. -bool GSM3ShieldV1DataNetworkProvider::parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp) -{ - if (!(theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("\r\n","\r\n", LocalIP, LocalIPlength))) - rsp = false; - else - rsp = true; - return true; -} - -//Get IP main function. -int GSM3ShieldV1DataNetworkProvider::getIP(char* LocalIP, int LocalIPlength) -{ - theGSM3ShieldV1ModemCore.setPhoneNumber(LocalIP); - theGSM3ShieldV1ModemCore.setPort(LocalIPlength); - theGSM3ShieldV1ModemCore.openCommand(this,GETIP); - getIPContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -void GSM3ShieldV1DataNetworkProvider::getIPContinue() -{ - - bool resp; - // 1: Read Local IP "AT+QILOCIP" - // 2: Waiting for IP. - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //AT+QILOCIP - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILOCIP")); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(parseQILOCIP_rsp(theGSM3ShieldV1ModemCore.getPhoneNumber(), theGSM3ShieldV1ModemCore.getPort(), resp)) - { - if (resp) - theGSM3ShieldV1ModemCore.closeCommand(1); - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - theGSM3ShieldV1ModemCore.theBuffer().flush(); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - break; - } -} - -//Get IP with IPAddress object -IPAddress GSM3ShieldV1DataNetworkProvider::getIPAddress() { - char ip_temp[15]=""; - getIP(ip_temp, 15); - unsigned long m=millis(); - - while((millis()-m)<10*1000 && (!ready())){ - // wait for a response from the modem: - delay(100); - } - IPAddress ip; - inet_aton(ip_temp, ip); - return ip; -} - -int GSM3ShieldV1DataNetworkProvider::inet_aton(const char* aIPAddrString, IPAddress& aResult) -{ - // See if we've been given a valid IP address - const char* p =aIPAddrString; - while (*p && - ( (*p == '.') || (*p >= '0') || (*p <= '9') )) - { - p++; - } - - if (*p == '\0') - { - // It's looking promising, we haven't found any invalid characters - p = aIPAddrString; - int segment =0; - int segmentValue =0; - while (*p && (segment < 4)) - { - if (*p == '.') - { - // We've reached the end of a segment - if (segmentValue > 255) - { - // You can't have IP address segments that don't fit in a byte - return 0; - } - else - { - aResult[segment] = (byte)segmentValue; - segment++; - segmentValue = 0; - } - } - else - { - // Next digit - segmentValue = (segmentValue*10)+(*p - '0'); - } - p++; - } - // We've reached the end of address, but there'll still be the last - // segment to deal with - if ((segmentValue > 255) || (segment > 3)) - { - // You can't have IP address segments that don't fit in a byte, - // or more than four segments - return 0; - } - else - { - aResult[segment] = (byte)segmentValue; - return 1; - } - } - else - { - return 0; - } -} - -//Response management. -void GSM3ShieldV1DataNetworkProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case ATTACHGPRS: - attachGPRSContinue(); - break; - case DETACHGPRS: - detachGPRSContinue(); - break; - case GETIP: - getIPContinue(); - break; - } -} diff --git a/libraries/GSM/GSM3ShieldV1DataNetworkProvider.h b/libraries/GSM/GSM3ShieldV1DataNetworkProvider.h deleted file mode 100644 index 012a0ca..0000000 --- a/libraries/GSM/GSM3ShieldV1DataNetworkProvider.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3SHIELDV1DATANETWORKPROVIDER_ -#define _GSM3SHIELDV1DATANETWORKPROVIDER_ - -#include -#include -#include -#include - -class GSM3ShieldV1DataNetworkProvider : public GSM3MobileDataNetworkProvider, public GSM3ShieldV1BaseProvider -{ - private: - - char* user; // Username for GPRS - char* passwd; // Password for GPRS - - /** Continue to attach GPRS function - */ - void attachGPRSContinue(); - - /** Continue to detach GPRS function - */ - void detachGPRSContinue(); - - /** Parse QILOCIP response - @param LocalIP Buffer for save local IP address - @param LocalIPlength Buffer size - @param rsp Returns true if expected response exists - @return true if command executed correctly - */ - bool parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp); - - /** Continue to get IP function - */ - void getIPContinue(); - - /** Implementation of inet_aton standard function - @param aIPAddrString IP address in characters buffer - @param aResult IP address in IPAddress format - @return 1 if the address is successfully converted, or 0 if the conversion failed - */ - int inet_aton(const char* aIPAddrString, IPAddress& aResult); - - public: - - /** Attach to GPRS/GSM network - @param networkId APN GPRS - @param user Username - @param pass Password - @return connection status - */ - GSM3_NetworkStatus_t networkAttach(char* networkId, char* user, char* pass) - { - return attachGPRS(networkId, user, pass); - }; - - /** Detach GPRS/GSM network - @return connection status - */ - GSM3_NetworkStatus_t networkDetach(){ return detachGPRS();}; - - /** Attach to GPRS service - @param apn APN GPRS - @param user_name Username - @param password Password - @param synchronous Sync mode - @return connection status - */ - GSM3_NetworkStatus_t attachGPRS(char* apn, char* user_name, char* password, bool synchronous=true); - - /** Detach GPRS service - @param synchronous Sync mode - @return connection status - */ - GSM3_NetworkStatus_t detachGPRS(bool synchronous=true); - - /** Returns 0 if last command is still executing - @return 1 if success, >1 if error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - /** Get network status (connection) - @return status - */ - inline GSM3_NetworkStatus_t getStatus(){return theGSM3ShieldV1ModemCore.getStatus();}; - - /** Get actual assigned IP address - @param LocalIP Buffer for copy IP address - @param LocalIPlength Buffer length - @return command error if exists - */ - int getIP(char* LocalIP, int LocalIPlength); - - /** Get actual assigned IP address in IPAddress format - @return IP address in IPAddress format - */ - IPAddress getIPAddress(); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1DirectModemProvider.cpp b/libraries/GSM/GSM3ShieldV1DirectModemProvider.cpp deleted file mode 100644 index 47aa52b..0000000 --- a/libraries/GSM/GSM3ShieldV1DirectModemProvider.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include -#include -#include - -#define __RESETPIN__ 7 - -//Constructor -GSM3ShieldV1DirectModemProvider::GSM3ShieldV1DirectModemProvider(bool t) -{ - trace=t; -}; - -void GSM3ShieldV1DirectModemProvider::begin() -{ - theGSM3ShieldV1ModemCore.gss.begin(9600); -} - -void GSM3ShieldV1DirectModemProvider::restartModem() -{ - pinMode(__RESETPIN__, OUTPUT); - digitalWrite(__RESETPIN__, HIGH); - delay(12000); - digitalWrite(__RESETPIN__, LOW); - delay(1000); - -} - -//To enable the debug process -void GSM3ShieldV1DirectModemProvider::connect() -{ - theGSM3ShieldV1ModemCore.registerActiveProvider(this); -} - -//To disable the debug process -void GSM3ShieldV1DirectModemProvider::disconnect() -{ - theGSM3ShieldV1ModemCore.registerActiveProvider(0); -} - -//Write to the modem by means of SoftSerial -size_t GSM3ShieldV1DirectModemProvider::write(uint8_t c) -{ - theGSM3ShieldV1ModemCore.write(c); -} - -//Detect if data to be read -int/*bool*/ GSM3ShieldV1DirectModemProvider::available() -{ - if (theGSM3ShieldV1ModemCore.gss.cb.peek(1)) return 1; - else return 0; -} - -//Read data -int/*char*/ GSM3ShieldV1DirectModemProvider::read() -{ - int dataRead; - dataRead = theGSM3ShieldV1ModemCore.gss.cb.read(); - //In case last char in xof mode. - if (!(theGSM3ShieldV1ModemCore.gss.cb.peek(0))) { - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - delay(100); - } - return dataRead; -} - -//Peek data -int/*char*/ GSM3ShieldV1DirectModemProvider::peek() -{ - return theGSM3ShieldV1ModemCore.gss.cb.peek(0); -} - -//Flush data -void GSM3ShieldV1DirectModemProvider::flush() -{ - return theGSM3ShieldV1ModemCore.gss.cb.flush(); -} - -String GSM3ShieldV1DirectModemProvider::writeModemCommand(String ATcommand, int responseDelay) -{ - - if(trace) - Serial.println(ATcommand); - - // Flush other texts - flush(); - - //Enter debug mode. - connect(); - //Send the AT command. - println(ATcommand); - - delay(responseDelay); - - //Get response data from modem. - String result = ""; - if(trace) - theGSM3ShieldV1ModemCore.gss.cb.debugBuffer(); - - while (available()) - { - char c = read(); - result += c; - } - if(trace) - Serial.println(result); - //Leave the debug mode. - disconnect(); - return result; -} \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1DirectModemProvider.h b/libraries/GSM/GSM3ShieldV1DirectModemProvider.h deleted file mode 100644 index 2d20412..0000000 --- a/libraries/GSM/GSM3ShieldV1DirectModemProvider.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ - -#ifndef __GSM3DIRECTMODEMPROVIDER__ -#define __GSM3DIRECTMODEMPROVIDER__ - -#include -#include -#include -#include -#include - -class GSM3ShieldV1DirectModemProvider : public GSM3ShieldV1BaseProvider, public Stream -{ - private: - - bool trace; - - public: - - /** Constructor - @param trace if true, dumps all AT dialogue to Serial - */ - GSM3ShieldV1DirectModemProvider(bool trace=false); - - /** - */ - void begin(); - - /** - */ - void restartModem(); - - /** Enable the debug process. - */ - void connect(); - - /** Disable the debug process. - */ - void disconnect(); - - /** Debug write to modem by means of SoftSerial. - @param c Character - @return size - */ - size_t write(uint8_t c); - - /** Check for incoming bytes in buffer - @return - */ - int available(); - - /** Read from circular buffer - @return character - */ - int read(); - - /** Read from circular buffer, but do not delete it - @return character - */ - int peek(); - - /** Empty circular buffer - */ - void flush(); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to){}; - - /** Recognize unsolicited event - @param from - @return true if successful - */ - bool recognizeUnsolicitedEvent(byte from){return false;}; - - /** Send AT command to modem - @param command AT command - @param delay Time to wait for response - @return response from modem - */ - String writeModemCommand(String command, int delay); -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1ModemCore.cpp b/libraries/GSM/GSM3ShieldV1ModemCore.cpp deleted file mode 100644 index c90ff4d..0000000 --- a/libraries/GSM/GSM3ShieldV1ModemCore.cpp +++ /dev/null @@ -1,198 +0,0 @@ -#include -#include - -GSM3ShieldV1ModemCore theGSM3ShieldV1ModemCore; - -char* __ok__="OK"; - -GSM3ShieldV1ModemCore::GSM3ShieldV1ModemCore() : gss() -{ - gss.registerMgr(this); - _dataInBufferFrom=0; - _dataInBufferTo=0; - commandError=1; - commandCounter=0; - ongoingCommand=NONE; - takeMilliseconds(); - - for(int i=0;irecognizeUnsolicitedEvent(from); - } - if((!recognized)&&(activeProvider)) - activeProvider->manageResponse(from, to); -} - - -void GSM3ShieldV1ModemCore::openCommand(GSM3ShieldV1BaseProvider* provider, GSM3_commandType_e c) -{ - activeProvider=provider; - commandError=0; - commandCounter=1; - ongoingCommand=c; - _dataInBufferFrom=0; - _dataInBufferTo=0; - -}; - -size_t GSM3ShieldV1ModemCore::writePGM(PROGMEM prog_char str[], bool CR) -{ - int i=0; - char c; - - do - { - c=pgm_read_byte_near(str + i); - if(c!=0) - write(c); - i++; - } while (c!=0); - if(CR) - print("\r"); - - return 1; -} - -size_t GSM3ShieldV1ModemCore::write(uint8_t c) -{ - if(_debug) - GSM3CircularBuffer::printCharDebug(c); - return gss.write(c); -} - -unsigned long GSM3ShieldV1ModemCore::takeMilliseconds() -{ - unsigned long now=millis(); - unsigned long delta; - delta=now-milliseconds; - milliseconds=now; - return delta; -} - -void GSM3ShieldV1ModemCore::delayInsideInterrupt(unsigned long milliseconds) -{ - for (unsigned long k=0;k -#include -#include -#include - -#define UMPROVIDERS 3 - -class GSM3ShieldV1ModemCore : public GSM3SoftSerialMgr, public Print -{ - private: - - // Phone number, used when calling, sending SMS and reading calling numbers - // Also PIN in modem configuration - // Also APN - // Also remote server - char* phoneNumber; - - // Working port. Port used in the ongoing command, while opening a server - // Also for IP address length - int port; - - // 0 = ongoing - // 1 = OK - // 2 = Error. Incorrect state - // 3 = Unexpected modem message - // 4 = OK but not available data. - uint8_t commandError; - - // Counts the steps by the command - uint8_t commandCounter; - - // Presently ongoing command - GSM3_commandType_e ongoingCommand; - - // Enable/disable debug - bool _debug; - byte _dataInBufferFrom; - byte _dataInBufferTo; - - // This is the modem (known) status - GSM3_NetworkStatus_t _status; - - GSM3ShieldV1BaseProvider* UMProvider[UMPROVIDERS]; - GSM3ShieldV1BaseProvider* activeProvider; - - // Private function for anage message - void manageMsgNow(byte from, byte to); - - unsigned long milliseconds; - - public: - - /** Constructor */ - GSM3ShieldV1ModemCore(); - - GSM3SoftSerial gss; // Direct access to modem - - /** Get phone number - @return phone number - */ - char *getPhoneNumber(){return phoneNumber;}; - - /** Establish a new phone number - @param n Phone number - */ - void setPhoneNumber(char *n){phoneNumber=n;}; - - /** Get port used - @return port - */ - int getPort(){return port;}; - - /** Establish a new port for use - @param p Port - */ - void setPort(int p){port=p;}; - - /** Get command error - @return command error - */ - uint8_t getCommandError(){return commandError;}; - - /** Establish a command error - @param n Command error - */ - void setCommandError(uint8_t n){commandError=n;}; - - /** Get command counter - @return command counter - */ - uint8_t getCommandCounter(){return commandCounter;}; - - /** Set command counter - @param c Initial value - */ - void setCommandCounter(uint8_t c){commandCounter=c;}; - - /** Get ongoing command - @return command - */ - GSM3_commandType_e getOngoingCommand(){return ongoingCommand;}; - - /** Set ongoing command - @param c New ongoing command - */ - void setOngoingCommand(GSM3_commandType_e c){ongoingCommand=c;}; - - /** Open command - @param activeProvider Active provider - @param c Command for open - */ - void openCommand(GSM3ShieldV1BaseProvider* activeProvider, GSM3_commandType_e c); - - /** Close command - @param code Close code - */ - void closeCommand(int code); - - // These functions allow writing to the SoftwareSerial - // If debug is set, dump to the console - - /** Write a character in serial - @param c Character - @return size - */ - size_t write(uint8_t c); - - /** Write PGM - @param str Buffer for write - @param CR Carriadge return adding automatically - @return size - */ - virtual size_t writePGM(PROGMEM prog_char str[], bool CR=true); - - /** Establish debug mode - @param db Boolean that indicates debug on or off - */ - void setDebug(bool db){_debug=db;}; - - /** Generic response parser - @param rsp Returns true if expected response exists - @param string Substring expected in response - @param string2 Second substring expected in response - @return true if parsed correctly - */ - bool genericParse_rsp(bool& rsp, char* string=0, char* string2=0); - - /** Generates a generic AT command request from PROGMEM prog_char buffer - @param str Buffer with AT command - @param addCR Carriadge return adding automatically - */ - void genericCommand_rq(PROGMEM prog_char str[], bool addCR=true); - - /** Generates a generic AT command request from a simple char buffer - @param str Buffer with AT command - @param addCR Carriadge return adding automatically - */ - void genericCommand_rqc(const char* str, bool addCR=true); - - /** Generates a generic AT command request from characters buffer - @param str Buffer with AT command - @param addCR Carriadge return adding automatically - */ - void genericCommand_rq(const char* str, bool addCR=true); - - /** Returns the circular buffer - @return circular buffer - */ - inline GSM3CircularBuffer& theBuffer(){return gss.cb;}; - - /** Establish a new network status - @param status Network status - */ - inline void setStatus(GSM3_NetworkStatus_t status) { _status = status; }; - - /** Returns actual network status - @return network status - */ - inline GSM3_NetworkStatus_t getStatus() { return _status; }; - - /** Register provider as willing to receive unsolicited messages - @param provider Pointer to provider able to receive unsolicited messages - */ - void registerUMProvider(GSM3ShieldV1BaseProvider* provider); - - /** unegister provider as willing to receive unsolicited messages - @param provider Pointer to provider able to receive unsolicited messages - */ - void unRegisterUMProvider(GSM3ShieldV1BaseProvider* provider); - - - /** Register a provider as "dialoguing" talking in facto with the modem - @param provider Pointer to provider receiving responses - */ - void registerActiveProvider(GSM3ShieldV1BaseProvider* provider){activeProvider=provider;}; - - /** Needed to manage the SoftSerial. Receives the call when received data - If _debugging, no code is called - @param from Starting byte to read - @param to Last byte to read - */ - void manageMsg(byte from, byte to); - - /** If _debugging, this call is assumed to be made out of interrupts - Prints incoming info and calls manageMsgNow - */ - void manageReceivedData(); - - /** Chronometer. Measure milliseconds from last call - @return milliseconds from las time function was called - */ - unsigned long takeMilliseconds(); - - /** Delay for interrupts - @param milliseconds Delay time in milliseconds - */ - void delayInsideInterrupt(unsigned long milliseconds); - -}; - -extern GSM3ShieldV1ModemCore theGSM3ShieldV1ModemCore; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1ModemVerification.cpp b/libraries/GSM/GSM3ShieldV1ModemVerification.cpp deleted file mode 100644 index e5d190f..0000000 --- a/libraries/GSM/GSM3ShieldV1ModemVerification.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ - -#include - -// constructor -GSM3ShieldV1ModemVerification::GSM3ShieldV1ModemVerification() -{ -}; - -// reset the modem for direct access -int GSM3ShieldV1ModemVerification::begin() -{ - int result=0; - String modemResponse; - - // check modem response - modemAccess.begin(); - - // reset hardware - modemAccess.restartModem(); - - modemResponse=modemAccess.writeModemCommand("AT", 1000); - if(modemResponse.indexOf("OK")>=0) - result=1; - modemResponse=modemAccess.writeModemCommand("ATE0", 1000); - return result; -} - -// get IMEI -String GSM3ShieldV1ModemVerification::getIMEI() -{ - String number; - // AT command for obtain IMEI - String modemResponse = modemAccess.writeModemCommand("AT+GSN", 2000); - // Parse and check response - char res_to_compare[modemResponse.length()]; - modemResponse.toCharArray(res_to_compare, modemResponse.length()); - if(strstr(res_to_compare,"OK") == NULL) - { - return NULL; - } - else - { - number = modemResponse.substring(1, 17); - return number; - } -} diff --git a/libraries/GSM/GSM3ShieldV1ModemVerification.h b/libraries/GSM/GSM3ShieldV1ModemVerification.h deleted file mode 100644 index e03980e..0000000 --- a/libraries/GSM/GSM3ShieldV1ModemVerification.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3SHIELDV1MODEMVERIFICATION_ -#define _GSM3SHIELDV1MODEMVERIFICATION_ - -#include -#include - -class GSM3ShieldV1ModemVerification -{ - - private: - - GSM3ShieldV1DirectModemProvider modemAccess; - GSM3ShieldV1AccessProvider gsm; // Access provider to GSM/GPRS network - - public: - - /** Constructor */ - GSM3ShieldV1ModemVerification(); - - /** Check modem response and restart it - */ - int begin(); - - /** Obtain modem IMEI (command AT) - @return modem IMEI number - */ - String getIMEI(); - -}; - -#endif; \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1MultiClientProvider.cpp b/libraries/GSM/GSM3ShieldV1MultiClientProvider.cpp deleted file mode 100644 index 797424f..0000000 --- a/libraries/GSM/GSM3ShieldV1MultiClientProvider.cpp +++ /dev/null @@ -1,583 +0,0 @@ -#include -#include - -char _command_MultiQISRVC[] PROGMEM = "AT+QISRVC="; - -#define __TOUTFLUSH__ 10000 - -GSM3ShieldV1MultiClientProvider::GSM3ShieldV1MultiClientProvider() -{ - theGSM3MobileClientProvider=this; - theGSM3ShieldV1ModemCore.registerUMProvider(this); -}; - -//Response management. -void GSM3ShieldV1MultiClientProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case XON: - if (flagReadingSocket) - { -// flagReadingSocket = 0; - fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3); - } - else theGSM3ShieldV1ModemCore.setOngoingCommand(NONE); - break; - case NONE: - theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from); - break; - case CONNECTTCPCLIENT: - connectTCPClientContinue(); - break; - case DISCONNECTTCP: - disconnectTCPContinue(); - break; - case BEGINWRITESOCKET: - beginWriteSocketContinue(); - break; - case ENDWRITESOCKET: - endWriteSocketContinue(); - break; - case AVAILABLESOCKET: - availableSocketContinue(); - break; - case FLUSHSOCKET: - fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3); - flushSocketContinue(); - break; - } -} - -//Connect TCP main function. -int GSM3ShieldV1MultiClientProvider::connectTCPClient(const char* server, int port, int id_socket) -{ - theGSM3ShieldV1ModemCore.setPort(port); - idSocket = id_socket; - - theGSM3ShieldV1ModemCore.setPhoneNumber((char*)server); - theGSM3ShieldV1ModemCore.openCommand(this,CONNECTTCPCLIENT); - connectTCPClientContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -int GSM3ShieldV1MultiClientProvider::connectTCPClient(IPAddress add, int port, int id_socket) -{ - remoteIP=add; - theGSM3ShieldV1ModemCore.setPhoneNumber(0); - return connectTCPClient(0, port, id_socket); -} - -//Connect TCP continue function. -void GSM3ShieldV1MultiClientProvider::connectTCPClientContinue() -{ - bool resp; - // 0: Dot or DNS notation activation - // 1: Disable SW flow control - // 2: Waiting for IFC OK - // 3: Start-up TCP connection "AT+QIOPEN" - // 4: Wait for connection OK - // 5: Wait for CONNECT - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIDNSIP="), false); - if ((theGSM3ShieldV1ModemCore.getPhoneNumber()!=0)&& - ((*(theGSM3ShieldV1ModemCore.getPhoneNumber())<'0')||((*(theGSM3ShieldV1ModemCore.getPhoneNumber())>'9')))) - { - theGSM3ShieldV1ModemCore.print('1'); - theGSM3ShieldV1ModemCore.print('\r'); - } - else - { - theGSM3ShieldV1ModemCore.print('0'); - theGSM3ShieldV1ModemCore.print('\r'); - } - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - //Response received - if(resp) - { - // AT+QIOPEN - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIOPEN="),false); - theGSM3ShieldV1ModemCore.print(idSocket); - theGSM3ShieldV1ModemCore.print(",\"TCP\",\""); - if(theGSM3ShieldV1ModemCore.getPhoneNumber()!=0) - { - theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber()); - } - else - { - remoteIP.printTo(theGSM3ShieldV1ModemCore); - } - theGSM3ShieldV1ModemCore.print('"'); - theGSM3ShieldV1ModemCore.print(','); - theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPort()); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - - case 3: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Response received - if(resp) - { - // OK Received - // Great. Go for the next step - theGSM3ShieldV1ModemCore.setCommandCounter(4); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - case 4: - char auxLocate [12]; - prepareAuxLocate(PSTR("CONNECT OK"), auxLocate); - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp,auxLocate)) - { - // Response received - if(resp) - { - // Received CONNECT OK - // Great. We're done - theGSM3ShieldV1ModemCore.closeCommand(1); - } - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - - } -} - -//Disconnect TCP main function. -int GSM3ShieldV1MultiClientProvider::disconnectTCP(bool client1Server0, int id_socket) -{ - idSocket = id_socket; - - // First of all, we will flush the socket synchronously - unsigned long m; - m=millis(); - flushSocket(); - while(((millis()-m)< __TOUTFLUSH__ )&&(ready()==0)) - delay(10); - - // Could not flush the communications... strange - if(ready()==0) - { - theGSM3ShieldV1ModemCore.setCommandError(2); - return theGSM3ShieldV1ModemCore.getCommandError(); - } - - // Set up the command - client1_server0 = client1Server0; - flagReadingSocket=0; - theGSM3ShieldV1ModemCore.openCommand(this,DISCONNECTTCP); - disconnectTCPContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Disconnect TCP continue function -void GSM3ShieldV1MultiClientProvider::disconnectTCPContinue() -{ - bool resp; - // 1: Send AT+QISRVC - // 2: "AT+QICLOSE" - // 3: Wait for OK - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_MultiQISRVC, false); - if (client1_server0) theGSM3ShieldV1ModemCore.print('1'); - else theGSM3ShieldV1ModemCore.print('2'); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - // Parse response to QISRVC - theGSM3ShieldV1ModemCore.genericParse_rsp(resp); - if(resp) - { - // Send QICLOSE command - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QICLOSE="),false); - theGSM3ShieldV1ModemCore.print(idSocket); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else - theGSM3ShieldV1ModemCore.closeCommand(3); - break; - case 3: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - theGSM3ShieldV1ModemCore.setCommandCounter(0); - if (resp) - theGSM3ShieldV1ModemCore.closeCommand(1); - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Write socket first chain main function. -void GSM3ShieldV1MultiClientProvider::beginWriteSocket(bool client1Server0, int id_socket) -{ - idSocket = id_socket; - client1_server0 = client1Server0; - theGSM3ShieldV1ModemCore.openCommand(this,BEGINWRITESOCKET); - beginWriteSocketContinue(); -} - -//Write socket first chain continue function. -void GSM3ShieldV1MultiClientProvider::beginWriteSocketContinue() -{ - bool resp; - // 1: Send AT+QISRVC - // 2: Send AT+QISEND - // 3: wait for > and Write text - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - // AT+QISRVC - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_MultiQISRVC, false); - if (client1_server0) - theGSM3ShieldV1ModemCore.print('1'); - else - theGSM3ShieldV1ModemCore.print('2'); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Response received - if(resp) - { - // AT+QISEND - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QISEND="), false); - theGSM3ShieldV1ModemCore.print(idSocket); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else - { - theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - break; - case 3: - char aux[2]; - aux[0]='>'; - aux[1]=0; - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, aux)) - { - if(resp) - { - // Received ">" - theGSM3ShieldV1ModemCore.closeCommand(1); - } - else - { - theGSM3ShieldV1ModemCore.closeCommand(3); - } - } - break; - } -} - -//Write socket next chain function. -void GSM3ShieldV1MultiClientProvider::writeSocket(const char* buf) -{ - theGSM3ShieldV1ModemCore.print(buf); -} - -//Write socket character function. -void GSM3ShieldV1MultiClientProvider::writeSocket(char c) -{ - theGSM3ShieldV1ModemCore.print(c); -} - -//Write socket last chain main function. -void GSM3ShieldV1MultiClientProvider::endWriteSocket() -{ - theGSM3ShieldV1ModemCore.openCommand(this,ENDWRITESOCKET); - endWriteSocketContinue(); -} - -//Write socket last chain continue function. -void GSM3ShieldV1MultiClientProvider::endWriteSocketContinue() -{ - bool resp; - // 1: Write text (ctrl-Z) - // 2: Wait for OK - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.write(26); // Ctrl-Z - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // OK received - if (resp) theGSM3ShieldV1ModemCore.closeCommand(1); - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Available socket main function. -int GSM3ShieldV1MultiClientProvider::availableSocket(bool client1Server0, int id_socket) -{ - if(flagReadingSocket==1) - { - theGSM3ShieldV1ModemCore.setCommandError(1); - return 1; - } - client1_server0 = client1Server0; - idSocket = id_socket; - theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESOCKET); - availableSocketContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Available socket continue function. -void GSM3ShieldV1MultiClientProvider::availableSocketContinue() -{ - bool resp; - // 1: AT+QIRD - // 2: Wait for OK and Next necessary AT+QIRD - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIRD=0,"),false); - if (client1_server0) - theGSM3ShieldV1ModemCore.print('1'); - else - theGSM3ShieldV1ModemCore.print('2'); - theGSM3ShieldV1ModemCore.print(','); - theGSM3ShieldV1ModemCore.print(idSocket); - theGSM3ShieldV1ModemCore.print(",1500"); - // theGSM3ShieldV1ModemCore.print(",120"); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(parseQIRD_head(resp)) - { - if (!resp) - { - theGSM3ShieldV1ModemCore.closeCommand(4); - } - else - { - flagReadingSocket=1; - theGSM3ShieldV1ModemCore.closeCommand(1); - } - } - else - { - theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Read Socket Parse head. -bool GSM3ShieldV1MultiClientProvider::parseQIRD_head(bool& rsp) -{ - char _qird [8]; - prepareAuxLocate(PSTR("+QIRD:"), _qird); - fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3); - if(theGSM3ShieldV1ModemCore.theBuffer().locate(_qird)) - { - theGSM3ShieldV1ModemCore.theBuffer().chopUntil(_qird, true); - // Saving more memory, reuse _qird - _qird[0]='\n'; - _qird[1]=0; - theGSM3ShieldV1ModemCore.theBuffer().chopUntil(_qird, true); - rsp = true; - return true; - } - else if(theGSM3ShieldV1ModemCore.theBuffer().locate("OK")) - { - rsp = false; - return true; - } - else - { - rsp = false; - return false; - } -} -/* -//Read socket main function. -int GSM3ShieldV1MultiClientProvider::readSocket() -{ - char charSocket; - charSocket = theGSM3ShieldV1ModemCore.theBuffer().read(); - //Case buffer not full - if (!fullBufferSocket) - { - //The last part of the buffer after data is CRLFOKCRLF - if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==125) - { - //Start again availableSocket function. - flagReadingSocket=0; - theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESOCKET); - availableSocketContinue(); - } - } - else if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==127) - { - // The buffer is full, no more action is possible until we have read() - theGSM3ShieldV1ModemCore.theBuffer().flush(); - flagReadingSocket = 1; - theGSM3ShieldV1ModemCore.openCommand(this,XON); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - //A small delay to assure data received after xon. - delay(10); - } - //To distinguish the case no more available data in socket. - if (ready()==1) - return charSocket; - else - return 0; -} -*/ -int GSM3ShieldV1MultiClientProvider::readSocket() -{ - char charSocket; - - if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==0) - { - Serial.println();Serial.println("*"); - return 0; - } - - charSocket = theGSM3ShieldV1ModemCore.theBuffer().read(); - //Case buffer not full - if (!fullBufferSocket) - { - //The last part of the buffer after data is CRLFOKCRLF - if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==125) - { - //Start again availableSocket function. - flagReadingSocket=0; - theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESOCKET); - availableSocketContinue(); - } - } - else if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()>=100) - { - // The buffer was full, we have to let the data flow again - // theGSM3ShieldV1ModemCore.theBuffer().flush(); - flagReadingSocket = 1; - theGSM3ShieldV1ModemCore.openCommand(this,XON); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - //A small delay to assure data received after xon. - delay(100); - if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes() >=6) - fullBufferSocket=false; - } - - return charSocket; - -} - -//Read socket main function. -int GSM3ShieldV1MultiClientProvider::peekSocket() -{ - return theGSM3ShieldV1ModemCore.theBuffer().peek(0); -} - - -//Flush SMS main function. -void GSM3ShieldV1MultiClientProvider::flushSocket() -{ - flagReadingSocket=0; - theGSM3ShieldV1ModemCore.openCommand(this,FLUSHSOCKET); - flushSocketContinue(); -} - -//Send SMS continue function. -void GSM3ShieldV1MultiClientProvider::flushSocketContinue() -{ - bool resp; - // 1: Deleting SMS - // 2: wait for OK - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //DEBUG - //Serial.println("Flushing Socket."); - theGSM3ShieldV1ModemCore.theBuffer().flush(); - if (fullBufferSocket) - { - //Serial.println("Buffer flushed."); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - } - else - { - //Serial.println("Socket flushed completely."); - theGSM3ShieldV1ModemCore.closeCommand(1); - } - break; - } -} - -//URC recognize. -// Momentarily, we will not recognize "closes" in client mode -bool GSM3ShieldV1MultiClientProvider::recognizeUnsolicitedEvent(byte oldTail) -{ - return false; -} - -int GSM3ShieldV1MultiClientProvider::getSocket(int socket) -{ - if(socket==-1) - { - int i; - for(i=minSocket(); i<=maxSocket(); i++) - { - if (!(sockets&(0x0001<8) - return 0; - if(sockets&(0x0001< -#include - -class GSM3ShieldV1MultiClientProvider : public GSM3MobileClientProvider, public GSM3ShieldV1BaseProvider -{ - private: - - int remotePort; // Current operation remote port - int idSocket; // Remote ID socket - IPAddress remoteIP; // Remote IP address - - uint16_t sockets; - - /** Continue to connect TCP client function - */ - void connectTCPClientContinue(); - - /** Continue to disconnect TCP client function - */ - void disconnectTCPContinue(); - - /** Continue to begin socket for write function - */ - void beginWriteSocketContinue(); - - /** Continue to end write socket function - */ - void endWriteSocketContinue(); - - /** Continue to available socket function - */ - void availableSocketContinue(); - - /** Continue to flush socket function - */ - void flushSocketContinue(); - - // GATHER! - bool flagReadingSocket; //In case socket data being read, update fullBufferSocket in the next buffer. - bool fullBufferSocket; //To detect if the socket data being read needs another buffer. - bool client1_server0; //1 Client, 0 Server. - - /** Parse QIRD response - @param rsp Returns true if expected response exists - @return true if command executed correctly - */ - bool parseQIRD_head(bool& rsp); - - public: - - /** Constructor */ - GSM3ShieldV1MultiClientProvider(); - - /** Minimum socket - @return 0 - */ - int minSocket(){return 0;}; - - /** Maximum socket - @return 5 - */ - int maxSocket(){return 5;}; - - /** Connect to a remote TCP server - @param server String with IP or server name - @param port Remote port number - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - int connectTCPClient(const char* server, int port, int id_socket); - - /** Connect to a remote TCP server - @param add Remote IP address - @param port Remote port number - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - int connectTCPClient(IPAddress add, int port, int id_socket); - - /** Begin writing through a socket - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - void beginWriteSocket(bool client1Server0, int id_socket); - - /** Write through a socket. MUST go after beginWriteSocket() - @param buf characters to be written (final 0 will not be written) - */ - void writeSocket(const char* buf); - - /** Write through a socket. MUST go after beginWriteSocket() - @param c character to be written - */ - void writeSocket(char c); - - /** Finish current writing - */ - void endWriteSocket(); - - /** Check if there are data to be read in socket. - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if there are data available, 4 if no data, otherwise error - */ - int availableSocket(bool client, int id_socket); // With "available" and "readSocket" ask the modem for 1500 bytes. - - /** Read a character from socket - @return socket - */ - int readSocket(); //If Read() gets to the end of the QIRD response, execute again QIRD SYNCHRONOUSLY - - /** Flush socket - */ - void flushSocket(); - - /** Get a character but will not advance the buffer head - @return character - */ - int peekSocket(); - - /** Close a socket - @param client1Server0 1 if modem acts as client, 0 if acts as server - @param id_socket Local socket number - @return 0 if command running, 1 if success, otherwise error - */ - int disconnectTCP(bool client1Server0, int id_socket); - - /** Recognize unsolicited event - @param from - @return true if successful - */ - bool recognizeUnsolicitedEvent(byte from); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - /** Get client socket - @param socket - @return socket - */ - int getSocket(int socket=-1); - - /** Release socket - @param socket Socket for release - */ - void releaseSocket(int socket); - - /** Get socket client status - @param socket Socket - @return socket client status - */ - bool getStatusSocketClient(uint8_t socket); - -}; - - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1MultiServerProvider.cpp b/libraries/GSM/GSM3ShieldV1MultiServerProvider.cpp deleted file mode 100644 index 6a915f2..0000000 --- a/libraries/GSM/GSM3ShieldV1MultiServerProvider.cpp +++ /dev/null @@ -1,357 +0,0 @@ -#include -#include -#include - -#define __NCLIENTS_MAX__ 3 - -char _command_QILOCIP[] PROGMEM = "AT+QILOCIP"; - -GSM3ShieldV1MultiServerProvider::GSM3ShieldV1MultiServerProvider() -{ - theGSM3MobileServerProvider=this; - socketsAsServer=0; - socketsAccepted=0; - theGSM3ShieldV1ModemCore.registerUMProvider(this); -}; - -//Response management. -void GSM3ShieldV1MultiServerProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case NONE: - theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from); - break; - case CONNECTSERVER: - connectTCPServerContinue(); - break; - case GETIP: - getIPContinue(); - break; - } -} - -//Connect Server main function. -int GSM3ShieldV1MultiServerProvider::connectTCPServer(int port) -{ - // We forget about LocalIP as it has no real use, the modem does whatever it likes - theGSM3ShieldV1ModemCore.setPort(port); - theGSM3ShieldV1ModemCore.openCommand(this,CONNECTSERVER); - connectTCPServerContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Connect Server continue function. -void GSM3ShieldV1MultiServerProvider::connectTCPServerContinue() -{ - - bool resp; - // 1: Read Local IP "AT+QILOCIP" - // 2: Waiting for IP and Set local port "AT+QILPORT" - // 3: Waiting for QILPOR OK andConfigure as server "AT+QISERVER" - // 4: Wait for SERVER OK - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //"AT+QILOCIP." - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_QILOCIP); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - //Not IP storing but the command is necessary. - //if(parseQILOCIP_rsp(local_IP, local_IP_Length, resp)) - // This awful trick saves some RAM bytes - char aux[3]; - aux[0]='\r';aux[1]='\n';aux[2]=0; - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, aux)) - { - //Response received - if(resp) - { - // Great. Go for the next step - // AT+QILPORT - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILPORT=\"TCP\","),false); - theGSM3ShieldV1ModemCore.print( theGSM3ShieldV1ModemCore.getPort()); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - case 3: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Response received - if(resp) - { - // OK received - // Great. Go for the next step - // AT+QISERVER - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QISERVER=0,"),false); - theGSM3ShieldV1ModemCore.print(__NCLIENTS_MAX__); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(4); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - case 4: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Response received - // OK received, kathapoon, chessespoon - if (resp) theGSM3ShieldV1ModemCore.closeCommand(1); - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//QILOCIP parse. -bool GSM3ShieldV1MultiServerProvider::parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp) -{ - if (!(theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("\r\n","\r\n", LocalIP, LocalIPlength))) - rsp = false; - else - rsp = true; - return true; -} - -//Get IP main function. -int GSM3ShieldV1MultiServerProvider::getIP(char* LocalIP, int LocalIPlength) -{ - theGSM3ShieldV1ModemCore.setPhoneNumber(LocalIP); - theGSM3ShieldV1ModemCore.setPort(LocalIPlength); - theGSM3ShieldV1ModemCore.openCommand(this,GETIP); - getIPContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -void GSM3ShieldV1MultiServerProvider::getIPContinue() -{ - - bool resp; - // 1: Read Local IP "AT+QILOCIP" - // 2: Waiting for IP. - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //AT+QILOCIP - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_QILOCIP); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(parseQILOCIP_rsp(theGSM3ShieldV1ModemCore.getPhoneNumber(), theGSM3ShieldV1ModemCore.getPort(), resp)) - { - if (resp) - theGSM3ShieldV1ModemCore.closeCommand(1); - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -bool GSM3ShieldV1MultiServerProvider::getSocketAsServerModemStatus(int s) -{ - if (socketsAccepted&(0x0001< -#include - -class GSM3ShieldV1MultiServerProvider : public GSM3MobileServerProvider, public GSM3ShieldV1BaseProvider -{ - private: - - // Used sockets - uint8_t socketsAsServer; - uint8_t socketsAccepted; - - /** Continue to connect TCP server function - */ - void connectTCPServerContinue(); - - /** Continue to get IP function - */ - void getIPContinue(); - - /** Release socket - @param socket Socket - */ - void releaseSocket(int socket); - - /** Parse QILOCIP response - @param LocalIP Buffer for save local IP address - @param LocalIPlength Buffer size - @param rsp Returns if expected response exists - @return true if command executed correctly - */ - bool parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp); - - public: - - /** Constructor */ - GSM3ShieldV1MultiServerProvider(); - - /** minSocketAsServer - @return 0 - */ - int minSocketAsServer(){return 0;}; - - /** maxSocketAsServer - @return 0 - */ - int maxSocketAsServer(){return 4;}; - - /** Get modem status - @param s - @return modem status (true if connected) - */ - bool getSocketAsServerModemStatus(int s); - - /** Get new occupied socket as server - @return command error if exists - */ - int getNewOccupiedSocketAsServer(); - - /** Connect server to TCP port - @param port TCP port - @return command error if exists - */ - int connectTCPServer(int port); - - /** Get server IP address - @param LocalIP Buffer for copy IP address - @param LocalIPlength Length of buffer - @return command error if exists - */ - int getIP(char* LocalIP, int LocalIPlength); - -// int disconnectTCP(bool client1Server0, int id_socket); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - /** Get socket status as server - @param socket Socket to get status - @return socket status - */ - bool getStatusSocketAsServer(uint8_t socket); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - /** Recognize unsolicited event - @param oldTail - @return true if successful - */ - bool recognizeUnsolicitedEvent(byte oldTail); - - -}; - -#endif diff --git a/libraries/GSM/GSM3ShieldV1PinManagement.cpp b/libraries/GSM/GSM3ShieldV1PinManagement.cpp deleted file mode 100644 index 0c0c749..0000000 --- a/libraries/GSM/GSM3ShieldV1PinManagement.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ - -#include - -// constructor -GSM3ShieldV1PinManagement::GSM3ShieldV1PinManagement() -{ -}; - -// reset the modem for direct access -void GSM3ShieldV1PinManagement::begin() -{ - // reset hardware - gsm.HWrestart(); - - pin_used = false; - - // check modem response - modemAccess.writeModemCommand("AT", 1000); - modemAccess.writeModemCommand("ATE0", 1000); -} - -/* - Check PIN status -*/ -int GSM3ShieldV1PinManagement::isPIN() -{ - String res = modemAccess.writeModemCommand("AT+CPIN?",1000); - // Check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "READY") != NULL) - return 0; - else if(strstr(res_to_compare, "SIM PIN") != NULL) - return 1; - else if(strstr(res_to_compare, "SIM PUK") != NULL) - return -1; - else - return -2; -} - -/* - Check PIN code -*/ -int GSM3ShieldV1PinManagement::checkPIN(String pin) -{ - String res = modemAccess.writeModemCommand("AT+CPIN=" + pin,1000); - // check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "OK") == NULL) - return -1; - else - return 0; -} - -/* - Check PUK code -*/ -int GSM3ShieldV1PinManagement::checkPUK(String puk, String pin) -{ - String res = modemAccess.writeModemCommand("AT+CPIN=\"" + puk + "\",\"" + pin + "\"",1000); - // check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "OK") == NULL) - return -1; - else - return 0; -} - -/* - Change PIN code -*/ -void GSM3ShieldV1PinManagement::changePIN(String old, String pin) -{ - String res = modemAccess.writeModemCommand("AT+CPWD=\"SC\",\"" + old + "\",\"" + pin + "\"",2000); - Serial.println(res); - // check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "OK") != NULL) - Serial.println("Pin changed succesfully."); - else - Serial.println("ERROR"); -} - -/* - Switch PIN status -*/ -void GSM3ShieldV1PinManagement::switchPIN(String pin) -{ - String res = modemAccess.writeModemCommand("AT+CLCK=\"SC\",2",1000); - // check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "0") != NULL) - { - res = modemAccess.writeModemCommand("AT+CLCK=\"SC\",1,\"" + pin + "\"",1000); - // check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "OK") == NULL) - { - Serial.println("ERROR"); - pin_used = false; - } - else - { - Serial.println("OK. PIN lock on."); - pin_used = true; - } - } - else if(strstr(res_to_compare, "1") != NULL) - { - res = modemAccess.writeModemCommand("AT+CLCK=\"SC\",0,\"" + pin + "\"",1000); - // check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "OK") == NULL) - { - Serial.println("ERROR"); - pin_used = true; - } - else - { - Serial.println("OK. PIN lock off."); - pin_used = false; - } - } - else - { - Serial.println("ERROR"); - } -} - -/* - Check registrer -*/ -int GSM3ShieldV1PinManagement::checkReg() -{ - delay(5000); - String res = modemAccess.writeModemCommand("AT+CREG?",1000); - // check response - char res_to_compare[res.length()]; - res.toCharArray(res_to_compare, res.length()); - if(strstr(res_to_compare, "1") != NULL) - return 0; - else if(strstr(res_to_compare, "5") != NULL) - return 1; - else - return -1; -} - -/* - Return if PIN lock is used -*/ -bool GSM3ShieldV1PinManagement::getPINUsed() -{ - return pin_used; -} - -/* - Set if PIN lock is used -*/ -void GSM3ShieldV1PinManagement::setPINUsed(bool used) -{ - pin_used = used; -} \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1PinManagement.h b/libraries/GSM/GSM3ShieldV1PinManagement.h deleted file mode 100644 index ce43cdd..0000000 --- a/libraries/GSM/GSM3ShieldV1PinManagement.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3SHIELDV1PINMANAGEMENT_ -#define _GSM3SHIELDV1PINMANAGEMENT_ - -#include -#include - -class GSM3ShieldV1PinManagement -{ - - private: - - GSM3ShieldV1AccessProvider gsm; // GSM access required for network register with PIN code - GSM3ShieldV1DirectModemProvider modemAccess; - bool pin_used; // determines if pin lock is activated - - public: - - /** Constructor */ - GSM3ShieldV1PinManagement(); - - /** Check modem response and restart it - */ - void begin(); - - /** Check if PIN lock or PUK lock is activated - @return 0 if PIN lock is off, 1 if PIN lock is on, -1 if PUK lock is on, -2 if error exists - */ - int isPIN(); - - /** Check if PIN code is correct and valid - @param pin PIN code - @return 0 if is correct, -1 if is incorrect - */ - int checkPIN(String pin); - - /** Check if PUK code is correct and establish new PIN code - @param puk PUK code - @param pin New PIN code - @return 0 if successful, otherwise return -1 - */ - int checkPUK(String puk, String pin); - - /** Change PIN code - @param old Old PIN code - @param pin New PIN code - */ - void changePIN(String old, String pin); - - /** Change PIN lock status - @param pin PIN code - */ - void switchPIN(String pin); - - /** Check if modem was registered in GSM/GPRS network - @return 0 if modem was registered, 1 if modem was registered in roaming, -1 if error exists - */ - int checkReg(); - - /** Return if PIN lock is used - @return true if PIN lock is used, otherwise, return false - */ - bool getPINUsed(); - - /** Set PIN lock status - @param used New PIN lock status - */ - void setPINUsed(bool used); -}; - -#endif; \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1SMSProvider.cpp b/libraries/GSM/GSM3ShieldV1SMSProvider.cpp deleted file mode 100644 index 9ed075e..0000000 --- a/libraries/GSM/GSM3ShieldV1SMSProvider.cpp +++ /dev/null @@ -1,293 +0,0 @@ -#include -#include - -GSM3ShieldV1SMSProvider::GSM3ShieldV1SMSProvider() -{ - theGSM3SMSProvider=this; -}; - -//Send SMS begin function. -int GSM3ShieldV1SMSProvider::beginSMS(const char* to) -{ - if((theGSM3ShieldV1ModemCore.getStatus() != GSM_READY)&&(theGSM3ShieldV1ModemCore.getStatus() != GPRS_READY)) - return 2; - - theGSM3ShieldV1ModemCore.setPhoneNumber((char*)to); - theGSM3ShieldV1ModemCore.openCommand(this,BEGINSMS); - beginSMSContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Send SMS continue function. -void GSM3ShieldV1SMSProvider::beginSMSContinue() -{ - bool resp; - // 1: Send AT - // 2: wait for > and write text - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.setCommandCounter(2); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGS=\""), false); - theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber()); - theGSM3ShieldV1ModemCore.print("\"\r"); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, ">")) - { - if (resp) theGSM3ShieldV1ModemCore.closeCommand(1); - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Send SMS write function. -void GSM3ShieldV1SMSProvider::writeSMS(char c) -{ - theGSM3ShieldV1ModemCore.write(c); -} - -//Send SMS begin function. -int GSM3ShieldV1SMSProvider::endSMS() -{ - theGSM3ShieldV1ModemCore.openCommand(this,ENDSMS); - endSMSContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Send SMS continue function. -void GSM3ShieldV1SMSProvider::endSMSContinue() -{ - bool resp; - // 1: Send #26 - // 2: wait for OK - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.setCommandCounter(2); - theGSM3ShieldV1ModemCore.write(26); - theGSM3ShieldV1ModemCore.print("\r"); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if (resp) - theGSM3ShieldV1ModemCore.closeCommand(1); - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Available SMS main function. -int GSM3ShieldV1SMSProvider::availableSMS() -{ - flagReadingSMS = 0; - theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESMS); - availableSMSContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Available SMS continue function. -void GSM3ShieldV1SMSProvider::availableSMSContinue() -{ - // 1: AT+CMGL="REC UNREAD",1 - // 2: Receive +CMGL: _id_ ... READ","_numero_" ... \n_mensaje_\nOK - // 3: Send AT+CMGD= _id_ - // 4: Receive OK - // 5: Remaining SMS text in case full buffer. - // This implementation really does not care much if the modem aswers trash to CMGL - bool resp; - //int msglength_aux; - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGL=\"REC UNREAD\",1")); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(parseCMGL_available(resp)) - { - if (!resp) theGSM3ShieldV1ModemCore.closeCommand(4); - else theGSM3ShieldV1ModemCore.closeCommand(1); - } - break; - } - -} - -//SMS available parse. -bool GSM3ShieldV1SMSProvider::parseCMGL_available(bool& rsp) -{ - fullBufferSMS = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<=4); - if (!(theGSM3ShieldV1ModemCore.theBuffer().chopUntil("+CMGL:", true))) - rsp = false; - else - rsp = true; - idSMS=theGSM3ShieldV1ModemCore.theBuffer().readInt(); - - //If there are 2 SMS in buffer, response is ...CRLFCRLF+CMGL - twoSMSinBuffer = theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\n+"); - - checkSecondBuffer = 0; - - return true; -} - -//remoteNumber SMS function. -int GSM3ShieldV1SMSProvider::remoteSMSNumber(char* number, int nlength) -{ - theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("READ\",\"", "\"", number, nlength); - - return 1; -} - -//remoteNumber SMS function. -int GSM3ShieldV1SMSProvider::readSMS() -{ - char charSMS; - //First char. - if (!flagReadingSMS) - { - flagReadingSMS = 1; - theGSM3ShieldV1ModemCore.theBuffer().chopUntil("\n", true); - } - charSMS = theGSM3ShieldV1ModemCore.theBuffer().read(); - - //Second Buffer. - if (checkSecondBuffer) - { - checkSecondBuffer = 0; - twoSMSinBuffer = theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\n+"); - } - - //Case the last char in buffer. - if ((!twoSMSinBuffer)&&fullBufferSMS&&(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==127)) - { - theGSM3ShieldV1ModemCore.theBuffer().flush(); - fullBufferSMS = 0; - checkSecondBuffer = 1; - theGSM3ShieldV1ModemCore.openCommand(this,XON); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - delay(10); - - return charSMS; - } - //Case two SMS in buffer - else if (twoSMSinBuffer) - { - if (theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\n+")) - { - return charSMS; - } - else - { - theGSM3ShieldV1ModemCore.theBuffer().flush(); - theGSM3ShieldV1ModemCore.openCommand(this,XON); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - delay(10); - return 0; - } - } - //Case 1 SMS and buffer not full - else if (!fullBufferSMS) - { - if (theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\nOK")) - { - return charSMS; - } - else - { - theGSM3ShieldV1ModemCore.theBuffer().flush(); - theGSM3ShieldV1ModemCore.openCommand(this,XON); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - delay(10); - return 0; - } - } - //Case to read all the chars in buffer to the end. - else - { - return charSMS; - } -} - -//Read socket main function. -int GSM3ShieldV1SMSProvider::peekSMS() -{ - if (!flagReadingSMS) - { - flagReadingSMS = 1; - theGSM3ShieldV1ModemCore.theBuffer().chopUntil("\n", true); - } - - return theGSM3ShieldV1ModemCore.theBuffer().peek(0); -} - -//Flush SMS main function. -void GSM3ShieldV1SMSProvider::flushSMS() -{ - - //With this, sms data can fill up to 2x128+5x128 bytes. - for (int aux = 0;aux<5;aux++) - { - theGSM3ShieldV1ModemCore.theBuffer().flush(); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - delay(10); - } - - theGSM3ShieldV1ModemCore.openCommand(this,FLUSHSMS); - flushSMSContinue(); -} - -//Send SMS continue function. -void GSM3ShieldV1SMSProvider::flushSMSContinue() -{ - bool resp; - // 1: Deleting SMS - // 2: wait for OK - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.setCommandCounter(2); - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGD="), false); - theGSM3ShieldV1ModemCore.print(idSMS); - theGSM3ShieldV1ModemCore.print("\r"); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - if (resp) theGSM3ShieldV1ModemCore.closeCommand(1); - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -void GSM3ShieldV1SMSProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { -/* case XON: - if (flagReadingSocket) - { -// flagReadingSocket = 0; - fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3); - } - else theGSM3ShieldV1ModemCore.openCommand(this,NONE); - break; -*/ case NONE: - theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from); - break; - case BEGINSMS: - beginSMSContinue(); - break; - case ENDSMS: - endSMSContinue(); - break; - case AVAILABLESMS: - availableSMSContinue(); - break; - case FLUSHSMS: - flushSMSContinue(); - break; - } -} diff --git a/libraries/GSM/GSM3ShieldV1SMSProvider.h b/libraries/GSM/GSM3ShieldV1SMSProvider.h deleted file mode 100644 index 408da33..0000000 --- a/libraries/GSM/GSM3ShieldV1SMSProvider.h +++ /dev/null @@ -1,130 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_SHIELDV1SMSPROVIDER__ -#define __GSM3_SHIELDV1SMSPROVIDER__ - -#include -#include -#include - - -class GSM3ShieldV1SMSProvider : public GSM3MobileSMSProvider, public GSM3ShieldV1BaseProvider -{ - public: - GSM3ShieldV1SMSProvider(); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - /** Begin a SMS to send it - @param to Destination - @return error command if it exists - */ - inline int beginSMS(const char* to); - - /** Write a SMS character by character - @param c Character - */ - inline void writeSMS(char c); - - /** End SMS - @return error command if it exists - */ - inline int endSMS(); - - /** Check if SMS available and prepare it to be read - @return number of bytes in a received SMS - */ - int availableSMS(); - - /** Read a byte but do not advance the buffer header (circular buffer) - @return character - */ - int peekSMS(); - - /** Delete the SMS from Modem memory and proccess answer - */ - void flushSMS(); - - /** Read sender number phone - @param number Buffer for save number phone - @param nlength Buffer length - @return 1 success, >1 error - */ - int remoteSMSNumber(char* number, int nlength); //Before reading the SMS, read the phone number. - - /** Read one char for SMS buffer (advance circular buffer) - @return character - */ - int readSMS(); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - private: - - int idSMS; // Id from current SMS being read. - bool flagReadingSMS; // To detect first SMS char if not yet reading. - bool fullBufferSMS; // To detect if the SMS being read needs another buffer. - bool twoSMSinBuffer; // To detect if the buffer has more than 1 SMS. - bool checkSecondBuffer; // Pending to detect if the second buffer has more than 1 SMS. - - /** Continue to begin SMS function - */ - void beginSMSContinue(); - - /** Continue to end SMS function - */ - void endSMSContinue(); - - /** Continue to available SMS function - */ - void availableSMSContinue(); - - /** Continue to flush SMS function - */ - void flushSMSContinue(); - - /** Parse CMGL response - @param rsp Returns true if expected response exists - @return true if command executed correctly - */ - bool parseCMGL_available(bool& rsp); -}; -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1ScanNetworks.cpp b/libraries/GSM/GSM3ShieldV1ScanNetworks.cpp deleted file mode 100644 index 23da8a6..0000000 --- a/libraries/GSM/GSM3ShieldV1ScanNetworks.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ - -#include - -GSM3ShieldV1ScanNetworks::GSM3ShieldV1ScanNetworks(bool trace): modem(trace) -{ -} - -GSM3_NetworkStatus_t GSM3ShieldV1ScanNetworks::begin() -{ - modem.begin(); - modem.restartModem(); - // check modem response - modem.writeModemCommand("AT", 1000); - modem.writeModemCommand("ATE0", 1000); - return IDLE; -} - -String GSM3ShieldV1ScanNetworks::getCurrentCarrier() -{ - String modemResponse = modem.writeModemCommand("AT+COPS?", 2000); - - // Parse and check response - char res_to_split[modemResponse.length()]; - modemResponse.toCharArray(res_to_split, modemResponse.length()); - if(strstr(res_to_split,"ERROR") == NULL){ - // Tokenizer - char *ptr_token; - ptr_token = strtok(res_to_split, "\""); - ptr_token = strtok(NULL, "\""); - String final_result = ptr_token; - return final_result; - }else{ - return NULL; - } -} - -String GSM3ShieldV1ScanNetworks::getSignalStrength() -{ - String modemResponse = modem.writeModemCommand("AT+CSQ", 2000); - char res_to_split[modemResponse.length()]; - modemResponse.toCharArray(res_to_split, modemResponse.length()); - if((strstr(res_to_split,"ERROR") == NULL) | (strstr(res_to_split,"99") == NULL)){ - // Tokenizer - char *ptr_token; - ptr_token = strtok(res_to_split, ":"); - ptr_token = strtok(NULL, ":"); - ptr_token = strtok(ptr_token, ","); - String final_result = ptr_token; - final_result.trim(); - return final_result; - }else{ - return NULL; - } -} - -String GSM3ShieldV1ScanNetworks::readNetworks() -{ - String modemResponse = modem.writeModemCommand("AT+COPS=?",20000); - String result; - bool inQuotes=false; - int quoteCounter=0; - for(int i=0; i -#include - -class GSM3ShieldV1ScanNetworks -{ - private: - GSM3ShieldV1DirectModemProvider modem; - - public: - - /** Constructor - @param trace if true, dumps all AT dialogue to Serial - @return - - */ - GSM3ShieldV1ScanNetworks(bool trace=false); - - /** begin (forces modem hardware restart, so we begin from scratch) - @return Always returns IDLE status - */ - GSM3_NetworkStatus_t begin(); - - /** Read current carrier - @return Current carrier - */ - String getCurrentCarrier(); - - /** Obtain signal strength - @return Signal Strength - */ - String getSignalStrength(); - - /** Search available carriers - @return A string with list of networks available - */ - String readNetworks(); -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1ServerProvider.cpp b/libraries/GSM/GSM3ShieldV1ServerProvider.cpp deleted file mode 100644 index 77f5436..0000000 --- a/libraries/GSM/GSM3ShieldV1ServerProvider.cpp +++ /dev/null @@ -1,205 +0,0 @@ -#include -#include -#include - -GSM3ShieldV1ServerProvider::GSM3ShieldV1ServerProvider() -{ - theGSM3MobileServerProvider=this; -}; - -//Response management. -void GSM3ShieldV1ServerProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case NONE: - theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from); - break; - case CONNECTSERVER: - connectTCPServerContinue(); - break; - /*case GETIP: - getIPContinue(); - break;*/ - } -} - -//Connect Server main function. -int GSM3ShieldV1ServerProvider::connectTCPServer(int port) -{ - // We forget about LocalIP as it has no real use, the modem does whatever it likes - theGSM3ShieldV1ModemCore.setPort(port); - theGSM3ShieldV1ModemCore.openCommand(this,CONNECTSERVER); - // From this moment on we wait for a call - connectTCPServerContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Connect Server continue function. -void GSM3ShieldV1ServerProvider::connectTCPServerContinue() -{ - - bool resp; - // 1: Read Local IP "AT+QILOCIP" - // 2: Waiting for IP and Set local port "AT+QILPORT" - // 3: Waiting for QILPOR OK andConfigure as server "AT+QISERVER" - // 4: Wait for SERVER OK - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //"AT+QILOCIP." - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILOCIP")); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - //Not IP storing but the command is necessary. - //if(parseQILOCIP_rsp(local_IP, local_IP_Length, resp)) - // This awful trick saves some RAM bytes - char aux[3]; - aux[0]='\r';aux[1]='\n';aux[2]=0; - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, aux)) - { - //Response received - if(resp) - { - // Great. Go for the next step - // AT+QILPORT - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILPORT=\"TCP\","),false); - theGSM3ShieldV1ModemCore.print( theGSM3ShieldV1ModemCore.getPort()); - theGSM3ShieldV1ModemCore.print('\r'); - theGSM3ShieldV1ModemCore.setCommandCounter(3); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - case 3: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Response received - if(resp) - { - // OK received - // Great. Go for the next step - // AT+QISERVER - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QISERVER"),true); - theGSM3ShieldV1ModemCore.setCommandCounter(4); - } - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - case 4: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - // Response received - // OK received, kathapoon, chessespoon - if (resp) - { - theGSM3ShieldV1ModemCore.registerUMProvider(this); - theGSM3ShieldV1ModemCore.closeCommand(1); - } - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//QILOCIP parse. -/*bool GSM3ShieldV1ServerProvider::parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp) -{ - if (!(theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("\r\n","\r\n", LocalIP, LocalIPlength))) - rsp = false; - else - rsp = true; - return true; -} - -//Get IP main function. -int GSM3ShieldV1ServerProvider::getIP(char* LocalIP, int LocalIPlength) -{ - theGSM3ShieldV1ModemCore.setPhoneNumber(LocalIP); - theGSM3ShieldV1ModemCore.setPort(LocalIPlength); - theGSM3ShieldV1ModemCore.openCommand(this,GETIP); - getIPContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -void GSM3ShieldV1ServerProvider::getIPContinue() -{ - - bool resp; - // 1: Read Local IP "AT+QILOCIP" - // 2: Waiting for IP. - - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //AT+QILOCIP - theGSM3ShieldV1ModemCore.genericCommand_rq(_command_MonoQILOCIP); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(parseQILOCIP_rsp(theGSM3ShieldV1ModemCore.getPhoneNumber(), theGSM3ShieldV1ModemCore.getPort(), resp)) - { - if (resp) - theGSM3ShieldV1ModemCore.closeCommand(1); - else - theGSM3ShieldV1ModemCore.closeCommand(3); - } - theGSM3ShieldV1ModemCore.theBuffer().flush(); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - break; - } -}*/ - -bool GSM3ShieldV1ServerProvider::getSocketAsServerModemStatus(int s) -{ - if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED) - return true; - else - return false; -} - - -//URC recognize. -bool GSM3ShieldV1ServerProvider::recognizeUnsolicitedEvent(byte oldTail) -{ - - int nlength; - char auxLocate [15]; - - //REMOTE SOCKET CLOSED. - prepareAuxLocate(PSTR("CLOSED\r\n"), auxLocate); - if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate)) - { - //To detect remote socket closed for example inside socket data. - theGSM3ShieldV1ModemCore.setStatus(GPRS_READY); - } - - - //REMOTE SOCKET ACCEPTED. - prepareAuxLocate(PSTR("CONNECT\r\n"), auxLocate); - if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate)) - { - //To detect remote socket closed for example inside socket data. - theGSM3ShieldV1ModemCore.theBuffer().chopUntil(auxLocate, true); - theGSM3ShieldV1ModemCore.gss.spaceAvailable(); - theGSM3ShieldV1ModemCore.setStatus(TRANSPARENT_CONNECTED); - return true; - } - - return false; -} - -bool GSM3ShieldV1ServerProvider::getStatusSocketAsServer(uint8_t socket) -{ - return(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED); -}; - -void GSM3ShieldV1ServerProvider::releaseSocket(int socket) -{ -} - -int GSM3ShieldV1ServerProvider::getNewOccupiedSocketAsServer() -{ - return 0; -} \ No newline at end of file diff --git a/libraries/GSM/GSM3ShieldV1ServerProvider.h b/libraries/GSM/GSM3ShieldV1ServerProvider.h deleted file mode 100644 index 93fcd89..0000000 --- a/libraries/GSM/GSM3ShieldV1ServerProvider.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_SHIELDV1SERVERPROVIDER__ -#define __GSM3_SHIELDV1SERVERPROVIDER__ - -#include -#include - -class GSM3ShieldV1ServerProvider : public GSM3MobileServerProvider, public GSM3ShieldV1BaseProvider -{ - private: - - /** Continue to connect to server with TCP protocol function - */ - void connectTCPServerContinue(); - - /** Continue to get IP address function - */ - //void getIPContinue(); - - /** Parse QILOCIP response - @param LocalIP Buffer for save local IP address - @param LocalIPlength Buffer size - @param rsp Returns if expected response exists - @return true if command executed correctly - */ - //bool parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp); - - /** Release socket - @param socket Socket - */ - void releaseSocket(int socket); - - public: - - /** Constructor */ - GSM3ShieldV1ServerProvider(); - - /** minSocketAsServer - @return 0 - */ - int minSocketAsServer(){return 0;}; - - /** maxSocketAsServer - @return 0 - */ - int maxSocketAsServer(){return 0;}; - - /** Get modem status - @param s Socket - @return modem status (true if connected) - */ - bool getSocketAsServerModemStatus(int s); - - /** Get new occupied socket as server - @return return -1 if no new socket has been occupied - */ - int getNewOccupiedSocketAsServer(); - - /** Connect server to TCP port - @param port TCP port - @return command error if exists - */ - int connectTCPServer(int port); - - //int getIP(char* LocalIP, int LocalIPlength); -// int disconnectTCP(bool client1Server0, int id_socket); - - /** Get last command status - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - /** Get socket status as server - @param socket Socket to get status - @return socket status - */ - bool getStatusSocketAsServer(uint8_t socket); - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - /** Recognize unsolicited event - @param oldTail - @return true if successful - */ - bool recognizeUnsolicitedEvent(byte oldTail); - - -}; - -#endif diff --git a/libraries/GSM/GSM3ShieldV1VoiceProvider.cpp b/libraries/GSM/GSM3ShieldV1VoiceProvider.cpp deleted file mode 100644 index 98a50b9..0000000 --- a/libraries/GSM/GSM3ShieldV1VoiceProvider.cpp +++ /dev/null @@ -1,215 +0,0 @@ -#include -#include - -GSM3ShieldV1VoiceProvider::GSM3ShieldV1VoiceProvider() - { - phonelength=0; - theGSM3MobileVoiceProvider=this; - } - - void GSM3ShieldV1VoiceProvider::initialize() - { - theGSM3ShieldV1ModemCore.registerUMProvider(this); - } - -//Voice Call main function. -int GSM3ShieldV1VoiceProvider::voiceCall(const char* to) -{ - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATD"),false); - theGSM3ShieldV1ModemCore.print(to); - theGSM3ShieldV1ModemCore.print(";\r"); - setvoiceCallStatus(CALLING); - return 1; -} - -//Retrieve calling number main function. -int GSM3ShieldV1VoiceProvider::retrieveCallingNumber (char* buffer, int bufsize) -{ - theGSM3ShieldV1ModemCore.setPhoneNumber(buffer); - phonelength = bufsize; - theGSM3ShieldV1ModemCore.setCommandError(0); - theGSM3ShieldV1ModemCore.setCommandCounter(1); - theGSM3ShieldV1ModemCore.openCommand(this,RETRIEVECALLINGNUMBER); - retrieveCallingNumberContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Retrieve calling number Continue function. -void GSM3ShieldV1VoiceProvider::retrieveCallingNumberContinue() -{ - // 1: AT+CLCC - // 2: Receive +CLCC: 1,1,4,0,0,"num",129,"" - // This implementation really does not care much if the modem aswers trash to CMGL - bool resp; - //int msglength_aux; - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CLCC")); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(parseCLCC(theGSM3ShieldV1ModemCore.getPhoneNumber(), phonelength)) - { - theGSM3ShieldV1ModemCore.closeCommand(1); - } - break; - } -} - -//CLCC parse. -bool GSM3ShieldV1VoiceProvider::parseCLCC(char* number, int nlength) -{ - theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("+CLCC: 1,1,4,0,0,\"","\"", number, nlength); - theGSM3ShieldV1ModemCore.theBuffer().flush(); - return true; -} - -//Answer Call main function. -int GSM3ShieldV1VoiceProvider::answerCall() -{ - theGSM3ShieldV1ModemCore.setCommandError(0); - theGSM3ShieldV1ModemCore.setCommandCounter(1); - theGSM3ShieldV1ModemCore.openCommand(this,ANSWERCALL); - answerCallContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Answer Call continue function. -void GSM3ShieldV1VoiceProvider::answerCallContinue() -{ - // 1: ATA - // 2: Waiting for OK - - // This implementation really does not care much if the modem aswers trash to CMGL - bool resp; - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - // ATA ; - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATA")); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - setvoiceCallStatus(TALKING); - if (resp) theGSM3ShieldV1ModemCore.closeCommand(1); - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Hang Call main function. -int GSM3ShieldV1VoiceProvider::hangCall() -{ - theGSM3ShieldV1ModemCore.setCommandError(0); - theGSM3ShieldV1ModemCore.setCommandCounter(1); - theGSM3ShieldV1ModemCore.openCommand(this,HANGCALL); - hangCallContinue(); - return theGSM3ShieldV1ModemCore.getCommandError(); -} - -//Hang Call continue function. -void GSM3ShieldV1VoiceProvider::hangCallContinue() -{ - // 1: ATH - // 2: Waiting for OK - - bool resp; - switch (theGSM3ShieldV1ModemCore.getCommandCounter()) { - case 1: - //ATH - theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATH")); - theGSM3ShieldV1ModemCore.setCommandCounter(2); - break; - case 2: - if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp)) - { - setvoiceCallStatus(IDLE_CALL); - if (resp) theGSM3ShieldV1ModemCore.closeCommand(1); - else theGSM3ShieldV1ModemCore.closeCommand(3); - } - break; - } -} - -//Response management. -void GSM3ShieldV1VoiceProvider::manageResponse(byte from, byte to) -{ - switch(theGSM3ShieldV1ModemCore.getOngoingCommand()) - { - case ANSWERCALL: - answerCallContinue(); - break; - case HANGCALL: - hangCallContinue(); - break; - case RETRIEVECALLINGNUMBER: - retrieveCallingNumberContinue(); - break; - - } -} - -//URC recognize. -bool GSM3ShieldV1VoiceProvider::recognizeUnsolicitedEvent(byte oldTail) -{ - - int nlength; - char auxLocate [15]; - //RING. - prepareAuxLocate(PSTR("RING"), auxLocate); - if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate)) - { - // RING - setvoiceCallStatus(RECEIVINGCALL); - theGSM3ShieldV1ModemCore.theBuffer().flush(); - return true; - } - - //CALL ACEPTED. - prepareAuxLocate(PSTR("+COLP:"), auxLocate); - if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate)) - { - //DEBUG - //Serial.println("Call Accepted."); - setvoiceCallStatus(TALKING); - theGSM3ShieldV1ModemCore.theBuffer().flush(); - return true; - } - - //NO CARRIER. - prepareAuxLocate(PSTR("NO CARRIER"), auxLocate); - if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate)) - { - //DEBUG - //Serial.println("NO CARRIER received."); - setvoiceCallStatus(IDLE_CALL); - theGSM3ShieldV1ModemCore.theBuffer().flush(); - return true; - } - - //BUSY. - prepareAuxLocate(PSTR("BUSY"), auxLocate); - if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate)) - { - //DEBUG - //Serial.println("BUSY received."); - setvoiceCallStatus(IDLE_CALL); - theGSM3ShieldV1ModemCore.theBuffer().flush(); - return true; - } - - //CALL RECEPTION. - prepareAuxLocate(PSTR("+CLIP:"), auxLocate); - if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate)) - { - theGSM3ShieldV1ModemCore.theBuffer().flush(); - setvoiceCallStatus(RECEIVINGCALL); - return true; - } - - return false; -} - - diff --git a/libraries/GSM/GSM3ShieldV1VoiceProvider.h b/libraries/GSM/GSM3ShieldV1VoiceProvider.h deleted file mode 100644 index b961385..0000000 --- a/libraries/GSM/GSM3ShieldV1VoiceProvider.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ - -#ifndef _GSM3SHIELDV1VOICEPROVIDER_ -#define _GSM3SHIELDV1VOICEPROVIDER_ - -#include -#include -#include - -class GSM3ShieldV1VoiceProvider : public GSM3MobileVoiceProvider, public GSM3ShieldV1BaseProvider -{ - public: - - /** Constructor */ - GSM3ShieldV1VoiceProvider(); - - /** initilizer, links with modem provider */ - void initialize(); - - - /** Manages modem response - @param from Initial byte of buffer - @param to Final byte of buffer - */ - void manageResponse(byte from, byte to); - - //Call functions. - - /** Launch a voice call - @param number Phone number to be called - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - int voiceCall(const char* number); - - /** Answer a voice call - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - int answerCall(); - - /** Hang a voice call - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - int hangCall(); - - /** Retrieve phone number of caller - @param buffer Buffer for copy phone number - @param bufsize Buffer size - @return If asynchronous, returns 0. If synchronous, 1 if success, other if error - */ - int retrieveCallingNumber(char* buffer, int bufsize); - - /** Get last command status - @return Returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(){return GSM3ShieldV1BaseProvider::ready();}; - - /** Recognize URC - @param oldTail - @return true if successful - */ - bool recognizeUnsolicitedEvent(byte oldTail); - - /** Returns voice call status - @return voice call status - */ - GSM3_voiceCall_st getvoiceCallStatus(){ready(); return _voiceCallstatus;}; - - /** Set voice call status - @param status New status for voice call - */ - void setvoiceCallStatus(GSM3_voiceCall_st status) { _voiceCallstatus = status; }; - - - private: - - int phonelength; // Phone number length - - GSM3_voiceCall_st _voiceCallstatus; // The voiceCall status - - /** Continue to voice call function - */ - void voiceCallContinue(); - - /** Continue to answer call function - */ - void answerCallContinue(); - - /** Continue to hang call function - */ - void hangCallContinue(); - - /** Continue to retrieve calling number function - */ - void retrieveCallingNumberContinue(); - - /** Parse CLCC response from buffer - @param number Number initial for extract substring of response - @param nlength Substring length - @return true if successful - */ - bool parseCLCC(char* number, int nlength); - -}; - -#endif diff --git a/libraries/GSM/GSM3SoftSerial.cpp b/libraries/GSM/GSM3SoftSerial.cpp deleted file mode 100644 index 176e8cb..0000000 --- a/libraries/GSM/GSM3SoftSerial.cpp +++ /dev/null @@ -1,537 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include "GSM3SoftSerial.h" -#include -#include -#include "pins_arduino.h" -#include -#include - -#if defined(__AVR_ATmega328P__) -#define __TXPIN__ 3 -#define __RXPIN__ 2 -#define __RXINT__ 3 -#elif defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) -#define __TXPIN__ 3 -#define __RXPIN__ 10 -#define __RXINT__ 4 -#elif defined(__AVR_ATmega32U4__) -#define __TXPIN__ 3 -#define __RXPIN__ 8 -#define __RXINT__ 3 -#endif - -#define __XON__ 0x11 -#define __XOFF__ 0x13 - -#define _GSMSOFTSERIALFLAGS_ESCAPED_ 0x01 -#define _GSMSOFTSERIALFLAGS_SENTXOFF_ 0x02 - -// -// Lookup table -// -#define __PARAGRAPHGUARD__ 50 -typedef struct _DELAY_TABLE -{ - long baud; - unsigned short rx_delay_centering; - unsigned short rx_delay_intrabit; - unsigned short rx_delay_stopbit; - unsigned short tx_delay; -} DELAY_TABLE; - -#if F_CPU == 16000000 - -static const DELAY_TABLE PROGMEM table[] = -{ - // baud rxcenter rxintra rxstop tx - { 115200, 1, 17, 17, 12, }, - { 57600, 10, 37, 37, 33, }, - { 38400, 25, 57, 57, 54, }, - { 31250, 31, 70, 70, 68, }, - { 28800, 34, 77, 77, 74, }, - { 19200, 54, 117, 117, 114, }, - { 14400, 74, 156, 156, 153, }, - { 9600, 114, 236, 236, 233, }, - { 4800, 233, 474, 474, 471, }, - { 2400, 471, 950, 950, 947, }, - { 1200, 947, 1902, 1902, 1899, }, - { 300, 3804, 7617, 7617, 7614, }, -}; - -const int XMIT_START_ADJUSTMENT = 5; - -#elif F_CPU == 8000000 - -static const DELAY_TABLE table[] PROGMEM = -{ - // baud rxcenter rxintra rxstop tx - { 115200, 1, 5, 5, 3, }, - { 57600, 1, 15, 15, 13, }, - { 38400, 2, 25, 26, 23, }, - { 31250, 7, 32, 33, 29, }, - { 28800, 11, 35, 35, 32, }, - { 19200, 20, 55, 55, 52, }, - { 14400, 30, 75, 75, 72, }, - { 9600, 50, 114, 114, 112, }, - { 4800, 110, 233, 233, 230, }, - { 2400, 229, 472, 472, 469, }, - { 1200, 467, 948, 948, 945, }, - { 300, 1895, 3805, 3805, 3802, }, -}; - -const int XMIT_START_ADJUSTMENT = 4; - -#elif F_CPU == 20000000 - -// 20MHz support courtesy of the good people at macegr.com. -// Thanks, Garrett! - -static const DELAY_TABLE PROGMEM table[] = -{ - // baud rxcenter rxintra rxstop tx - { 115200, 3, 21, 21, 18, }, - { 57600, 20, 43, 43, 41, }, - { 38400, 37, 73, 73, 70, }, - { 31250, 45, 89, 89, 88, }, - { 28800, 46, 98, 98, 95, }, - { 19200, 71, 148, 148, 145, }, - { 14400, 96, 197, 197, 194, }, - { 9600, 146, 297, 297, 294, }, - { 4800, 296, 595, 595, 592, }, - { 2400, 592, 1189, 1189, 1186, }, - { 1200, 1187, 2379, 2379, 2376, }, - { 300, 4759, 9523, 9523, 9520, }, -}; - -const int XMIT_START_ADJUSTMENT = 6; - -#else - -#error This version of GSM3SoftSerial supports only 20, 16 and 8MHz processors - -#endif - -GSM3SoftSerial* GSM3SoftSerial::_activeObject=0; - -GSM3SoftSerial::GSM3SoftSerial(): - _rx_delay_centering(0), - _rx_delay_intrabit(0), - _rx_delay_stopbit(0), - _tx_delay(0), - cb(this) -{ - setTX(); - setRX(); - //comStatus=0; - //waitingAnswer=false; -} - -int GSM3SoftSerial::begin(long speed) -{ - _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0; - - for (unsigned i=0; ifinalWrite(0x77); - return this->finalWrite(0xEE); - } - - if(c==0x13) - { - this->finalWrite(0x77); - return this->finalWrite(0xEC); - } - - if(c==0x77) - { - this->finalWrite(0x77); - return this->finalWrite(0x88); - } - - return this->finalWrite(c); -} - -size_t GSM3SoftSerial::finalWrite(uint8_t c) -{ - - uint8_t oldSREG = SREG; - cli(); // turn off interrupts for a clean txmit - - // Write the start bit - tx_pin_write(LOW); - tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT); - - // Write each of the 8 bits - for (byte mask = 0x01; mask; mask <<= 1) - { - if (c & mask) // choose bit - tx_pin_write(HIGH); // send 1 - else - tx_pin_write(LOW); // send 0 - tunedDelay(_tx_delay); - } - - tx_pin_write(HIGH); // restore pin to natural state - - SREG = oldSREG; // turn interrupts back on - tunedDelay(_tx_delay); - - return 1; -} - -/*inline*/ void GSM3SoftSerial::tunedDelay(uint16_t delay) { - uint8_t tmp=0; - - asm volatile("sbiw %0, 0x01 \n\t" - "ldi %1, 0xFF \n\t" - "cpi %A0, 0xFF \n\t" - "cpc %B0, %1 \n\t" - "brne .-10 \n\t" - : "+r" (delay), "+a" (tmp) - : "0" (delay) - ); -} - -void GSM3SoftSerial::tx_pin_write(uint8_t pin_state) -{ - // Direct port manipulation is faster than digitalWrite/Read - if (pin_state == LOW) - *_transmitPortRegister &= ~_transmitBitMask; - else - *_transmitPortRegister |= _transmitBitMask; -} - -void GSM3SoftSerial::setTX() -{ - pinMode(__TXPIN__, OUTPUT); - digitalWrite(__TXPIN__, HIGH); - // For digital port direct manipulation - _transmitBitMask = digitalPinToBitMask(__TXPIN__); - uint8_t port = digitalPinToPort(__TXPIN__); - _transmitPortRegister = portOutputRegister(port); -} - -void GSM3SoftSerial::setRX() -{ - pinMode(__RXPIN__, INPUT); - digitalWrite(__RXPIN__, HIGH); // pullup for normal logic! - // For digital port direct manipulation - _receiveBitMask = digitalPinToBitMask(__RXPIN__); - uint8_t port = digitalPinToPort(__RXPIN__); - _receivePortRegister = portInputRegister(port); - -#ifdef __AVR_ATmega32U4__ -//#define __RXINT__ 1 - attachInterrupt(__RXINT__, GSM3SoftSerial::handle_interrupt, FALLING); -#endif - // This line comes from the High Middle Ages... - // attachInterrupt(__RXINT__, GSM3SoftSerial::handle_interrupt, FALLING); -} - -void GSM3SoftSerial::handle_interrupt() -{ - if(_activeObject) - _activeObject->recv(); -} - -uint8_t GSM3SoftSerial::rx_pin_read() -{ - // Digital port manipulation - return *_receivePortRegister & _receiveBitMask; -} - -void GSM3SoftSerial::recv() -{ - -#if GCC_VERSION < 40302 -// Work-around for avr-gcc 4.3.0 OSX version bug -// Preserve the registers that the compiler misses -// (courtesy of Arduino forum user *etracer*) - asm volatile( - "push r18 \n\t" - "push r19 \n\t" - "push r20 \n\t" - "push r21 \n\t" - "push r22 \n\t" - "push r23 \n\t" - "push r26 \n\t" - "push r27 \n\t" - ::); -#endif - - bool firstByte=true; - byte thisHead; - - uint8_t d = 0; - bool morebytes=false; - //bool fullbuffer=(cb.availableBytes()<3); - bool fullbuffer; - bool capturado_fullbuffer = 0; - int i; - byte oldTail; - - // If RX line is high, then we don't see any start bit - // so interrupt is probably not for us - if (!rx_pin_read()) - { - do - { - oldTail=cb.getTail(); - // Wait approximately 1/2 of a bit width to "center" the sample - tunedDelay(_rx_delay_centering); - - fullbuffer=(cb.availableBytes()<6); - - - if(fullbuffer&&(!capturado_fullbuffer)) - tx_pin_write(LOW); - - - // Read each of the 8 bits - for (uint8_t i=0x1; i; i <<= 1) - { - tunedDelay(_rx_delay_intrabit); - uint8_t noti = ~i; - if (rx_pin_read()) - d |= i; - else // else clause added to ensure function timing is ~balanced - d &= noti; - - if(fullbuffer&&(!capturado_fullbuffer)) - { - if((uint8_t)__XOFF__ & i) - tx_pin_write(HIGH); - else - tx_pin_write(LOW); - } - } - - if(fullbuffer&&(!capturado_fullbuffer)) - { - tunedDelay(_rx_delay_intrabit); - tx_pin_write(HIGH); - } - - // So, we know the buffer is full, and we have sent a XOFF - if (fullbuffer) - { - capturado_fullbuffer =1; - _flags |=_GSMSOFTSERIALFLAGS_SENTXOFF_; - } - - - // skip the stop bit - if (!fullbuffer) tunedDelay(_rx_delay_stopbit); - - if(keepThisChar(&d)) - { - cb.write(d); - if(firstByte) - { - firstByte=false; - thisHead=cb.getTail(); - } - } - - - // This part is new. It is used to detect the end of a "paragraph" - // Caveat: the old fashion would let processor a bit of time between bytes, - // that here is lost - // This active waiting avoids drifting - morebytes=false; - // TO-DO. This PARAGRAPHGUARD is empyric. We should test it for every speed - for(i=0;i<__PARAGRAPHGUARD__;i++) - { - tunedDelay(1); - if(!rx_pin_read()) - { - morebytes=true; - break; - } - } - }while(morebytes); - // If we find a line feed, we are at the end of a paragraph - // check! - - if (fullbuffer) - { - // And... go handle it! - if(mgr) - mgr->manageMsg(thisHead, cb.getTail()); - } - else if(d==10) - { - // And... go handle it! - if(mgr) - mgr->manageMsg(thisHead, cb.getTail()); - } - else if (d==32) - { - // And... go handle it! - if(mgr) - mgr->manageMsg(thisHead, cb.getTail()); - } - } - -#if GCC_VERSION < 40302 -// Work-around for avr-gcc 4.3.0 OSX version bug -// Restore the registers that the compiler misses - asm volatile( - "pop r27 \n\t" - "pop r26 \n\t" - "pop r23 \n\t" - "pop r22 \n\t" - "pop r21 \n\t" - "pop r20 \n\t" - "pop r19 \n\t" - "pop r18 \n\t" - ::); -#endif -} - -bool GSM3SoftSerial::keepThisChar(uint8_t* c) -{ - // Horrible things for Quectel XON/XOFF - // 255 is the answer to a XOFF - // It comes just once - if((*c==255)&&(_flags & _GSMSOFTSERIALFLAGS_SENTXOFF_)) - { - _flags ^= _GSMSOFTSERIALFLAGS_SENTXOFF_; - return false; - } - - // 0x77, w, is the escape character - if(*c==0x77) - { - _flags |= _GSMSOFTSERIALFLAGS_ESCAPED_; - return false; - } - - // and these are the escaped codes - if(_flags & _GSMSOFTSERIALFLAGS_ESCAPED_) - { - if(*c==0xEE) - *c=0x11; - else if(*c==0xEC) - *c=0x13; - else if(*c==0x88) - *c=0x77; - - _flags ^= _GSMSOFTSERIALFLAGS_ESCAPED_; - return true; - } - - return true; -} - -void GSM3SoftSerial::spaceAvailable() -{ - // If there is spaceAvailable in the buffer, lets send a XON - finalWrite((byte)__XON__); -} - - -// This is here to avoid problems with Arduino compiler -void GSM3SoftSerialMgr::manageMsg(byte from, byte to){}; - -//#define PCINT1_vect _VECTOR(2) -//#undef PCINT1_vect - -#if defined(PCINT0_vect) -ISR(PCINT0_vect) -{ - GSM3SoftSerial::handle_interrupt(); -} -#endif - -#if defined(PCINT1_vect) -ISR(PCINT1_vect) -{ - GSM3SoftSerial::handle_interrupt(); -} -#endif - -#if defined(PCINT2_vect) -ISR(PCINT2_vect) -{ - GSM3SoftSerial::handle_interrupt(); -} -#endif - -#if defined(PCINT3_vect) -ISR(PCINT3_vect) -{ - GSM3SoftSerial::handle_interrupt(); -} -#endif - diff --git a/libraries/GSM/GSM3SoftSerial.h b/libraries/GSM/GSM3SoftSerial.h deleted file mode 100644 index c35ef68..0000000 --- a/libraries/GSM/GSM3SoftSerial.h +++ /dev/null @@ -1,174 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef __GSM3_SOFTSERIAL__ -#define __GSM3_SOFTSERIAL__ - -// An adaptation of NewSoftSerial for Modem Shields -// Assumes directly that Serial is attached to Pins 2 and 3, not inverse -// We are implementing it because NewSoftSerial does not deal correctly with floods -// of data -#include "GSM3CircularBuffer.h" -#include - -/* -#define _COMSTATUS_ANSWERRECEIVED_ 0x100 -#define _COMSTATUS_SMSRECEIVED_ 0x80 -#define _COMSTATUS_CALLRECEIVED_ 0x40 - -// PLEASE, when accessing the sockets use "for" and >> (bitwise operator) -#define _COMSTATUS_SOCKET6RECEIVED_ 0x20 -#define _COMSTATUS_SOCKET5RECEIVED_ 0x10 -#define _COMSTATUS_SOCKET4RECEIVED_ 0x08 -#define _COMSTATUS_SOCKET3RECEIVED_ 0x04 -#define _COMSTATUS_SOCKET2RECEIVED_ 0x02 -#define _COMSTATUS_SOCKET1RECEIVED_ 0x01 - -#define __CALLTABLEMASK__ 0x3 -*/ - -class GSM3SoftSerialMgr -{ - public: - - /** Manages soft serial message - @param from Initial byte - @param to Final byte - */ - virtual void manageMsg(byte from, byte to); -}; - -// This class manages software serial communications -// Changing it so it doesn't know about modems or whatever - -class GSM3SoftSerial : public GSM3CircularBufferManager -{ - private: - - uint8_t _receiveBitMask; - volatile uint8_t *_receivePortRegister; - uint8_t _transmitBitMask; - volatile uint8_t *_transmitPortRegister; - - static GSM3SoftSerial* _activeObject; - GSM3SoftSerialMgr* mgr; - - uint16_t _rx_delay_centering; - uint16_t _rx_delay_intrabit; - uint16_t _rx_delay_stopbit; - uint16_t _tx_delay; - uint8_t _flags; - - /** Write in tx_pin - @param pin_state Pin state - */ - void tx_pin_write(uint8_t pin_state); - - /** Set transmission - */ - void setTX(); - - /** Set receiver - */ - void setRX(); - - /** Receive - */ - void recv(); - - /** Read from rx_pin - @return receive bit mask - */ - uint8_t rx_pin_read(); - - void setComsReceived(); - - /** Write a character in serial connection, final action after escaping - @param c Character - @return 1 if succesful, 0 if transmission delay = 0 - */ - virtual size_t finalWrite(uint8_t); - - /** Decide, attending to escapes, if the received character should we - kept, forgotten, or changed - @param c Character, may be changed - @return 1 if shall be kept, 0 if forgotten - */ - bool keepThisChar(uint8_t* c); - - // Checks the buffer for well-known events. - //bool recognizeUnsolicitedEvent(byte oldTail); - - public: - - /** Tuned delay in microcontroller - @param delay Time to delay - */ - static /*inline */void tunedDelay(uint16_t delay); - - GSM3CircularBuffer cb; // Circular buffer - - /** Register serial manager - @param manager Serial manager - */ - inline void registerMgr(GSM3SoftSerialMgr* manager){mgr=manager;}; - - /** If there is spaceAvailable in the buffer, lets send a XON - */ - void spaceAvailable(); - - /** Write a character in serial connection - @param c Character - @return 1 if succesful, 0 if transmission delay = 0 - */ - virtual size_t write(uint8_t); - - /** Constructor */ - GSM3SoftSerial(); - - /** Establish serial connection - @param speed Baudrate - @return - */ - int begin(long speed); - - /** Manage interruptions - */ - static inline void handle_interrupt(); - - /** Close serial connection - */ - void close(); -}; - -#endif \ No newline at end of file diff --git a/libraries/GSM/GSM3VoiceCallService.cpp b/libraries/GSM/GSM3VoiceCallService.cpp deleted file mode 100644 index fefb0f0..0000000 --- a/libraries/GSM/GSM3VoiceCallService.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#include -#include - -#include -GSM3ShieldV1VoiceProvider theShieldV1VoiceProvider; - -// While there is only a shield (ShieldV1) we will include it by default - -#define GSM3VOICECALLSERVICE_SYNCH 0x01 // 1: synchronous 0: asynchronous -#define __TOUT__ 10000 - - - - -GSM3VoiceCallService::GSM3VoiceCallService(bool synch) -{ - if(synch) - flags |= GSM3VOICECALLSERVICE_SYNCH; - theGSM3MobileVoiceProvider->initialize(); -} - -GSM3_voiceCall_st GSM3VoiceCallService::getvoiceCallStatus() -{ - if(theGSM3MobileVoiceProvider==0) - return IDLE_CALL; - - return theGSM3MobileVoiceProvider->getvoiceCallStatus(); -} - -int GSM3VoiceCallService::ready() -{ - if(theGSM3MobileVoiceProvider==0) - return 0; - - return theGSM3MobileVoiceProvider->ready(); -} - -int GSM3VoiceCallService::voiceCall(const char* to, unsigned long timeout) -{ - if(theGSM3MobileVoiceProvider==0) - return 0; - - if(flags & GSM3VOICECALLSERVICE_SYNCH ) - { - theGSM3MobileVoiceProvider->voiceCall(to); - unsigned long m; - m=millis(); - // Wait an answer for timeout - while(((millis()-m)< timeout )&&(getvoiceCallStatus()==CALLING)) - delay(100); - - if(getvoiceCallStatus()==TALKING) - return 1; - else - return 0; - } - else - { - return theGSM3MobileVoiceProvider->voiceCall(to); - } - -} - -int GSM3VoiceCallService::answerCall() -{ - if(theGSM3MobileVoiceProvider==0) - return 0; - - return waitForAnswerIfNeeded(theGSM3MobileVoiceProvider->answerCall()); -} - -int GSM3VoiceCallService::hangCall() -{ - if(theGSM3MobileVoiceProvider==0) - return 0; - - return waitForAnswerIfNeeded(theGSM3MobileVoiceProvider->hangCall()); -} - -int GSM3VoiceCallService::retrieveCallingNumber(char* buffer, int bufsize) -{ - if(theGSM3MobileVoiceProvider==0) - return 0; - - return waitForAnswerIfNeeded(theGSM3MobileVoiceProvider->retrieveCallingNumber(buffer, bufsize)); -} - -int GSM3VoiceCallService::waitForAnswerIfNeeded(int returnvalue) -{ - // If synchronous - if(flags & GSM3VOICECALLSERVICE_SYNCH ) - { - unsigned long m; - m=millis(); - // Wait for __TOUT__ - while(((millis()-m)< __TOUT__ )&&(ready()==0)) - delay(100); - // If everything was OK, return 1 - // else (timeout or error codes) return 0; - if(ready()==1) - return 1; - else - return 0; - } - // If not synchronous just kick ahead the coming result - return ready(); -} - - - - diff --git a/libraries/GSM/GSM3VoiceCallService.h b/libraries/GSM/GSM3VoiceCallService.h deleted file mode 100644 index 089d579..0000000 --- a/libraries/GSM/GSM3VoiceCallService.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -This file is part of the GSM3 communications library for Arduino --- Multi-transport communications platform --- Fully asynchronous --- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1 --- Voice calls --- SMS --- TCP/IP connections --- HTTP basic clients - -This library has been developed by Telefónica Digital - PDI - -- Physical Internet Lab, as part as its collaboration with -Arduino and the Open Hardware Community. - -September-December 2012 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -https://github.com/BlueVia/Official-Arduino -*/ -#ifndef _GSM3VOICECALLSERVICE_ -#define _GSM3VOICECALLSERVICE_ - -#include -#include - -class GSM3VoiceCallService -{ - private: - uint8_t flags; - - /** Make synchronous the functions, if needed - @param returnvalue Return value - @return returns 0 if last command is still executing, 1 success, >1 error - */ - int waitForAnswerIfNeeded(int returnvalue); - - public: - /** Service creation - @param synch If true, the service calls are synchronois - */ - GSM3VoiceCallService(bool synch=true); - - /** Voice call status - @return Status of the voice call, as described in GSM3MobileVoiceProvider.h - { IDLE_CALL, CALLING, RECEIVINGCALL, TALKING}; - */ - GSM3_voiceCall_st getvoiceCallStatus(); - - /** Get last command status - @return Returns 0 if last command is still executing, 1 success, >1 error - */ - int ready(); - - /** Place a voice call. If asynchronous, returns while ringing. If synchronous - returns if the call is stablished or cancelled. - @param to Receiver number. Country extension can be used or not. - Char buffer should not be released or used until command is over - @param timeout In millisecods. Time ringing before closing the call. - Only used in synchronous mode. - If zero, ring undefinitely - @return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error - In synchronous mode returns 1 if the call is placed, 0 if not. - */ - int voiceCall(const char* to, unsigned long timeout=30000); - - /** Accept an incoming voice call - @return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error - In synchronous mode returns 1 if the call is answered, 0 if not. - */ - int answerCall(); - - /** Hang a stablished call or an incoming ring - @return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error - In synchronous mode returns 1 if the call is answered, 0 if not. - */ - int hangCall(); - - /** Retrieve the calling number, put it in buffer - @param buffer pointer to the buffer memory - @param bufsize size of available memory area, at least should be 10 characters - @return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error - In synchronous mode returns 1 if the number is correcty taken 0 if not - */ - int retrieveCallingNumber(char* buffer, int bufsize); -}; - - -#endif \ No newline at end of file diff --git a/libraries/GSM/License.txt b/libraries/GSM/License.txt deleted file mode 100644 index fb6d90b..0000000 --- a/libraries/GSM/License.txt +++ /dev/null @@ -1,166 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. - diff --git a/libraries/GSM/examples/GSMPachubeClient/GSMPachubeClient.ino b/libraries/GSM/examples/GSMPachubeClient/GSMPachubeClient.ino deleted file mode 100644 index 2885c9b..0000000 --- a/libraries/GSM/examples/GSMPachubeClient/GSMPachubeClient.ino +++ /dev/null @@ -1,186 +0,0 @@ -/* - GSM Pachube client - - This sketch connects an analog sensor to Pachube (http://www.pachube.com) - using a Telefonica GSM/GPRS shield. - - This example has been updated to use version 2.0 of the Pachube.com API. - To make it work, create a feed with a datastream, and give it the ID - sensor1. Or change the code below to match your feed. - - Circuit: - * Analog sensor attached to analog in 0 - * GSM shield attached to an Arduino - * SIM card with a data plan - - created 4 March 2012 - by Tom Igoe - and adapted for GSM shield by David Del Peral - - This code is in the public domain. - - http://arduino.cc/en/Tutorial/GSMExamplesPachubeClient - - */ - -// libraries -#include - -// Pachube Client data -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Project" // user agent is the project name - -// PIN Number -#define PINNUMBER "" - -// APN data -#define GPRS_APN "GPRS_APN" // replace your GPRS APN -#define GPRS_LOGIN "login" // replace with your GPRS login -#define GPRS_PASSWORD "password" // replace with your GPRS password - -// initialize the library instance: -GSMClient client; -GPRS gprs; -GSM gsmAccess; - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -// IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -char server[] = "api.pachube.com"; // name address for pachube API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // connection state - boolean notConnected = true; - - // After starting the modem with GSM.begin() - // attach the shield to the GPRS network with the APN, login and password - while(notConnected) - { - if((gsmAccess.begin(PINNUMBER)==GSM_READY) & - (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } -} - -void loop() -{ - // read the analog sensor: - int sensorReading = analogRead(A0); - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - if (client.available()) - { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) - { - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && ((millis() - lastConnectionTime) > postingInterval)) - { - sendData(sensorReading); - } - - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -/* - This method makes a HTTP connection to the server. -*/ -void sendData(int thisData) -{ - // if there's a successful connection: - if (client.connect(server, 80)) - { - Serial.println("connecting..."); - - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); - client.print("X-ApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - - // calculate the length of the sensor reading in bytes: - // 8 bytes for "sensor1," + number of digits of the data: - int thisLength = 8 + getLength(thisData); - client.println(thisLength); - - // last pieces of the HTTP PUT request: - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request: - client.print("sensor1,"); - client.println(thisData); - } - else - { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted - lastConnectionTime = millis(); -} - -/* - This method calculates the number of digits in the - sensor reading. Since each digit of the ASCII decimal - representation is a byte, the number of digits equals - the number of bytes. -*/ -int getLength(int someValue) -{ - // there's at least one byte: - int digits = 1; - - // continually divide the value by ten, - // adding one to the digit count for each - // time you divide, until you're at 0: - int dividend = someValue /10; - while (dividend > 0) - { - dividend = dividend /10; - digits++; - } - - // return the number of digits: - return digits; -} - diff --git a/libraries/GSM/examples/GSMPachubeClientString/GSMPachubeClientString.ino b/libraries/GSM/examples/GSMPachubeClientString/GSMPachubeClientString.ino deleted file mode 100644 index 9f6ea53..0000000 --- a/libraries/GSM/examples/GSMPachubeClientString/GSMPachubeClientString.ino +++ /dev/null @@ -1,167 +0,0 @@ -/* - Pachube client with Strings - - This sketch connects two analog sensors to Pachube (http://www.pachube.com) - through a Telefonica GSM/GPRS shield. - - This example has been updated to use version 2.0 of the Pachube.com API. - To make it work, create a feed with two datastreams, and give them the IDs - sensor1 and sensor2. Or change the code below to match your feed. - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * Analog sensors attached to A0 and A1 - * GSM shield attached to an Arduino - * SIM card with a data plan - - created 8 March 2012 - by Tom Igoe - and adapted for GSM shield by David Del Peral - - This code is in the public domain. - - */ - -// Include the GSM library -#include - -// Pachube login information -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Project" // user agent is the project name - -// PIN Number -#define PINNUMBER "" - -// APN data -#define GPRS_APN "GPRS_APN" // replace your GPRS APN -#define GPRS_LOGIN "login" // replace with your GPRS login -#define GPRS_PASSWORD "password" // replace with your GPRS password - -// initialize the library instance -GSMClient client; -GPRS gprs; -GSM gsmAccess; - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -// IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -char server[] = "api.pachube.com"; // name address for Pachube API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; // delay between updates to Pachube.com - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // connection state - boolean notConnected = true; - - // After starting the modem with GSM.begin() - // attach the shield to the GPRS network with the APN, login and password - while(notConnected) - { - if((gsmAccess.begin(PINNUMBER)==GSM_READY) & - (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("Connected to GPRS network"); -} - -void loop() -{ - // read the sensor on A0 - int sensorReading = analogRead(A0); - - // convert the data to a String - String dataString = "sensor1,"; - dataString += sensorReading; - - // you can append multiple readings to this String to - // send the pachube feed multiple values - int otherSensorReading = analogRead(A1); - dataString += "\nsensor2,"; - dataString += otherSensorReading; - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only - if (client.available()) - { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client - if (!client.connected() && lastConnected) - { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) - { - sendData(dataString); - } - // store the state of the connection for next time through - // the loop - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server -void sendData(String thisData) -{ - // if there's a successful connection: - if (client.connect(server, 80)) - { - Serial.println("connecting..."); - - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); - client.print("X-ApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - client.println(thisData.length()); - - // last pieces of the HTTP PUT request - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request - client.println(thisData); - } - else - { - // if you couldn't make a connection - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted: - lastConnectionTime = millis(); -} diff --git a/libraries/GSM/examples/GsmTwitterClient/GsmTwitterClient.ino b/libraries/GSM/examples/GsmTwitterClient/GsmTwitterClient.ino deleted file mode 100644 index 3032141..0000000 --- a/libraries/GSM/examples/GsmTwitterClient/GsmTwitterClient.ino +++ /dev/null @@ -1,162 +0,0 @@ -/* - GSM Twitter Client with Strings - - This sketch connects to Twitter using an Arduino GSM shield. - It parses the XML returned, and looks for the string this is a tweet - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * GSM shield attached to an Arduino - * SIM card with a data plan - - created 8 Mar 2012 - by Tom Igoe - - http://arduino.cc/en/Tutorial/GSMExamplesTwitterClient - - This code is in the public domain. - - */ - -// libraries -#include - -// PIN Number -#define PINNUMBER "" - -// APN data -#define GPRS_APN "APN" // replace your GPRS APN -#define GPRS_LOGIN "LOGIN" // replace with your GPRS login -#define GPRS_PASSWORD "PASSWORD" // replace with your GPRS password - -// initialize the library instance -GSMClient client; -GPRS gprs; -GSM gsmAccess; - -const unsigned long requestInterval = 30*1000; // delay between requests: 30 seconds - -// API Twitter URL -char server[] = "api.twitter.com"; - -boolean requested; // whether you've made a request since connecting -unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds - -String currentLine = ""; // string to hold the text from server -String tweet = ""; // string to hold the tweet -boolean readingTweet = false; // if you're currently reading the tweet - -void setup() -{ - // reserve space for the strings: - currentLine.reserve(256); - tweet.reserve(150); - - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // connection state - boolean notConnected = true; - - // After starting the modem with GSM.begin() - // attach the shield to the GPRS network with the APN, login and password - while(notConnected) - { - if((gsmAccess.begin(PINNUMBER)==GSM_READY) & - (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("Connected to GPRS network"); - - Serial.println("connecting..."); - connectToServer(); -} - - - -void loop() -{ - char c; - if (client.connected()) - { - if (client.available()) - { - // read incoming bytes: - char inChar = client.read(); - - // add incoming byte to end of line: - currentLine += inChar; - - // if you get a newline, clear the line: - if (inChar == '\n') - { - currentLine = ""; - } - - // if the current line ends with , it will - // be followed by the tweet: - if (currentLine.endsWith("")) - { - // tweet is beginning. Clear the tweet string: - readingTweet = true; - tweet = ""; - } - - // if you're currently reading the bytes of a tweet, - // add them to the tweet String: - if (readingTweet) - { - if (inChar != '<') - { - tweet += inChar; - } - else - { - // if you got a "<" character, - // you've reached the end of the tweet: - readingTweet = false; - Serial.println(tweet); - - // close the connection to the server: - client.stop(); - } - } - } - } - else if (millis() - lastAttemptTime > requestInterval) - { - // if you're not connected, and two minutes have passed since - // your last connection, then attempt to connect again: - connectToServer(); - } -} - -/* - Connect to API Twitter server and do a request for timeline -*/ -void connectToServer() -{ - // attempt to connect, and wait a millisecond: - Serial.println("connecting to server..."); - if (client.connect(server, 80)) - { - Serial.println("making HTTP request..."); - // make HTTP GET request to twitter: - client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino&count=1 HTTP/1.1"); - client.println("HOST: api.twitter.com"); - client.println(); - } - // note the time of this connect attempt: - lastAttemptTime = millis(); -} diff --git a/libraries/GSM/examples/GsmWebClient/GsmWebClient.ino b/libraries/GSM/examples/GsmWebClient/GsmWebClient.ino deleted file mode 100644 index e7eb275..0000000 --- a/libraries/GSM/examples/GsmWebClient/GsmWebClient.ino +++ /dev/null @@ -1,109 +0,0 @@ -/* - Web client - - This sketch connects to a website through a GSM shield. Specifically, - this example downloads the URL "http://arduino.cc/asciilogo.txt" and - prints it to the Serial monitor. - - Circuit: - * GSM shield attached to an Arduino - * SIM card with a data plan - - created 8 Mar 2012 - by Tom Igoe - - http://arduino.cc/en/Tutorial/GSMExamplesWebClient - - */ - -// libraries -#include - -// PIN Number -#define PINNUMBER "" - -// APN data -#define GPRS_APN "GPRS_APN" // replace your GPRS APN -#define GPRS_LOGIN "login" // replace with your GPRS login -#define GPRS_PASSWORD "password" // replace with your GPRS password - -// initialize the library instance -GSMClient client; -GPRS gprs; -GSM gsmAccess; - -// URL, path & port (for example: arduino.cc) -char server[] = "arduino.cc"; -char path[] = "/asciilogo.txt"; -int port = 80; // port 80 is the default for HTTP - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("Starting Arduino web client."); - // connection state - boolean notConnected = true; - - // After starting the modem with GSM.begin() - // attach the shield to the GPRS network with the APN, login and password - while(notConnected) - { - if((gsmAccess.begin(PINNUMBER)==GSM_READY) & - (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("connecting..."); - - // if you get a connection, report back via serial: - if (client.connect(server, port)) - { - Serial.println("connected"); - // Make a HTTP request: - client.print("GET "); - client.print(path); - client.println(" HTTP/1.1"); - client.print("Host: "); - client.println(server); - client.println("Connection: close"); - client.println(); - } - else - { - // if you didn't get a connection to the server: - Serial.println("connection failed"); - } -} - -void loop() -{ - // if there are incoming bytes available - // from the server, read them and print them: - if (client.available()) - { - char c = client.read(); - Serial.print(c); - } - - // if the server's disconnected, stop the client: - if (!client.available() && !client.connected()) - { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - - // do nothing forevermore: - for(;;) - ; - } -} diff --git a/libraries/GSM/examples/GsmWebServer/GsmWebServer.ino b/libraries/GSM/examples/GsmWebServer/GsmWebServer.ino deleted file mode 100644 index e957b4c..0000000 --- a/libraries/GSM/examples/GsmWebServer/GsmWebServer.ino +++ /dev/null @@ -1,118 +0,0 @@ -/* - GSM Web Server - - A simple web server that shows the value of the analog input pins. - using a GSM shield. - - Circuit: - * GSM shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 8 Mar 2012 - by Tom Igoe - */ - -// libraries -#include - -// PIN Number -#define PINNUMBER "" - -// APN data -#define GPRS_APN "GPRS_APN" // replace your GPRS APN -#define GPRS_LOGIN "login" // replace with your GPRS login -#define GPRS_PASSWORD "password" // replace with your GPRS password - - -// initialize the library instance -GPRS gprs; -GSM gsmAccess; // include a 'true' parameter for debug enabled -GSMServer server(80); // port 80 (http default) - -// timeout -const unsigned long __TIMEOUT__ = 10*1000; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // connection state - boolean notConnected = true; - - // Start GSM shield - // If your SIM has PIN, pass it as a parameter of begin() in quotes - while(notConnected) - { - if((gsmAccess.begin(PINNUMBER)==GSM_READY) & - (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("Connected to GPRS network"); - - // start server - server.begin(); - - //Get IP. - IPAddress LocalIP = gprs.getIPAddress(); - Serial.println("Server IP address="); - Serial.println(LocalIP); -} - -void loop() { - - - // listen for incoming clients - GSMClient client = server.available(); - - - - if (client) - { - while (client.connected()) - { - if (client.available()) - { - Serial.println("Receiving request!"); - bool sendResponse = false; - while(char c=client.read()) { - if (c == '\n') sendResponse = true; - } - - // if you've gotten to the end of the line (received a newline - // character) - if (sendResponse) - { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println(); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(analogRead(analogChannel)); - client.println("
"); - } - client.println(""); - //necessary delay - delay(1000); - client.stop(); - } - } - } - } -} - - diff --git a/libraries/GSM/examples/MakeVoiceCall/MakeVoiceCall.ino b/libraries/GSM/examples/MakeVoiceCall/MakeVoiceCall.ino deleted file mode 100644 index 64df44a..0000000 --- a/libraries/GSM/examples/MakeVoiceCall/MakeVoiceCall.ino +++ /dev/null @@ -1,116 +0,0 @@ -/* - Make Voice Call - - This sketch, for the Arduino GSM shield, puts a voice call to - a remote phone number that you enter through the serial monitor. - To make it work, open the serial monitor, and when you see the - READY message, type a phone number. Make sure the serial monitor - is set to send a just newline when you press return. - - Circuit: - * GSM shield - * Voice circuit. - With no voice circuit the call will send nor receive any sound - - - created Mar 2012 - by Javier Zorzano - - This example is in the public domain. - */ - -// libraries -#include - -// PIN Number -#define PINNUMBER "" - -// initialize the library instance -GSM gsmAccess; // include a 'true' parameter for debug enabled -GSMVoiceCall vcs; - -String remoteNumber = ""; // the number you will call -char charbuffer[20]; - -void setup() -{ - - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("Make Voice Call"); - - // connection state - boolean notConnected = true; - - // Start GSM shield - // If your SIM has PIN, pass it as a parameter of begin() in quotes - while(notConnected) - { - if(gsmAccess.begin(PINNUMBER)==GSM_READY) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("GSM initialized."); - Serial.println("Enter phone number to call."); - -} - -void loop() -{ - - // add any incoming characters to the String: - while (Serial.available() > 0) - { - char inChar = Serial.read(); - // if it's a newline, that means you should make the call: - if (inChar == '\n') - { - // make sure the phone number is not too long: - if (remoteNumber.length() < 20) - { - // let the user know you're calling: - Serial.print("Calling to : "); - Serial.println(remoteNumber); - Serial.println(); - - // Call the remote number - remoteNumber.toCharArray(charbuffer, 20); - - - // Check if the receiving end has picked up the call - if(vcs.voiceCall(charbuffer)) - { - Serial.println("Call Established. Enter line to end"); - // Wait for some input from the line - while(Serial.read()!='\n' && (vcs.getvoiceCallStatus()==TALKING)); - // And hang up - vcs.hangCall(); - } - Serial.println("Call Finished"); - remoteNumber=""; - Serial.println("Enter phone number to call."); - } - else - { - Serial.println("That's too long for a phone number. I'm forgetting it"); - remoteNumber = ""; - } - } - else - { - // add the latest character to the message to send: - if(inChar!='\r') - remoteNumber += inChar; - } - } -} - diff --git a/libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino b/libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino deleted file mode 100644 index af800f4..0000000 --- a/libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino +++ /dev/null @@ -1,98 +0,0 @@ -/* - SMS receiver - - This sketch, for the Arduino GSM shield, waits for a SMS message - and displays it through the Serial port. - - Circuit: - * GSM shield attached to and Arduino - * SIM card that can receive SMS messages - - created 25 Feb 2012 - by Javier Zorzano / TD - - This example is in the public domain. - - http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS - -*/ - -// include the GSM library -#include - -// PIN Number for the SIM -#define PINNUMBER "" - -// initialize the library instances -GSM gsmAccess; -GSM_SMS sms; - -// Array to hold the number a SMS is retreived from -char senderNumber[20]; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("SMS Messages Receiver"); - - // connection state - boolean notConnected = true; - - // Start GSM connection - while(notConnected) - { - if(gsmAccess.begin(PINNUMBER)==GSM_READY) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("GSM initialized"); - Serial.println("Waiting for messages"); -} - -void loop() -{ - char c; - - // If there are any SMSs available() - if (sms.available()) - { - Serial.println("Message received from:"); - - // Get remote number - sms.remoteNumber(senderNumber, 20); - Serial.println(senderNumber); - - // An example of message disposal - // Any messages starting with # should be discarded - if(sms.peek()=='#') - { - Serial.println("Discarded SMS"); - sms.flush(); - } - - // Read message bytes and print them - while(c=sms.read()) - Serial.print(c); - - Serial.println("\nEND OF MESSAGE"); - - // Delete message from modem memory - sms.flush(); - Serial.println("MESSAGE DELETED"); - } - - delay(1000); - -} - - diff --git a/libraries/GSM/examples/ReceiveVoiceCall/ReceiveVoiceCall.ino b/libraries/GSM/examples/ReceiveVoiceCall/ReceiveVoiceCall.ino deleted file mode 100644 index 14dbc5e..0000000 --- a/libraries/GSM/examples/ReceiveVoiceCall/ReceiveVoiceCall.ino +++ /dev/null @@ -1,105 +0,0 @@ -/* - Receive Voice Call - - This sketch, for the Arduino GSM shield, receives voice calls, - displays the calling number, waits a few seconds then hangs up. - - Circuit: - * GSM shield - * Voice circuit. Refer to to the GSM shield getting started guide - at http://arduino.cc/en/Guide/ArduinoGSMShield#toc11 - * SIM card that can accept voice calls - - With no voice circuit the call will connect, but will not send or receive sound - - created Mar 2012 - by Javier Zorzano - - This example is in the public domain. - - http://arduino.cc/en/Tutorial/GSMExamplesReceiveVoiceCall - - */ - -// Include the GSM library -#include - -// PIN Number -#define PINNUMBER "" - -// initialize the library instance -GSM gsmAccess; -GSMVoiceCall vcs; - -// Array to hold the number for the incoming call -char numtel[20]; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("Receive Voice Call"); - - // connection state - boolean notConnected = true; - - // Start GSM shield - // If your SIM has PIN, pass it as a parameter of begin() in quotes - while(notConnected) - { - if(gsmAccess.begin(PINNUMBER)==GSM_READY) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - // This makes sure the modem correctly reports incoming events - vcs.hangCall(); - - Serial.println("Waiting for a call"); -} - -void loop() -{ - // Check the status of the voice call - switch (vcs.getvoiceCallStatus()) - { - case IDLE_CALL: // Nothing is happening - - break; - - case RECEIVINGCALL: // Yes! Someone is calling us - - Serial.println("RECEIVING CALL"); - - // Retrieve the calling number - vcs.retrieveCallingNumber(numtel, 20); - - // Print the calling number - Serial.print("Number:"); - Serial.println(numtel); - - // Answer the call, establish the call - vcs.answerCall(); - break; - - case TALKING: // In this case the call would be established - - Serial.println("TALKING. Press enter to hang up."); - while(Serial.read()!='\n') - delay(100); - vcs.hangCall(); - Serial.println("Hanging up and waiting for the next call."); - break; - } - delay(1000); -} - - diff --git a/libraries/GSM/examples/SendSMS/SendSMS.ino b/libraries/GSM/examples/SendSMS/SendSMS.ino deleted file mode 100644 index 677442a..0000000 --- a/libraries/GSM/examples/SendSMS/SendSMS.ino +++ /dev/null @@ -1,110 +0,0 @@ -/* - SMS sender - - This sketch, for the Arduino GSM shield,sends an SMS message - you enter in the serial monitor. Connect your Arduino with the - GSM shield and SIM card, open the serial monitor, and wait for - the "READY" message to appear in the monitor. Next, type a - message to send and press "return". Make sure the serial - monitor is set to send a newline when you press return. - - Circuit: - * GSM shield - * SIM card that can send SMS - - created 25 Feb 2012 - by Tom Igoe - - This example is in the public domain. - - http://arduino.cc/en/Tutorial/GSMExamplesSendSMS - - */ - -// Include the GSM library -#include - -#define PINNUMBER "" - -// initialize the library instance -GSM gsmAccess; -GSM_SMS sms; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("SMS Messages Sender"); - - // connection state - boolean notConnected = true; - - // Start GSM shield - // If your SIM has PIN, pass it as a parameter of begin() in quotes - while(notConnected) - { - if(gsmAccess.begin(PINNUMBER)==GSM_READY) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("GSM initialized"); -} - -void loop() -{ - - Serial.print("Enter a mobile number: "); - char remoteNum[20]; // telephone number to send sms - readSerial(remoteNum); - Serial.println(remoteNum); - - // sms text - Serial.print("Now, enter SMS content: "); - char txtMsg[200]; - readSerial(txtMsg); - Serial.println("SENDING"); - Serial.println(); - Serial.println("Message:"); - Serial.println(txtMsg); - - // send the message - sms.beginSMS(remoteNum); - sms.print(txtMsg); - sms.endSMS(); - Serial.println("\nCOMPLETE!\n"); -} - -/* - Read input serial - */ -int readSerial(char result[]) -{ - int i = 0; - while(1) - { - while (Serial.available() > 0) - { - char inChar = Serial.read(); - if (inChar == '\n') - { - result[i] = '\0'; - Serial.flush(); - return 0; - } - if(inChar!='\r') - { - result[i] = inChar; - i++; - } - } - } -} diff --git a/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino b/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino deleted file mode 100644 index 84d8c71..0000000 --- a/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino +++ /dev/null @@ -1,120 +0,0 @@ -/* - Band Management - - This sketch, for the Arduino GSM shield, checks the band - currently configured in the modem and allows you to change - it. - - Please check http://www.worldtimezone.com/gsm.html - Usual configurations: - Europe, Africa, Middle East: E-GSM(900)+DCS(1800) - USA, Canada, South America: GSM(850)+PCS(1900) - Mexico: PCS(1900) - Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900) - - - Circuit: - * GSM shield - - created 12 June 2012 - by Javier Zorzano, Scott Fitzgerald - - This example is in the public domain. - */ - -// libraries -#include - -// initialize the library instance -GSMBand band; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // Beginning the band manager restarts the modem - Serial.println("Restarting modem..."); - band.begin(); - Serial.println("Modem restarted."); - -}; - - -void loop() -{ - // Get current band - String bandName = band.getBand(); // Get and print band name - Serial.print("Current band:"); - Serial.println(bandName); - Serial.println("Want to change the band you’re on?"); - String newBandName; - newBandName = askUser(); - // Tell the user what we are about to do… - Serial.print("\nConfiguring band "); - Serial.println(newBandName); - // Change the band - boolean operationSuccess; - operationSuccess = band.setBand(newBandName); - // Tell the user if the operation was OK - if(operationSuccess) - { - Serial.println("Success"); - } - else - { - Serial.println("Error while changing band"); - } - - if(operationSuccess) - { - while(true); - } -} - -// This function offers the user different options -// through the Serial interface -// The user selects one -String askUser() -{ - String newBand; - Serial.println("Select band:"); - // Print the different options - Serial.println("1 : E-GSM(900)"); - Serial.println("2 : DCS(1800)"); - Serial.println("3 : PCS(1900)"); - Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe"); - Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am."); - Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)"); - - // Empty the incoming buffer - while(Serial.available()) - Serial.read(); - - // Wait for an answer, just look at the first character - while(!Serial.available()); - char c= Serial.read(); - if(c=='1') - newBand=GSM_MODE_EGSM; - else if(c=='2') - newBand=GSM_MODE_DCS; - else if(c=='3') - newBand=GSM_MODE_PCS; - else if(c=='4') - newBand=GSM_MODE_EGSM_DCS; - else if(c=='5') - newBand=GSM_MODE_GSM850_PCS; - else if(c=='6') - newBand=GSM_MODE_GSM850_EGSM_DCS_PCS; - else - newBand="GSM_MODE_UNDEFINED"; - return newBand; -} - - - - - diff --git a/libraries/GSM/examples/Tools/GsmScanNetworks/GsmScanNetworks.ino b/libraries/GSM/examples/Tools/GsmScanNetworks/GsmScanNetworks.ino deleted file mode 100644 index 0e442eb..0000000 --- a/libraries/GSM/examples/Tools/GsmScanNetworks/GsmScanNetworks.ino +++ /dev/null @@ -1,95 +0,0 @@ -/* - - GSM Scan Networks - - This example prints out the IMEI number of the modem, - then checks to see if it's connected to a carrier. If so, - it prints the phone number associated with the card. - Then it scans for nearby networks and prints out their signal strengths. - - Circuit: - * GSM shield - * SIM card - - Created 8 Mar 2012 - by Tom Igoe, implemented by Javier Carazo - Modified 4 Feb 2013 - by Scott Fitzgerald - - http://arduino.cc/en/Tutorial/GSMToolsGsmScanNetworks - - This example code is part of the public domain - */ - -// libraries -#include - -// PIN Number -#define PINNUMBER "" - -// initialize the library instance -GSM gsmAccess; // include a 'true' parameter to enable debugging -GSMScanner scannerNetworks; -GSMModem modemTest; - -// Save data variables -String IMEI = ""; - -// serial monitor result messages -String errortext = "ERROR"; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("GSM networks scanner"); - scannerNetworks.begin(); - - // connection state - boolean notConnected = true; - - // Start GSM shield - // If your SIM has PIN, pass it as a parameter of begin() in quotes - while(notConnected) - { - if(gsmAccess.begin(PINNUMBER)==GSM_READY) - notConnected = false; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - // get modem parameters - // IMEI, modem unique identifier - Serial.print("Modem IMEI: "); - IMEI = modemTest.getIMEI(); - IMEI.replace("\n",""); - if(IMEI != NULL) - Serial.println(IMEI); -} - -void loop() -{ - // scan for existing networks, displays a list of networks - Serial.println("Scanning available networks. May take some seconds."); - Serial.println(scannerNetworks.readNetworks()); - - // currently connected carrier - Serial.print("Current carrier: "); - Serial.println(scannerNetworks.getCurrentCarrier()); - - // returns strength and ber - // signal strength in 0-31 scale. 31 means power > 51dBm - // BER is the Bit Error Rate. 0-7 scale. 99=not detectable - Serial.print("Signal Strength: "); - Serial.print(scannerNetworks.getSignalStrength()); - Serial.println(" [0-31]"); - -} - diff --git a/libraries/GSM/examples/Tools/PinManagement/PinManagement.ino b/libraries/GSM/examples/Tools/PinManagement/PinManagement.ino deleted file mode 100644 index 654d1b8..0000000 --- a/libraries/GSM/examples/Tools/PinManagement/PinManagement.ino +++ /dev/null @@ -1,168 +0,0 @@ -/* - - This example enables you to change or remove the PIN number of - a SIM card inserted into a GSM shield. - - Circuit: - * GSM shield - * SIM card - - Created 12 Jun 2012 - by David del Peral - - This example code is part of the public domain - - http://arduino.cc/en/Tutorial/GSMToolsPinManagement - - */ - -// libraries -#include - -// pin manager object -GSMPIN PINManager; - -// save input in serial by user -String user_input = ""; - -// authenticated with PIN code -boolean auth = false; - -// serial monitor result messages -String oktext = "OK"; -String errortext = "ERROR"; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("Change PIN example\n"); - PINManager.begin(); - - // check if the SIM have pin lock - while(!auth){ - int pin_query = PINManager.isPIN(); - if(pin_query == 1) - { - // if SIM is locked, enter PIN code - Serial.print("Enter PIN code: "); - user_input = readSerial(); - // check PIN code - if(PINManager.checkPIN(user_input) == 0) - { - auth = true; - PINManager.setPINUsed(true); - Serial.println(oktext); - } - else - { - // if PIN code was incorrected - Serial.println("Incorrect PIN. Remember that you have 3 opportunities."); - } - } - else if(pin_query == -1) - { - // PIN code is locked, user must enter PUK code - Serial.println("PIN locked. Enter PUK code: "); - String puk = readSerial(); - Serial.print("Now, enter a new PIN code: "); - user_input = readSerial(); - // check PUK code - if(PINManager.checkPUK(puk, user_input) == 0) - { - auth = true; - PINManager.setPINUsed(true); - Serial.println(oktext); - } - else - { - // if PUK o the new PIN are incorrect - Serial.println("Incorrect PUK or invalid new PIN. Try again!."); - } - } - else if(pin_query == -2) - { - // the worst case, PIN and PUK are locked - Serial.println("PIN & PUK locked. Use PIN2/PUK2 in a mobile phone."); - while(true); - } - else - { - // SIM does not requires authetication - Serial.println("No pin necessary."); - auth = true; - } - } - - // start GSM shield - Serial.print("Checking register in GSM network..."); - if(PINManager.checkReg() == 0) - Serial.println(oktext); - // if you are connect by roaming - else if(PINManager.checkReg() == 1) - Serial.println("ROAMING " + oktext); - else - { - // error connection - Serial.println(errortext); - while(true); - } -} - -void loop() -{ - // Function loop implements pin management user menu - // Only if you SIM use pin lock, you can change PIN code - // user_op variables save user option - - Serial.println("Choose an option:\n1 - On/Off PIN."); - if(PINManager.getPINUsed()) - Serial.println("2 - Change PIN."); - String user_op = readSerial(); - if(user_op == "1") - { - Serial.println("Enter your PIN code:"); - user_input = readSerial(); - // activate/deactivate PIN lock - PINManager.switchPIN(user_input); - } - else if(user_op == "2" & PINManager.getPINUsed()) - { - Serial.println("Enter your actual PIN code:"); - String oldPIN = readSerial(); - Serial.println("Now, enter your new PIN code:"); - String newPIN = readSerial(); - // change PIN - PINManager.changePIN(oldPIN, newPIN); - } - else - { - Serial.println("Incorrect option. Try again!."); - } - delay(1000); -} - -/* - Read input serial - */ -String readSerial() -{ - String text = ""; - while(1) - { - while (Serial.available() > 0) - { - char inChar = Serial.read(); - if (inChar == '\n') - { - return text; - } - if(inChar!='\r') - text += inChar; - } - } -} diff --git a/libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino b/libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino deleted file mode 100644 index ab4a2be..0000000 --- a/libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino +++ /dev/null @@ -1,204 +0,0 @@ -/* - - This sketch test the GSM shield's ability to connect to a - GPERS network. It asks for APN information through the - serial monitor and tries to connect to arduino.cc. - - Circuit: - * GSM shield attached - * SIM card with data plan - - Created 18 Jun 2012 - by David del Peral - - This example code is part of the public domain - - http://arduino.cc/en/Tutorial/GSMToolsTestGPRS - - */ - -// libraries -#include - -// PIN Number -#define PINNUMBER "" - -// initialize the library instance -GSM gsmAccess; // GSM access: include a 'true' parameter for debug enabled -GPRS gprsAccess; // GPRS access -GSMClient client; // Client service for TCP connection - -// messages for serial monitor response -String oktext = "OK"; -String errortext = "ERROR"; - -// URL and path (for example: arduino.cc) -char url[] = "arduino.cc"; -char urlproxy[] = "http://arduino.cc"; -char path[] = "/"; - -// variable for save response obtained -String response = ""; - -// use a proxy -boolean use_proxy = false; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } -} - -void loop() -{ - use_proxy = false; - - // start GSM shield - // if your SIM has PIN, pass it as a parameter of begin() in quotes - Serial.print("Connecting GSM network..."); - if(gsmAccess.begin(PINNUMBER)!=GSM_READY) - { - Serial.println(errortext); - while(true); - } - Serial.println(oktext); - - // read APN introduced by user - char apn[50]; - Serial.print("Enter your APN: "); - readSerial(apn); - Serial.println(apn); - - // Read APN login introduced by user - char login[50]; - Serial.print("Now, enter your login: "); - readSerial(login); - Serial.println(login); - - // read APN password introduced by user - char password[20]; - Serial.print("Finally, enter your password: "); - readSerial(password); - - // attach GPRS - Serial.println("Attaching to GPRS with your APN..."); - if(gprsAccess.attachGPRS(apn, login, password)!=GPRS_READY) - { - Serial.println(errortext); - } - else{ - - Serial.println(oktext); - - // read proxy introduced by user - char proxy[100]; - Serial.print("If your carrier uses a proxy, enter it, if not press enter: "); - readSerial(proxy); - Serial.println(proxy); - - // if user introduced a proxy, asks him for proxy port - int pport; - if(proxy[0] != '\0'){ - // read proxy port introduced by user - char proxyport[10]; - Serial.print("Enter the proxy port: "); - readSerial(proxyport); - // cast proxy port introduced to integer - pport = (int) proxyport; - use_proxy = true; - Serial.println(proxyport); - } - - // connection with arduino.cc and realize HTTP request - Serial.print("Connecting and sending GET request to arduino.cc..."); - int res_connect; - - // if use a proxy, connect with it - if(use_proxy) - res_connect = client.connect(proxy, pport); - else - res_connect = client.connect(url, 80); - - if (res_connect) - { - // make a HTTP 1.0 GET request (client sends the request) - client.print("GET "); - - // if use a proxy, the path is arduino.cc URL - if(use_proxy) - client.print(urlproxy); - else - client.print(path); - - client.println(" HTTP/1.0"); - client.println(); - Serial.println(oktext); - } - else - { - // if you didn't get a connection to the server - Serial.println(errortext); - } - Serial.print("Receiving response..."); - - boolean test = true; - while(test) - { - // if there are incoming bytes available - // from the server, read and check them - if (client.available()) - { - char c = client.read(); - response += c; - - // cast response obtained from string to char array - char responsechar[response.length()+1]; - response.toCharArray(responsechar, response.length()+1); - - // if response includes a "200 OK" substring - if(strstr(responsechar, "200 OK") != NULL){ - Serial.println(oktext); - Serial.println("TEST COMPLETE!"); - test = false; - } - } - - // if the server's disconnected, stop the client: - if (!client.connected()) - { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - test = false; - } - } - } -} - -/* - Read input serial - */ -int readSerial(char result[]) -{ - int i = 0; - while(1) - { - while (Serial.available() > 0) - { - char inChar = Serial.read(); - if (inChar == '\n') - { - result[i] = '\0'; - return 0; - } - if(inChar!='\r') - { - result[i] = inChar; - i++; - } - } - } -} diff --git a/libraries/GSM/examples/Tools/TestModem/TestModem.ino b/libraries/GSM/examples/Tools/TestModem/TestModem.ino deleted file mode 100644 index de61fff..0000000 --- a/libraries/GSM/examples/Tools/TestModem/TestModem.ino +++ /dev/null @@ -1,77 +0,0 @@ -/* - - This example tests to see if the modem of the - GSM shield is working correctly. You do not need - a SIM card for this example. - - Circuit: - * GSM shield attached - - Created 12 Jun 2012 - by David del Peral - modified 21 Nov 2012 - by Tom Igoe - - http://arduino.cc/en/Tutorial/GSMToolsTestModem - - This sample code is part of the public domain - - */ - -// libraries -#include - -// modem verification object -GSMModem modem; - -// IMEI variable -String IMEI = ""; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // start modem test (reset and check response) - Serial.print("Starting modem test..."); - if(modem.begin()) - Serial.println("modem.begin() succeeded"); - else - Serial.println("ERROR, no modem answer."); -} - -void loop() -{ - // get modem IMEI - Serial.print("Checking IMEI..."); - IMEI = modem.getIMEI(); - - // check IMEI response - if(IMEI != NULL) - { - // show IMEI in serial monitor - Serial.println("Modem's IMEI: " + IMEI); - // reset modem to check booting: - Serial.print("Resetting modem..."); - modem.begin(); - // get and check IMEI one more time - if(modem.getIMEI() != NULL) - { - Serial.println("Modem is functoning properly"); - } - else - { - Serial.println("Error: getIMEI() failed after modem.begin()"); - } - } - else - { - Serial.println("Error: Could not get IMEI"); - } - // do nothing: - while(true); -} - diff --git a/libraries/GSM/examples/Tools/TestWebServer/TestWebServer.ino b/libraries/GSM/examples/Tools/TestWebServer/TestWebServer.ino deleted file mode 100644 index 5cc3f8a..0000000 --- a/libraries/GSM/examples/Tools/TestWebServer/TestWebServer.ino +++ /dev/null @@ -1,85 +0,0 @@ -/* - Basic Web Server - - A simple web server that replies with nothing, but prints the client's request - and the server IP address. - - Circuit: - * GSM shield attached - - created - by David Cuartielles - modified 21 Nov 2012 - by Tom Igoe - - http://arduino.cc/en/Tutorial/GSMToolsTestWebServer - - This example code is part of the public domain - */ - #include - -// PIN Number -#define PINNUMBER "" - -// APN data -#define GPRS_APN "GPRS_APN" // replace your GPRS APN -#define GPRS_LOGIN "login" // replace with your GPRS login -#define GPRS_PASSWORD "password" // replace with your GPRS password - - -// initialize the library instance -GPRS gprs; -GSM gsmAccess; // include a 'true' parameter for debug enabled -GSMServer server(80); // port 80 (http default) - -// timeout -const unsigned long __TIMEOUT__ = 10*1000; - -void setup() -{ - // initialize serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - Serial.println("starting,.."); - // connection state - boolean connected = true; - - // Start GSM shield - // If your SIM has PIN, pass it as a parameter of begin() in quotes - while(!connected) - { - if((gsmAccess.begin(PINNUMBER)==GSM_READY) & - (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) - connected = true; - else - { - Serial.println("Not connected"); - delay(1000); - } - } - - Serial.println("Connected to GPRS network"); - - // start server - server.begin(); - - //Get IP. - IPAddress LocalIP = gprs.getIPAddress(); - Serial.println("Server IP address="); - Serial.println(LocalIP); -} - -void loop(){ - GSMClient client = server.available(); - - if (client) { - if (client.available()) { - Serial.write(client.read()); - } -} - -} - diff --git a/libraries/GSM/keywords.txt b/libraries/GSM/keywords.txt deleted file mode 100644 index 0662e75..0000000 --- a/libraries/GSM/keywords.txt +++ /dev/null @@ -1,72 +0,0 @@ -####################################### -# Syntax Coloring Map For GSM -####################################### -# Class -####################################### - -GSM KEYWORD3 -GSMVoiceCall KEYWORD3 -GSM_SMS KEYWORD3 -GPRS KEYWORD3 -GSMClient KEYWORD3 -GSMServer KEYWORD3 -GSMModem KEYWORD3 -GSMScanner KEYWORD3 -GSMPIN KEYWORD3 -GSMBand KEYWORD3 - -####################################### -# Methods and Functions -####################################### - -begin KEYWORD2 -shutdown KEYWORD2 -gatVoiceCallStatus KEYWORD2 -ready KEYWORD2 -voiceCall KEYWORD2 -answerCall KEYWORD2 -hangCall KEYWORD2 -retrieveCallingNumber KEYWORD2 -beginSMS KEYWORD2 -endSMS KEYWORD2 -remoteNumber KEYWORD2 -attachGPRS KEYWORD2 -begnWrite KEYWORD2 -endWrite KEYWORD2 -getIMEI KEYWORD2 -getCurrentCarrier KEYWORD2 -getSignalStrength KEYWORD2 -readNetworks KEYWORD2 -isPIN KEYWORD2 -checkPIN KEYWORD2 -checkPUK KEYWORD2 -changePIN KEYWORD2 -switchPIN KEYWORD2 -checkReg KEYWORD2 -getPINUsed KEYWORD2 -setPINUsed KEYWORD2 -getBand KEYWORD2 -setBand KEYWORD2 -getvoiceCallStatus KEYWORD2 - -####################################### -# Constants -####################################### - -ERROR LITERAL1 -IDLE LITERAL1 -CONNECTING LITERAL1 -GSM_READY LITERAL1 -GPRS_READY LITERAL1 -TRANSPARENT_CONNECTED LITERAL1 -IDLE_CALL LITERAL1 -CALLING LITERAL1 -RECEIVINGCALL LITERAL1 -TALKING LITERAL1 -GSM_MODE_UNDEFINED LITERAL1 -GSM_MODE_EGSM LITERAL1 -GSM_MODE_DCS LITERAL1 -GSM_MODE_PCS LITERAL1 -GSM_MODE_EGSM_DCS LITERAL1 -GSM_MODE_GSM850_PCS LITERAL1 -GSM_MODE_GSM850_EGSM_DCS_PCS LITERAL1 \ No newline at end of file -- cgit v1.2.3-18-g5258 From f40a546151183f58ce5d801283134e9f7b070a07 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Wed, 3 Jul 2013 23:18:21 +0200 Subject: SoftwareSerial library to the new format --- libraries/SoftwareSerial/SoftwareSerial.cpp | 518 --------------------- libraries/SoftwareSerial/SoftwareSerial.h | 112 ----- .../SoftwareSerialExample.ino | 55 --- .../examples/TwoPortReceive/TwoPortReceive.ino | 93 ---- libraries/SoftwareSerial/keywords.txt | 30 -- 5 files changed, 808 deletions(-) delete mode 100644 libraries/SoftwareSerial/SoftwareSerial.cpp delete mode 100644 libraries/SoftwareSerial/SoftwareSerial.h delete mode 100644 libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino delete mode 100644 libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino delete mode 100644 libraries/SoftwareSerial/keywords.txt diff --git a/libraries/SoftwareSerial/SoftwareSerial.cpp b/libraries/SoftwareSerial/SoftwareSerial.cpp deleted file mode 100644 index 64496fe..0000000 --- a/libraries/SoftwareSerial/SoftwareSerial.cpp +++ /dev/null @@ -1,518 +0,0 @@ -/* -SoftwareSerial.cpp (formerly NewSoftSerial.cpp) - -Multi-instance software serial library for Arduino/Wiring --- Interrupt-driven receive and other improvements by ladyada - (http://ladyada.net) --- Tuning, circular buffer, derivation from class Print/Stream, - multi-instance support, porting to 8MHz processors, - various optimizations, PROGMEM delay tables, inverse logic and - direct port writing by Mikal Hart (http://www.arduiniana.org) --- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com) --- 20MHz processor support by Garrett Mace (http://www.macetech.com) --- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/) - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -The latest version of this library can always be found at -http://arduiniana.org. -*/ - -// When set, _DEBUG co-opts pins 11 and 13 for debugging with an -// oscilloscope or logic analyzer. Beware: it also slightly modifies -// the bit times, so don't rely on it too much at high baud rates -#define _DEBUG 0 -#define _DEBUG_PIN1 11 -#define _DEBUG_PIN2 13 -// -// Includes -// -#include -#include -#include -#include -// -// Lookup table -// -typedef struct _DELAY_TABLE -{ - long baud; - unsigned short rx_delay_centering; - unsigned short rx_delay_intrabit; - unsigned short rx_delay_stopbit; - unsigned short tx_delay; -} DELAY_TABLE; - -#if F_CPU == 16000000 - -static const DELAY_TABLE PROGMEM table[] = -{ - // baud rxcenter rxintra rxstop tx - { 115200, 1, 17, 17, 12, }, - { 57600, 10, 37, 37, 33, }, - { 38400, 25, 57, 57, 54, }, - { 31250, 31, 70, 70, 68, }, - { 28800, 34, 77, 77, 74, }, - { 19200, 54, 117, 117, 114, }, - { 14400, 74, 156, 156, 153, }, - { 9600, 114, 236, 236, 233, }, - { 4800, 233, 474, 474, 471, }, - { 2400, 471, 950, 950, 947, }, - { 1200, 947, 1902, 1902, 1899, }, - { 600, 1902, 3804, 3804, 3800, }, - { 300, 3804, 7617, 7617, 7614, }, -}; - -const int XMIT_START_ADJUSTMENT = 5; - -#elif F_CPU == 8000000 - -static const DELAY_TABLE table[] PROGMEM = -{ - // baud rxcenter rxintra rxstop tx - { 115200, 1, 5, 5, 3, }, - { 57600, 1, 15, 15, 13, }, - { 38400, 2, 25, 26, 23, }, - { 31250, 7, 32, 33, 29, }, - { 28800, 11, 35, 35, 32, }, - { 19200, 20, 55, 55, 52, }, - { 14400, 30, 75, 75, 72, }, - { 9600, 50, 114, 114, 112, }, - { 4800, 110, 233, 233, 230, }, - { 2400, 229, 472, 472, 469, }, - { 1200, 467, 948, 948, 945, }, - { 600, 948, 1895, 1895, 1890, }, - { 300, 1895, 3805, 3805, 3802, }, -}; - -const int XMIT_START_ADJUSTMENT = 4; - -#elif F_CPU == 20000000 - -// 20MHz support courtesy of the good people at macegr.com. -// Thanks, Garrett! - -static const DELAY_TABLE PROGMEM table[] = -{ - // baud rxcenter rxintra rxstop tx - { 115200, 3, 21, 21, 18, }, - { 57600, 20, 43, 43, 41, }, - { 38400, 37, 73, 73, 70, }, - { 31250, 45, 89, 89, 88, }, - { 28800, 46, 98, 98, 95, }, - { 19200, 71, 148, 148, 145, }, - { 14400, 96, 197, 197, 194, }, - { 9600, 146, 297, 297, 294, }, - { 4800, 296, 595, 595, 592, }, - { 2400, 592, 1189, 1189, 1186, }, - { 1200, 1187, 2379, 2379, 2376, }, - { 600, 2379, 4759, 4759, 4755, }, - { 300, 4759, 9523, 9523, 9520, }, -}; - -const int XMIT_START_ADJUSTMENT = 6; - -#else - -#error This version of SoftwareSerial supports only 20, 16 and 8MHz processors - -#endif - -// -// Statics -// -SoftwareSerial *SoftwareSerial::active_object = 0; -char SoftwareSerial::_receive_buffer[_SS_MAX_RX_BUFF]; -volatile uint8_t SoftwareSerial::_receive_buffer_tail = 0; -volatile uint8_t SoftwareSerial::_receive_buffer_head = 0; - -// -// Debugging -// -// This function generates a brief pulse -// for debugging or measuring on an oscilloscope. -inline void DebugPulse(uint8_t pin, uint8_t count) -{ -#if _DEBUG - volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin)); - - uint8_t val = *pport; - while (count--) - { - *pport = val | digitalPinToBitMask(pin); - *pport = val; - } -#endif -} - -// -// Private methods -// - -/* static */ -inline void SoftwareSerial::tunedDelay(uint16_t delay) { - uint8_t tmp=0; - - asm volatile("sbiw %0, 0x01 \n\t" - "ldi %1, 0xFF \n\t" - "cpi %A0, 0xFF \n\t" - "cpc %B0, %1 \n\t" - "brne .-10 \n\t" - : "+r" (delay), "+a" (tmp) - : "0" (delay) - ); -} - -// This function sets the current object as the "listening" -// one and returns true if it replaces another -bool SoftwareSerial::listen() -{ - if (active_object != this) - { - _buffer_overflow = false; - uint8_t oldSREG = SREG; - cli(); - _receive_buffer_head = _receive_buffer_tail = 0; - active_object = this; - SREG = oldSREG; - return true; - } - - return false; -} - -// -// The receive routine called by the interrupt handler -// -void SoftwareSerial::recv() -{ - -#if GCC_VERSION < 40302 -// Work-around for avr-gcc 4.3.0 OSX version bug -// Preserve the registers that the compiler misses -// (courtesy of Arduino forum user *etracer*) - asm volatile( - "push r18 \n\t" - "push r19 \n\t" - "push r20 \n\t" - "push r21 \n\t" - "push r22 \n\t" - "push r23 \n\t" - "push r26 \n\t" - "push r27 \n\t" - ::); -#endif - - uint8_t d = 0; - - // If RX line is high, then we don't see any start bit - // so interrupt is probably not for us - if (_inverse_logic ? rx_pin_read() : !rx_pin_read()) - { - // Wait approximately 1/2 of a bit width to "center" the sample - tunedDelay(_rx_delay_centering); - DebugPulse(_DEBUG_PIN2, 1); - - // Read each of the 8 bits - for (uint8_t i=0x1; i; i <<= 1) - { - tunedDelay(_rx_delay_intrabit); - DebugPulse(_DEBUG_PIN2, 1); - uint8_t noti = ~i; - if (rx_pin_read()) - d |= i; - else // else clause added to ensure function timing is ~balanced - d &= noti; - } - - // skip the stop bit - tunedDelay(_rx_delay_stopbit); - DebugPulse(_DEBUG_PIN2, 1); - - if (_inverse_logic) - d = ~d; - - // if buffer full, set the overflow flag and return - if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head) - { - // save new data in buffer: tail points to where byte goes - _receive_buffer[_receive_buffer_tail] = d; // save new byte - _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF; - } - else - { -#if _DEBUG // for scope: pulse pin as overflow indictator - DebugPulse(_DEBUG_PIN1, 1); -#endif - _buffer_overflow = true; - } - } - -#if GCC_VERSION < 40302 -// Work-around for avr-gcc 4.3.0 OSX version bug -// Restore the registers that the compiler misses - asm volatile( - "pop r27 \n\t" - "pop r26 \n\t" - "pop r23 \n\t" - "pop r22 \n\t" - "pop r21 \n\t" - "pop r20 \n\t" - "pop r19 \n\t" - "pop r18 \n\t" - ::); -#endif -} - -void SoftwareSerial::tx_pin_write(uint8_t pin_state) -{ - if (pin_state == LOW) - *_transmitPortRegister &= ~_transmitBitMask; - else - *_transmitPortRegister |= _transmitBitMask; -} - -uint8_t SoftwareSerial::rx_pin_read() -{ - return *_receivePortRegister & _receiveBitMask; -} - -// -// Interrupt handling -// - -/* static */ -inline void SoftwareSerial::handle_interrupt() -{ - if (active_object) - { - active_object->recv(); - } -} - -#if defined(PCINT0_vect) -ISR(PCINT0_vect) -{ - SoftwareSerial::handle_interrupt(); -} -#endif - -#if defined(PCINT1_vect) -ISR(PCINT1_vect) -{ - SoftwareSerial::handle_interrupt(); -} -#endif - -#if defined(PCINT2_vect) -ISR(PCINT2_vect) -{ - SoftwareSerial::handle_interrupt(); -} -#endif - -#if defined(PCINT3_vect) -ISR(PCINT3_vect) -{ - SoftwareSerial::handle_interrupt(); -} -#endif - -// -// Constructor -// -SoftwareSerial::SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) : - _rx_delay_centering(0), - _rx_delay_intrabit(0), - _rx_delay_stopbit(0), - _tx_delay(0), - _buffer_overflow(false), - _inverse_logic(inverse_logic) -{ - setTX(transmitPin); - setRX(receivePin); -} - -// -// Destructor -// -SoftwareSerial::~SoftwareSerial() -{ - end(); -} - -void SoftwareSerial::setTX(uint8_t tx) -{ - pinMode(tx, OUTPUT); - digitalWrite(tx, HIGH); - _transmitBitMask = digitalPinToBitMask(tx); - uint8_t port = digitalPinToPort(tx); - _transmitPortRegister = portOutputRegister(port); -} - -void SoftwareSerial::setRX(uint8_t rx) -{ - pinMode(rx, INPUT); - if (!_inverse_logic) - digitalWrite(rx, HIGH); // pullup for normal logic! - _receivePin = rx; - _receiveBitMask = digitalPinToBitMask(rx); - uint8_t port = digitalPinToPort(rx); - _receivePortRegister = portInputRegister(port); -} - -// -// Public methods -// - -void SoftwareSerial::begin(long speed) -{ - _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0; - - for (unsigned i=0; i -#include - -/****************************************************************************** -* Definitions -******************************************************************************/ - -#define _SS_MAX_RX_BUFF 64 // RX buffer size -#ifndef GCC_VERSION -#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) -#endif - -class SoftwareSerial : public Stream -{ -private: - // per object data - uint8_t _receivePin; - uint8_t _receiveBitMask; - volatile uint8_t *_receivePortRegister; - uint8_t _transmitBitMask; - volatile uint8_t *_transmitPortRegister; - - uint16_t _rx_delay_centering; - uint16_t _rx_delay_intrabit; - uint16_t _rx_delay_stopbit; - uint16_t _tx_delay; - - uint16_t _buffer_overflow:1; - uint16_t _inverse_logic:1; - - // static data - static char _receive_buffer[_SS_MAX_RX_BUFF]; - static volatile uint8_t _receive_buffer_tail; - static volatile uint8_t _receive_buffer_head; - static SoftwareSerial *active_object; - - // private methods - void recv(); - uint8_t rx_pin_read(); - void tx_pin_write(uint8_t pin_state); - void setTX(uint8_t transmitPin); - void setRX(uint8_t receivePin); - - // private static method for timing - static inline void tunedDelay(uint16_t delay); - -public: - // public methods - SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false); - ~SoftwareSerial(); - void begin(long speed); - bool listen(); - void end(); - bool isListening() { return this == active_object; } - bool overflow() { bool ret = _buffer_overflow; _buffer_overflow = false; return ret; } - int peek(); - - virtual size_t write(uint8_t byte); - virtual int read(); - virtual int available(); - virtual void flush(); - - using Print::write; - - // public only for easy access by interrupt handlers - static inline void handle_interrupt(); -}; - -// Arduino 0012 workaround -#undef int -#undef char -#undef long -#undef byte -#undef float -#undef abs -#undef round - -#endif diff --git a/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino b/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino deleted file mode 100644 index 6101bb1..0000000 --- a/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino +++ /dev/null @@ -1,55 +0,0 @@ -/* - Software serial multple serial test - - Receives from the hardware serial, sends to software serial. - Receives from software serial, sends to hardware serial. - - The circuit: - * RX is digital pin 10 (connect to TX of other device) - * TX is digital pin 11 (connect to RX of other device) - - Note: - Not all pins on the Mega and Mega 2560 support change interrupts, - so only the following can be used for RX: - 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69 - - Not all pins on the Leonardo support change interrupts, - so only the following can be used for RX: - 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI). - - created back in the mists of time - modified 25 May 2012 - by Tom Igoe - based on Mikal Hart's example - - This example code is in the public domain. - - */ -#include - -SoftwareSerial mySerial(10, 11); // RX, TX - -void setup() -{ - // Open serial communications and wait for port to open: - Serial.begin(57600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - Serial.println("Goodnight moon!"); - - // set the data rate for the SoftwareSerial port - mySerial.begin(4800); - mySerial.println("Hello, world?"); -} - -void loop() // run over and over -{ - if (mySerial.available()) - Serial.write(mySerial.read()); - if (Serial.available()) - mySerial.write(Serial.read()); -} - diff --git a/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino b/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino deleted file mode 100644 index d607ee6..0000000 --- a/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino +++ /dev/null @@ -1,93 +0,0 @@ -/* - Software serial multple serial test - - Receives from the two software serial ports, - sends to the hardware serial port. - - In order to listen on a software port, you call port.listen(). - When using two software serial ports, you have to switch ports - by listen()ing on each one in turn. Pick a logical time to switch - ports, like the end of an expected transmission, or when the - buffer is empty. This example switches ports when there is nothing - more to read from a port - - The circuit: - Two devices which communicate serially are needed. - * First serial device's TX attached to digital pin 2, RX to pin 3 - * Second serial device's TX attached to digital pin 4, RX to pin 5 - - Note: - Not all pins on the Mega and Mega 2560 support change interrupts, - so only the following can be used for RX: - 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69 - - Not all pins on the Leonardo support change interrupts, - so only the following can be used for RX: - 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI). - - created 18 Apr. 2011 - modified 25 May 2012 - by Tom Igoe - based on Mikal Hart's twoPortRXExample - - This example code is in the public domain. - - */ - -#include -// software serial #1: TX = digital pin 10, RX = digital pin 11 -SoftwareSerial portOne(10,11); - -// software serial #2: TX = digital pin 8, RX = digital pin 9 -// on the Mega, use other pins instead, since 8 and 9 don't work on the Mega -SoftwareSerial portTwo(8,9); - -void setup() -{ - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - - // Start each software serial port - portOne.begin(9600); - portTwo.begin(9600); -} - -void loop() -{ - // By default, the last intialized port is listening. - // when you want to listen on a port, explicitly select it: - portOne.listen(); - Serial.println("Data from port one:"); - // while there is data coming in, read it - // and send to the hardware serial port: - while (portOne.available() > 0) { - char inByte = portOne.read(); - Serial.write(inByte); - } - - // blank line to separate data from the two ports: - Serial.println(); - - // Now listen on the second port - portTwo.listen(); - // while there is data coming in, read it - // and send to the hardware serial port: - Serial.println("Data from port two:"); - while (portTwo.available() > 0) { - char inByte = portTwo.read(); - Serial.write(inByte); - } - - // blank line to separate data from the two ports: - Serial.println(); -} - - - - - - diff --git a/libraries/SoftwareSerial/keywords.txt b/libraries/SoftwareSerial/keywords.txt deleted file mode 100644 index 3f36dfc..0000000 --- a/libraries/SoftwareSerial/keywords.txt +++ /dev/null @@ -1,30 +0,0 @@ -####################################### -# Syntax Coloring Map for SoftwareSerial -# (formely NewSoftSerial) -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -SoftwareSerial KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -end KEYWORD2 -read KEYWORD2 -write KEYWORD2 -available KEYWORD2 -isListening KEYWORD2 -overflow KEYWORD2 -flush KEYWORD2 -listen KEYWORD2 -peek KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - -- cgit v1.2.3-18-g5258 From 8df1ed0ad2785b9bd4a7ac48921c0c5a0649729f Mon Sep 17 00:00:00 2001 From: Fede85 Date: Thu, 4 Jul 2013 13:29:15 +0200 Subject: updated Firmata library to version 2.3.5 and moved to the new library format --- libraries/Firmata/Boards.h | 366 ------------ libraries/Firmata/Firmata.cpp | 444 -------------- libraries/Firmata/Firmata.h | 163 ------ libraries/Firmata/LICENSE.txt | 458 --------------- libraries/Firmata/TODO.txt | 14 - .../examples/AllInputsFirmata/AllInputsFirmata.ino | 90 --- .../examples/AnalogFirmata/AnalogFirmata.ino | 94 --- .../Firmata/examples/EchoString/EchoString.ino | 46 -- .../Firmata/examples/I2CFirmata/I2CFirmata.ino | 228 -------- .../examples/OldStandardFirmata/LICENSE.txt | 458 --------------- .../OldStandardFirmata/OldStandardFirmata.ino | 239 -------- .../Firmata/examples/ServoFirmata/ServoFirmata.ino | 53 -- .../SimpleAnalogFirmata/SimpleAnalogFirmata.ino | 46 -- .../SimpleDigitalFirmata/SimpleDigitalFirmata.ino | 72 --- .../Firmata/examples/StandardFirmata/LICENSE.txt | 458 --------------- .../examples/StandardFirmata/StandardFirmata.ino | 636 --------------------- libraries/Firmata/keywords.txt | 62 -- 17 files changed, 3927 deletions(-) delete mode 100644 libraries/Firmata/Boards.h delete mode 100644 libraries/Firmata/Firmata.cpp delete mode 100644 libraries/Firmata/Firmata.h delete mode 100644 libraries/Firmata/LICENSE.txt delete mode 100644 libraries/Firmata/TODO.txt delete mode 100644 libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino delete mode 100644 libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino delete mode 100644 libraries/Firmata/examples/EchoString/EchoString.ino delete mode 100644 libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino delete mode 100644 libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt delete mode 100644 libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino delete mode 100644 libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino delete mode 100644 libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino delete mode 100644 libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino delete mode 100644 libraries/Firmata/examples/StandardFirmata/LICENSE.txt delete mode 100644 libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino delete mode 100644 libraries/Firmata/keywords.txt diff --git a/libraries/Firmata/Boards.h b/libraries/Firmata/Boards.h deleted file mode 100644 index 06f69c6..0000000 --- a/libraries/Firmata/Boards.h +++ /dev/null @@ -1,366 +0,0 @@ -/* Boards.h - Hardware Abstraction Layer for Firmata library */ - -#ifndef Firmata_Boards_h -#define Firmata_Boards_h - -#include - -#if defined(ARDUINO) && ARDUINO >= 100 -#include "Arduino.h" // for digitalRead, digitalWrite, etc -#else -#include "WProgram.h" -#endif - -// Normally Servo.h must be included before Firmata.h (which then includes -// this file). If Servo.h wasn't included, this allows the code to still -// compile, but without support for any Servos. Hopefully that's what the -// user intended by not including Servo.h -#ifndef MAX_SERVOS -#define MAX_SERVOS 0 -#endif - -/* - Firmata Hardware Abstraction Layer - -Firmata is built on top of the hardware abstraction functions of Arduino, -specifically digitalWrite, digitalRead, analogWrite, analogRead, and -pinMode. While these functions offer simple integer pin numbers, Firmata -needs more information than is provided by Arduino. This file provides -all other hardware specific details. To make Firmata support a new board, -only this file should require editing. - -The key concept is every "pin" implemented by Firmata may be mapped to -any pin as implemented by Arduino. Usually a simple 1-to-1 mapping is -best, but such mapping should not be assumed. This hardware abstraction -layer allows Firmata to implement any number of pins which map onto the -Arduino implemented pins in almost any arbitrary way. - - -General Constants: - -These constants provide basic information Firmata requires. - -TOTAL_PINS: The total number of pins Firmata implemented by Firmata. - Usually this will match the number of pins the Arduino functions - implement, including any pins pins capable of analog or digital. - However, Firmata may implement any number of pins. For example, - on Arduino Mini with 8 analog inputs, 6 of these may be used - for digital functions, and 2 are analog only. On such boards, - Firmata can implement more pins than Arduino's pinMode() - function, in order to accommodate those special pins. The - Firmata protocol supports a maximum of 128 pins, so this - constant must not exceed 128. - -TOTAL_ANALOG_PINS: The total number of analog input pins implemented. - The Firmata protocol allows up to 16 analog inputs, accessed - using offsets 0 to 15. Because Firmata presents the analog - inputs using different offsets than the actual pin numbers - (a legacy of Arduino's analogRead function, and the way the - analog input capable pins are physically labeled on all - Arduino boards), the total number of analog input signals - must be specified. 16 is the maximum. - -VERSION_BLINK_PIN: When Firmata starts up, it will blink the version - number. This constant is the Arduino pin number where a - LED is connected. - - -Pin Mapping Macros: - -These macros provide the mapping between pins as implemented by -Firmata protocol and the actual pin numbers used by the Arduino -functions. Even though such mappings are often simple, pin -numbers received by Firmata protocol should always be used as -input to these macros, and the result of the macro should be -used with with any Arduino function. - -When Firmata is extended to support a new pin mode or feature, -a pair of macros should be added and used for all hardware -access. For simple 1:1 mapping, these macros add no actual -overhead, yet their consistent use allows source code which -uses them consistently to be easily adapted to all other boards -with different requirements. - -IS_PIN_XXXX(pin): The IS_PIN macros resolve to true or non-zero - if a pin as implemented by Firmata corresponds to a pin - that actually implements the named feature. - -PIN_TO_XXXX(pin): The PIN_TO macros translate pin numbers as - implemented by Firmata to the pin numbers needed as inputs - to the Arduino functions. The corresponding IS_PIN macro - should always be tested before using a PIN_TO macro, so - these macros only need to handle valid Firmata pin - numbers for the named feature. - - -Port Access Inline Funtions: - -For efficiency, Firmata protocol provides access to digital -input and output pins grouped by 8 bit ports. When these -groups of 8 correspond to actual 8 bit ports as implemented -by the hardware, these inline functions can provide high -speed direct port access. Otherwise, a default implementation -using 8 calls to digitalWrite or digitalRead is used. - -When porting Firmata to a new board, it is recommended to -use the default functions first and focus only on the constants -and macros above. When those are working, if optimized port -access is desired, these inline functions may be extended. -The recommended approach defines a symbol indicating which -optimization to use, and then conditional complication is -used within these functions. - -readPort(port, bitmask): Read an 8 bit port, returning the value. - port: The port number, Firmata pins port*8 to port*8+7 - bitmask: The actual pins to read, indicated by 1 bits. - -writePort(port, value, bitmask): Write an 8 bit port. - port: The port number, Firmata pins port*8 to port*8+7 - value: The 8 bit value to write - bitmask: The actual pins to write, indicated by 1 bits. -*/ - -/*============================================================================== - * Board Specific Configuration - *============================================================================*/ - -#ifndef digitalPinHasPWM -#define digitalPinHasPWM(p) IS_PIN_DIGITAL(p) -#endif - -// Arduino Duemilanove, Diecimila, and NG -#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) -#if defined(NUM_ANALOG_INPUTS) && NUM_ANALOG_INPUTS == 6 -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 20 // 14 digital + 6 analog -#else -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS 22 // 14 digital + 8 analog -#endif -#define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) -#define ARDUINO_PINOUT_OPTIMIZE 1 - - -// Wiring (and board) -#elif defined(WIRING) -#define VERSION_BLINK_PIN WLED -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= FIRST_ANALOG_PIN && (p) < (FIRST_ANALOG_PIN+TOTAL_ANALOG_PINS)) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - FIRST_ANALOG_PIN) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// old Arduinos -#elif defined(__AVR_ATmega8__) -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 20 // 14 digital + 6 analog -#define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) -#define ARDUINO_PINOUT_OPTIMIZE 1 - - -// Arduino Mega -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define TOTAL_ANALOG_PINS 16 -#define TOTAL_PINS 70 // 54 digital + 16 analog -#define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 54) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// Teensy 1.0 -#elif defined(__AVR_AT90USB162__) -#define TOTAL_ANALOG_PINS 0 -#define TOTAL_PINS 21 // 21 digital + no analog -#define VERSION_BLINK_PIN 6 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) (0) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (0) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Teensy 2.0 -#elif defined(__AVR_ATmega32U4__) -#define TOTAL_ANALOG_PINS 12 -#define TOTAL_PINS 25 // 11 digital + 12 analog -#define VERSION_BLINK_PIN 11 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 11 && (p) <= 22) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 5 || (p) == 6) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (((p)<22)?21-(p):11) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Teensy++ 1.0 and 2.0 -#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS 46 // 38 digital + 8 analog -#define VERSION_BLINK_PIN 6 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 38 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 0 || (p) == 1) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 38) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Sanguino -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS 32 // 24 digital + 8 analog -#define VERSION_BLINK_PIN 0 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 24) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// Illuminato -#elif defined(__AVR_ATmega645__) -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 42 // 36 digital + 6 analog -#define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 36 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 36) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// anything else -#else -#error "Please edit Boards.h with a hardware abstraction for this board" -#endif - - -/*============================================================================== - * readPort() - Read an 8 bit port - *============================================================================*/ - -static inline unsigned char readPort(byte, byte) __attribute__((always_inline, unused)); -static inline unsigned char readPort(byte port, byte bitmask) -{ -#if defined(ARDUINO_PINOUT_OPTIMIZE) - if (port == 0) return (PIND & 0xFC) & bitmask; // ignore Rx/Tx 0/1 - if (port == 1) return ((PINB & 0x3F) | ((PINC & 0x03) << 6)) & bitmask; - if (port == 2) return ((PINC & 0x3C) >> 2) & bitmask; - return 0; -#else - unsigned char out=0, pin=port*8; - if (IS_PIN_DIGITAL(pin+0) && (bitmask & 0x01) && digitalRead(PIN_TO_DIGITAL(pin+0))) out |= 0x01; - if (IS_PIN_DIGITAL(pin+1) && (bitmask & 0x02) && digitalRead(PIN_TO_DIGITAL(pin+1))) out |= 0x02; - if (IS_PIN_DIGITAL(pin+2) && (bitmask & 0x04) && digitalRead(PIN_TO_DIGITAL(pin+2))) out |= 0x04; - if (IS_PIN_DIGITAL(pin+3) && (bitmask & 0x08) && digitalRead(PIN_TO_DIGITAL(pin+3))) out |= 0x08; - if (IS_PIN_DIGITAL(pin+4) && (bitmask & 0x10) && digitalRead(PIN_TO_DIGITAL(pin+4))) out |= 0x10; - if (IS_PIN_DIGITAL(pin+5) && (bitmask & 0x20) && digitalRead(PIN_TO_DIGITAL(pin+5))) out |= 0x20; - if (IS_PIN_DIGITAL(pin+6) && (bitmask & 0x40) && digitalRead(PIN_TO_DIGITAL(pin+6))) out |= 0x40; - if (IS_PIN_DIGITAL(pin+7) && (bitmask & 0x80) && digitalRead(PIN_TO_DIGITAL(pin+7))) out |= 0x80; - return out; -#endif -} - -/*============================================================================== - * writePort() - Write an 8 bit port, only touch pins specified by a bitmask - *============================================================================*/ - -static inline unsigned char writePort(byte, byte, byte) __attribute__((always_inline, unused)); -static inline unsigned char writePort(byte port, byte value, byte bitmask) -{ -#if defined(ARDUINO_PINOUT_OPTIMIZE) - if (port == 0) { - bitmask = bitmask & 0xFC; // do not touch Tx & Rx pins - byte valD = value & bitmask; - byte maskD = ~bitmask; - cli(); - PORTD = (PORTD & maskD) | valD; - sei(); - } else if (port == 1) { - byte valB = (value & bitmask) & 0x3F; - byte valC = (value & bitmask) >> 6; - byte maskB = ~(bitmask & 0x3F); - byte maskC = ~((bitmask & 0xC0) >> 6); - cli(); - PORTB = (PORTB & maskB) | valB; - PORTC = (PORTC & maskC) | valC; - sei(); - } else if (port == 2) { - bitmask = bitmask & 0x0F; - byte valC = (value & bitmask) << 2; - byte maskC = ~(bitmask << 2); - cli(); - PORTC = (PORTC & maskC) | valC; - sei(); - } -#else - byte pin=port*8; - if ((bitmask & 0x01)) digitalWrite(PIN_TO_DIGITAL(pin+0), (value & 0x01)); - if ((bitmask & 0x02)) digitalWrite(PIN_TO_DIGITAL(pin+1), (value & 0x02)); - if ((bitmask & 0x04)) digitalWrite(PIN_TO_DIGITAL(pin+2), (value & 0x04)); - if ((bitmask & 0x08)) digitalWrite(PIN_TO_DIGITAL(pin+3), (value & 0x08)); - if ((bitmask & 0x10)) digitalWrite(PIN_TO_DIGITAL(pin+4), (value & 0x10)); - if ((bitmask & 0x20)) digitalWrite(PIN_TO_DIGITAL(pin+5), (value & 0x20)); - if ((bitmask & 0x40)) digitalWrite(PIN_TO_DIGITAL(pin+6), (value & 0x40)); - if ((bitmask & 0x80)) digitalWrite(PIN_TO_DIGITAL(pin+7), (value & 0x80)); -#endif -} - - - - -#ifndef TOTAL_PORTS -#define TOTAL_PORTS ((TOTAL_PINS + 7) / 8) -#endif - - -#endif /* Firmata_Boards_h */ - diff --git a/libraries/Firmata/Firmata.cpp b/libraries/Firmata/Firmata.cpp deleted file mode 100644 index 36f8ed1..0000000 --- a/libraries/Firmata/Firmata.cpp +++ /dev/null @@ -1,444 +0,0 @@ -/* - Firmata.cpp - Firmata library - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. -*/ - -//****************************************************************************** -//* Includes -//****************************************************************************** - -#include "Firmata.h" -#include "HardwareSerial.h" - -extern "C" { -#include -#include -} - -//****************************************************************************** -//* Support Functions -//****************************************************************************** - -void FirmataClass::sendValueAsTwo7bitBytes(int value) -{ - FirmataSerial.write(value & B01111111); // LSB - FirmataSerial.write(value >> 7 & B01111111); // MSB -} - -void FirmataClass::startSysex(void) -{ - FirmataSerial.write(START_SYSEX); -} - -void FirmataClass::endSysex(void) -{ - FirmataSerial.write(END_SYSEX); -} - -//****************************************************************************** -//* Constructors -//****************************************************************************** - -FirmataClass::FirmataClass(Stream &s) : FirmataSerial(s) -{ - firmwareVersionCount = 0; - systemReset(); -} - -//****************************************************************************** -//* Public Methods -//****************************************************************************** - -/* begin method for overriding default serial bitrate */ -void FirmataClass::begin(void) -{ - begin(57600); -} - -/* begin method for overriding default serial bitrate */ -void FirmataClass::begin(long speed) -{ - Serial.begin(speed); - FirmataSerial = Serial; - blinkVersion(); - printVersion(); - printFirmwareVersion(); -} - -void FirmataClass::begin(Stream &s) -{ - FirmataSerial = s; - systemReset(); - printVersion(); - printFirmwareVersion(); -} - -// output the protocol version message to the serial port -void FirmataClass::printVersion(void) { - FirmataSerial.write(REPORT_VERSION); - FirmataSerial.write(FIRMATA_MAJOR_VERSION); - FirmataSerial.write(FIRMATA_MINOR_VERSION); -} - -void FirmataClass::blinkVersion(void) -{ - // flash the pin with the protocol version - pinMode(VERSION_BLINK_PIN,OUTPUT); - pin13strobe(FIRMATA_MAJOR_VERSION, 40, 210); - delay(250); - pin13strobe(FIRMATA_MINOR_VERSION, 40, 210); - delay(125); -} - -void FirmataClass::printFirmwareVersion(void) -{ - byte i; - - if(firmwareVersionCount) { // make sure that the name has been set before reporting - startSysex(); - FirmataSerial.write(REPORT_FIRMWARE); - FirmataSerial.write(firmwareVersionVector[0]); // major version number - FirmataSerial.write(firmwareVersionVector[1]); // minor version number - for(i=2; i 0) && (inputData < 128) ) { - waitForData--; - storedInputData[waitForData] = inputData; - if( (waitForData==0) && executeMultiByteCommand ) { // got the whole message - switch(executeMultiByteCommand) { - case ANALOG_MESSAGE: - if(currentAnalogCallback) { - (*currentAnalogCallback)(multiByteChannel, - (storedInputData[0] << 7) - + storedInputData[1]); - } - break; - case DIGITAL_MESSAGE: - if(currentDigitalCallback) { - (*currentDigitalCallback)(multiByteChannel, - (storedInputData[0] << 7) - + storedInputData[1]); - } - break; - case SET_PIN_MODE: - if(currentPinModeCallback) - (*currentPinModeCallback)(storedInputData[1], storedInputData[0]); - break; - case REPORT_ANALOG: - if(currentReportAnalogCallback) - (*currentReportAnalogCallback)(multiByteChannel,storedInputData[0]); - break; - case REPORT_DIGITAL: - if(currentReportDigitalCallback) - (*currentReportDigitalCallback)(multiByteChannel,storedInputData[0]); - break; - } - executeMultiByteCommand = 0; - } - } else { - // remove channel info from command byte if less than 0xF0 - if(inputData < 0xF0) { - command = inputData & 0xF0; - multiByteChannel = inputData & 0x0F; - } else { - command = inputData; - // commands in the 0xF* range don't use channel data - } - switch (command) { - case ANALOG_MESSAGE: - case DIGITAL_MESSAGE: - case SET_PIN_MODE: - waitForData = 2; // two data bytes needed - executeMultiByteCommand = command; - break; - case REPORT_ANALOG: - case REPORT_DIGITAL: - waitForData = 1; // one data byte needed - executeMultiByteCommand = command; - break; - case START_SYSEX: - parsingSysex = true; - sysexBytesRead = 0; - break; - case SYSTEM_RESET: - systemReset(); - break; - case REPORT_VERSION: - Firmata.printVersion(); - break; - } - } -} - -//------------------------------------------------------------------------------ -// Serial Send Handling - -// send an analog message -void FirmataClass::sendAnalog(byte pin, int value) -{ - // pin can only be 0-15, so chop higher bits - FirmataSerial.write(ANALOG_MESSAGE | (pin & 0xF)); - sendValueAsTwo7bitBytes(value); -} - -// send a single digital pin in a digital message -void FirmataClass::sendDigital(byte pin, int value) -{ - /* TODO add single pin digital messages to the protocol, this needs to - * track the last digital data sent so that it can be sure to change just - * one bit in the packet. This is complicated by the fact that the - * numbering of the pins will probably differ on Arduino, Wiring, and - * other boards. The DIGITAL_MESSAGE sends 14 bits at a time, but it is - * probably easier to send 8 bit ports for any board with more than 14 - * digital pins. - */ - - // TODO: the digital message should not be sent on the serial port every - // time sendDigital() is called. Instead, it should add it to an int - // which will be sent on a schedule. If a pin changes more than once - // before the digital message is sent on the serial port, it should send a - // digital message for each change. - - // if(value == 0) - // sendDigitalPortPair(); -} - - -// send 14-bits in a single digital message (protocol v1) -// send an 8-bit port in a single digital message (protocol v2) -void FirmataClass::sendDigitalPort(byte portNumber, int portData) -{ - FirmataSerial.write(DIGITAL_MESSAGE | (portNumber & 0xF)); - FirmataSerial.write((byte)portData % 128); // Tx bits 0-6 - FirmataSerial.write(portData >> 7); // Tx bits 7-13 -} - - -void FirmataClass::sendSysex(byte command, byte bytec, byte* bytev) -{ - byte i; - startSysex(); - FirmataSerial.write(command); - for(i=0; i - -byte pin; - -int analogValue; -int previousAnalogValues[TOTAL_ANALOG_PINS]; - -byte portStatus[TOTAL_PORTS]; // each bit: 1=pin is digital input, 0=other/ignore -byte previousPINs[TOTAL_PORTS]; - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -/* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you - get long, random delays. So only read analogs every 20ms or so */ -int samplingInterval = 19; // how often to run the main loop (in ms) - -void sendPort(byte portNumber, byte portValue) -{ - portValue = portValue & portStatus[portNumber]; - if(previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -void setup() -{ - byte i, port, status; - - Firmata.setFirmwareVersion(0, 1); - - for(pin = 0; pin < TOTAL_PINS; pin++) { - if IS_PIN_DIGITAL(pin) pinMode(PIN_TO_DIGITAL(pin), INPUT); - } - - for (port=0; port samplingInterval) { - previousMillis += samplingInterval; - while(Firmata.available()) { - Firmata.processInput(); - } - for(pin = 0; pin < TOTAL_ANALOG_PINS; pin++) { - analogValue = analogRead(pin); - if(analogValue != previousAnalogValues[pin]) { - Firmata.sendAnalog(pin, analogValue); - previousAnalogValues[pin] = analogValue; - } - } - } -} - - diff --git a/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino b/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino deleted file mode 100644 index ff1d664..0000000 --- a/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* This firmware supports as many analog ports as possible, all analog inputs, - * four PWM outputs, and two with servo support. - * - * This example code is in the public domain. - */ -#include -#include - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* servos */ -Servo servo9, servo10; // one instance per pin -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting -int analogPin = 0; // counter for reading analog pins -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis - - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void analogWriteCallback(byte pin, int value) -{ - switch(pin) { - case 9: servo9.write(value); break; - case 10: servo10.write(value); break; - case 3: - case 5: - case 6: - case 11: // PWM pins - analogWrite(pin, value); - break; - } -} -// ----------------------------------------------------------------------------- -// sets bits in a bit array (int) to toggle the reporting of the analogIns -void reportAnalogCallback(byte pin, int value) -{ - if(value == 0) { - analogInputsToReport = analogInputsToReport &~ (1 << pin); - } - else { // everything but 0 enables reporting of that pin - analogInputsToReport = analogInputsToReport | (1 << pin); - } - // TODO: save status to EEPROM here, if changed -} - -/*============================================================================== - * SETUP() - *============================================================================*/ -void setup() -{ - Firmata.setFirmwareVersion(0, 2); - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - - servo9.attach(9); - servo10.attach(10); - Firmata.begin(57600); -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - while(Firmata.available()) - Firmata.processInput(); - currentMillis = millis(); - if(currentMillis - previousMillis > 20) { - previousMillis += 20; // run this every 20ms - for(analogPin=0;analogPin - -byte analogPin; - -void stringCallback(char *myString) -{ - Firmata.sendString(myString); -} - - -void sysexCallback(byte command, byte argc, byte*argv) -{ - Firmata.sendSysex(command, argc, argv); -} - -void setup() -{ - Firmata.setFirmwareVersion(0, 1); - Firmata.attach(STRING_DATA, stringCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.begin(57600); -} - -void loop() -{ - while(Firmata.available()) { - Firmata.processInput(); - } -} - - diff --git a/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino b/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino deleted file mode 100644 index 1da8963..0000000 --- a/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* - Copyright (C) 2009 Jeff Hoefs. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - */ - -#include -#include - - -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 - -#define MAX_QUERIES 8 - -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -unsigned int samplingInterval = 32; // default sampling interval is 33ms -unsigned int i2cReadDelayTime = 0; // default delay time between i2c read request and Wire.requestFrom() -unsigned int powerPinsEnabled = 0; // use as boolean to prevent enablePowerPins from being called more than once - -#define MINIMUM_SAMPLING_INTERVAL 10 - -#define REGISTER_NOT_SPECIFIED -1 - -struct i2c_device_info { - byte addr; - byte reg; - byte bytes; -}; - -i2c_device_info query[MAX_QUERIES]; - -byte i2cRxData[32]; -boolean readingContinuously = false; -byte queryIndex = 0; - -void readAndReportData(byte address, int theRegister, byte numBytes) -{ - if (theRegister != REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - Wire.write((byte)theRegister); - Wire.endTransmission(); - delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck - } - else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); - - // check to be sure correct number of bytes were returned by slave - if(numBytes == Wire.available()) { - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - for (int i = 0; i < numBytes; i++) { - i2cRxData[2 + i] = Wire.read(); - } - // send slave address, register and received bytes - Firmata.sendSysex(I2C_REPLY, numBytes + 2, i2cRxData); - } - else { - if(numBytes > Wire.available()) { - Firmata.sendString("I2C Read Error: Too many bytes received"); - } else { - Firmata.sendString("I2C Read Error: Too few bytes received"); - } - } - -} - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte slaveAddress; - byte slaveRegister; - byte data; - int delayTime; - - if (command == I2C_REQUEST) { - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - slaveAddress = argv[0]; - - switch(mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - Wire.write(data); - } - Wire.endTransmission(); - delayMicroseconds(70); // TODO is this needed? - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - readAndReportData(slaveAddress, (int)slaveRegister, data); - } - else { - // a slave register is NOT specified - data = argv[2] + (argv[3] << 7); // bytes to read - readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data); - } - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = argv[2] + (argv[3] << 7); - query[queryIndex].bytes = argv[4] + (argv[5] << 7); - readingContinuously = true; - queryIndex++; - break; - case I2C_STOP_READING: - readingContinuously = false; - queryIndex = 0; - break; - default: - break; - } - } - else if (command == SAMPLING_INTERVAL) { - samplingInterval = argv[0] + (argv[1] << 7); - - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - - samplingInterval -= 1; - Firmata.sendString("sampling interval"); - } - - else if (command == I2C_CONFIG) { - delayTime = (argv[4] + (argv[5] << 7)); // MSB - delayTime = (delayTime << 8) + (argv[2] + (argv[3] << 7)); // add LSB - - if((argv[0] + (argv[1] << 7)) > 0) { - enablePowerPins(PORTC3, PORTC2); - } - - if(delayTime > 0) { - i2cReadDelayTime = delayTime; - } - - if(argc > 6) { - // If you extend I2C_Config, handle your data here - } - - } -} - -void systemResetCallback() -{ - readingContinuously = false; - queryIndex = 0; -} - -/* reference: BlinkM_funcs.h by Tod E. Kurt, ThingM, http://thingm.com/ */ -// Enables Pins A2 and A3 to be used as GND and Power -// so that I2C devices can be plugged directly -// into Arduino header (pins A2 - A5) -static void enablePowerPins(byte pwrpin, byte gndpin) -{ - if(powerPinsEnabled == 0) { - DDRC |= _BV(pwrpin) | _BV(gndpin); - PORTC &=~ _BV(gndpin); - PORTC |= _BV(pwrpin); - powerPinsEnabled = 1; - Firmata.sendString("Power pins enabled"); - delay(100); - } -} - -void setup() -{ - Firmata.setFirmwareVersion(2, 0); - - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - - for (int i = 0; i < TOTAL_PINS; ++i) { - pinMode(i, OUTPUT); - } - - Firmata.begin(57600); - Wire.begin(); -} - -void loop() -{ - while (Firmata.available()) { - Firmata.processInput(); - } - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - - for (byte i = 0; i < queryIndex; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes); - } - } -} diff --git a/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt b/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt deleted file mode 100644 index 77cec6d..0000000 --- a/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino b/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino deleted file mode 100644 index d306c70..0000000 --- a/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - */ - -/* - * This is an old version of StandardFirmata (v2.0). It is kept here because - * its the last version that works on an ATMEGA8 chip. Also, it can be used - * for host software that has not been updated to a newer version of the - * protocol. It also uses the old baud rate of 115200 rather than 57600. - */ - -#include -#include - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting -int analogPin = 0; // counter for reading analog pins - -/* digital pins */ -byte reportPINs[TOTAL_PORTS]; // PIN == input port -byte previousPINs[TOTAL_PORTS]; // PIN == input port -byte pinStatus[TOTAL_PINS]; // store pin status, default OUTPUT -byte portStatus[TOTAL_PORTS]; - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis - - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void outputPort(byte portNumber, byte portValue) -{ - portValue = portValue &~ portStatus[portNumber]; - if(previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - Firmata.sendDigitalPort(portNumber, portValue); - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Serial output queue using Serial.print() */ -void checkDigitalInputs(void) -{ - byte i, tmp; - for(i=0; i < TOTAL_PORTS; i++) { - if(reportPINs[i]) { - switch(i) { - case 0: outputPort(0, PIND &~ B00000011); break; // ignore Rx/Tx 0/1 - case 1: outputPort(1, PINB); break; - case 2: outputPort(2, PINC); break; - } - } - } -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) { - byte port = 0; - byte offset = 0; - - if (pin < 8) { - port = 0; - offset = 0; - } else if (pin < 14) { - port = 1; - offset = 8; - } else if (pin < 22) { - port = 2; - offset = 14; - } - - if(pin > 1) { // ignore RxTx (pins 0 and 1) - pinStatus[pin] = mode; - switch(mode) { - case INPUT: - pinMode(pin, INPUT); - portStatus[port] = portStatus[port] &~ (1 << (pin - offset)); - break; - case OUTPUT: - digitalWrite(pin, LOW); // disable PWM - case PWM: - pinMode(pin, OUTPUT); - portStatus[port] = portStatus[port] | (1 << (pin - offset)); - break; - //case ANALOG: // TODO figure this out - default: - Firmata.sendString(""); - } - // TODO: save status to EEPROM here, if changed - } -} - -void analogWriteCallback(byte pin, int value) -{ - setPinModeCallback(pin,PWM); - analogWrite(pin, value); -} - -void digitalWriteCallback(byte port, int value) -{ - switch(port) { - case 0: // pins 2-7 (don't change Rx/Tx, pins 0 and 1) - // 0xFF03 == B1111111100000011 0x03 == B00000011 - PORTD = (value &~ 0xFF03) | (PORTD & 0x03); - break; - case 1: // pins 8-13 (14,15 are disabled for the crystal) - PORTB = (byte)value; - break; - case 2: // analog pins used as digital - PORTC = (byte)value; - break; - } -} - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte pin, int value) -{ - if(value == 0) { - analogInputsToReport = analogInputsToReport &~ (1 << pin); - } - else { // everything but 0 enables reporting of that pin - analogInputsToReport = analogInputsToReport | (1 << pin); - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - reportPINs[port] = (byte)value; - if(port == 2) // turn off analog reporting when used as digital - analogInputsToReport = 0; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ -void setup() -{ - byte i; - - Firmata.setFirmwareVersion(2, 0); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - - portStatus[0] = B00000011; // ignore Tx/RX pins - portStatus[1] = B11000000; // ignore 14/15 pins - portStatus[2] = B00000000; - -// for(i=0; i 20) { - previousMillis += 20; // run this every 20ms - /* SERIALREAD - Serial.read() uses a 128 byte circular buffer, so handle - * all serialReads at once, i.e. empty the buffer */ - while(Firmata.available()) - Firmata.processInput(); - /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over - * 60 bytes. use a timer to sending an event character every 4 ms to - * trigger the buffer to dump. */ - - /* ANALOGREAD - right after the event character, do all of the - * analogReads(). These only need to be done every 4ms. */ - for(analogPin=0;analogPin -#include - -Servo servos[MAX_SERVOS]; - -void analogWriteCallback(byte pin, int value) -{ - if (IS_PIN_SERVO(pin)) { - servos[PIN_TO_SERVO(pin)].write(value); - } -} - -void setup() -{ - byte pin; - - Firmata.setFirmwareVersion(0, 2); - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - - for (pin=0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_SERVO(pin)) { - servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin)); - } - } - - Firmata.begin(57600); -} - -void loop() -{ - while(Firmata.available()) - Firmata.processInput(); -} - diff --git a/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino b/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino deleted file mode 100644 index 44ea91e..0000000 --- a/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* Supports as many analog inputs and analog PWM outputs as possible. - * - * This example code is in the public domain. - */ -#include - -byte analogPin = 0; - -void analogWriteCallback(byte pin, int value) -{ - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), value); - } -} - -void setup() -{ - Firmata.setFirmwareVersion(0, 1); - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.begin(57600); -} - -void loop() -{ - while(Firmata.available()) { - Firmata.processInput(); - } - // do one analogRead per loop, so if PC is sending a lot of - // analog write messages, we will only delay 1 analogRead - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - analogPin = analogPin + 1; - if (analogPin >= TOTAL_ANALOG_PINS) analogPin = 0; -} - diff --git a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino deleted file mode 100644 index a0d764f..0000000 --- a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* Supports as many digital inputs and outputs as possible. - * - * This example code is in the public domain. - */ -#include - -byte previousPIN[TOTAL_PORTS]; // PIN means PORT for input -byte previousPORT[TOTAL_PORTS]; - -void outputPort(byte portNumber, byte portValue) -{ - // only send the data when it changes, otherwise you get too many messages! - if (previousPIN[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPIN[portNumber] = portValue; - } -} - -void setPinModeCallback(byte pin, int mode) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), mode); - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte i; - byte currentPinValue, previousPinValue; - - if (port < TOTAL_PORTS && value != previousPORT[port]) { - for(i=0; i<8; i++) { - currentPinValue = (byte) value & (1 << i); - previousPinValue = previousPORT[port] & (1 << i); - if(currentPinValue != previousPinValue) { - digitalWrite(i + (port*8), currentPinValue); - } - } - previousPORT[port] = value; - } -} - -void setup() -{ - Firmata.setFirmwareVersion(0, 1); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.begin(57600); -} - -void loop() -{ - byte i; - - for (i=0; i -#include -#include - -// move the following defines to Firmata.h? -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 -#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 - -#define MAX_QUERIES 8 -#define MINIMUM_SAMPLING_INTERVAL 10 - -#define REGISTER_NOT_SPECIFIED -1 - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting - -/* digital input ports */ -byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence -byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent - -/* pins configuration */ -byte pinConfig[TOTAL_PINS]; // configuration of every pin -byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else -int pinState[TOTAL_PINS]; // any value that has been written - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -int samplingInterval = 19; // how often to run the main loop (in ms) - -/* i2c data */ -struct i2c_device_info { - byte addr; - byte reg; - byte bytes; -}; - -/* for i2c read continuous more */ -i2c_device_info query[MAX_QUERIES]; - -byte i2cRxData[32]; -boolean isI2CEnabled = false; -signed char queryIndex = -1; -unsigned int i2cReadDelayTime = 0; // default delay time between i2c read request and Wire.requestFrom() - -Servo servos[MAX_SERVOS]; -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void readAndReportData(byte address, int theRegister, byte numBytes) { - // allow I2C requests that don't require a register read - // for example, some devices using an interrupt pin to signify new data available - // do not always require the register read so upon interrupt you call Wire.requestFrom() - if (theRegister != REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - #if ARDUINO >= 100 - Wire.write((byte)theRegister); - #else - Wire.send((byte)theRegister); - #endif - Wire.endTransmission(); - delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck - } else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom - - // check to be sure correct number of bytes were returned by slave - if(numBytes == Wire.available()) { - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - for (int i = 0; i < numBytes; i++) { - #if ARDUINO >= 100 - i2cRxData[2 + i] = Wire.read(); - #else - i2cRxData[2 + i] = Wire.receive(); - #endif - } - } - else { - if(numBytes > Wire.available()) { - Firmata.sendString("I2C Read Error: Too many bytes received"); - } else { - Firmata.sendString("I2C Read Error: Too few bytes received"); - } - } - - // send slave address, register and received bytes - Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); -} - -void outputPort(byte portNumber, byte portValue, byte forceSend) -{ - // pins not configured as INPUT are cleared to zeros - portValue = portValue & portConfigInputs[portNumber]; - // only send if the value is different than previously sent - if(forceSend || previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Serial output queue using Serial.print() */ -void checkDigitalInputs(void) -{ - /* Using non-looping code allows constants to be given to readPort(). - * The compiler will apply substantial optimizations if the inputs - * to readPort() are compile-time constants. */ - if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); - if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); - if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); - if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); - if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); - if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); - if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); - if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); - if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); - if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); - if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); - if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); - if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); - if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); - if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); - if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) -{ - if (pinConfig[pin] == I2C && isI2CEnabled && mode != I2C) { - // disable i2c so pins can be used for other functions - // the following if statements should reconfigure the pins properly - disableI2CPins(); - } - if (IS_PIN_SERVO(pin) && mode != SERVO && servos[PIN_TO_SERVO(pin)].attached()) { - servos[PIN_TO_SERVO(pin)].detach(); - } - if (IS_PIN_ANALOG(pin)) { - reportAnalogCallback(PIN_TO_ANALOG(pin), mode == ANALOG ? 1 : 0); // turn on/off reporting - } - if (IS_PIN_DIGITAL(pin)) { - if (mode == INPUT) { - portConfigInputs[pin/8] |= (1 << (pin & 7)); - } else { - portConfigInputs[pin/8] &= ~(1 << (pin & 7)); - } - } - pinState[pin] = 0; - switch(mode) { - case ANALOG: - if (IS_PIN_ANALOG(pin)) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups - } - pinConfig[pin] = ANALOG; - } - break; - case INPUT: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups - pinConfig[pin] = INPUT; - } - break; - case OUTPUT: - if (IS_PIN_DIGITAL(pin)) { - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - pinConfig[pin] = OUTPUT; - } - break; - case PWM: - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_PWM(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), 0); - pinConfig[pin] = PWM; - } - break; - case SERVO: - if (IS_PIN_SERVO(pin)) { - pinConfig[pin] = SERVO; - if (!servos[PIN_TO_SERVO(pin)].attached()) { - servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin)); - } - } - break; - case I2C: - if (IS_PIN_I2C(pin)) { - // mark the pin as i2c - // the user must call I2C_CONFIG to enable I2C for a device - pinConfig[pin] = I2C; - } - break; - default: - Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM - } - // TODO: save status to EEPROM here, if changed -} - -void analogWriteCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS) { - switch(pinConfig[pin]) { - case SERVO: - if (IS_PIN_SERVO(pin)) - servos[PIN_TO_SERVO(pin)].write(value); - pinState[pin] = value; - break; - case PWM: - if (IS_PIN_PWM(pin)) - analogWrite(PIN_TO_PWM(pin), value); - pinState[pin] = value; - break; - } - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte pin, lastPin, mask=1, pinWriteMask=0; - - if (port < TOTAL_PORTS) { - // create a mask of the pins on this port that are writable. - lastPin = port*8+8; - if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; - for (pin=port*8; pin < lastPin; pin++) { - // do not disturb non-digital pins (eg, Rx & Tx) - if (IS_PIN_DIGITAL(pin)) { - // only write to OUTPUT and INPUT (enables pullup) - // do not touch pins in PWM, ANALOG, SERVO or other modes - if (pinConfig[pin] == OUTPUT || pinConfig[pin] == INPUT) { - pinWriteMask |= mask; - pinState[pin] = ((byte)value & mask) ? 1 : 0; - } - } - mask = mask << 1; - } - writePort(port, (byte)value, pinWriteMask); - } -} - - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte analogPin, int value) -{ - if (analogPin < TOTAL_ANALOG_PINS) { - if(value == 0) { - analogInputsToReport = analogInputsToReport &~ (1 << analogPin); - } else { - analogInputsToReport = analogInputsToReport | (1 << analogPin); - } - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - if (port < TOTAL_PORTS) { - reportPINs[port] = (byte)value; - } - // do not disable analog reporting on these 8 pins, to allow some - // pins used for digital, others analog. Instead, allow both types - // of reporting to be enabled, but check if the pin is configured - // as analog when sampling the analog inputs. Likewise, while - // scanning digital pins, portConfigInputs will mask off values from any - // pins configured as analog -} - -/*============================================================================== - * SYSEX-BASED commands - *============================================================================*/ - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte slaveAddress; - byte slaveRegister; - byte data; - unsigned int delayTime; - - switch(command) { - case I2C_REQUEST: - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { - Firmata.sendString("10-bit addressing mode is not yet supported"); - return; - } - else { - slaveAddress = argv[0]; - } - - switch(mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - #if ARDUINO >= 100 - Wire.write(data); - #else - Wire.send(data); - #endif - } - Wire.endTransmission(); - delayMicroseconds(70); - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - readAndReportData(slaveAddress, (int)slaveRegister, data); - } - else { - // a slave register is NOT specified - data = argv[2] + (argv[3] << 7); // bytes to read - readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data); - } - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - queryIndex++; - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = argv[2] + (argv[3] << 7); - query[queryIndex].bytes = argv[4] + (argv[5] << 7); - break; - case I2C_STOP_READING: - byte queryIndexToSkip; - // if read continuous mode is enabled for only 1 i2c device, disable - // read continuous reporting for that device - if (queryIndex <= 0) { - queryIndex = -1; - } else { - // if read continuous mode is enabled for multiple devices, - // determine which device to stop reading and remove it's data from - // the array, shifiting other array data to fill the space - for (byte i = 0; i < queryIndex + 1; i++) { - if (query[i].addr = slaveAddress) { - queryIndexToSkip = i; - break; - } - } - - for (byte i = queryIndexToSkip; i 0) { - i2cReadDelayTime = delayTime; - } - - if (!isI2CEnabled) { - enableI2CPins(); - } - - break; - case SERVO_CONFIG: - if(argc > 4) { - // these vars are here for clarity, they'll optimized away by the compiler - byte pin = argv[0]; - int minPulse = argv[1] + (argv[2] << 7); - int maxPulse = argv[3] + (argv[4] << 7); - - if (IS_PIN_SERVO(pin)) { - if (servos[PIN_TO_SERVO(pin)].attached()) - servos[PIN_TO_SERVO(pin)].detach(); - servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); - setPinModeCallback(pin, SERVO); - } - } - break; - case SAMPLING_INTERVAL: - if (argc > 1) { - samplingInterval = argv[0] + (argv[1] << 7); - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - } else { - //Firmata.sendString("Not enough data"); - } - break; - case EXTENDED_ANALOG: - if (argc > 1) { - int val = argv[1]; - if (argc > 2) val |= (argv[2] << 7); - if (argc > 3) val |= (argv[3] << 14); - analogWriteCallback(argv[0], val); - } - break; - case CAPABILITY_QUERY: - Serial.write(START_SYSEX); - Serial.write(CAPABILITY_RESPONSE); - for (byte pin=0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - Serial.write((byte)INPUT); - Serial.write(1); - Serial.write((byte)OUTPUT); - Serial.write(1); - } - if (IS_PIN_ANALOG(pin)) { - Serial.write(ANALOG); - Serial.write(10); - } - if (IS_PIN_PWM(pin)) { - Serial.write(PWM); - Serial.write(8); - } - if (IS_PIN_SERVO(pin)) { - Serial.write(SERVO); - Serial.write(14); - } - if (IS_PIN_I2C(pin)) { - Serial.write(I2C); - Serial.write(1); // to do: determine appropriate value - } - Serial.write(127); - } - Serial.write(END_SYSEX); - break; - case PIN_STATE_QUERY: - if (argc > 0) { - byte pin=argv[0]; - Serial.write(START_SYSEX); - Serial.write(PIN_STATE_RESPONSE); - Serial.write(pin); - if (pin < TOTAL_PINS) { - Serial.write((byte)pinConfig[pin]); - Serial.write((byte)pinState[pin] & 0x7F); - if (pinState[pin] & 0xFF80) Serial.write((byte)(pinState[pin] >> 7) & 0x7F); - if (pinState[pin] & 0xC000) Serial.write((byte)(pinState[pin] >> 14) & 0x7F); - } - Serial.write(END_SYSEX); - } - break; - case ANALOG_MAPPING_QUERY: - Serial.write(START_SYSEX); - Serial.write(ANALOG_MAPPING_RESPONSE); - for (byte pin=0; pin < TOTAL_PINS; pin++) { - Serial.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); - } - Serial.write(END_SYSEX); - break; - } -} - -void enableI2CPins() -{ - byte i; - // is there a faster way to do this? would probaby require importing - // Arduino.h to get SCL and SDA pins - for (i=0; i < TOTAL_PINS; i++) { - if(IS_PIN_I2C(i)) { - // mark pins as i2c so they are ignore in non i2c data requests - setPinModeCallback(i, I2C); - } - } - - isI2CEnabled = true; - - // is there enough time before the first I2C request to call this here? - Wire.begin(); -} - -/* disable the i2c pins so they can be used for other functions */ -void disableI2CPins() { - isI2CEnabled = false; - // disable read continuous mode for all devices - queryIndex = -1; - // uncomment the following if or when the end() method is added to Wire library - // Wire.end(); -} - -/*============================================================================== - * SETUP() - *============================================================================*/ - -void systemResetCallback() -{ - // initialize a defalt state - // TODO: option to load config from EEPROM instead of default - if (isI2CEnabled) { - disableI2CPins(); - } - for (byte i=0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; // by default, reporting off - portConfigInputs[i] = 0; // until activated - previousPINs[i] = 0; - } - // pins with analog capability default to analog input - // otherwise, pins default to digital output - for (byte i=0; i < TOTAL_PINS; i++) { - if (IS_PIN_ANALOG(i)) { - // turns off pullup, configures everything - setPinModeCallback(i, ANALOG); - } else { - // sets the output to 0, configures portConfigInputs - setPinModeCallback(i, OUTPUT); - } - } - // by default, do not report any analog inputs - analogInputsToReport = 0; - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - /* - TODO: this can never execute, since no pins default to digital input - but it will be needed when/if we support EEPROM stored config - for (byte i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - */ -} - -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - - Firmata.begin(57600); - systemResetCallback(); // reset to default config -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - byte pin, analogPin; - - /* DIGITALREAD - as fast as possible, check for changes and output them to the - * FTDI buffer using Serial.print() */ - checkDigitalInputs(); - - /* SERIALREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while(Firmata.available()) - Firmata.processInput(); - - /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over - * 60 bytes. use a timer to sending an event character every 4 ms to - * trigger the buffer to dump. */ - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - /* ANALOGREAD - do all analogReads() at the configured sampling interval */ - for(pin=0; pin -1) { - for (byte i = 0; i < queryIndex + 1; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes); - } - } - } -} diff --git a/libraries/Firmata/keywords.txt b/libraries/Firmata/keywords.txt deleted file mode 100644 index 52e0a9c..0000000 --- a/libraries/Firmata/keywords.txt +++ /dev/null @@ -1,62 +0,0 @@ -####################################### -# Syntax Coloring Map For Firmata -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Firmata KEYWORD1 -callbackFunction KEYWORD1 -systemResetCallbackFunction KEYWORD1 -stringCallbackFunction KEYWORD1 -sysexCallbackFunction KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -begin KEYWORD2 -printVersion KEYWORD2 -blinkVersion KEYWORD2 -printFirmwareVersion KEYWORD2 -setFirmwareVersion KEYWORD2 -setFirmwareNameAndVersion KEYWORD2 -available KEYWORD2 -processInput KEYWORD2 -sendAnalog KEYWORD2 -sendDigital KEYWORD2 -sendDigitalPortPair KEYWORD2 -sendDigitalPort KEYWORD2 -sendString KEYWORD2 -sendString KEYWORD2 -sendSysex KEYWORD2 -attach KEYWORD2 -detach KEYWORD2 -flush KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### - -MAX_DATA_BYTES LITERAL1 - -DIGITAL_MESSAGE LITERAL1 -ANALOG_MESSAGE LITERAL1 -REPORT_ANALOG LITERAL1 -REPORT_DIGITAL LITERAL1 -REPORT_VERSION LITERAL1 -SET_PIN_MODE LITERAL1 -SYSTEM_RESET LITERAL1 - -START_SYSEX LITERAL1 -END_SYSEX LITERAL1 - -PWM LITERAL1 - -TOTAL_ANALOG_PINS LITERAL1 -TOTAL_DIGITAL_PINS LITERAL1 -TOTAL_PORTS LITERAL1 -ANALOG_PORT LITERAL1 -- cgit v1.2.3-18-g5258 From cfebeec56699b44a6df3bf257545fb1a32acac32 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Thu, 4 Jul 2013 15:54:30 +0200 Subject: Esplora library to new format --- .../EsploraAccelerometer/EsploraAccelerometer.ino | 38 ---- .../Beginners/EsploraBlink/EsploraBlink.ino | 42 ---- .../EsploraJoystickMouse/EsploraJoystickMouse.ino | 50 ----- .../Beginners/EsploraLedShow/EsploraLedShow.ino | 42 ---- .../Beginners/EsploraLedShow2/EsploraLedShow2.ino | 55 ------ .../EsploraLightCalibrator.ino | 91 --------- .../Beginners/EsploraMusic/EsploraMusic.ino | 53 ----- .../EsploraSoundSensor/EsploraSoundSensor.ino | 41 ---- .../EsploraTemperatureSensor.ino | 37 ---- libraries/Esplora/Esplora.cpp | 184 ------------------ libraries/Esplora/Esplora.h | 165 ---------------- .../Esplora/Experts/EsploraKart/EsploraKart.ino | 125 ------------ .../Esplora/Experts/EsploraPong/EsploraPong.ino | 44 ----- .../Experts/EsploraRemote/EsploraRemote.ino | 116 ----------- .../Esplora/Experts/EsploraTable/EsploraTable.ino | 213 --------------------- libraries/Esplora/keywords.txt | 69 ------- 16 files changed, 1365 deletions(-) delete mode 100644 libraries/Esplora/Beginners/EsploraAccelerometer/EsploraAccelerometer.ino delete mode 100644 libraries/Esplora/Beginners/EsploraBlink/EsploraBlink.ino delete mode 100644 libraries/Esplora/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino delete mode 100644 libraries/Esplora/Beginners/EsploraLedShow/EsploraLedShow.ino delete mode 100644 libraries/Esplora/Beginners/EsploraLedShow2/EsploraLedShow2.ino delete mode 100644 libraries/Esplora/Beginners/EsploraLightCalibrator/EsploraLightCalibrator.ino delete mode 100644 libraries/Esplora/Beginners/EsploraMusic/EsploraMusic.ino delete mode 100644 libraries/Esplora/Beginners/EsploraSoundSensor/EsploraSoundSensor.ino delete mode 100644 libraries/Esplora/Beginners/EsploraTemperatureSensor/EsploraTemperatureSensor.ino delete mode 100644 libraries/Esplora/Esplora.cpp delete mode 100644 libraries/Esplora/Esplora.h delete mode 100644 libraries/Esplora/Experts/EsploraKart/EsploraKart.ino delete mode 100644 libraries/Esplora/Experts/EsploraPong/EsploraPong.ino delete mode 100644 libraries/Esplora/Experts/EsploraRemote/EsploraRemote.ino delete mode 100644 libraries/Esplora/Experts/EsploraTable/EsploraTable.ino delete mode 100644 libraries/Esplora/keywords.txt diff --git a/libraries/Esplora/Beginners/EsploraAccelerometer/EsploraAccelerometer.ino b/libraries/Esplora/Beginners/EsploraAccelerometer/EsploraAccelerometer.ino deleted file mode 100644 index db5cc93..0000000 --- a/libraries/Esplora/Beginners/EsploraAccelerometer/EsploraAccelerometer.ino +++ /dev/null @@ -1,38 +0,0 @@ -/* - Esplora Accelerometer - - This sketch shows you how to read the values from the accelerometer. - To see it in action, open the serial monitor and tilt the board. You'll see - the accelerometer values for each axis change when you tilt the board - on that axis. - - Created on 22 Dec 2012 - by Tom Igoe - - This example is in the public domain. - */ - -#include - -void setup() -{ - Serial.begin(9600); // initialize serial communications with your computer -} - -void loop() -{ - int xAxis = Esplora.readAccelerometer(X_AXIS); // read the X axis - int yAxis = Esplora.readAccelerometer(Y_AXIS); // read the Y axis - int zAxis = Esplora.readAccelerometer(Z_AXIS); // read the Z axis - - Serial.print("x: "); // print the label for X - Serial.print(xAxis); // print the value for the X axis - Serial.print("\ty: "); // print a tab character, then the label for Y - Serial.print(yAxis); // print the value for the Y axis - Serial.print("\tz: "); // print a tab character, then the label for Z - Serial.println(zAxis); // print the value for the Z axis - - delay(500); // wait half a second (500 milliseconds) -} - - diff --git a/libraries/Esplora/Beginners/EsploraBlink/EsploraBlink.ino b/libraries/Esplora/Beginners/EsploraBlink/EsploraBlink.ino deleted file mode 100644 index e198551..0000000 --- a/libraries/Esplora/Beginners/EsploraBlink/EsploraBlink.ino +++ /dev/null @@ -1,42 +0,0 @@ - -/* - Esplora Blink - - This sketch blinks the Esplora's RGB LED. It goes through - all three primary colors (red, green, blue), then it - combines them for secondary colors(yellow, cyan, magenta), then - it turns on all the colors for white. - For best results cover the LED with a piece of white paper to see the colors. - - Created on 22 Dec 2012 - by Tom Igoe - - This example is in the public domain. - */ - -#include - - -void setup() { - // There's nothing to set up for this sketch -} - -void loop() { - Esplora.writeRGB(255,0,0); // make the LED red - delay(1000); // wait 1 second - Esplora.writeRGB(0,255,0); // make the LED green - delay(1000); // wait 1 second - Esplora.writeRGB(0,0,255); // make the LED blue - delay(1000); // wait 1 second - Esplora.writeRGB(255,255,0); // make the LED yellow - delay(1000); // wait 1 second - Esplora.writeRGB(0,255,255); // make the LED cyan - delay(1000); // wait 1 second - Esplora.writeRGB(255,0,255); // make the LED magenta - delay(1000); // wait 1 second - Esplora.writeRGB(255,255,255);// make the LED white - delay(1000); // wait 1 second - -} - - diff --git a/libraries/Esplora/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino b/libraries/Esplora/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino deleted file mode 100644 index 8d9260e..0000000 --- a/libraries/Esplora/Beginners/EsploraJoystickMouse/EsploraJoystickMouse.ino +++ /dev/null @@ -1,50 +0,0 @@ -/* - Esplora Joystick Mouse - - This sketch shows you how to read the joystick and use it to control the movement - of the cursor on your computer. You're making your Esplora into a mouse! - - WARNING: this sketch will take over your mouse movement. If you lose control - of your mouse do the following: - 1) unplug the Esplora. - 2) open the EsploraBlink sketch - 3) hold the reset button down while plugging your Esplora back in - 4) while holding reset, click "Upload" - 5) when you see the message "Done compiling", release the reset button. - - This will stop your Esplora from controlling your mouse while you upload a sketch - that doesn't take control of the mouse. - - Created on 22 Dec 2012 - by Tom Igoe - - This example is in the public domain. - */ - -#include - -void setup() -{ - Serial.begin(9600); // initialize serial communication with your computer - Mouse.begin(); // take control of the mouse -} - -void loop() -{ - int xValue = Esplora.readJoystickX(); // read the joystick's X position - int yValue = Esplora.readJoystickY(); // read the joystick's Y position - int button = Esplora.readJoystickSwitch(); // read the joystick pushbutton - Serial.print("Joystick X: "); // print a label for the X value - Serial.print(xValue); // print the X value - Serial.print("\tY: "); // print a tab character and a label for the Y value - Serial.print(yValue); // print the Y value - Serial.print("\tButton: "); // print a tab character and a label for the button - Serial.print(button); // print the button value - - int mouseX = map( xValue,-512, 512, 10, -10); // map the X value to a range of movement for the mouse X - int mouseY = map( yValue,-512, 512, -10, 10); // map the Y value to a range of movement for the mouse Y - Mouse.move(mouseX, mouseY, 0); // move the mouse - - delay(10); // a short delay before moving again -} - diff --git a/libraries/Esplora/Beginners/EsploraLedShow/EsploraLedShow.ino b/libraries/Esplora/Beginners/EsploraLedShow/EsploraLedShow.ino deleted file mode 100644 index 3c617dc..0000000 --- a/libraries/Esplora/Beginners/EsploraLedShow/EsploraLedShow.ino +++ /dev/null @@ -1,42 +0,0 @@ -/* - Esplora LED Show - - Makes the RGB LED bright and glow as the joystick or the - slider are moved. - - Created on 22 november 2012 - By Enrico Gueli - Modified 22 Dec 2012 - by Tom Igoe -*/ -#include - -void setup() { - // initialize the serial communication: - Serial.begin(9600); -} - -void loop() { - // read the sensors into variables: - int xAxis = Esplora.readJoystickX(); - int yAxis = Esplora.readJoystickY(); - int slider = Esplora.readSlider(); - - // convert the sensor readings to light levels: - byte red = map(xAxis, -512, 512, 0, 255); - byte green = map(yAxis, -512, 512, 0, 255); - byte blue = slider/4; - - // print the light levels: - Serial.print(red); - Serial.print(' '); - Serial.print(green); - Serial.print(' '); - Serial.println(blue); - - // write the light levels to the LED. - Esplora.writeRGB(red, green, blue); - - // add a delay to keep the LED from flickering: - delay(10); -} diff --git a/libraries/Esplora/Beginners/EsploraLedShow2/EsploraLedShow2.ino b/libraries/Esplora/Beginners/EsploraLedShow2/EsploraLedShow2.ino deleted file mode 100644 index 8f9f8a2..0000000 --- a/libraries/Esplora/Beginners/EsploraLedShow2/EsploraLedShow2.ino +++ /dev/null @@ -1,55 +0,0 @@ -/* - Esplora Led/Microphone - - This simple sketch reads the microphone, light sensor, and slider. - Then it uses those readings to set the brightness of red, green and blue - channels of the RGB LED. The red channel will change with the loudness - "heared" by the microphone, the green channel changes as the - amount of light in the room and the blue channel will change - with the position of the slider. - - Created on 22 november 2012 - By Enrico Gueli - Modified 24 Nov 2012 - by Tom Igoe -*/ - -#include - -void setup() { - // initialize the serial communication: - Serial.begin(9600); -} - -int lowLight = 400; // the light sensor reading when it's covered -int highLight = 1023; // the maximum light sensor reading -int minGreen = 0; // minimum brightness of the green LED -int maxGreen = 100; // maximum brightness of the green LED - -void loop() { - // read the sensors into variables: - int mic = Esplora.readMicrophone(); - int light = Esplora.readLightSensor(); - int slider = Esplora.readSlider(); - - // convert the sensor readings to light levels: - byte red = constrain(mic, 0, 255); - byte green = constrain( - map(light, lowLight, highLight, minGreen, maxGreen), - 0, 255); - byte blue = slider/4; - - // print the light levels (to see what's going on): - Serial.print(red); - Serial.print(' '); - Serial.print(green); - Serial.print(' '); - Serial.println(blue); - - // write the light levels to the LED. - // note that the green value is always 0: - Esplora.writeRGB(red, green, blue); - - // add a delay to keep the LED from flickering: - delay(10); -} diff --git a/libraries/Esplora/Beginners/EsploraLightCalibrator/EsploraLightCalibrator.ino b/libraries/Esplora/Beginners/EsploraLightCalibrator/EsploraLightCalibrator.ino deleted file mode 100644 index c3eaff4..0000000 --- a/libraries/Esplora/Beginners/EsploraLightCalibrator/EsploraLightCalibrator.ino +++ /dev/null @@ -1,91 +0,0 @@ -/* - Esplora Led calibration - - This sketch shows you how to read and calibrate the light sensor. - Because light levels vary from one location to another, you need to calibrate the - sensor for each location. To do this, you read the sensor for a few seconds, - and save the highest and lowest readings as maximum and minimum. - Then, when you're using the sensor's reading (for example, to set the brightness - of the LED), you map the sensor's reading to a range between the minimum - and the maximum. - - Created on 22 Dec 2012 - by Tom Igoe - - This example is in the public domain. - */ - -#include - -// variables: -int lightMin = 1023; // minimum sensor value -int lightMax = 0; // maximum sensor value -boolean calibrated = false; // whether the sensor's been calibrated yet - -void setup() { - // initialize the serial communication: - Serial.begin(9600); - - // print an intial message - Serial.println("To calibrate the light sensor, press and hold Switch 1"); -} - -void loop() { - // if switch 1 is pressed, go to the calibration function again: - if (Esplora.readButton(1) == LOW) { - calibrate(); - } - // read the sensor into a variable: - int light = Esplora.readLightSensor(); - - // map the light level to a brightness level for the LED - // using the calibration min and max: - int brightness = map(light, lightMin, lightMax, 0, 255); - // limit the brightness to a range from 0 to 255: - brightness = constrain(brightness, 0, 255); - // write the brightness to the blue LED. - Esplora.writeBlue(brightness); - - // if the calibration's been done, show the sensor and brightness - // levels in the serial monitor: - if (calibrated == true) { - // print the light sensor levels and the LED levels (to see what's going on): - Serial.print("light sensor level: "); - Serial.print(light); - Serial.print(" blue brightness: "); - Serial.println(brightness); - } - // add a delay to keep the LED from flickering: - delay(10); -} - -void calibrate() { - // tell the user what do to using the serial monitor: - Serial.println("While holding switch 1, shine a light on the light sensor, then cover it."); - - // calibrate while switch 1 is pressed: - while(Esplora.readButton(1) == LOW) { - // read the sensor value: - int light = Esplora.readLightSensor(); - - // record the maximum sensor value: - if (light > lightMax) { - lightMax = light; - } - - // record the minimum sensor value: - if (light < lightMin) { - lightMin = light; - } - // note that you're calibrated, for future reference: - calibrated = true; - } -} - - - - - - - - diff --git a/libraries/Esplora/Beginners/EsploraMusic/EsploraMusic.ino b/libraries/Esplora/Beginners/EsploraMusic/EsploraMusic.ino deleted file mode 100644 index 7a950fb..0000000 --- a/libraries/Esplora/Beginners/EsploraMusic/EsploraMusic.ino +++ /dev/null @@ -1,53 +0,0 @@ -/* - Esplora Music - - This sketch turns the Esplora in a simple musical instrument. - Press the Switch 1 and move the slider to see how it works. - - Created on 22 november 2012 - By Enrico Gueli - modified 22 Dec 2012 - by Tom Igoe -*/ - - -#include - -// these are the frequencies for the notes from middle C -// to one octave above middle C: -const int note[] = { -262, // C -277, // C# -294, // D -311, // D# -330, // E -349, // F -370, // F# -392, // G -415, // G# -440, // A -466, // A# -494, // B -523 // C next octave -}; - -void setup() { -} - -void loop() { - // read the button labeled SWITCH_DOWN. If it's low, - // then play a note: - if (Esplora.readButton(SWITCH_DOWN) == LOW) { - int slider = Esplora.readSlider(); - - // use map() to map the slider's range to the - // range of notes you have: - byte thisNote = map(slider, 0, 1023, 0, 13); - // play the note corresponding to the slider's position: - Esplora.tone(note[thisNote]); - } - else { - // if the button isn't pressed, turn the note off: - Esplora.noTone(); - } -} diff --git a/libraries/Esplora/Beginners/EsploraSoundSensor/EsploraSoundSensor.ino b/libraries/Esplora/Beginners/EsploraSoundSensor/EsploraSoundSensor.ino deleted file mode 100644 index 3bf454f..0000000 --- a/libraries/Esplora/Beginners/EsploraSoundSensor/EsploraSoundSensor.ino +++ /dev/null @@ -1,41 +0,0 @@ -/* - Esplora Sound Sensor - - This sketch shows you how to read the microphone sensor. The microphone -will range from 0 (total silence) to 1023 (really loud). - When you're using the sensor's reading (for example, to set the brightness - of the LED), you map the sensor's reading to a range between the minimum - and the maximum. - - Created on 22 Dec 2012 - by Tom Igoe - - This example is in the public domain. - */ - -#include - -void setup() { - // initialize the serial communication: - Serial.begin(9600); -} - -void loop() { - // read the sensor into a variable: - int loudness = Esplora.readMicrophone(); - - // map the sound level to a brightness level for the LED: - int brightness = map(loudness, 0, 1023, 0, 255); - // write the brightness to the green LED: - Esplora.writeGreen(brightness); - - - // print the microphone levels and the LED levels (to see what's going on): - Serial.print("sound level: "); - Serial.print(loudness); - Serial.print(" Green brightness: "); - Serial.println(brightness); - // add a delay to keep the LED from flickering: - delay(10); -} - diff --git a/libraries/Esplora/Beginners/EsploraTemperatureSensor/EsploraTemperatureSensor.ino b/libraries/Esplora/Beginners/EsploraTemperatureSensor/EsploraTemperatureSensor.ino deleted file mode 100644 index 72bbf04..0000000 --- a/libraries/Esplora/Beginners/EsploraTemperatureSensor/EsploraTemperatureSensor.ino +++ /dev/null @@ -1,37 +0,0 @@ -/* - Esplora Temperature Sensor - - This sketch shows you how to read the Esplora's temperature sensor - You can read the temperature sensor in Farhenheit or Celsius. - - Created on 22 Dec 2012 - by Tom Igoe - - This example is in the public domain. - */ -#include - -void setup() -{ - Serial.begin(9600); // initialize serial communications with your computer -} - -void loop() -{ - // read the temperature sensor in Celsius, then Fahrenheit: - int celsius = Esplora.readTemperature(DEGREES_C); - int fahrenheit = Esplora.readTemperature(DEGREES_F); - - // print the results: - Serial.print("Temperature is: "); - Serial.print(celsius); - Serial.print(" degrees Celsius, or "); - Serial.print(fahrenheit); - Serial.println(" degrees Fahrenheit."); - Serial.println(" Fahrenheit = (9/5 * Celsius) + 32"); - - // wait a second before reading again: - delay(1000); -} - - diff --git a/libraries/Esplora/Esplora.cpp b/libraries/Esplora/Esplora.cpp deleted file mode 100644 index 29c9e19..0000000 --- a/libraries/Esplora/Esplora.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/* - Esplora.cpp - Arduino Esplora board library - Written by Enrico Gueli - Copyright (c) 2012 Arduino(TM) All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -#include "Esplora.h" - -_Esplora Esplora; - -/* - * The following constants tell, for each accelerometer - * axis, which values are returned when the axis measures - * zero acceleration. - */ -const int ACCEL_ZERO_X = 320; -const int ACCEL_ZERO_Y = 330; -const int ACCEL_ZERO_Z = 310; - -const byte MUX_ADDR_PINS[] = { A0, A1, A2, A3 }; -const byte MUX_COM_PIN = A4; - -const int JOYSTICK_DEAD_ZONE = 100; - -const byte RED_PIN = 5; -const byte BLUE_PIN = 9; -const byte GREEN_PIN = 10; - -const byte BUZZER_PIN = 6; - -// non-multiplexer Esplora pins: -// Accelerometer: x-A5, y-A7, z-A6 -// External outputs: D3, D11 -// Buzzer: A8 -// RGB Led: red-D5, green-D10/A11, blue-D9/A10 -// Led 13: D13 - -const byte ACCEL_X_PIN = A5; -const byte ACCEL_Y_PIN = A11; -const byte ACCEL_Z_PIN = A6; - -const byte LED_PIN = 13; - -_Esplora::_Esplora() { - for (byte p=0; p<4; p++) { - pinMode(MUX_ADDR_PINS[p], OUTPUT); - } - pinMode(RED_PIN, OUTPUT); - pinMode(GREEN_PIN, OUTPUT); - pinMode(BLUE_PIN, OUTPUT); -} - -unsigned int _Esplora::readChannel(byte channel) { - digitalWrite(MUX_ADDR_PINS[0], (channel & 1) ? HIGH : LOW); - digitalWrite(MUX_ADDR_PINS[1], (channel & 2) ? HIGH : LOW); - digitalWrite(MUX_ADDR_PINS[2], (channel & 4) ? HIGH : LOW); - digitalWrite(MUX_ADDR_PINS[3], (channel & 8) ? HIGH : LOW); - // workaround to cope with lack of pullup resistor on joystick switch - if (channel == CH_JOYSTICK_SW) { - pinMode(MUX_COM_PIN, INPUT_PULLUP); - unsigned int joystickSwitchState = (digitalRead(MUX_COM_PIN) == HIGH) ? 1023 : 0; - digitalWrite(MUX_COM_PIN, LOW); - return joystickSwitchState; - } - else - return analogRead(MUX_COM_PIN); -} - -boolean _Esplora::joyLowHalf(byte joyCh) { - return (readChannel(joyCh) < 512 - JOYSTICK_DEAD_ZONE) - ? LOW : HIGH; -} - -boolean _Esplora::joyHighHalf(byte joyCh) { - return (readChannel(joyCh) > 512 + JOYSTICK_DEAD_ZONE) - ? LOW : HIGH; -} - -boolean _Esplora::readButton(byte ch) { - if (ch >= SWITCH_1 && ch <= SWITCH_4) { - ch--; - } - - switch(ch) { - case JOYSTICK_RIGHT: - return joyLowHalf(CH_JOYSTICK_X); - case JOYSTICK_LEFT: - return joyHighHalf(CH_JOYSTICK_X); - case JOYSTICK_UP: - return joyLowHalf(CH_JOYSTICK_Y); - case JOYSTICK_DOWN: - return joyHighHalf(CH_JOYSTICK_Y); - } - - unsigned int val = readChannel(ch); - return (val > 512) ? HIGH : LOW; -} - -boolean _Esplora::readJoystickButton() { - if (readChannel(CH_JOYSTICK_SW) == 1023) { - return HIGH; - } else if (readChannel(CH_JOYSTICK_SW) == 0) { - return LOW; - } -} - - -void _Esplora::writeRGB(byte r, byte g, byte b) { - writeRed(r); - writeGreen(g); - writeBlue(b); -} - -#define RGB_FUNC(name, pin, lastVar) \ -void _Esplora::write##name(byte val) { \ - if (val == lastVar) \ - return; \ - analogWrite(pin, val); \ - lastVar = val; \ - delay(5); \ -} \ -\ -byte _Esplora::read##name() { \ - return lastVar; \ -} - -RGB_FUNC(Red, RED_PIN, lastRed) -RGB_FUNC(Green, GREEN_PIN, lastGreen) -RGB_FUNC(Blue, BLUE_PIN, lastBlue) - -void _Esplora::tone(unsigned int freq) { - if (freq > 0) - ::tone(BUZZER_PIN, freq); - else - ::noTone(BUZZER_PIN); -} - -void _Esplora::tone(unsigned int freq, unsigned long duration) { - if (freq > 0) - ::tone(BUZZER_PIN, freq, duration); - else - ::noTone(BUZZER_PIN); -} - -void _Esplora::noTone() { - ::noTone(BUZZER_PIN); -} - -int _Esplora::readTemperature(const byte scale) { - long rawT = readChannel(CH_TEMPERATURE); - if (scale == DEGREES_C) { - return (int)((rawT * 500 / 1024) - 50); - } - else if (scale == DEGREES_F) { - return (int)((rawT * 450 / 512 ) - 58); - } - else { - return readTemperature(DEGREES_C); - } -} - -int _Esplora::readAccelerometer(const byte axis) { - switch (axis) { - case X_AXIS: return analogRead(ACCEL_X_PIN) - ACCEL_ZERO_X; - case Y_AXIS: return analogRead(ACCEL_Y_PIN) - ACCEL_ZERO_Y; - case Z_AXIS: return analogRead(ACCEL_Z_PIN) - ACCEL_ZERO_Z; - default: return 0; - } -} diff --git a/libraries/Esplora/Esplora.h b/libraries/Esplora/Esplora.h deleted file mode 100644 index 4f55345..0000000 --- a/libraries/Esplora/Esplora.h +++ /dev/null @@ -1,165 +0,0 @@ -/* - Esplora.h - Arduino Esplora board library - Written by Enrico Gueli - Copyright (c) 2012 Arduino(TM) All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef ESPLORA_H_ -#define ESPLORA_H_ - -#include - -/* - * The following constants are used internally by the Esplora - * library code. - */ - -const byte JOYSTICK_BASE = 16; // it's a "virtual" channel: its ID won't conflict with real ones - -const byte MAX_CHANNELS = 13; - -const byte CH_SWITCH_1 = 0; -const byte CH_SWITCH_2 = 1; -const byte CH_SWITCH_3 = 2; -const byte CH_SWITCH_4 = 3; -const byte CH_SLIDER = 4; -const byte CH_LIGHT = 5; -const byte CH_TEMPERATURE = 6; -const byte CH_MIC = 7; -const byte CH_JOYSTICK_SW = 10; -const byte CH_JOYSTICK_X = 11; -const byte CH_JOYSTICK_Y = 12; - -/* - * The following constants can be used with the readButton() - * method. - */ - -const byte SWITCH_1 = 1; -const byte SWITCH_2 = 2; -const byte SWITCH_3 = 3; -const byte SWITCH_4 = 4; - -const byte SWITCH_DOWN = SWITCH_1; -const byte SWITCH_LEFT = SWITCH_2; -const byte SWITCH_UP = SWITCH_3; -const byte SWITCH_RIGHT = SWITCH_4; - -const byte JOYSTICK_DOWN = JOYSTICK_BASE; -const byte JOYSTICK_LEFT = JOYSTICK_BASE+1; -const byte JOYSTICK_UP = JOYSTICK_BASE+2; -const byte JOYSTICK_RIGHT = JOYSTICK_BASE+3; - -/* - * These constants can be use for comparison with the value returned - * by the readButton() method. - */ -const boolean PRESSED = LOW; -const boolean RELEASED = HIGH; - -/* - * The following constants can be used with the readTemperature() - * method to specify the desired scale. - */ -const byte DEGREES_C = 0; -const byte DEGREES_F = 1; - -/* - * The following constants can be used with the readAccelerometer() - * method to specify the desired axis to return. - */ -const byte X_AXIS = 0; -const byte Y_AXIS = 1; -const byte Z_AXIS = 2; - - -class _Esplora { -private: - byte lastRed; - byte lastGreen; - byte lastBlue; - - unsigned int readChannel(byte channel); - - boolean joyLowHalf(byte joyCh); - boolean joyHighHalf(byte joyCh); - -public: - _Esplora(); - - /* - * Returns a number corresponding to the position of the - * linear potentiometer. 0 means full right, 1023 means - * full left. - */ - inline unsigned int readSlider() { return readChannel(CH_SLIDER); } - - /* - * Returns a number corresponding to the amount of ambient - * light sensed by the light sensor. - */ - inline unsigned int readLightSensor() { return readChannel(CH_LIGHT); } - - /* - * Returns the current ambient temperature, expressed either in Celsius - * or Fahreneit scale. - */ - int readTemperature(const byte scale); - - /* - * Returns a number corresponding to the amount of ambient noise. - */ - inline unsigned int readMicrophone() { return readChannel(CH_MIC); } - - inline unsigned int readJoystickSwitch() { return readChannel(CH_JOYSTICK_SW); } - - inline int readJoystickX() { - return readChannel(CH_JOYSTICK_X) - 512; - } - inline int readJoystickY() { - return readChannel(CH_JOYSTICK_Y) - 512; - } - - int readAccelerometer(const byte axis); - - /* - * Reads the current state of a button. It will return - * LOW if the button is pressed, and HIGH otherwise. - */ - boolean readButton(byte channel); - - boolean readJoystickButton(); - - void writeRGB(byte red, byte green, byte blue); - void writeRed(byte red); - void writeGreen(byte green); - void writeBlue(byte blue); - - byte readRed(); - byte readGreen(); - byte readBlue(); - - void tone(unsigned int freq); - void tone(unsigned int freq, unsigned long duration); - void noTone(); -}; - - - -extern _Esplora Esplora; - -#endif // ESPLORA_H_ diff --git a/libraries/Esplora/Experts/EsploraKart/EsploraKart.ino b/libraries/Esplora/Experts/EsploraKart/EsploraKart.ino deleted file mode 100644 index 4c1621c..0000000 --- a/libraries/Esplora/Experts/EsploraKart/EsploraKart.ino +++ /dev/null @@ -1,125 +0,0 @@ -/* - Esplora Kart - - This sketch turns the Esplora into a PC game pad. - - It uses the both the analog joystick and the four switches. - By moving the joystick in a direction or by pressing a switch, - the PC will "see" that a key is pressed. If the PC is running - a game that has keyboard input, the Esplora can control it. - - The default configuration is suitable for SuperTuxKart, an - open-source racing game. It can be downloaded from - http://supertuxkart.sourceforge.net/ . - - Created on 22 november 2012 - By Enrico Gueli -*/ - - -#include - -/* - You're going to handle eight different buttons. You'll use arrays, - which are ordered lists of variables with a fixed size. Each array - has an index (counting from 0) to keep track of the position - you're reading in the array, and each position can contain a number. - - This code uses three different arrays: one for the buttons you'll read; - a second to hold the current states of those buttons; and a third to hold - the keystrokes associated with each button. - */ - -/* - This array holds the last sensed state of each of the buttons - you're reading. - Later in the code, you'll read the button states, and compare them - to the previous states that are stored in this array. If the two - states are different, it means that the button was either - pressed or released. - */ -boolean buttonStates[8]; - -/* - This array holds the names of the buttons being read. - Later in the sketch, you'll use these names with - the method Esplora.readButton(x), where x - is one of these buttons. - */ -const byte buttons[] = { - JOYSTICK_DOWN, - JOYSTICK_LEFT, - JOYSTICK_UP, - JOYSTICK_RIGHT, - SWITCH_RIGHT, // fire - SWITCH_LEFT, // bend - SWITCH_UP, // nitro - SWITCH_DOWN, // look back -}; - -/* - This array tells what keystroke to send to the PC when a - button is pressed. - If you look at this array and the above one, you can see that - the "cursor down" keystroke is sent when the joystick is moved - down, the "cursor up" keystroke when the joystick is moved up - and so on. -*/ -const char keystrokes[] = { - KEY_DOWN_ARROW, - KEY_LEFT_ARROW, - KEY_UP_ARROW, - KEY_RIGHT_ARROW, - ' ', - 'V', - 'N', - 'B' -}; - -/* - This is code is run only at startup, to initialize the - virtual USB keyboard. -*/ -void setup() { - Keyboard.begin(); -} - -/* - After setup() is finished, this code is run continuously. - Here we continuously check if something happened with the - buttons. -*/ -void loop() { - - // Iterate through all the buttons: - for (byte thisButton=0; thisButton<8; thisButton++) { - boolean lastState = buttonStates[thisButton]; - boolean newState = Esplora.readButton(buttons[thisButton]); - if (lastState != newState) { // Something changed! - /* - The Keyboard library allows you to "press" and "release" the - keys as two distinct actions. These actions can be - linked to the buttons we're handling. - */ - if (newState == PRESSED) { - Keyboard.press(keystrokes[thisButton]); - } - else if (newState == RELEASED) { - Keyboard.release(keystrokes[thisButton]); - } - } - - // Store the new button state, so you can sense a difference later: - buttonStates[thisButton] = newState; - } - - /* - Wait a little bit (50ms) between a check and another. - When a mechanical switch is pressed or released, the - contacts may bounce very rapidly. If the check is done too - fast, these bounces may be confused as multiple presses and - may lead to unexpected behaviour. - */ - delay(50); -} - diff --git a/libraries/Esplora/Experts/EsploraPong/EsploraPong.ino b/libraries/Esplora/Experts/EsploraPong/EsploraPong.ino deleted file mode 100644 index 725a109..0000000 --- a/libraries/Esplora/Experts/EsploraPong/EsploraPong.ino +++ /dev/null @@ -1,44 +0,0 @@ -/* - Esplora Pong - - This sketch connects serially to a Processing sketch to control a Pong game. - It sends the position of the slider and the states of three pushbuttons to the - Processing sketch serially, separated by commas. The Processing sketch uses that - data to control the graphics in the sketch. - - The slider sets a paddle's height - Switch 1 is resets the game - Switch 2 resets the ball to the center - Switch 3 reverses the players - - You can play this game with one or two Esploras. - - Created on 22 Dec 2012 - by Tom Igoe - - This example is in the public domain. - */ - -#include - -void setup() { - Serial.begin(9600); // initialize serial communication -} - -void loop() { - // read the slider and three of the buttons - int slider = Esplora.readSlider(); - int resetButton = Esplora.readButton(SWITCH_1); - int serveButton = Esplora.readButton(SWITCH_3); - int switchPlayerButton = Esplora.readButton(SWITCH_4); - - Serial.print(slider); // print the slider value - Serial.print(","); // add a comma - Serial.print(resetButton); // print the reset button value - Serial.print(","); // add another comma - Serial.print(serveButton); // print the serve button value - Serial.print(","); // add another comma - Serial.println(switchPlayerButton); // print the last button with a newline - delay(10); // delay before sending the next set -} - diff --git a/libraries/Esplora/Experts/EsploraRemote/EsploraRemote.ino b/libraries/Esplora/Experts/EsploraRemote/EsploraRemote.ino deleted file mode 100644 index 2701089..0000000 --- a/libraries/Esplora/Experts/EsploraRemote/EsploraRemote.ino +++ /dev/null @@ -1,116 +0,0 @@ -/* - Esplora Remote - - This sketch allows to test all the Esplora's peripherals. - It is also used with the ProcessingStart sketch (for Processing). - - When uploaded, you can open the Serial monitor and write one of - the following commands (without quotes) to get an answer: - - "D": prints the current value of all sensors, separated by a comma. - See the dumpInputs() function below to get the meaning of - each value. - - "Rxxx" - "Gxxx" - "Bxxx": set the color of the RGB led. For example, write "R255" - to turn on the red to full brightness, "G128" to turn - the green to half brightness, or "G0" to turn off - the green channel. - - "Txxxx": play a tone with the buzzer. The number is the - frequency, e.g. "T440" plays the central A note. - Write "T0" to turn off the buzzer. - - - Created on 22 november 2012 - By Enrico Gueli - Modified 23 Dec 2012 - by Tom Igoe - */ - -#include - -void setup() { - while(!Serial); // needed for Leonardo-based board like Esplora - Serial.begin(9600); -} - -void loop() { - if (Serial.available()) - parseCommand(); -} - -/* - * This function reads a character from the serial line and - * decide what to do next. The "what to do" part is given by - * function it calls (e.g. dumpInputs(), setRed() and so on). - */ -void parseCommand() { - char cmd = Serial.read(); - switch(cmd) { - case 'D': - dumpInputs(); - break; - case 'R': - setRed(); - break; - case 'G': - setGreen(); - break; - case 'B': - setBlue(); - break; - case 'T': - setTone(); - break; - } -} - -void dumpInputs() { - Serial.print(Esplora.readButton(SWITCH_1)); - Serial.print(','); - Serial.print(Esplora.readButton(SWITCH_2)); - Serial.print(','); - Serial.print(Esplora.readButton(SWITCH_3)); - Serial.print(','); - Serial.print(Esplora.readButton(SWITCH_4)); - Serial.print(','); - Serial.print(Esplora.readSlider()); - Serial.print(','); - Serial.print(Esplora.readLightSensor()); - Serial.print(','); - Serial.print(Esplora.readTemperature(DEGREES_C)); - Serial.print(','); - Serial.print(Esplora.readMicrophone()); - Serial.print(','); - Serial.print(Esplora.readJoystickSwitch()); - Serial.print(','); - Serial.print(Esplora.readJoystickX()); - Serial.print(','); - Serial.print(Esplora.readJoystickY()); - Serial.print(','); - Serial.print(Esplora.readAccelerometer(X_AXIS)); - Serial.print(','); - Serial.print(Esplora.readAccelerometer(Y_AXIS)); - Serial.print(','); - Serial.print(Esplora.readAccelerometer(Z_AXIS)); - Serial.println(); -} - -void setRed() { - Esplora.writeRed(Serial.parseInt()); -} - -void setGreen() { - Esplora.writeGreen(Serial.parseInt()); -} - -void setBlue() { - Esplora.writeBlue(Serial.parseInt()); -} - -void setTone() { - Esplora.tone(Serial.parseInt()); -} - diff --git a/libraries/Esplora/Experts/EsploraTable/EsploraTable.ino b/libraries/Esplora/Experts/EsploraTable/EsploraTable.ino deleted file mode 100644 index 712dffa..0000000 --- a/libraries/Esplora/Experts/EsploraTable/EsploraTable.ino +++ /dev/null @@ -1,213 +0,0 @@ -/* - Esplora Table - - Acts like a keyboard that prints sensor - data in a table-like text, row by row. - - At startup, it does nothing. It waits for you to open a - spreadsheet (e.g. Google Drive spreadsheet) so it can write - data. By pressing Switch 1, it starts printing the table - headers and the first row of data. It waits a bit, then it - will print another row, and so on. - - The amount of time between each row is determined by the slider. - If put to full left, the sketch will wait 10 seconds; at - full right position, it will wait 5 minutes. An intermediate - position will make the sketch wait for some time in-between. - - Clicking the Switch 1 at any time will stop the logging. - - The color LED shows what the sketch is doing: - blue = idle, waiting for you to press Switch 1 to start logging - green = active; will print soon - red = printing data to the PC - - Created on 22 november 2012 - By Enrico Gueli - modified 24 Nov 2012 - by Tom Igoe -*/ - -#include - -/* - * this variable tells if the data-logging is currently active. - */ -boolean active = false; - -/* - * this variable holds the time in the future when the sketch - * will "sample" the data (sampling is the act of reading some - * input at a known time). This variable is checked continuously - * against millis() to know when it's time to sample. - */ -unsigned long nextSampleAt = 0; - -/* - * This variable just holds the millis() value at the time the - * logging was activated. This is needed to enter the correct - * value in the "Time" column in the printed table. - */ -unsigned long startedAt = 0; - - -/* - * when the "active" variable is set to true, the same is done - * with this variable. This is needed because the code that does - * the "just-after-activation" stuff is run some time later than - * the code that says "be active now". - */ -boolean justActivated = false; - - -/* - * this variable holds the last sensed status of the switch press - * button. If the code sees a difference between the value of - * this variable and the current status of the switch, it means - * that the button was either pressed or released. - */ -boolean lastStartBtn = HIGH; - -/* - * Initialization code. The virtual USB keyboard must be - * initialized; the Serial class is needed just for debugging. - */ -void setup() { - Keyboard.begin(); - Serial.begin(9600); -} - -/* - * This code is run continuously. - */ -void loop() { - /* - * note: we don't use Arduino's delay() here, because we can't - * normally do anything while delaying. Our own version lets us - * check for button presses often enough to not miss any event. - */ - activeDelay(50); - - /* - * the justActivated variable may be set to true in the - * checkSwitchPress() function. Here we check its status to - * print the table headers and configure what's needed to. - */ - if (justActivated == true) { - justActivated = false; // do this just once - printHeaders(); - // do next sampling ASAP - nextSampleAt = startedAt = millis(); - } - - if (active == true) { - if (nextSampleAt < millis()) { - // it's time to sample! - int slider = Esplora.readSlider(); - // the row below maps the slider position to a range between - // 10 and 290 seconds. - int sampleInterval = map(slider, 0, 1023, 10, 290); - nextSampleAt = millis() + sampleInterval * 1000; - - logAndPrint(); - } - - // let the RGB led blink green once per second, for 200ms. - unsigned int ms = millis() % 1000; - if (ms < 200) - Esplora.writeGreen(50); - else - Esplora.writeGreen(0); - - Esplora.writeBlue(0); - } - else - // while not active, keep a reassuring blue color coming - // from the Esplora... - Esplora.writeBlue(20); - -} - -/* - * Print the table headers. - */ -void printHeaders() { - Keyboard.print("Time"); - Keyboard.write(KEY_TAB); - activeDelay(300); // Some spreadsheets are slow, e.g. Google - // Drive that wants to save every edit. - Keyboard.print("Accel X"); - Keyboard.write(KEY_TAB); - activeDelay(300); - Keyboard.print("Accel Y"); - Keyboard.write(KEY_TAB); - activeDelay(300); - Keyboard.print("Accel Z"); - Keyboard.println(); - activeDelay(300); -} - -void logAndPrint() { - // do all the samplings at once, because keystrokes have delays - unsigned long timeSecs = (millis() - startedAt) /1000; - int xAxis = Esplora.readAccelerometer(X_AXIS); - int yAxis = Esplora.readAccelerometer(Y_AXIS); - int zAxis = Esplora.readAccelerometer(Z_AXIS); - - Esplora.writeRed(100); - - Keyboard.print(timeSecs); - Keyboard.write(KEY_TAB); - activeDelay(300); - Keyboard.print(xAxis); - Keyboard.write(KEY_TAB); - activeDelay(300); - Keyboard.print(yAxis); - Keyboard.write(KEY_TAB); - activeDelay(300); - Keyboard.print(zAxis); - Keyboard.println(); - activeDelay(300); - Keyboard.write(KEY_HOME); - - Esplora.writeRed(0); -} - -/** - * Similar to delay(), but allows the program to do something else - * in the meanwhile. In particular, it calls checkSwitchPress(). - * Note 1: it may wait longer than the specified amount, not less; - * Note 2: beware of data synchronization issues, e.g. if the - * activeDelay() function alters some variables used by the - * caller of this function. - */ -void activeDelay(unsigned long amount) { - unsigned long at = millis() + amount; - while (millis() < at) { - checkSwitchPress(); - } -} - -/* - * This function reads the status of the switch; if it sees that - * it was pressed, toggles the status of the "active" variable. - * If it's set to true, also the justActivated variable is set to - * true, so the loop() function above can do the right things. - * This function should be called as often as possible and do as - * little as possible, because it can be called while another - * function is running. - */ -void checkSwitchPress() { - boolean startBtn = Esplora.readButton(SWITCH_DOWN); - - if (startBtn != lastStartBtn) { - if (startBtn == HIGH) { // button released - active = !active; - if (active) - justActivated = true; - } - - lastStartBtn = startBtn; - } -} - diff --git a/libraries/Esplora/keywords.txt b/libraries/Esplora/keywords.txt deleted file mode 100644 index b225991..0000000 --- a/libraries/Esplora/keywords.txt +++ /dev/null @@ -1,69 +0,0 @@ -####################################### -# Syntax Coloring Map For Esplora -####################################### -# Class -####################################### - -Esplora KEYWORD3 - -####################################### -# Methods and Functions -####################################### - -begin KEYWORD2 -readSlider KEYWORD2 -readLightSensor KEYWORD2 -readTemperature KEYWORD2 -readMicrophone KEYWORD2 -readJoystickSwitch KEYWORD2 -readJoystickButton KEYWORD2 -readJoystickX KEYWORD2 -readJoystickY KEYWORD2 -readAccelerometer KEYWORD2 -readButton KEYWORD2 -writeRGB KEYWORD2 -writeRed KEYWORD2 -writeGreen KEYWORD2 -writeBlue KEYWORD2 -readRed KEYWORD2 -readGreen KEYWORD2 -readBlue KEYWORD2 -tone KEYWORD2 -noTone KEYWORD2 - - -####################################### -# Constants -####################################### - -JOYSTICK_BASE LITERAL1 -MAX_CHANNELS LITERAL1 -CH_SWITCH_1 LITERAL1 -CH_SWITCH_2 LITERAL1 -CH_SWITCH_3 LITERAL1 -CH_SWITCH_4 LITERAL1 -CH_SLIDER LITERAL1 -CH_LIGHT LITERAL1 -CH_TEMPERATURE LITERAL1 -CH_MIC LITERAL1 -CH_JOYSTICK_SW LITERAL1 -CH_JOYSTICK_X LITERAL1 -CH_JOYSTICK_Y LITERAL1 -SWITCH_1 LITERAL1 -SWITCH_2 LITERAL1 -SWITCH_3 LITERAL1 -SWITCH_4 LITERAL1 -SWITCH_DOWN LITERAL1 -SWITCH_LEFT LITERAL1 -SWITCH_UP LITERAL1 -SWITCH_RIGHT LITERAL1 -JOYSTICK_DOWN LITERAL1 -JOYSTICK_LEFT LITERAL1 -JOYSTICK_UP LITERAL1 -PRESSED LITERAL1 -RELEASED LITERAL1 -DEGREES_C LITERAL1 -DEGREES_F LITERAL1 -X_AXIS LITERAL1 -Y_AXIS LITERAL1 -Z_AXIS LITERAL1 -- cgit v1.2.3-18-g5258 From 5527c44aa443b20d63cf7a276180a36695233924 Mon Sep 17 00:00:00 2001 From: Fede85 Date: Fri, 19 Jul 2013 16:20:34 +0200 Subject: WiFi library to the new format --- libraries/WiFi/WiFi.cpp | 231 --------- libraries/WiFi/WiFi.h | 227 --------- libraries/WiFi/WiFiClient.cpp | 179 ------- libraries/WiFi/WiFiClient.h | 40 -- libraries/WiFi/WiFiServer.cpp | 89 ---- libraries/WiFi/WiFiServer.h | 27 - libraries/WiFi/WiFiUdp.cpp | 163 ------ libraries/WiFi/WiFiUdp.h | 61 --- .../ConnectNoEncryption/ConnectNoEncryption.ino | 121 ----- .../examples/ConnectWithWEP/ConnectWithWEP.ino | 126 ----- .../examples/ConnectWithWPA/ConnectWithWPA.ino | 116 ----- .../WiFi/examples/ScanNetworks/ScanNetworks.ino | 119 ----- .../SimpleWebServerWiFi/SimpleWebServerWiFi.ino | 129 ----- .../examples/WiFiChatServer/WiFiChatServer.ino | 111 ---- .../WiFiPachubeClient/WiFiPachubeClient.ino | 190 ------- .../WiFiPachubeClientString.ino | 177 ------- .../WiFiTwitterClient/WiFiTwitterClient.ino | 163 ------ .../examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino | 182 ------- .../WiFiUdpSendReceiveString.ino | 112 ----- .../WiFi/examples/WiFiWebClient/WiFiWebClient.ino | 121 ----- .../WiFiWebClientRepeating.ino | 138 ----- .../WiFi/examples/WiFiWebServer/WiFiWebServer.ino | 134 ----- libraries/WiFi/keywords.txt | 51 -- libraries/WiFi/utility/debug.h | 77 --- libraries/WiFi/utility/server_drv.cpp | 308 ------------ libraries/WiFi/utility/server_drv.h | 41 -- libraries/WiFi/utility/socket.c | 20 - libraries/WiFi/utility/socket.h | 87 ---- libraries/WiFi/utility/spi_drv.cpp | 506 ------------------- libraries/WiFi/utility/spi_drv.h | 83 --- libraries/WiFi/utility/wifi_drv.cpp | 560 --------------------- libraries/WiFi/utility/wifi_drv.h | 248 --------- libraries/WiFi/utility/wifi_spi.h | 153 ------ libraries/WiFi/utility/wl_definitions.h | 52 -- libraries/WiFi/utility/wl_types.h | 31 -- 35 files changed, 5173 deletions(-) delete mode 100644 libraries/WiFi/WiFi.cpp delete mode 100644 libraries/WiFi/WiFi.h delete mode 100644 libraries/WiFi/WiFiClient.cpp delete mode 100644 libraries/WiFi/WiFiClient.h delete mode 100644 libraries/WiFi/WiFiServer.cpp delete mode 100644 libraries/WiFi/WiFiServer.h delete mode 100644 libraries/WiFi/WiFiUdp.cpp delete mode 100644 libraries/WiFi/WiFiUdp.h delete mode 100644 libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino delete mode 100644 libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino delete mode 100644 libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino delete mode 100644 libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino delete mode 100644 libraries/WiFi/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino delete mode 100644 libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino delete mode 100644 libraries/WiFi/examples/WiFiPachubeClient/WiFiPachubeClient.ino delete mode 100644 libraries/WiFi/examples/WiFiPachubeClientString/WiFiPachubeClientString.ino delete mode 100644 libraries/WiFi/examples/WiFiTwitterClient/WiFiTwitterClient.ino delete mode 100644 libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino delete mode 100644 libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino delete mode 100644 libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino delete mode 100644 libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino delete mode 100644 libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino delete mode 100644 libraries/WiFi/keywords.txt delete mode 100644 libraries/WiFi/utility/debug.h delete mode 100644 libraries/WiFi/utility/server_drv.cpp delete mode 100644 libraries/WiFi/utility/server_drv.h delete mode 100644 libraries/WiFi/utility/socket.c delete mode 100644 libraries/WiFi/utility/socket.h delete mode 100644 libraries/WiFi/utility/spi_drv.cpp delete mode 100644 libraries/WiFi/utility/spi_drv.h delete mode 100644 libraries/WiFi/utility/wifi_drv.cpp delete mode 100644 libraries/WiFi/utility/wifi_drv.h delete mode 100644 libraries/WiFi/utility/wifi_spi.h delete mode 100644 libraries/WiFi/utility/wl_definitions.h delete mode 100644 libraries/WiFi/utility/wl_types.h diff --git a/libraries/WiFi/WiFi.cpp b/libraries/WiFi/WiFi.cpp deleted file mode 100644 index f209280..0000000 --- a/libraries/WiFi/WiFi.cpp +++ /dev/null @@ -1,231 +0,0 @@ -#include "wifi_drv.h" -#include "WiFi.h" - -extern "C" { - #include "utility/wl_definitions.h" - #include "utility/wl_types.h" - #include "debug.h" -} - -// XXX: don't make assumptions about the value of MAX_SOCK_NUM. -int16_t WiFiClass::_state[MAX_SOCK_NUM] = { NA_STATE, NA_STATE, NA_STATE, NA_STATE }; -uint16_t WiFiClass::_server_port[MAX_SOCK_NUM] = { 0, 0, 0, 0 }; - -WiFiClass::WiFiClass() -{ - // Driver initialization - init(); -} - -void WiFiClass::init() -{ - WiFiDrv::wifiDriverInit(); -} - -uint8_t WiFiClass::getSocket() -{ - for (uint8_t i = 0; i < MAX_SOCK_NUM; ++i) - { - if (WiFiClass::_server_port[i] == 0) - { - return i; - } - } - return NO_SOCKET_AVAIL; -} - -char* WiFiClass::firmwareVersion() -{ - return WiFiDrv::getFwVersion(); -} - -int WiFiClass::begin(char* ssid) -{ - uint8_t status = WL_IDLE_STATUS; - uint8_t attempts = WL_MAX_ATTEMPT_CONNECTION; - - if (WiFiDrv::wifiSetNetwork(ssid, strlen(ssid)) != WL_FAILURE) - { - do - { - delay(WL_DELAY_START_CONNECTION); - status = WiFiDrv::getConnectionStatus(); - } - while ((( status == WL_IDLE_STATUS)||(status == WL_SCAN_COMPLETED))&&(--attempts>0)); - }else - { - status = WL_CONNECT_FAILED; - } - return status; -} - -int WiFiClass::begin(char* ssid, uint8_t key_idx, const char *key) -{ - uint8_t status = WL_IDLE_STATUS; - uint8_t attempts = WL_MAX_ATTEMPT_CONNECTION; - - // set encryption key - if (WiFiDrv::wifiSetKey(ssid, strlen(ssid), key_idx, key, strlen(key)) != WL_FAILURE) - { - do - { - delay(WL_DELAY_START_CONNECTION); - status = WiFiDrv::getConnectionStatus(); - }while ((( status == WL_IDLE_STATUS)||(status == WL_SCAN_COMPLETED))&&(--attempts>0)); - }else{ - status = WL_CONNECT_FAILED; - } - return status; -} - -int WiFiClass::begin(char* ssid, const char *passphrase) -{ - uint8_t status = WL_IDLE_STATUS; - uint8_t attempts = WL_MAX_ATTEMPT_CONNECTION; - - // set passphrase - if (WiFiDrv::wifiSetPassphrase(ssid, strlen(ssid), passphrase, strlen(passphrase))!= WL_FAILURE) - { - do - { - delay(WL_DELAY_START_CONNECTION); - status = WiFiDrv::getConnectionStatus(); - } - while ((( status == WL_IDLE_STATUS)||(status == WL_SCAN_COMPLETED))&&(--attempts>0)); - }else{ - status = WL_CONNECT_FAILED; - } - return status; -} - -void WiFiClass::config(IPAddress local_ip) -{ - WiFiDrv::config(1, (uint32_t)local_ip, 0, 0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server) -{ - WiFiDrv::config(1, (uint32_t)local_ip, 0, 0); - WiFiDrv::setDNS(1, (uint32_t)dns_server, 0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway) -{ - WiFiDrv::config(2, (uint32_t)local_ip, (uint32_t)gateway, 0); - WiFiDrv::setDNS(1, (uint32_t)dns_server, 0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) -{ - WiFiDrv::config(3, (uint32_t)local_ip, (uint32_t)gateway, (uint32_t)subnet); - WiFiDrv::setDNS(1, (uint32_t)dns_server, 0); -} - -void WiFiClass::setDNS(IPAddress dns_server1) -{ - WiFiDrv::setDNS(1, (uint32_t)dns_server1, 0); -} - -void WiFiClass::setDNS(IPAddress dns_server1, IPAddress dns_server2) -{ - WiFiDrv::setDNS(2, (uint32_t)dns_server1, (uint32_t)dns_server2); -} - -int WiFiClass::disconnect() -{ - return WiFiDrv::disconnect(); -} - -uint8_t* WiFiClass::macAddress(uint8_t* mac) -{ - uint8_t* _mac = WiFiDrv::getMacAddress(); - memcpy(mac, _mac, WL_MAC_ADDR_LENGTH); - return mac; -} - -IPAddress WiFiClass::localIP() -{ - IPAddress ret; - WiFiDrv::getIpAddress(ret); - return ret; -} - -IPAddress WiFiClass::subnetMask() -{ - IPAddress ret; - WiFiDrv::getSubnetMask(ret); - return ret; -} - -IPAddress WiFiClass::gatewayIP() -{ - IPAddress ret; - WiFiDrv::getGatewayIP(ret); - return ret; -} - -char* WiFiClass::SSID() -{ - return WiFiDrv::getCurrentSSID(); -} - -uint8_t* WiFiClass::BSSID(uint8_t* bssid) -{ - uint8_t* _bssid = WiFiDrv::getCurrentBSSID(); - memcpy(bssid, _bssid, WL_MAC_ADDR_LENGTH); - return bssid; -} - -int32_t WiFiClass::RSSI() -{ - return WiFiDrv::getCurrentRSSI(); -} - -uint8_t WiFiClass::encryptionType() -{ - return WiFiDrv::getCurrentEncryptionType(); -} - - -int8_t WiFiClass::scanNetworks() -{ - uint8_t attempts = 10; - uint8_t numOfNetworks = 0; - - if (WiFiDrv::startScanNetworks() == WL_FAILURE) - return WL_FAILURE; - do - { - delay(2000); - numOfNetworks = WiFiDrv::getScanNetworks(); - } - while (( numOfNetworks == 0)&&(--attempts>0)); - return numOfNetworks; -} - -char* WiFiClass::SSID(uint8_t networkItem) -{ - return WiFiDrv::getSSIDNetoworks(networkItem); -} - -int32_t WiFiClass::RSSI(uint8_t networkItem) -{ - return WiFiDrv::getRSSINetoworks(networkItem); -} - -uint8_t WiFiClass::encryptionType(uint8_t networkItem) -{ - return WiFiDrv::getEncTypeNetowrks(networkItem); -} - -uint8_t WiFiClass::status() -{ - return WiFiDrv::getConnectionStatus(); -} - -int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) -{ - return WiFiDrv::getHostByName(aHostname, aResult); -} - -WiFiClass WiFi; diff --git a/libraries/WiFi/WiFi.h b/libraries/WiFi/WiFi.h deleted file mode 100644 index ef36a84..0000000 --- a/libraries/WiFi/WiFi.h +++ /dev/null @@ -1,227 +0,0 @@ -#ifndef WiFi_h -#define WiFi_h - -#include - -extern "C" { - #include "utility/wl_definitions.h" - #include "utility/wl_types.h" -} - -#include "IPAddress.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -class WiFiClass -{ -private: - - static void init(); -public: - static int16_t _state[MAX_SOCK_NUM]; - static uint16_t _server_port[MAX_SOCK_NUM]; - - WiFiClass(); - - /* - * Get the first socket available - */ - static uint8_t getSocket(); - - /* - * Get firmware version - */ - static char* firmwareVersion(); - - - /* Start Wifi connection for OPEN networks - * - * param ssid: Pointer to the SSID string. - */ - int begin(char* ssid); - - /* Start Wifi connection with WEP encryption. - * Configure a key into the device. The key type (WEP-40, WEP-104) - * is determined by the size of the key (5 bytes for WEP-40, 13 bytes for WEP-104). - * - * param ssid: Pointer to the SSID string. - * param key_idx: The key index to set. Valid values are 0-3. - * param key: Key input buffer. - */ - int begin(char* ssid, uint8_t key_idx, const char* key); - - /* Start Wifi connection with passphrase - * the most secure supported mode will be automatically selected - * - * param ssid: Pointer to the SSID string. - * param passphrase: Passphrase. Valid characters in a passphrase - * must be between ASCII 32-126 (decimal). - */ - int begin(char* ssid, const char *passphrase); - - /* Change Ip configuration settings disabling the dhcp client - * - * param local_ip: Static ip configuration - */ - void config(IPAddress local_ip); - - /* Change Ip configuration settings disabling the dhcp client - * - * param local_ip: Static ip configuration - * param dns_server: IP configuration for DNS server 1 - */ - void config(IPAddress local_ip, IPAddress dns_server); - - /* Change Ip configuration settings disabling the dhcp client - * - * param local_ip: Static ip configuration - * param dns_server: IP configuration for DNS server 1 - * param gateway : Static gateway configuration - */ - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway); - - /* Change Ip configuration settings disabling the dhcp client - * - * param local_ip: Static ip configuration - * param dns_server: IP configuration for DNS server 1 - * param gateway: Static gateway configuration - * param subnet: Static Subnet mask - */ - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); - - /* Change DNS Ip configuration - * - * param dns_server1: ip configuration for DNS server 1 - */ - void setDNS(IPAddress dns_server1); - - /* Change DNS Ip configuration - * - * param dns_server1: ip configuration for DNS server 1 - * param dns_server2: ip configuration for DNS server 2 - * - */ - void setDNS(IPAddress dns_server1, IPAddress dns_server2); - - /* - * Disconnect from the network - * - * return: one value of wl_status_t enum - */ - int disconnect(void); - - /* - * Get the interface MAC address. - * - * return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH - */ - uint8_t* macAddress(uint8_t* mac); - - /* - * Get the interface IP address. - * - * return: Ip address value - */ - IPAddress localIP(); - - /* - * Get the interface subnet mask address. - * - * return: subnet mask address value - */ - IPAddress subnetMask(); - - /* - * Get the gateway ip address. - * - * return: gateway ip address value - */ - IPAddress gatewayIP(); - - /* - * Return the current SSID associated with the network - * - * return: ssid string - */ - char* SSID(); - - /* - * Return the current BSSID associated with the network. - * It is the MAC address of the Access Point - * - * return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH - */ - uint8_t* BSSID(uint8_t* bssid); - - /* - * Return the current RSSI /Received Signal Strength in dBm) - * associated with the network - * - * return: signed value - */ - int32_t RSSI(); - - /* - * Return the Encryption Type associated with the network - * - * return: one value of wl_enc_type enum - */ - uint8_t encryptionType(); - - /* - * Start scan WiFi networks available - * - * return: Number of discovered networks - */ - int8_t scanNetworks(); - - /* - * Return the SSID discovered during the network scan. - * - * param networkItem: specify from which network item want to get the information - * - * return: ssid string of the specified item on the networks scanned list - */ - char* SSID(uint8_t networkItem); - - /* - * Return the encryption type of the networks discovered during the scanNetworks - * - * param networkItem: specify from which network item want to get the information - * - * return: encryption type (enum wl_enc_type) of the specified item on the networks scanned list - */ - uint8_t encryptionType(uint8_t networkItem); - - /* - * Return the RSSI of the networks discovered during the scanNetworks - * - * param networkItem: specify from which network item want to get the information - * - * return: signed value of RSSI of the specified item on the networks scanned list - */ - int32_t RSSI(uint8_t networkItem); - - /* - * Return Connection status. - * - * return: one of the value defined in wl_status_t - */ - uint8_t status(); - - /* - * Resolve the given hostname to an IP address. - * param aHostname: Name to be resolved - * param aResult: IPAddress structure to store the returned IP address - * result: 1 if aIPAddrString was successfully converted to an IP address, - * else error code - */ - int hostByName(const char* aHostname, IPAddress& aResult); - - friend class WiFiClient; - friend class WiFiServer; -}; - -extern WiFiClass WiFi; - -#endif diff --git a/libraries/WiFi/WiFiClient.cpp b/libraries/WiFi/WiFiClient.cpp deleted file mode 100644 index 0b4b6dc..0000000 --- a/libraries/WiFi/WiFiClient.cpp +++ /dev/null @@ -1,179 +0,0 @@ -extern "C" { - #include "utility/wl_definitions.h" - #include "utility/wl_types.h" - #include "socket.h" - #include "string.h" - #include "utility/debug.h" -} - -#include "WiFi.h" -#include "WiFiClient.h" -#include "WiFiServer.h" -#include "server_drv.h" - - -uint16_t WiFiClient::_srcport = 1024; - -WiFiClient::WiFiClient() : _sock(MAX_SOCK_NUM) { -} - -WiFiClient::WiFiClient(uint8_t sock) : _sock(sock) { -} - -int WiFiClient::connect(const char* host, uint16_t port) { - IPAddress remote_addr; - if (WiFi.hostByName(host, remote_addr)) - { - return connect(remote_addr, port); - } - return 0; -} - -int WiFiClient::connect(IPAddress ip, uint16_t port) { - _sock = getFirstSocket(); - if (_sock != NO_SOCKET_AVAIL) - { - ServerDrv::startClient(uint32_t(ip), port, _sock); - WiFiClass::_state[_sock] = _sock; - - unsigned long start = millis(); - - // wait 4 second for the connection to close - while (!connected() && millis() - start < 10000) - delay(1); - - if (!connected()) - { - return 0; - } - }else{ - Serial.println("No Socket available"); - return 0; - } - return 1; -} - -size_t WiFiClient::write(uint8_t b) { - return write(&b, 1); -} - -size_t WiFiClient::write(const uint8_t *buf, size_t size) { - if (_sock >= MAX_SOCK_NUM) - { - setWriteError(); - return 0; - } - if (size==0) - { - setWriteError(); - return 0; - } - - - if (!ServerDrv::sendData(_sock, buf, size)) - { - setWriteError(); - return 0; - } - if (!ServerDrv::checkDataSent(_sock)) - { - setWriteError(); - return 0; - } - - return size; -} - -int WiFiClient::available() { - if (_sock != 255) - { - return ServerDrv::availData(_sock); - } - - return 0; -} - -int WiFiClient::read() { - uint8_t b; - if (!available()) - return -1; - - ServerDrv::getData(_sock, &b); - return b; -} - - -int WiFiClient::read(uint8_t* buf, size_t size) { - if (!ServerDrv::getDataBuf(_sock, buf, &size)) - return -1; - return 0; -} - -int WiFiClient::peek() { - uint8_t b; - if (!available()) - return -1; - - ServerDrv::getData(_sock, &b, 1); - return b; -} - -void WiFiClient::flush() { - while (available()) - read(); -} - -void WiFiClient::stop() { - - if (_sock == 255) - return; - - ServerDrv::stopClient(_sock); - WiFiClass::_state[_sock] = NA_STATE; - - int count = 0; - // wait maximum 5 secs for the connection to close - while (status() != CLOSED && ++count < 50) - delay(100); - - _sock = 255; -} - -uint8_t WiFiClient::connected() { - - if (_sock == 255) { - return 0; - } else { - uint8_t s = status(); - - return !(s == LISTEN || s == CLOSED || s == FIN_WAIT_1 || - s == FIN_WAIT_2 || s == TIME_WAIT || - s == SYN_SENT || s== SYN_RCVD || - (s == CLOSE_WAIT)); - } -} - -uint8_t WiFiClient::status() { - if (_sock == 255) { - return CLOSED; - } else { - return ServerDrv::getClientState(_sock); - } -} - -WiFiClient::operator bool() { - return _sock != 255; -} - -// Private Methods -uint8_t WiFiClient::getFirstSocket() -{ - for (int i = 0; i < MAX_SOCK_NUM; i++) { - if (WiFiClass::_state[i] == NA_STATE) - { - return i; - } - } - return SOCK_NOT_AVAIL; -} - diff --git a/libraries/WiFi/WiFiClient.h b/libraries/WiFi/WiFiClient.h deleted file mode 100644 index 5a7f0f3..0000000 --- a/libraries/WiFi/WiFiClient.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef wificlient_h -#define wificlient_h -#include "Arduino.h" -#include "Print.h" -#include "Client.h" -#include "IPAddress.h" - -class WiFiClient : public Client { - -public: - WiFiClient(); - WiFiClient(uint8_t sock); - - uint8_t status(); - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char *host, uint16_t port); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual int available(); - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - virtual void flush(); - virtual void stop(); - virtual uint8_t connected(); - virtual operator bool(); - - friend class WiFiServer; - - using Print::write; - -private: - static uint16_t _srcport; - uint8_t _sock; //not used - uint16_t _socket; - - uint8_t getFirstSocket(); -}; - -#endif diff --git a/libraries/WiFi/WiFiServer.cpp b/libraries/WiFi/WiFiServer.cpp deleted file mode 100644 index 2f03bc1..0000000 --- a/libraries/WiFi/WiFiServer.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include -#include "server_drv.h" - -extern "C" { - #include "utility/debug.h" -} - -#include "WiFi.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -WiFiServer::WiFiServer(uint16_t port) -{ - _port = port; -} - -void WiFiServer::begin() -{ - uint8_t _sock = WiFiClass::getSocket(); - if (_sock != NO_SOCKET_AVAIL) - { - ServerDrv::startServer(_port, _sock); - WiFiClass::_server_port[_sock] = _port; - WiFiClass::_state[_sock] = _sock; - } -} - -WiFiClient WiFiServer::available(byte* status) -{ - static int cycle_server_down = 0; - const int TH_SERVER_DOWN = 50; - - for (int sock = 0; sock < MAX_SOCK_NUM; sock++) - { - if (WiFiClass::_server_port[sock] == _port) - { - WiFiClient client(sock); - uint8_t _status = client.status(); - uint8_t _ser_status = this->status(); - - if (status != NULL) - *status = _status; - - //server not in listen state, restart it - if ((_ser_status == 0)&&(cycle_server_down++ > TH_SERVER_DOWN)) - { - ServerDrv::startServer(_port, sock); - cycle_server_down = 0; - } - - if (_status == ESTABLISHED) - { - return client; //TODO - } - } - } - - return WiFiClient(255); -} - -uint8_t WiFiServer::status() { - return ServerDrv::getServerState(0); -} - - -size_t WiFiServer::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t WiFiServer::write(const uint8_t *buffer, size_t size) -{ - size_t n = 0; - - for (int sock = 0; sock < MAX_SOCK_NUM; sock++) - { - if (WiFiClass::_server_port[sock] != 0) - { - WiFiClient client(sock); - - if (WiFiClass::_server_port[sock] == _port && - client.status() == ESTABLISHED) - { - n+=client.write(buffer, size); - } - } - } - return n; -} diff --git a/libraries/WiFi/WiFiServer.h b/libraries/WiFi/WiFiServer.h deleted file mode 100644 index 68b574c..0000000 --- a/libraries/WiFi/WiFiServer.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef wifiserver_h -#define wifiserver_h - -extern "C" { - #include "utility/wl_definitions.h" -} - -#include "Server.h" - -class WiFiClient; - -class WiFiServer : public Server { -private: - uint16_t _port; - void* pcb; -public: - WiFiServer(uint16_t); - WiFiClient available(uint8_t* status = NULL); - void begin(); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - uint8_t status(); - - using Print::write; -}; - -#endif diff --git a/libraries/WiFi/WiFiUdp.cpp b/libraries/WiFi/WiFiUdp.cpp deleted file mode 100644 index 7020df8..0000000 --- a/libraries/WiFi/WiFiUdp.cpp +++ /dev/null @@ -1,163 +0,0 @@ - -extern "C" { - #include "utility/debug.h" - #include "utility/wifi_spi.h" -} -#include -#include "server_drv.h" -#include "wifi_drv.h" - -#include "WiFi.h" -#include "WiFiUdp.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - - -/* Constructor */ -WiFiUDP::WiFiUDP() : _sock(NO_SOCKET_AVAIL) {} - -/* Start WiFiUDP socket, listening at local port PORT */ -uint8_t WiFiUDP::begin(uint16_t port) { - - uint8_t sock = WiFiClass::getSocket(); - if (sock != NO_SOCKET_AVAIL) - { - ServerDrv::startServer(port, sock, UDP_MODE); - WiFiClass::_server_port[sock] = port; - _sock = sock; - _port = port; - return 1; - } - return 0; - -} - -/* return number of bytes available in the current packet, - will return zero if parsePacket hasn't been called yet */ -int WiFiUDP::available() { - if (_sock != NO_SOCKET_AVAIL) - { - return ServerDrv::availData(_sock); - } - return 0; -} - -/* Release any resources being used by this WiFiUDP instance */ -void WiFiUDP::stop() -{ - if (_sock == NO_SOCKET_AVAIL) - return; - - ServerDrv::stopClient(_sock); - - _sock = NO_SOCKET_AVAIL; -} - -int WiFiUDP::beginPacket(const char *host, uint16_t port) -{ - // Look up the host first - int ret = 0; - IPAddress remote_addr; - if (WiFi.hostByName(host, remote_addr)) - { - return beginPacket(remote_addr, port); - } - return ret; -} - -int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) -{ - if (_sock == NO_SOCKET_AVAIL) - _sock = WiFiClass::getSocket(); - if (_sock != NO_SOCKET_AVAIL) - { - ServerDrv::startClient(uint32_t(ip), port, _sock, UDP_MODE); - WiFiClass::_state[_sock] = _sock; - return 1; - } - return 0; -} - -int WiFiUDP::endPacket() -{ - return ServerDrv::sendUdpData(_sock); -} - -size_t WiFiUDP::write(uint8_t byte) -{ - return write(&byte, 1); -} - -size_t WiFiUDP::write(const uint8_t *buffer, size_t size) -{ - ServerDrv::insertDataBuf(_sock, buffer, size); - return size; -} - -int WiFiUDP::parsePacket() -{ - return available(); -} - -int WiFiUDP::read() -{ - uint8_t b; - if (available()) - { - ServerDrv::getData(_sock, &b); - return b; - }else{ - return -1; - } -} - -int WiFiUDP::read(unsigned char* buffer, size_t len) -{ - if (available()) - { - size_t size = 0; - if (!ServerDrv::getDataBuf(_sock, buffer, &size)) - return -1; - // TODO check if the buffer is too smal respect to buffer size - return size; - }else{ - return -1; - } -} - -int WiFiUDP::peek() -{ - uint8_t b; - if (!available()) - return -1; - - ServerDrv::getData(_sock, &b, 1); - return b; -} - -void WiFiUDP::flush() -{ - while (available()) - read(); -} - -IPAddress WiFiUDP::remoteIP() -{ - uint8_t _remoteIp[4] = {0}; - uint8_t _remotePort[2] = {0}; - - WiFiDrv::getRemoteData(_sock, _remoteIp, _remotePort); - IPAddress ip(_remoteIp); - return ip; -} - -uint16_t WiFiUDP::remotePort() -{ - uint8_t _remoteIp[4] = {0}; - uint8_t _remotePort[2] = {0}; - - WiFiDrv::getRemoteData(_sock, _remoteIp, _remotePort); - uint16_t port = (_remotePort[0]<<8)+_remotePort[1]; - return port; -} - diff --git a/libraries/WiFi/WiFiUdp.h b/libraries/WiFi/WiFiUdp.h deleted file mode 100644 index 1b31693..0000000 --- a/libraries/WiFi/WiFiUdp.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef wifiudp_h -#define wifiudp_h - -#include - -#define UDP_TX_PACKET_MAX_SIZE 24 - -class WiFiUDP : public UDP { -private: - uint8_t _sock; // socket ID for Wiz5100 - uint16_t _port; // local port to listen on - -public: - WiFiUDP(); // Constructor - virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - virtual void stop(); // Finish with the UDP socket - - // Sending UDP packets - - // Start building up a packet to send to the remote host specific in ip and port - // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port - virtual int beginPacket(IPAddress ip, uint16_t port); - // Start building up a packet to send to the remote host specific in host and port - // Returns 1 if successful, 0 if there was a problem resolving the hostname or port - virtual int beginPacket(const char *host, uint16_t port); - // Finish off this packet and send it - // Returns 1 if the packet was sent successfully, 0 if there was an error - virtual int endPacket(); - // Write a single byte into the packet - virtual size_t write(uint8_t); - // Write size bytes from buffer into the packet - virtual size_t write(const uint8_t *buffer, size_t size); - - using Print::write; - - // Start processing the next available incoming packet - // Returns the size of the packet in bytes, or 0 if no packets are available - virtual int parsePacket(); - // Number of bytes remaining in the current packet - virtual int available(); - // Read a single byte from the current packet - virtual int read(); - // Read up to len bytes from the current packet and place them into buffer - // Returns the number of bytes read, or 0 if none are available - virtual int read(unsigned char* buffer, size_t len); - // Read up to len characters from the current packet and place them into buffer - // Returns the number of characters read, or 0 if none are available - virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; - // Return the next byte from the current packet without moving on to the next byte - virtual int peek(); - virtual void flush(); // Finish reading the current packet - - // Return the IP address of the host who sent the current incoming packet - virtual IPAddress remoteIP(); - // Return the port of the host who sent the current incoming packet - virtual uint16_t remotePort(); - - friend class WiFiDrv; -}; - -#endif diff --git a/libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino deleted file mode 100644 index f42a7f3..0000000 --- a/libraries/WiFi/examples/ConnectNoEncryption/ConnectNoEncryption.ino +++ /dev/null @@ -1,121 +0,0 @@ -/* - - This example connects to an unencrypted Wifi network. - Then it prints the MAC address of the Wifi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ - #include - -char ssid[] = "yourNetwork"; // the name of your network -int status = WL_IDLE_STATUS; // the Wifi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to open SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWifiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWifiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5],HEX); - Serial.print(":"); - Serial.print(mac[4],HEX); - Serial.print(":"); - Serial.print(mac[3],HEX); - Serial.print(":"); - Serial.print(mac[2],HEX); - Serial.print(":"); - Serial.print(mac[1],HEX); - Serial.print(":"); - Serial.println(mac[0],HEX); - - // print your subnet mask: - IPAddress subnet = WiFi.subnetMask(); - Serial.print("NetMask: "); - Serial.println(subnet); - - // print your gateway address: - IPAddress gateway = WiFi.gatewayIP(); - Serial.print("Gateway: "); - Serial.println(gateway); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5],HEX); - Serial.print(":"); - Serial.print(bssid[4],HEX); - Serial.print(":"); - Serial.print(bssid[3],HEX); - Serial.print(":"); - Serial.print(bssid[2],HEX); - Serial.print(":"); - Serial.print(bssid[1],HEX); - Serial.print(":"); - Serial.println(bssid[0],HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption,HEX); -} - diff --git a/libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino b/libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino deleted file mode 100644 index 19736b5..0000000 --- a/libraries/WiFi/examples/ConnectWithWEP/ConnectWithWEP.ino +++ /dev/null @@ -1,126 +0,0 @@ -/* - - This example connects to a WEP-encrypted Wifi network. - Then it prints the MAC address of the Wifi shield, - the IP address obtained, and other network details. - - If you use 40-bit WEP, you need a key that is 10 characters long, - and the characters must be hexadecimal (0-9 or A-F). - e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work - (too short) and ABBAISDEAF won't work (I and S are not - hexadecimal characters). - - For 128-bit, you need a string that is 26 characters long. - D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, - all in the 0-9, A-F range. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char key[] = "D0D0DEADF00DABBADEAFBEADED"; // your network key -int keyIndex = 0; // your network key Index number -int status = WL_IDLE_STATUS; // the Wifi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WEP network, SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid, keyIndex, key); - - // wait 10 seconds for connection: - delay(10000); - } - - // once you are connected : - Serial.print("You're connected to the network"); - printCurrentNet(); - printWifiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWifiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5],HEX); - Serial.print(":"); - Serial.print(mac[4],HEX); - Serial.print(":"); - Serial.print(mac[3],HEX); - Serial.print(":"); - Serial.print(mac[2],HEX); - Serial.print(":"); - Serial.print(mac[1],HEX); - Serial.print(":"); - Serial.println(mac[0],HEX); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5],HEX); - Serial.print(":"); - Serial.print(bssid[4],HEX); - Serial.print(":"); - Serial.print(bssid[3],HEX); - Serial.print(":"); - Serial.print(bssid[2],HEX); - Serial.print(":"); - Serial.print(bssid[1],HEX); - Serial.print(":"); - Serial.println(bssid[0],HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption,HEX); - Serial.println(); -} - - - diff --git a/libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino b/libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino deleted file mode 100644 index fcc33ec..0000000 --- a/libraries/WiFi/examples/ConnectWithWPA/ConnectWithWPA.ino +++ /dev/null @@ -1,116 +0,0 @@ -/* - - This example connects to an unencrypted Wifi network. - Then it prints the MAC address of the Wifi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ - #include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password -int status = WL_IDLE_STATUS; // the Wifi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWifiData(); - -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWifiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5],HEX); - Serial.print(":"); - Serial.print(mac[4],HEX); - Serial.print(":"); - Serial.print(mac[3],HEX); - Serial.print(":"); - Serial.print(mac[2],HEX); - Serial.print(":"); - Serial.print(mac[1],HEX); - Serial.print(":"); - Serial.println(mac[0],HEX); - -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5],HEX); - Serial.print(":"); - Serial.print(bssid[4],HEX); - Serial.print(":"); - Serial.print(bssid[3],HEX); - Serial.print(":"); - Serial.print(bssid[2],HEX); - Serial.print(":"); - Serial.print(bssid[1],HEX); - Serial.print(":"); - Serial.println(bssid[0],HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption,HEX); - Serial.println(); -} - diff --git a/libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino b/libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino deleted file mode 100644 index 93b3000..0000000 --- a/libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino +++ /dev/null @@ -1,119 +0,0 @@ -/* - - This example prints the Wifi shield's MAC address, and - scans for available Wifi networks using the Wifi shield. - Every ten seconds, it scans again. It doesn't actually - connect to any network, so no encryption scheme is specified. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 21 Junn 2012 - by Tom Igoe and Jaymes Dec - */ - - -#include -#include - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // Print WiFi MAC address: - printMacAddress(); - - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void loop() { - delay(10000); - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void printMacAddress() { - // the MAC address of your Wifi shield - byte mac[6]; - - // print your MAC address: - WiFi.macAddress(mac); - Serial.print("MAC: "); - Serial.print(mac[5],HEX); - Serial.print(":"); - Serial.print(mac[4],HEX); - Serial.print(":"); - Serial.print(mac[3],HEX); - Serial.print(":"); - Serial.print(mac[2],HEX); - Serial.print(":"); - Serial.print(mac[1],HEX); - Serial.print(":"); - Serial.println(mac[0],HEX); -} - -void listNetworks() { - // scan for nearby networks: - Serial.println("** Scan Networks **"); - int numSsid = WiFi.scanNetworks(); - if (numSsid == -1) - { - Serial.println("Couldn't get a wifi connection"); - while(true); - } - - // print the list of networks seen: - Serial.print("number of available networks:"); - Serial.println(numSsid); - - // print the network number and name for each network found: - for (int thisNet = 0; thisNet -#include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -WiFiServer server(80); - -void setup() { - Serial.begin(9600); // initialize serial communication - pinMode(9, OUTPUT); // set the LED pin mode - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - while(true); // don't continue - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); // start the web server on port 80 - printWifiStatus(); // you're connected now, so print out the status -} - - -void loop() { - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { // if you get a client, - Serial.println("new client"); // print a message out the serial port - String currentLine = ""; // make a String to hold incoming data from the client - while (client.connected()) { // loop while the client's connected - if (client.available()) { // if there's bytes to read from the client, - char c = client.read(); // read a byte, then - Serial.write(c); // print it out the serial monitor - if (c == '\n') { // if the byte is a newline character - - // if the current line is blank, you got two newline characters in a row. - // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { - // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - - // the content of the HTTP response follows the header: - client.print("Click here turn the LED on pin 9 on
"); - client.print("Click here turn the LED on pin 9 off
"); - - // The HTTP response ends with another blank line: - client.println(); - // break out of the while loop: - break; - } - else { // if you got a newline, then clear currentLine: - currentLine = ""; - } - } - else if (c != '\r') { // if you got anything else but a carriage return character, - currentLine += c; // add it to the end of the currentLine - } - - // Check to see if the client request was "GET /H" or "GET /L": - if (currentLine.endsWith("GET /H")) { - digitalWrite(9, HIGH); // GET /H turns the LED on - } - if (currentLine.endsWith("GET /L")) { - digitalWrite(9, LOW); // GET /L turns the LED off - } - } - } - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - // print where to go in a browser: - Serial.print("To see this page in action, open a browser to http://"); - Serial.println(ip); -} diff --git a/libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino b/libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino deleted file mode 100644 index e4b1d1a..0000000 --- a/libraries/WiFi/examples/WiFiChatServer/WiFiChatServer.ino +++ /dev/null @@ -1,111 +0,0 @@ -/* - Chat Server - - A simple server that distributes any incoming messages to all - connected clients. To use telnet to your device's IP address and type. - You can see the client's input in the serial monitor as well. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - - Circuit: - * WiFi shield attached - - created 18 Dec 2009 - by David A. Mellis - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP) - -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(23); - -boolean alreadyConnected = false; // whether or not the client was connected previously - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // start the server: - server.begin(); - // you're connected now, so print out the status: - printWifiStatus(); - } - - -void loop() { - // wait for a new client: - WiFiClient client = server.available(); - - - // when the client sends the first byte, say hello: - if (client) { - if (!alreadyConnected) { - // clead out the input buffer: - client.flush(); - Serial.println("We have a new client"); - client.println("Hello, client!"); - alreadyConnected = true; - } - - if (client.available() > 0) { - // read the bytes incoming from the client: - char thisChar = client.read(); - // echo the bytes back to the client: - server.write(thisChar); - // echo the bytes to the server as well: - Serial.write(thisChar); - } - } -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - diff --git a/libraries/WiFi/examples/WiFiPachubeClient/WiFiPachubeClient.ino b/libraries/WiFi/examples/WiFiPachubeClient/WiFiPachubeClient.ino deleted file mode 100644 index f8ffc07..0000000 --- a/libraries/WiFi/examples/WiFiPachubeClient/WiFiPachubeClient.ino +++ /dev/null @@ -1,190 +0,0 @@ -/* - Wifi Pachube sensor client - - This sketch connects an analog sensor to Pachube (http://www.pachube.com) - using an Arduino Wifi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - This example has been updated to use version 2.0 of the Pachube API. - To make it work, create a feed with a datastream, and give it the ID - sensor1. Or change the code below to match your feed. - - Circuit: - * Analog sensor attached to analog in 0 - * Wifi shield attached to pins 10, 11, 12, 13 - - created 13 Mar 2012 - modified 31 May 2012 - by Tom Igoe - modified 8 Sept 2012 - by Scott Fitzgerald - - This code is in the public domain. - - */ -#include -#include - -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Arduino Project" // user agent is the project name - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password - -int status = WL_IDLE_STATUS; - -// initialize the library instance: -WiFiClient client; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -//char server[] = "api.pachube.com"; // name address for pachube API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWifiStatus(); -} - - -void loop() { - // read the analog sensor: - int sensorReading = analogRead(A0); - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - while (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - sendData(sensorReading); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void sendData(int thisData) { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); - client.print("X-ApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - - // calculate the length of the sensor reading in bytes: - // 8 bytes for "sensor1," + number of digits of the data: - int thisLength = 8 + getLength(thisData); - client.println(thisLength); - - // last pieces of the HTTP PUT request: - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request: - client.print("sensor1,"); - client.println(thisData); - - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted: - lastConnectionTime = millis(); -} - - -// This method calculates the number of digits in the -// sensor reading. Since each digit of the ASCII decimal -// representation is a byte, the number of digits equals -// the number of bytes: - -int getLength(int someValue) { - // there's at least one byte: - int digits = 1; - // continually divide the value by ten, - // adding one to the digit count for each - // time you divide, until you're at 0: - int dividend = someValue /10; - while (dividend > 0) { - dividend = dividend /10; - digits++; - } - // return the number of digits: - return digits; -} - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - diff --git a/libraries/WiFi/examples/WiFiPachubeClientString/WiFiPachubeClientString.ino b/libraries/WiFi/examples/WiFiPachubeClientString/WiFiPachubeClientString.ino deleted file mode 100644 index 243fe83..0000000 --- a/libraries/WiFi/examples/WiFiPachubeClientString/WiFiPachubeClientString.ino +++ /dev/null @@ -1,177 +0,0 @@ -/* - Wifi Pachube sensor client with Strings - - This sketch connects an analog sensor to Pachube (http://www.pachube.com) - using a Arduino Wifi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - This example has been updated to use version 2.0 of the pachube.com API. - To make it work, create a feed with a datastream, and give it the ID - sensor1. Or change the code below to match your feed. - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * Analog sensor attached to analog in 0 - * Wifi shield attached to pins 10, 11, 12, 13 - - created 16 Mar 2012 - modified 31 May 2012 - by Tom Igoe - modified 8 Sept 2012 - by Scott Fitzgerald - - This code is in the public domain. - - */ - -#include -#include - -#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here -#define FEEDID 00000 // replace your feed ID -#define USERAGENT "My Arduino Project" // user agent is the project name - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password - -int status = WL_IDLE_STATUS; - -// initialize the library instance: -WiFiClient client; - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(216,52,233,121); // numeric IP for api.pachube.com -char server[] = "api.pachube.com"; // name address for pachube API - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; //delay between updates to pachube.com - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWifiStatus(); -} - -void loop() { - // read the analog sensor: - int sensorReading = analogRead(A0); - // convert the data to a String to send it: - - String dataString = "sensor1,"; - dataString += sensorReading; - - // you can append multiple readings to this String if your - // pachube feed is set up to handle multiple values: - int otherSensorReading = analogRead(A1); - dataString += "\nsensor2,"; - dataString += otherSensorReading; - - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - while (client.available()) { - char c = client.read(); - Serial.print(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - sendData(dataString); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void sendData(String thisData) { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.print("PUT /v2/feeds/"); - client.print(FEEDID); - client.println(".csv HTTP/1.1"); - client.println("Host: api.pachube.com"); - client.print("X-ApiKey: "); - client.println(APIKEY); - client.print("User-Agent: "); - client.println(USERAGENT); - client.print("Content-Length: "); - client.println(thisData.length()); - - // last pieces of the HTTP PUT request: - client.println("Content-Type: text/csv"); - client.println("Connection: close"); - client.println(); - - // here's the actual content of the PUT request: - client.println(thisData); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - // note the time that the connection was made or attempted: - lastConnectionTime = millis(); -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - diff --git a/libraries/WiFi/examples/WiFiTwitterClient/WiFiTwitterClient.ino b/libraries/WiFi/examples/WiFiTwitterClient/WiFiTwitterClient.ino deleted file mode 100644 index d500cfb..0000000 --- a/libraries/WiFi/examples/WiFiTwitterClient/WiFiTwitterClient.ino +++ /dev/null @@ -1,163 +0,0 @@ -/* - Wifi Twitter Client with Strings - - This sketch connects to Twitter using using an Arduino WiFi shield. - It parses the XML returned, and looks for this is a tweet - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - This example uses the String library, which is part of the Arduino core from - version 0019. - - Circuit: - * WiFi shield attached to pins 10, 11, 12, 13 - - created 23 apr 2012 - modified 31 May 2012 - by Tom Igoe - - This code is in the public domain. - - */ -#include -#include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "password"; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; // status of the wifi connection - -// initialize the library instance: -WiFiClient client; - -const unsigned long requestInterval = 30*1000; // delay between requests; 30 seconds - -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(199,59,149,200); // numeric IP for api.twitter.com -char server[] = "api.twitter.com"; // name address for twitter API - -boolean requested; // whether you've made a request since connecting -unsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds - -String currentLine = ""; // string to hold the text from server -String tweet = ""; // string to hold the tweet -boolean readingTweet = false; // if you're currently reading the tweet - -void setup() { - // reserve space for the strings: - currentLine.reserve(256); - tweet.reserve(150); - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWifiStatus(); - connectToServer(); -} - -void loop() -{ - if (client.connected()) { - if (client.available()) { - // read incoming bytes: - char inChar = client.read(); - - // add incoming byte to end of line: - currentLine += inChar; - - // if you get a newline, clear the line: - if (inChar == '\n') { - currentLine = ""; - } - // if the current line ends with , it will - // be followed by the tweet: - if ( currentLine.endsWith("")) { - // tweet is beginning. Clear the tweet string: - readingTweet = true; - tweet = ""; - // break out of the loop so this character isn't added to the tweet: - return; - } - // if you're currently reading the bytes of a tweet, - // add them to the tweet String: - if (readingTweet) { - if (inChar != '<') { - tweet += inChar; - } - else { - // if you got a "<" character, - // you've reached the end of the tweet: - readingTweet = false; - Serial.println(tweet); - // close the connection to the server: - client.stop(); - } - } - } - } - else if (millis() - lastAttemptTime > requestInterval) { - // if you're not connected, and two minutes have passed since - // your last connection, then attempt to connect again: - connectToServer(); - } -} - -void connectToServer() { - // attempt to connect, and wait a millisecond: - Serial.println("connecting to server..."); - if (client.connect(server, 80)) { - Serial.println("making HTTP request..."); - // make HTTP GET request to twitter: - client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino HTTP/1.1"); - client.println("Host: api.twitter.com"); - client.println("Connection: close"); - client.println(); - } - // note the time of this connect attempt: - lastAttemptTime = millis(); -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - diff --git a/libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino deleted file mode 100644 index dd8b003..0000000 --- a/libraries/WiFi/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino +++ /dev/null @@ -1,182 +0,0 @@ -/* - - Udp NTP Client - - Get the time from a Network Time Protocol (NTP) time server - Demonstrates use of UDP sendPacket and ReceivePacket - For more on NTP time servers and the messages needed to communicate with them, - see http://en.wikipedia.org/wiki/Network_Time_Protocol - - created 4 Sep 2010 - by Michael Margolis - modified 9 Apr 2012 - by Tom Igoe - - This code is in the public domain. - - */ - -#include -#include -#include - -int status = WL_IDLE_STATUS; -char ssid[] = "mynetwork"; // your network SSID (name) -char pass[] = "mypassword"; // your network password -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen for UDP packets - -IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server - -const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message - -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets - -// A UDP instance to let us send and receive packets over UDP -WiFiUDP Udp; - -void setup() -{ - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - Serial.println("Connected to wifi"); - printWifiStatus(); - - Serial.println("\nStarting connection to server..."); - Udp.begin(localPort); -} - -void loop() -{ - sendNTPpacket(timeServer); // send an NTP packet to a time server - // wait to see if a reply is available - delay(1000); - Serial.println( Udp.parsePacket() ); - if ( Udp.parsePacket() ) { - Serial.println("packet received"); - // We've received a packet, read the data from it - Udp.read(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer - - //the timestamp starts at byte 40 of the received packet and is four bytes, - // or two words, long. First, esxtract the two words: - - unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); - unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); - // combine the four bytes (two words) into a long integer - // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; - Serial.print("Seconds since Jan 1 1900 = " ); - Serial.println(secsSince1900); - - // now convert NTP time into everyday time: - Serial.print("Unix time = "); - // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: - const unsigned long seventyYears = 2208988800UL; - // subtract seventy years: - unsigned long epoch = secsSince1900 - seventyYears; - // print Unix time: - Serial.println(epoch); - - - // print the hour, minute and second: - Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) - Serial.print(':'); - if ( ((epoch % 3600) / 60) < 10 ) { - // In the first 10 minutes of each hour, we'll want a leading '0' - Serial.print('0'); - } - Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) - Serial.print(':'); - if ( (epoch % 60) < 10 ) { - // In the first 10 seconds of each minute, we'll want a leading '0' - Serial.print('0'); - } - Serial.println(epoch %60); // print the second - } - // wait ten seconds before asking for the time again - delay(10000); -} - -// send an NTP request to the time server at the given address -unsigned long sendNTPpacket(IPAddress& address) -{ - //Serial.println("1"); - // set all bytes in the buffer to 0 - memset(packetBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - //Serial.println("2"); - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; - packetBuffer[13] = 0x4E; - packetBuffer[14] = 49; - packetBuffer[15] = 52; - - //Serial.println("3"); - - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - Udp.beginPacket(address, 123); //NTP requests are to port 123 - //Serial.println("4"); - Udp.write(packetBuffer,NTP_PACKET_SIZE); - //Serial.println("5"); - Udp.endPacket(); - //Serial.println("6"); -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - - - - - - diff --git a/libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino deleted file mode 100644 index eb11295..0000000 --- a/libraries/WiFi/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino +++ /dev/null @@ -1,112 +0,0 @@ - -/* - WiFi UDP Send and Receive String - - This sketch wait an UDP packet on localPort using a WiFi shield. - When a packet is received an Acknowledge packet is sent to the client on port remotePort - - Circuit: - * WiFi shield attached - - created 30 December 2012 - by dlf (Metodo2 srl) - - */ - - -#include -#include -#include - -int status = WL_IDLE_STATUS; -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen on - -char packetBuffer[255]; //buffer to hold incoming packet -char ReplyBuffer[] = "acknowledged"; // a string to send back - -WiFiUDP Udp; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWifiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - Udp.begin(localPort); -} - -void loop() { - - // if there's data available, read a packet - int packetSize = Udp.parsePacket(); - if(packetSize) - { - Serial.print("Received packet of size "); - Serial.println(packetSize); - Serial.print("From "); - IPAddress remoteIp = Udp.remoteIP(); - Serial.print(remoteIp); - Serial.print(", port "); - Serial.println(Udp.remotePort()); - - // read the packet into packetBufffer - int len = Udp.read(packetBuffer,255); - if (len >0) packetBuffer[len]=0; - Serial.println("Contents:"); - Serial.println(packetBuffer); - - // send a reply, to the IP address and port that sent us the packet we received - Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); - Udp.write(ReplyBuffer); - Udp.endPacket(); - } -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - diff --git a/libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino b/libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino deleted file mode 100644 index 310ec46..0000000 --- a/libraries/WiFi/examples/WiFiWebClient/WiFiWebClient.ino +++ /dev/null @@ -1,121 +0,0 @@ - -/* - Web client - - This sketch connects to a website (http://www.google.com) - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ - - -#include -#include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -WiFiClient client; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWifiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - if (client.connect(server, 80)) { - Serial.println("connected to server"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } -} - -void loop() { - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting from server."); - client.stop(); - - // do nothing forevermore: - while(true); - } -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - diff --git a/libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino deleted file mode 100644 index 96eb628..0000000 --- a/libraries/WiFi/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino +++ /dev/null @@ -1,138 +0,0 @@ -/* - Repeating Wifi Web client - - This sketch connects to a a web server and makes a request - using an Arduino Wifi shield. - - Circuit: - * Wifi shield attached to pins 10, 11, 12, 13 - - created 23 April 2012 - modifide 31 May 2012 - by Tom Igoe - - http://arduino.cc/en/Tutorial/WifiWebClientRepeating - This code is in the public domain. - */ - -#include -#include - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -// Initialize the Wifi client library -WiFiClient client; - -// server address: -char server[] = "www.arduino.cc"; -//IPAddress server(64,131,82,241); - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -boolean lastConnected = false; // state of the connection last time through the main loop -const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWifiStatus(); -} - -void loop() { - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if there's no net connection, but there was one last time - // through the loop, then stop the client: - if (!client.connected() && lastConnected) { - Serial.println(); - Serial.println("disconnecting."); - client.stop(); - } - - // if you're not connected, and ten seconds have passed since - // your last connection, then connect again and send data: - if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { - httpRequest(); - } - // store the state of the connection for next time through - // the loop: - lastConnected = client.connected(); -} - -// this method makes a HTTP connection to the server: -void httpRequest() { - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.println("GET /latest.txt HTTP/1.1"); - client.println("Host: www.arduino.cc"); - client.println("User-Agent: arduino-ethernet"); - client.println("Connection: close"); - client.println(); - - // note the time that the connection was made: - lastConnectionTime = millis(); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - Serial.println("disconnecting."); - client.stop(); - } -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - - diff --git a/libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino b/libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino deleted file mode 100644 index de861e8..0000000 --- a/libraries/WiFi/examples/WiFiWebServer/WiFiWebServer.ino +++ /dev/null @@ -1,134 +0,0 @@ -/* - WiFi Web Server - - A simple web server that shows the value of the analog input pins. - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the Wifi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - - -char ssid[] = "yourNetwork"; // your network SSID (name) -char pass[] = "secretPassword"; // your network password -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while(true); - } - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); - // you're connected now, so print out the status: - printWifiStatus(); -} - - -void loop() { - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - - -void printWifiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - diff --git a/libraries/WiFi/keywords.txt b/libraries/WiFi/keywords.txt deleted file mode 100644 index 4106a7d..0000000 --- a/libraries/WiFi/keywords.txt +++ /dev/null @@ -1,51 +0,0 @@ -####################################### -# Syntax Coloring Map For WiFi -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -WiFi KEYWORD1 -Client KEYWORD1 -Server KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -status KEYWORD2 -connect KEYWORD2 -write KEYWORD2 -available KEYWORD2 -config KEYWORD2 -setDNS KEYWORD2 -read KEYWORD2 -flush KEYWORD2 -stop KEYWORD2 -connected KEYWORD2 -begin KEYWORD2 -disconnect KEYWORD2 -macAddress KEYWORD2 -localIP KEYWORD2 -subnetMask KEYWORD2 -gatewayIP KEYWORD2 -SSID KEYWORD2 -BSSID KEYWORD2 -RSSI KEYWORD2 -encryptionType KEYWORD2 -getResult KEYWORD2 -getSocket KEYWORD2 -WiFiClient KEYWORD2 -WiFiServer KEYWORD2 -WiFiUDP KEYWORD2 -beginPacket KEYWORD2 -endPacket KEYWORD2 -parsePacket KEYWORD2 -remoteIP KEYWORD2 -remotePort KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/libraries/WiFi/utility/debug.h b/libraries/WiFi/utility/debug.h deleted file mode 100644 index 9f71055..0000000 --- a/libraries/WiFi/utility/debug.h +++ /dev/null @@ -1,77 +0,0 @@ -//*********************************************/ -// -// File: debug.h -// -// Author: dlf (Metodo2 srl) -// -//********************************************/ - - -#ifndef Debug_H -#define Debug_H - -#include -#include - -#define PRINT_FILE_LINE() do { \ - Serial.print("[");Serial.print(__FILE__); \ - Serial.print("::");Serial.print(__LINE__);Serial.print("]");\ -}while (0); - -#ifdef _DEBUG_ - -#define INFO(format, args...) do { \ - char buf[250]; \ - sprintf(buf, format, args); \ - Serial.println(buf); \ -} while(0); - -#define INFO1(x) do { PRINT_FILE_LINE() Serial.print("-I-");\ - Serial.println(x); \ -}while (0); - - -#define INFO2(x,y) do { PRINT_FILE_LINE() Serial.print("-I-");\ - Serial.print(x,16);Serial.print(",");Serial.println(y,16); \ -}while (0); - - -#else -#define INFO1(x) do {} while(0); -#define INFO2(x,y) do {} while(0); -#define INFO(format, args...) do {} while(0); -#endif - -#if 0 -#define WARN(args) do { PRINT_FILE_LINE() \ - Serial.print("-W-"); Serial.println(args); \ -}while (0); -#else -#define WARN(args) do {} while (0); -#endif - -#if _DEBUG_SPI_ -#define DBG_PIN2 5 -#define DBG_PIN 4 - -#define START() digitalWrite(DBG_PIN2, HIGH); -#define END() digitalWrite(DBG_PIN2, LOW); -#define SET_TRIGGER() digitalWrite(DBG_PIN, HIGH); -#define RST_TRIGGER() digitalWrite(DBG_PIN, LOW); - -#define INIT_TRIGGER() pinMode(DBG_PIN, OUTPUT); \ - pinMode(DBG_PIN2, OUTPUT); \ - RST_TRIGGER() -#define TOGGLE_TRIGGER() SET_TRIGGER() \ - delayMicroseconds(2); \ - RST_TRIGGER() -#else -#define START() -#define END() -#define SET_TRIGGER() -#define RST_TRIGGER() -#define INIT_TRIGGER() -#define TOGGLE_TRIGGER() -#endif - -#endif diff --git a/libraries/WiFi/utility/server_drv.cpp b/libraries/WiFi/utility/server_drv.cpp deleted file mode 100644 index 4a6d293..0000000 --- a/libraries/WiFi/utility/server_drv.cpp +++ /dev/null @@ -1,308 +0,0 @@ -//#define _DEBUG_ - -#include "server_drv.h" - -#include "Arduino.h" -#include "spi_drv.h" - -extern "C" { -#include "wl_types.h" -#include "debug.h" -} - - -// Start server TCP on port specified -void ServerDrv::startServer(uint16_t port, uint8_t sock, uint8_t protMode) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(START_SERVER_TCP_CMD, PARAM_NUMS_3); - SpiDrv::sendParam(port); - SpiDrv::sendParam(&sock, 1); - SpiDrv::sendParam(&protMode, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(START_SERVER_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); -} - -// Start server TCP on port specified -void ServerDrv::startClient(uint32_t ipAddress, uint16_t port, uint8_t sock, uint8_t protMode) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(START_CLIENT_TCP_CMD, PARAM_NUMS_4); - SpiDrv::sendParam((uint8_t*)&ipAddress, sizeof(ipAddress)); - SpiDrv::sendParam(port); - SpiDrv::sendParam(&sock, 1); - SpiDrv::sendParam(&protMode, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(START_CLIENT_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); -} - -// Start server TCP on port specified -void ServerDrv::stopClient(uint8_t sock) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(STOP_CLIENT_TCP_CMD, PARAM_NUMS_1); - SpiDrv::sendParam(&sock, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(STOP_CLIENT_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); -} - - -uint8_t ServerDrv::getServerState(uint8_t sock) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(GET_STATE_TCP_CMD, PARAM_NUMS_1); - SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(GET_STATE_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - return _data; -} - -uint8_t ServerDrv::getClientState(uint8_t sock) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(GET_CLIENT_STATE_TCP_CMD, PARAM_NUMS_1); - SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(GET_CLIENT_STATE_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - return _data; -} - -uint16_t ServerDrv::availData(uint8_t sock) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(AVAIL_DATA_TCP_CMD, PARAM_NUMS_1); - SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _dataLen = 0; - uint16_t len = 0; - - SpiDrv::waitResponseCmd(AVAIL_DATA_TCP_CMD, PARAM_NUMS_1, (uint8_t*)&len, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return len; -} - -bool ServerDrv::getData(uint8_t sock, uint8_t *data, uint8_t peek) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(GET_DATA_TCP_CMD, PARAM_NUMS_2); - SpiDrv::sendParam(&sock, sizeof(sock)); - SpiDrv::sendParam(peek, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseData8(GET_DATA_TCP_CMD, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - if (_dataLen!=0) - { - *data = _data; - return true; - } - return false; -} - -bool ServerDrv::getDataBuf(uint8_t sock, uint8_t *_data, uint16_t *_dataLen) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(GET_DATABUF_TCP_CMD, PARAM_NUMS_1); - SpiDrv::sendBuffer(&sock, sizeof(sock), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - if (!SpiDrv::waitResponseData16(GET_DATABUF_TCP_CMD, _data, _dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - if (*_dataLen!=0) - { - return true; - } - return false; -} - -bool ServerDrv::insertDataBuf(uint8_t sock, const uint8_t *data, uint16_t _len) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(INSERT_DATABUF_CMD, PARAM_NUMS_2); - SpiDrv::sendBuffer(&sock, sizeof(sock)); - SpiDrv::sendBuffer((uint8_t *)data, _len, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseData8(INSERT_DATABUF_CMD, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - if (_dataLen!=0) - { - return (_data == 1); - } - return false; -} - -bool ServerDrv::sendUdpData(uint8_t sock) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(SEND_DATA_UDP_CMD, PARAM_NUMS_1); - SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseData8(SEND_DATA_UDP_CMD, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - if (_dataLen!=0) - { - return (_data == 1); - } - return false; -} - - -bool ServerDrv::sendData(uint8_t sock, const uint8_t *data, uint16_t len) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(SEND_DATA_TCP_CMD, PARAM_NUMS_2); - SpiDrv::sendBuffer(&sock, sizeof(sock)); - SpiDrv::sendBuffer((uint8_t *)data, len, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseData8(SEND_DATA_TCP_CMD, &_data, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - if (_dataLen!=0) - { - return (_data == 1); - } - return false; -} - - -uint8_t ServerDrv::checkDataSent(uint8_t sock) -{ - const uint16_t TIMEOUT_DATA_SENT = 25; - uint16_t timeout = 0; - uint8_t _data = 0; - uint8_t _dataLen = 0; - - do { - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(DATA_SENT_TCP_CMD, PARAM_NUMS_1); - SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - if (!SpiDrv::waitResponseCmd(DATA_SENT_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse isDataSent"); - } - SpiDrv::spiSlaveDeselect(); - - if (_data) timeout = 0; - else{ - ++timeout; - delay(100); - } - - }while((_data==0)&&(timeout -#include "wifi_spi.h" - -typedef enum eProtMode {TCP_MODE, UDP_MODE}tProtMode; - -class ServerDrv -{ -public: - - // Start server TCP on port specified - static void startServer(uint16_t port, uint8_t sock, uint8_t protMode=TCP_MODE); - - static void startClient(uint32_t ipAddress, uint16_t port, uint8_t sock, uint8_t protMode=TCP_MODE); - - static void stopClient(uint8_t sock); - - static uint8_t getServerState(uint8_t sock); - - static uint8_t getClientState(uint8_t sock); - - static bool getData(uint8_t sock, uint8_t *data, uint8_t peek = 0); - - static bool getDataBuf(uint8_t sock, uint8_t *data, uint16_t *len); - - static bool insertDataBuf(uint8_t sock, const uint8_t *_data, uint16_t _dataLen); - - static bool sendData(uint8_t sock, const uint8_t *data, uint16_t len); - - static bool sendUdpData(uint8_t sock); - - static uint16_t availData(uint8_t sock); - - static uint8_t checkDataSent(uint8_t sock); -}; - -extern ServerDrv serverDrv; - -#endif diff --git a/libraries/WiFi/utility/socket.c b/libraries/WiFi/utility/socket.c deleted file mode 100644 index 665073b..0000000 --- a/libraries/WiFi/utility/socket.c +++ /dev/null @@ -1,20 +0,0 @@ -/* -* -@file socket.c -@brief define function of socket API -* -*/ -#include -#include "socket.h" - -SOCKET socket(uint8 protocol) {return 0;} // Opens a socket(TCP or UDP or IP_RAW mode) -void close(SOCKET s) {} // Close socket -uint8 connect(SOCKET s, uint8 * addr, uint16 port) {return 0;} // Establish TCP connection (Active connection) -void disconnect(SOCKET s) {} // disconnect the connection -uint8 listen(SOCKET s) { return 0;} // Establish TCP connection (Passive connection) -uint16 send(SOCKET s, const uint8 * buf, uint16 len) { return 0;} // Send data (TCP) -uint16 recv(SOCKET s, uint8 * buf, uint16 len) {return 0;} // Receive data (TCP) -uint16 sendto(SOCKET s, const uint8 * buf, uint16 len, uint8 * addr, uint16 port) {return 0;} // Send data (UDP/IP RAW) -uint16 recvfrom(SOCKET s, uint8 * buf, uint16 len, uint8 * addr, uint16 *port) {return 0;} // Receive data (UDP/IP RAW) - -uint16 igmpsend(SOCKET s, const uint8 * buf, uint16 len) {return 0;} diff --git a/libraries/WiFi/utility/socket.h b/libraries/WiFi/utility/socket.h deleted file mode 100644 index 9b06d00..0000000 --- a/libraries/WiFi/utility/socket.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -* -@file socket.h -@brief define function of socket API -* -*/ - -#ifndef _SOCKET_H_ -#define _SOCKET_H_ - -#define TCP_SOCKET 1 -#define UDP_SOCKET 2 -#define RAW_SOCKET 3 - -#define SOCK_NOT_AVAIL 255 - -#include "wl_definitions.h" -/** - * The 8-bit signed data type. - */ -typedef char int8; -/** - * The volatile 8-bit signed data type. - */ -typedef volatile char vint8; -/** - * The 8-bit unsigned data type. - */ -typedef unsigned char uint8; -/** - * The volatile 8-bit unsigned data type. - */ -typedef volatile unsigned char vuint8; - -/** - * The 16-bit signed data type. - */ -typedef int int16; -/** - * The volatile 16-bit signed data type. - */ -typedef volatile int vint16; -/** - * The 16-bit unsigned data type. - */ -typedef unsigned int uint16; -/** - * The volatile 16-bit unsigned data type. - */ -typedef volatile unsigned int vuint16; -/** - * The 32-bit signed data type. - */ -typedef long int32; -/** - * The volatile 32-bit signed data type. - */ -typedef volatile long vint32; -/** - * The 32-bit unsigned data type. - */ -typedef unsigned long uint32; -/** - * The volatile 32-bit unsigned data type. - */ -typedef volatile unsigned long vuint32; - -/* bsd */ -typedef uint8 u_char; /**< 8-bit value */ -typedef uint16_t SOCKET; -typedef uint16 u_short; /**< 16-bit value */ -typedef uint16 u_int; /**< 16-bit value */ -typedef uint32 u_long; /**< 32-bit value */ - -extern SOCKET socket(uint8 protocol); // Opens a socket(TCP or UDP or IP_RAW mode) -extern void close(SOCKET s); // Close socket -extern uint8 connect(SOCKET s, uint8 * addr, uint16 port); // Establish TCP connection (Active connection) -extern void disconnect(SOCKET s); // disconnect the connection -extern uint8 listen(SOCKET s); // Establish TCP connection (Passive connection) -extern uint16 send(SOCKET s, const uint8 * buf, uint16 len); // Send data (TCP) -extern uint16 recv(SOCKET s, uint8 * buf, uint16 len); // Receive data (TCP) -extern uint16 sendto(SOCKET s, const uint8 * buf, uint16 len, uint8 * addr, uint16 port); // Send data (UDP/IP RAW) -extern uint16 recvfrom(SOCKET s, uint8 * buf, uint16 len, uint8 * addr, uint16 *port); // Receive data (UDP/IP RAW) - -extern uint16 igmpsend(SOCKET s, const uint8 * buf, uint16 len); -#endif -/* _SOCKET_H_ */ diff --git a/libraries/WiFi/utility/spi_drv.cpp b/libraries/WiFi/utility/spi_drv.cpp deleted file mode 100644 index 12a320b..0000000 --- a/libraries/WiFi/utility/spi_drv.cpp +++ /dev/null @@ -1,506 +0,0 @@ - -#include "Arduino.h" -#include "spi_drv.h" -#include "pins_arduino.h" -//#define _DEBUG_ -extern "C" { -#include "debug.h" -} - -#define DATAOUT 11 // MOSI -#define DATAIN 12 // MISO -#define SPICLOCK 13 // sck -#define SLAVESELECT 10 // ss -#define SLAVEREADY 7 // handshake pin -#define WIFILED 9 // led on wifi shield - -#define DELAY_100NS do { asm volatile("nop"); }while(0); -#define DELAY_SPI(X) { int ii=0; do { asm volatile("nop"); }while(++ii 0) && (_readChar != waitChar)); - return (_readChar == waitChar); -} - -int SpiDrv::readAndCheckChar(char checkChar, char* readChar) -{ - getParam((uint8_t*)readChar); - - return (*readChar == checkChar); -} - -char SpiDrv::readChar() -{ - uint8_t readChar = 0; - getParam(&readChar); - return readChar; -} - -#define WAIT_START_CMD(x) waitSpiChar(START_CMD) - -#define IF_CHECK_START_CMD(x) \ - if (!WAIT_START_CMD(_data)) \ - { \ - TOGGLE_TRIGGER() \ - WARN("Error waiting START_CMD"); \ - return 0; \ - }else \ - -#define CHECK_DATA(check, x) \ - if (!readAndCheckChar(check, &x)) \ - { \ - TOGGLE_TRIGGER() \ - WARN("Reply error"); \ - INFO2(check, (uint8_t)x); \ - return 0; \ - }else \ - -#define waitSlaveReady() (digitalRead(SLAVEREADY) == LOW) -#define waitSlaveSign() (digitalRead(SLAVEREADY) == HIGH) -#define waitSlaveSignalH() while(digitalRead(SLAVEREADY) != HIGH){} -#define waitSlaveSignalL() while(digitalRead(SLAVEREADY) != LOW){} - -void SpiDrv::waitForSlaveSign() -{ - while (!waitSlaveSign()); -} - -void SpiDrv::waitForSlaveReady() -{ - while (!waitSlaveReady()); -} - -void SpiDrv::getParam(uint8_t* param) -{ - // Get Params data - *param = spiTransfer(DUMMY_DATA); - DELAY_TRANSFER(); -} - -int SpiDrv::waitResponseCmd(uint8_t cmd, uint8_t numParam, uint8_t* param, uint8_t* param_len) -{ - char _data = 0; - int ii = 0; - - IF_CHECK_START_CMD(_data) - { - CHECK_DATA(cmd | REPLY_FLAG, _data){}; - - CHECK_DATA(numParam, _data); - { - readParamLen8(param_len); - for (ii=0; ii<(*param_len); ++ii) - { - // Get Params data - //param[ii] = spiTransfer(DUMMY_DATA); - getParam(¶m[ii]); - } - } - - readAndCheckChar(END_CMD, &_data); - } - - return 1; -} -/* -int SpiDrv::waitResponse(uint8_t cmd, uint8_t numParam, uint8_t* param, uint16_t* param_len) -{ - char _data = 0; - int i =0, ii = 0; - - IF_CHECK_START_CMD(_data) - { - CHECK_DATA(cmd | REPLY_FLAG, _data){}; - - CHECK_DATA(numParam, _data); - { - readParamLen16(param_len); - for (ii=0; ii<(*param_len); ++ii) - { - // Get Params data - param[ii] = spiTransfer(DUMMY_DATA); - } - } - - readAndCheckChar(END_CMD, &_data); - } - - return 1; -} -*/ - -int SpiDrv::waitResponseData16(uint8_t cmd, uint8_t* param, uint16_t* param_len) -{ - char _data = 0; - uint16_t ii = 0; - - IF_CHECK_START_CMD(_data) - { - CHECK_DATA(cmd | REPLY_FLAG, _data){}; - - uint8_t numParam = readChar(); - if (numParam != 0) - { - readParamLen16(param_len); - for (ii=0; ii<(*param_len); ++ii) - { - // Get Params data - param[ii] = spiTransfer(DUMMY_DATA); - } - } - - readAndCheckChar(END_CMD, &_data); - } - - return 1; -} - -int SpiDrv::waitResponseData8(uint8_t cmd, uint8_t* param, uint8_t* param_len) -{ - char _data = 0; - int ii = 0; - - IF_CHECK_START_CMD(_data) - { - CHECK_DATA(cmd | REPLY_FLAG, _data){}; - - uint8_t numParam = readChar(); - if (numParam != 0) - { - readParamLen8(param_len); - for (ii=0; ii<(*param_len); ++ii) - { - // Get Params data - param[ii] = spiTransfer(DUMMY_DATA); - } - } - - readAndCheckChar(END_CMD, &_data); - } - - return 1; -} - -int SpiDrv::waitResponseParams(uint8_t cmd, uint8_t numParam, tParam* params) -{ - char _data = 0; - int i =0, ii = 0; - - - IF_CHECK_START_CMD(_data) - { - CHECK_DATA(cmd | REPLY_FLAG, _data){}; - - uint8_t _numParam = readChar(); - if (_numParam != 0) - { - for (i=0; i<_numParam; ++i) - { - params[i].paramLen = readParamLen8(); - for (ii=0; ii maxNumParams) - { - numParam = maxNumParams; - } - *numParamRead = numParam; - if (numParam != 0) - { - for (i=0; i maxNumParams) - { - numParam = maxNumParams; - } - *numParamRead = numParam; - if (numParam != 0) - { - for (i=0; i>8)); - spiTransfer((uint8_t)(param_len & 0xff)); -} - -uint8_t SpiDrv::readParamLen8(uint8_t* param_len) -{ - uint8_t _param_len = spiTransfer(DUMMY_DATA); - if (param_len != NULL) - { - *param_len = _param_len; - } - return _param_len; -} - -uint16_t SpiDrv::readParamLen16(uint16_t* param_len) -{ - uint16_t _param_len = spiTransfer(DUMMY_DATA)<<8 | (spiTransfer(DUMMY_DATA)& 0xff); - if (param_len != NULL) - { - *param_len = _param_len; - } - return _param_len; -} - - -void SpiDrv::sendBuffer(uint8_t* param, uint16_t param_len, uint8_t lastParam) -{ - uint16_t i = 0; - - // Send Spi paramLen - sendParamLen16(param_len); - - // Send Spi param data - for (i=0; i>8)); - spiTransfer((uint8_t)(param & 0xff)); - - // if lastParam==1 Send Spi END CMD - if (lastParam == 1) - spiTransfer(END_CMD); -} - -/* Cmd Struct Message */ -/* _________________________________________________________________________________ */ -/*| START CMD | C/R | CMD |[TOT LEN]| N.PARAM | PARAM LEN | PARAM | .. | END CMD | */ -/*|___________|______|______|_________|_________|___________|________|____|_________| */ -/*| 8 bit | 1bit | 7bit | 8bit | 8bit | 8bit | nbytes | .. | 8bit | */ -/*|___________|______|______|_________|_________|___________|________|____|_________| */ - -void SpiDrv::sendCmd(uint8_t cmd, uint8_t numParam) -{ - // Send Spi START CMD - spiTransfer(START_CMD); - - //waitForSlaveSign(); - //wait the interrupt trigger on slave - delayMicroseconds(SPI_START_CMD_DELAY); - - // Send Spi C + cmd - spiTransfer(cmd & ~(REPLY_FLAG)); - - // Send Spi totLen - //spiTransfer(totLen); - - // Send Spi numParam - spiTransfer(numParam); - - // If numParam == 0 send END CMD - if (numParam == 0) - spiTransfer(END_CMD); - -} - -SpiDrv spiDrv; diff --git a/libraries/WiFi/utility/spi_drv.h b/libraries/WiFi/utility/spi_drv.h deleted file mode 100644 index b7e4cb7..0000000 --- a/libraries/WiFi/utility/spi_drv.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef SPI_Drv_h -#define SPI_Drv_h - -#include -#include "wifi_spi.h" - -#define SPI_START_CMD_DELAY 10 - -#define NO_LAST_PARAM 0 -#define LAST_PARAM 1 - -#define DUMMY_DATA 0xFF - -#define WAIT_FOR_SLAVE_SELECT() \ - SpiDrv::waitForSlaveReady(); \ - SpiDrv::spiSlaveSelect(); - - - -class SpiDrv -{ -private: - //static bool waitSlaveReady(); - static void waitForSlaveSign(); - static void getParam(uint8_t* param); -public: - - static void begin(); - - static void end(); - - static void spiDriverInit(); - - static void spiSlaveSelect(); - - static void spiSlaveDeselect(); - - static char spiTransfer(volatile char data); - - static void waitForSlaveReady(); - - //static int waitSpiChar(char waitChar, char* readChar); - - static int waitSpiChar(unsigned char waitChar); - - static int readAndCheckChar(char checkChar, char* readChar); - - static char readChar(); - - static int waitResponseParams(uint8_t cmd, uint8_t numParam, tParam* params); - - static int waitResponseCmd(uint8_t cmd, uint8_t numParam, uint8_t* param, uint8_t* param_len); - - static int waitResponseData8(uint8_t cmd, uint8_t* param, uint8_t* param_len); - - static int waitResponseData16(uint8_t cmd, uint8_t* param, uint16_t* param_len); - /* - static int waitResponse(uint8_t cmd, tParam* params, uint8_t* numParamRead, uint8_t maxNumParams); - - static int waitResponse(uint8_t cmd, uint8_t numParam, uint8_t* param, uint16_t* param_len); -*/ - static int waitResponse(uint8_t cmd, uint8_t* numParamRead, uint8_t** params, uint8_t maxNumParams); - - static void sendParam(uint8_t* param, uint8_t param_len, uint8_t lastParam = NO_LAST_PARAM); - - static void sendParamLen8(uint8_t param_len); - - static void sendParamLen16(uint16_t param_len); - - static uint8_t readParamLen8(uint8_t* param_len = NULL); - - static uint16_t readParamLen16(uint16_t* param_len = NULL); - - static void sendBuffer(uint8_t* param, uint16_t param_len, uint8_t lastParam = NO_LAST_PARAM); - - static void sendParam(uint16_t param, uint8_t lastParam = NO_LAST_PARAM); - - static void sendCmd(uint8_t cmd, uint8_t numParam); -}; - -extern SpiDrv spiDrv; - -#endif diff --git a/libraries/WiFi/utility/wifi_drv.cpp b/libraries/WiFi/utility/wifi_drv.cpp deleted file mode 100644 index ccd5f25..0000000 --- a/libraries/WiFi/utility/wifi_drv.cpp +++ /dev/null @@ -1,560 +0,0 @@ -#include -#include -#include - -#include "Arduino.h" -#include "spi_drv.h" -#include "wifi_drv.h" - -#define _DEBUG_ - -extern "C" { -#include "wifi_spi.h" -#include "wl_types.h" -#include "debug.h" -} - -// Array of data to cache the information related to the networks discovered -char WiFiDrv::_networkSsid[][WL_SSID_MAX_LENGTH] = {{"1"},{"2"},{"3"},{"4"},{"5"}}; -int32_t WiFiDrv::_networkRssi[WL_NETWORKS_LIST_MAXNUM] = { 0 }; -uint8_t WiFiDrv::_networkEncr[WL_NETWORKS_LIST_MAXNUM] = { 0 }; - -// Cached values of retrieved data -char WiFiDrv::_ssid[] = {0}; -uint8_t WiFiDrv::_bssid[] = {0}; -uint8_t WiFiDrv::_mac[] = {0}; -uint8_t WiFiDrv::_localIp[] = {0}; -uint8_t WiFiDrv::_subnetMask[] = {0}; -uint8_t WiFiDrv::_gatewayIp[] = {0}; -// Firmware version -char WiFiDrv::fwVersion[] = {0}; - - -// Private Methods - -void WiFiDrv::getNetworkData(uint8_t *ip, uint8_t *mask, uint8_t *gwip) -{ - tParam params[PARAM_NUMS_3] = { {0, (char*)ip}, {0, (char*)mask}, {0, (char*)gwip}}; - - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_IPADDR_CMD, PARAM_NUMS_1); - - uint8_t _dummy = DUMMY_DATA; - SpiDrv::sendParam(&_dummy, sizeof(_dummy), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - SpiDrv::waitResponseParams(GET_IPADDR_CMD, PARAM_NUMS_3, params); - - SpiDrv::spiSlaveDeselect(); -} - -void WiFiDrv::getRemoteData(uint8_t sock, uint8_t *ip, uint8_t *port) -{ - tParam params[PARAM_NUMS_2] = { {0, (char*)ip}, {0, (char*)port} }; - - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_REMOTE_DATA_CMD, PARAM_NUMS_1); - SpiDrv::sendParam(&sock, sizeof(sock), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - SpiDrv::waitResponseParams(GET_REMOTE_DATA_CMD, PARAM_NUMS_2, params); - - SpiDrv::spiSlaveDeselect(); -} - - -// Public Methods - - -void WiFiDrv::wifiDriverInit() -{ - SpiDrv::begin(); -} - -int8_t WiFiDrv::wifiSetNetwork(char* ssid, uint8_t ssid_len) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(SET_NET_CMD, PARAM_NUMS_1); - SpiDrv::sendParam((uint8_t*)ssid, ssid_len, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(SET_NET_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - _data = WL_FAILURE; - } - SpiDrv::spiSlaveDeselect(); - - return(_data == WIFI_SPI_ACK) ? WL_SUCCESS : WL_FAILURE; -} - -int8_t WiFiDrv::wifiSetPassphrase(char* ssid, uint8_t ssid_len, const char *passphrase, const uint8_t len) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(SET_PASSPHRASE_CMD, PARAM_NUMS_2); - SpiDrv::sendParam((uint8_t*)ssid, ssid_len, NO_LAST_PARAM); - SpiDrv::sendParam((uint8_t*)passphrase, len, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(SET_PASSPHRASE_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - _data = WL_FAILURE; - } - SpiDrv::spiSlaveDeselect(); - return _data; -} - - -int8_t WiFiDrv::wifiSetKey(char* ssid, uint8_t ssid_len, uint8_t key_idx, const void *key, const uint8_t len) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(SET_KEY_CMD, PARAM_NUMS_3); - SpiDrv::sendParam((uint8_t*)ssid, ssid_len, NO_LAST_PARAM); - SpiDrv::sendParam(&key_idx, KEY_IDX_LEN, NO_LAST_PARAM); - SpiDrv::sendParam((uint8_t*)key, len, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(SET_KEY_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - _data = WL_FAILURE; - } - SpiDrv::spiSlaveDeselect(); - return _data; -} - -void WiFiDrv::config(uint8_t validParams, uint32_t local_ip, uint32_t gateway, uint32_t subnet) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(SET_IP_CONFIG_CMD, PARAM_NUMS_4); - SpiDrv::sendParam((uint8_t*)&validParams, 1, NO_LAST_PARAM); - SpiDrv::sendParam((uint8_t*)&local_ip, 4, NO_LAST_PARAM); - SpiDrv::sendParam((uint8_t*)&gateway, 4, NO_LAST_PARAM); - SpiDrv::sendParam((uint8_t*)&subnet, 4, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(SET_IP_CONFIG_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - _data = WL_FAILURE; - } - SpiDrv::spiSlaveDeselect(); -} - -void WiFiDrv::setDNS(uint8_t validParams, uint32_t dns_server1, uint32_t dns_server2) -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(SET_DNS_CONFIG_CMD, PARAM_NUMS_3); - SpiDrv::sendParam((uint8_t*)&validParams, 1, NO_LAST_PARAM); - SpiDrv::sendParam((uint8_t*)&dns_server1, 4, NO_LAST_PARAM); - SpiDrv::sendParam((uint8_t*)&dns_server2, 4, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(SET_DNS_CONFIG_CMD, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - _data = WL_FAILURE; - } - SpiDrv::spiSlaveDeselect(); -} - - - -int8_t WiFiDrv::disconnect() -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(DISCONNECT_CMD, PARAM_NUMS_1); - - uint8_t _dummy = DUMMY_DATA; - SpiDrv::sendParam(&_dummy, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - int8_t result = SpiDrv::waitResponseCmd(DISCONNECT_CMD, PARAM_NUMS_1, &_data, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return result; -} - -uint8_t WiFiDrv::getConnectionStatus() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_CONN_STATUS_CMD, PARAM_NUMS_0); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = -1; - uint8_t _dataLen = 0; - SpiDrv::waitResponseCmd(GET_CONN_STATUS_CMD, PARAM_NUMS_1, &_data, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return _data; -} - -uint8_t* WiFiDrv::getMacAddress() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_MACADDR_CMD, PARAM_NUMS_1); - - uint8_t _dummy = DUMMY_DATA; - SpiDrv::sendParam(&_dummy, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _dataLen = 0; - SpiDrv::waitResponseCmd(GET_MACADDR_CMD, PARAM_NUMS_1, _mac, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return _mac; -} - -void WiFiDrv::getIpAddress(IPAddress& ip) -{ - getNetworkData(_localIp, _subnetMask, _gatewayIp); - ip = _localIp; -} - - void WiFiDrv::getSubnetMask(IPAddress& mask) - { - getNetworkData(_localIp, _subnetMask, _gatewayIp); - mask = _subnetMask; - } - - void WiFiDrv::getGatewayIP(IPAddress& ip) - { - getNetworkData(_localIp, _subnetMask, _gatewayIp); - ip = _gatewayIp; - } - -char* WiFiDrv::getCurrentSSID() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_CURR_SSID_CMD, PARAM_NUMS_1); - - uint8_t _dummy = DUMMY_DATA; - SpiDrv::sendParam(&_dummy, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _dataLen = 0; - SpiDrv::waitResponseCmd(GET_CURR_SSID_CMD, PARAM_NUMS_1, (uint8_t*)_ssid, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return _ssid; -} - -uint8_t* WiFiDrv::getCurrentBSSID() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_CURR_BSSID_CMD, PARAM_NUMS_1); - - uint8_t _dummy = DUMMY_DATA; - SpiDrv::sendParam(&_dummy, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _dataLen = 0; - SpiDrv::waitResponseCmd(GET_CURR_BSSID_CMD, PARAM_NUMS_1, _bssid, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return _bssid; -} - -int32_t WiFiDrv::getCurrentRSSI() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_CURR_RSSI_CMD, PARAM_NUMS_1); - - uint8_t _dummy = DUMMY_DATA; - SpiDrv::sendParam(&_dummy, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _dataLen = 0; - int32_t rssi = 0; - SpiDrv::waitResponseCmd(GET_CURR_RSSI_CMD, PARAM_NUMS_1, (uint8_t*)&rssi, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return rssi; -} - -uint8_t WiFiDrv::getCurrentEncryptionType() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_CURR_ENCT_CMD, PARAM_NUMS_1); - - uint8_t _dummy = DUMMY_DATA; - SpiDrv::sendParam(&_dummy, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t dataLen = 0; - uint8_t encType = 0; - SpiDrv::waitResponseCmd(GET_CURR_ENCT_CMD, PARAM_NUMS_1, (uint8_t*)&encType, &dataLen); - - SpiDrv::spiSlaveDeselect(); - - return encType; -} - -int8_t WiFiDrv::startScanNetworks() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(START_SCAN_NETWORKS, PARAM_NUMS_0); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - - if (!SpiDrv::waitResponseCmd(START_SCAN_NETWORKS, PARAM_NUMS_1, &_data, &_dataLen)) - { - WARN("error waitResponse"); - _data = WL_FAILURE; - } - - SpiDrv::spiSlaveDeselect(); - - return (_data == WL_FAILURE)? _data : WL_SUCCESS; -} - - -uint8_t WiFiDrv::getScanNetworks() -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(SCAN_NETWORKS, PARAM_NUMS_0); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t ssidListNum = 0; - SpiDrv::waitResponse(SCAN_NETWORKS, &ssidListNum, (uint8_t**)_networkSsid, WL_NETWORKS_LIST_MAXNUM); - - SpiDrv::spiSlaveDeselect(); - - return ssidListNum; -} - -char* WiFiDrv::getSSIDNetoworks(uint8_t networkItem) -{ - if (networkItem >= WL_NETWORKS_LIST_MAXNUM) - return NULL; - - return _networkSsid[networkItem]; -} - -uint8_t WiFiDrv::getEncTypeNetowrks(uint8_t networkItem) -{ - if (networkItem >= WL_NETWORKS_LIST_MAXNUM) - return NULL; - - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_IDX_ENCT_CMD, PARAM_NUMS_1); - - SpiDrv::sendParam(&networkItem, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t dataLen = 0; - uint8_t encType = 0; - SpiDrv::waitResponseCmd(GET_IDX_ENCT_CMD, PARAM_NUMS_1, (uint8_t*)&encType, &dataLen); - - SpiDrv::spiSlaveDeselect(); - - return encType; -} - -int32_t WiFiDrv::getRSSINetoworks(uint8_t networkItem) -{ - if (networkItem >= WL_NETWORKS_LIST_MAXNUM) - return NULL; - int32_t networkRssi = 0; - - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(GET_IDX_RSSI_CMD, PARAM_NUMS_1); - - SpiDrv::sendParam(&networkItem, 1, LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t dataLen = 0; - SpiDrv::waitResponseCmd(GET_IDX_RSSI_CMD, PARAM_NUMS_1, (uint8_t*)&networkRssi, &dataLen); - - SpiDrv::spiSlaveDeselect(); - - return networkRssi; -} - -uint8_t WiFiDrv::reqHostByName(const char* aHostname) -{ - WAIT_FOR_SLAVE_SELECT(); - - // Send Command - SpiDrv::sendCmd(REQ_HOST_BY_NAME_CMD, PARAM_NUMS_1); - SpiDrv::sendParam((uint8_t*)aHostname, strlen(aHostname), LAST_PARAM); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _data = 0; - uint8_t _dataLen = 0; - uint8_t result = SpiDrv::waitResponseCmd(REQ_HOST_BY_NAME_CMD, PARAM_NUMS_1, &_data, &_dataLen); - - SpiDrv::spiSlaveDeselect(); - - return result; -} - -int WiFiDrv::getHostByName(IPAddress& aResult) -{ - uint8_t _ipAddr[WL_IPV4_LENGTH]; - IPAddress dummy(0xFF,0xFF,0xFF,0xFF); - int result = 0; - - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(GET_HOST_BY_NAME_CMD, PARAM_NUMS_0); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(GET_HOST_BY_NAME_CMD, PARAM_NUMS_1, _ipAddr, &_dataLen)) - { - WARN("error waitResponse"); - }else{ - aResult = _ipAddr; - result = (aResult != dummy); - } - SpiDrv::spiSlaveDeselect(); - return result; -} - -int WiFiDrv::getHostByName(const char* aHostname, IPAddress& aResult) -{ - uint8_t retry = 10; - if (reqHostByName(aHostname)) - { - while(!getHostByName(aResult) && --retry > 0) - { - delay(1000); - } - }else{ - return 0; - } - return (retry>0); -} - -char* WiFiDrv::getFwVersion() -{ - WAIT_FOR_SLAVE_SELECT(); - // Send Command - SpiDrv::sendCmd(GET_FW_VERSION_CMD, PARAM_NUMS_0); - - //Wait the reply elaboration - SpiDrv::waitForSlaveReady(); - - // Wait for reply - uint8_t _dataLen = 0; - if (!SpiDrv::waitResponseCmd(GET_FW_VERSION_CMD, PARAM_NUMS_1, (uint8_t*)fwVersion, &_dataLen)) - { - WARN("error waitResponse"); - } - SpiDrv::spiSlaveDeselect(); - return fwVersion; -} - -WiFiDrv wiFiDrv; diff --git a/libraries/WiFi/utility/wifi_drv.h b/libraries/WiFi/utility/wifi_drv.h deleted file mode 100644 index d6ec029..0000000 --- a/libraries/WiFi/utility/wifi_drv.h +++ /dev/null @@ -1,248 +0,0 @@ -#ifndef WiFi_Drv_h -#define WiFi_Drv_h - -#include -#include "wifi_spi.h" -#include "IPAddress.h" -#include "../WiFiUdp.h" - -// Key index length -#define KEY_IDX_LEN 1 -// 5 secs of delay to have the connection established -#define WL_DELAY_START_CONNECTION 5000 -// firmware version string length -#define WL_FW_VER_LENGTH 6 - -class WiFiDrv -{ -private: - // settings of requested network - static char _networkSsid[WL_NETWORKS_LIST_MAXNUM][WL_SSID_MAX_LENGTH]; - static int32_t _networkRssi[WL_NETWORKS_LIST_MAXNUM]; - static uint8_t _networkEncr[WL_NETWORKS_LIST_MAXNUM]; - - // firmware version string in the format a.b.c - static char fwVersion[WL_FW_VER_LENGTH]; - - // settings of current selected network - static char _ssid[WL_SSID_MAX_LENGTH]; - static uint8_t _bssid[WL_MAC_ADDR_LENGTH]; - static uint8_t _mac[WL_MAC_ADDR_LENGTH]; - static uint8_t _localIp[WL_IPV4_LENGTH]; - static uint8_t _subnetMask[WL_IPV4_LENGTH]; - static uint8_t _gatewayIp[WL_IPV4_LENGTH]; - - /* - * Get network Data information - */ - static void getNetworkData(uint8_t *ip, uint8_t *mask, uint8_t *gwip); - - static uint8_t reqHostByName(const char* aHostname); - - static int getHostByName(IPAddress& aResult); - - /* - * Get remote Data information on UDP socket - */ - static void getRemoteData(uint8_t sock, uint8_t *ip, uint8_t *port); - -public: - - /* - * Driver initialization - */ - static void wifiDriverInit(); - - /* - * Set the desired network which the connection manager should try to - * connect to. - * - * The ssid of the desired network should be specified. - * - * param ssid: The ssid of the desired network. - * param ssid_len: Lenght of ssid string. - * return: WL_SUCCESS or WL_FAILURE - */ - static int8_t wifiSetNetwork(char* ssid, uint8_t ssid_len); - - /* Start Wifi connection with passphrase - * the most secure supported mode will be automatically selected - * - * param ssid: Pointer to the SSID string. - * param ssid_len: Lenght of ssid string. - * param passphrase: Passphrase. Valid characters in a passphrase - * must be between ASCII 32-126 (decimal). - * param len: Lenght of passphrase string. - * return: WL_SUCCESS or WL_FAILURE - */ - static int8_t wifiSetPassphrase(char* ssid, uint8_t ssid_len, const char *passphrase, const uint8_t len); - - /* Start Wifi connection with WEP encryption. - * Configure a key into the device. The key type (WEP-40, WEP-104) - * is determined by the size of the key (5 bytes for WEP-40, 13 bytes for WEP-104). - * - * param ssid: Pointer to the SSID string. - * param ssid_len: Lenght of ssid string. - * param key_idx: The key index to set. Valid values are 0-3. - * param key: Key input buffer. - * param len: Lenght of key string. - * return: WL_SUCCESS or WL_FAILURE - */ - static int8_t wifiSetKey(char* ssid, uint8_t ssid_len, uint8_t key_idx, const void *key, const uint8_t len); - - /* Set ip configuration disabling dhcp client - * - * param validParams: set the number of parameters that we want to change - * i.e. validParams = 1 means that we'll change only ip address - * validParams = 3 means that we'll change ip address, gateway and netmask - * param local_ip: Static ip configuration - * param gateway: Static gateway configuration - * param subnet: Static subnet mask configuration - */ - static void config(uint8_t validParams, uint32_t local_ip, uint32_t gateway, uint32_t subnet); - - /* Set DNS ip configuration - * - * param validParams: set the number of parameters that we want to change - * i.e. validParams = 1 means that we'll change only dns_server1 - * validParams = 2 means that we'll change dns_server1 and dns_server2 - * param dns_server1: Static DNS server1 configuration - * param dns_server2: Static DNS server2 configuration - */ - static void setDNS(uint8_t validParams, uint32_t dns_server1, uint32_t dns_server2); - - /* - * Disconnect from the network - * - * return: WL_SUCCESS or WL_FAILURE - */ - static int8_t disconnect(); - - /* - * Disconnect from the network - * - * return: one value of wl_status_t enum - */ - static uint8_t getConnectionStatus(); - - /* - * Get the interface MAC address. - * - * return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH - */ - static uint8_t* getMacAddress(); - - /* - * Get the interface IP address. - * - * return: copy the ip address value in IPAddress object - */ - static void getIpAddress(IPAddress& ip); - - /* - * Get the interface subnet mask address. - * - * return: copy the subnet mask address value in IPAddress object - */ - static void getSubnetMask(IPAddress& mask); - - /* - * Get the gateway ip address. - * - * return: copy the gateway ip address value in IPAddress object - */ - static void getGatewayIP(IPAddress& ip); - - /* - * Return the current SSID associated with the network - * - * return: ssid string - */ - static char* getCurrentSSID(); - - /* - * Return the current BSSID associated with the network. - * It is the MAC address of the Access Point - * - * return: pointer to uint8_t array with length WL_MAC_ADDR_LENGTH - */ - static uint8_t* getCurrentBSSID(); - - /* - * Return the current RSSI /Received Signal Strength in dBm) - * associated with the network - * - * return: signed value - */ - static int32_t getCurrentRSSI(); - - /* - * Return the Encryption Type associated with the network - * - * return: one value of wl_enc_type enum - */ - static uint8_t getCurrentEncryptionType(); - - /* - * Start scan WiFi networks available - * - * return: Number of discovered networks - */ - static int8_t startScanNetworks(); - - /* - * Get the networks available - * - * return: Number of discovered networks - */ - static uint8_t getScanNetworks(); - - /* - * Return the SSID discovered during the network scan. - * - * param networkItem: specify from which network item want to get the information - * - * return: ssid string of the specified item on the networks scanned list - */ - static char* getSSIDNetoworks(uint8_t networkItem); - - /* - * Return the RSSI of the networks discovered during the scanNetworks - * - * param networkItem: specify from which network item want to get the information - * - * return: signed value of RSSI of the specified item on the networks scanned list - */ - static int32_t getRSSINetoworks(uint8_t networkItem); - - /* - * Return the encryption type of the networks discovered during the scanNetworks - * - * param networkItem: specify from which network item want to get the information - * - * return: encryption type (enum wl_enc_type) of the specified item on the networks scanned list - */ - static uint8_t getEncTypeNetowrks(uint8_t networkItem); - - /* - * Resolve the given hostname to an IP address. - * param aHostname: Name to be resolved - * param aResult: IPAddress structure to store the returned IP address - * result: 1 if aIPAddrString was successfully converted to an IP address, - * else error code - */ - static int getHostByName(const char* aHostname, IPAddress& aResult); - - /* - * Get the firmware version - * result: version as string with this format a.b.c - */ - static char* getFwVersion(); - - friend class WiFiUDP; - -}; - -extern WiFiDrv wiFiDrv; - -#endif diff --git a/libraries/WiFi/utility/wifi_spi.h b/libraries/WiFi/utility/wifi_spi.h deleted file mode 100644 index 8856e33..0000000 --- a/libraries/WiFi/utility/wifi_spi.h +++ /dev/null @@ -1,153 +0,0 @@ -#ifndef WiFi_Spi_h -#define WiFi_Spi_h - -#include "wl_definitions.h" - -#define CMD_FLAG 0 -#define REPLY_FLAG 1<<7 -#define DATA_FLAG 0x40 - -#define WIFI_SPI_ACK 1 -#define WIFI_SPI_ERR 0xFF - -#define TIMEOUT_CHAR 1000 - -//#define MAX_SOCK_NUM 4 /**< Maxmium number of socket */ -#define NO_SOCKET_AVAIL 255 - -#define START_CMD 0xE0 -#define END_CMD 0xEE -#define ERR_CMD 0xEF -#define CMD_POS 1 // Position of Command OpCode on SPI stream -#define PARAM_LEN_POS 2 // Position of Param len on SPI stream - - -enum { - SET_NET_CMD = 0x10, - SET_PASSPHRASE_CMD = 0x11, - SET_KEY_CMD = 0x12, - TEST_CMD = 0x13, - SET_IP_CONFIG_CMD = 0x14, - SET_DNS_CONFIG_CMD = 0x15, - - GET_CONN_STATUS_CMD = 0x20, - GET_IPADDR_CMD = 0x21, - GET_MACADDR_CMD = 0x22, - GET_CURR_SSID_CMD = 0x23, - GET_CURR_BSSID_CMD = 0x24, - GET_CURR_RSSI_CMD = 0x25, - GET_CURR_ENCT_CMD = 0x26, - SCAN_NETWORKS = 0x27, - START_SERVER_TCP_CMD= 0x28, - GET_STATE_TCP_CMD = 0x29, - DATA_SENT_TCP_CMD = 0x2A, - AVAIL_DATA_TCP_CMD = 0x2B, - GET_DATA_TCP_CMD = 0x2C, - START_CLIENT_TCP_CMD= 0x2D, - STOP_CLIENT_TCP_CMD = 0x2E, - GET_CLIENT_STATE_TCP_CMD= 0x2F, - DISCONNECT_CMD = 0x30, - GET_IDX_SSID_CMD = 0x31, - GET_IDX_RSSI_CMD = 0x32, - GET_IDX_ENCT_CMD = 0x33, - REQ_HOST_BY_NAME_CMD= 0x34, - GET_HOST_BY_NAME_CMD= 0x35, - START_SCAN_NETWORKS = 0x36, - GET_FW_VERSION_CMD = 0x37, - GET_TEST_CMD = 0x38, - SEND_DATA_UDP_CMD = 0x39, - GET_REMOTE_DATA_CMD = 0x3A, - - // All command with DATA_FLAG 0x40 send a 16bit Len - - SEND_DATA_TCP_CMD = 0x44, - GET_DATABUF_TCP_CMD = 0x45, - INSERT_DATABUF_CMD = 0x46, -}; - - -enum wl_tcp_state { - CLOSED = 0, - LISTEN = 1, - SYN_SENT = 2, - SYN_RCVD = 3, - ESTABLISHED = 4, - FIN_WAIT_1 = 5, - FIN_WAIT_2 = 6, - CLOSE_WAIT = 7, - CLOSING = 8, - LAST_ACK = 9, - TIME_WAIT = 10 -}; - - -enum numParams{ - PARAM_NUMS_0, - PARAM_NUMS_1, - PARAM_NUMS_2, - PARAM_NUMS_3, - PARAM_NUMS_4, - PARAM_NUMS_5, - MAX_PARAM_NUMS -}; - -#define MAX_PARAMS MAX_PARAM_NUMS-1 -#define PARAM_LEN_SIZE 1 - -typedef struct __attribute__((__packed__)) -{ - uint8_t paramLen; - char* param; -}tParam; - -typedef struct __attribute__((__packed__)) -{ - uint16_t dataLen; - char* data; -}tDataParam; - - -typedef struct __attribute__((__packed__)) -{ - unsigned char cmd; - unsigned char tcmd; - unsigned char nParam; - tParam params[MAX_PARAMS]; -}tSpiMsg; - -typedef struct __attribute__((__packed__)) -{ - unsigned char cmd; - unsigned char tcmd; - unsigned char nParam; - tDataParam params[MAX_PARAMS]; -}tSpiMsgData; - - -typedef struct __attribute__((__packed__)) -{ - unsigned char cmd; - unsigned char tcmd; - //unsigned char totLen; - unsigned char nParam; -}tSpiHdr; - -typedef struct __attribute__((__packed__)) -{ - uint8_t paramLen; - uint32_t param; -}tLongParam; - -typedef struct __attribute__((__packed__)) -{ - uint8_t paramLen; - uint16_t param; -}tIntParam; - -typedef struct __attribute__((__packed__)) -{ - uint8_t paramLen; - uint8_t param; -}tByteParam; - -#endif diff --git a/libraries/WiFi/utility/wl_definitions.h b/libraries/WiFi/utility/wl_definitions.h deleted file mode 100644 index 1ec8e71..0000000 --- a/libraries/WiFi/utility/wl_definitions.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * wl_definitions.h - * - * Created on: Mar 6, 2011 - * Author: dlafauci - */ - -#ifndef WL_DEFINITIONS_H_ -#define WL_DEFINITIONS_H_ - -// Maximum size of a SSID -#define WL_SSID_MAX_LENGTH 32 -// Length of passphrase. Valid lengths are 8-63. -#define WL_WPA_KEY_MAX_LENGTH 63 -// Length of key in bytes. Valid values are 5 and 13. -#define WL_WEP_KEY_MAX_LENGTH 13 -// Size of a MAC-address or BSSID -#define WL_MAC_ADDR_LENGTH 6 -// Size of a MAC-address or BSSID -#define WL_IPV4_LENGTH 4 -// Maximum size of a SSID list -#define WL_NETWORKS_LIST_MAXNUM 10 -// Maxmium number of socket -#define MAX_SOCK_NUM 4 -// Default state value for Wifi state field -#define NA_STATE -1 -//Maximum number of attempts to establish wifi connection -#define WL_MAX_ATTEMPT_CONNECTION 10 - -typedef enum { - WL_NO_SHIELD = 255, - WL_IDLE_STATUS = 0, - WL_NO_SSID_AVAIL, - WL_SCAN_COMPLETED, - WL_CONNECTED, - WL_CONNECT_FAILED, - WL_CONNECTION_LOST, - WL_DISCONNECTED -} wl_status_t; - -/* Encryption modes */ -enum wl_enc_type { /* Values map to 802.11 encryption suites... */ - ENC_TYPE_WEP = 5, - ENC_TYPE_TKIP = 2, - ENC_TYPE_CCMP = 4, - /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ - ENC_TYPE_NONE = 7, - ENC_TYPE_AUTO = 8 -}; - - -#endif /* WL_DEFINITIONS_H_ */ diff --git a/libraries/WiFi/utility/wl_types.h b/libraries/WiFi/utility/wl_types.h deleted file mode 100644 index 82b309d..0000000 --- a/libraries/WiFi/utility/wl_types.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * wl_types.h - * - * Created on: Jul 30, 2010 - * Author: dlafauci - */ - - -#ifndef _WL_TYPES_H_ -#define _WL_TYPES_H_ - -#include - -typedef enum { - WL_FAILURE = -1, - WL_SUCCESS = 1, -} wl_error_code_t; - -/* Authentication modes */ -enum wl_auth_mode { - AUTH_MODE_INVALID, - AUTH_MODE_AUTO, - AUTH_MODE_OPEN_SYSTEM, - AUTH_MODE_SHARED_KEY, - AUTH_MODE_WPA, - AUTH_MODE_WPA2, - AUTH_MODE_WPA_PSK, - AUTH_MODE_WPA2_PSK -}; - -#endif //_WL_TYPES_H_ -- cgit v1.2.3-18-g5258