From 88e858f6e39525cfea264f53e14de9a85010f902 Mon Sep 17 00:00:00 2001 From: amcewen Date: Mon, 10 Jan 2011 14:54:29 +0000 Subject: [PATCH 01/29] Fix for issue 439. UDP API changed to derive from Stream. The old sendPacket and readPacket calls have been removed, and replaced with Stream-derived alternatives which provide more commonality with other communications classes and to allow both buffered and full-packet-at-a-time uses. Also includes the introduction of an IPAddress class to make passing them around easier (and require fewer pointers to be exposed) --- libraries/Ethernet/IPAddress.cpp | 39 ++++ libraries/Ethernet/IPAddress.h | 55 ++++++ libraries/Ethernet/Udp.cpp | 175 +++++++++--------- libraries/Ethernet/Udp.h | 53 ++++-- .../UDPSendReceiveString.pde | 31 ++-- .../examples/UdpNtpClient/UdpNtpClient.pde | 15 +- libraries/Ethernet/keywords.txt | 7 + libraries/Ethernet/utility/socket.cpp | 55 ++++++ libraries/Ethernet/utility/socket.h | 21 +++ libraries/Ethernet/utility/w5100.cpp | 12 +- libraries/Ethernet/utility/w5100.h | 16 +- 11 files changed, 359 insertions(+), 120 deletions(-) create mode 100644 libraries/Ethernet/IPAddress.cpp create mode 100644 libraries/Ethernet/IPAddress.h diff --git a/libraries/Ethernet/IPAddress.cpp b/libraries/Ethernet/IPAddress.cpp new file mode 100644 index 000000000..389329de0 --- /dev/null +++ b/libraries/Ethernet/IPAddress.cpp @@ -0,0 +1,39 @@ + +#include +#include + +IPAddress::IPAddress() +{ + memset(_address, 0, sizeof(_address)); +} + +IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) +{ + _address[0] = first_octet; + _address[1] = second_octet; + _address[2] = third_octet; + _address[3] = fourth_octet; +} + +IPAddress::IPAddress(uint32_t address) +{ + memcpy(_address, &address, sizeof(_address)); +} + +IPAddress::IPAddress(const uint8_t *address) +{ + memcpy(_address, address, sizeof(_address)); +} + +IPAddress& IPAddress::operator=(const uint8_t *address) +{ + memcpy(_address, address, sizeof(_address)); + return *this; +} + +IPAddress& IPAddress::operator=(uint32_t address) +{ + memcpy(_address, (const uint8_t *)&address, sizeof(_address)); + return *this; +} + diff --git a/libraries/Ethernet/IPAddress.h b/libraries/Ethernet/IPAddress.h new file mode 100644 index 000000000..586385320 --- /dev/null +++ b/libraries/Ethernet/IPAddress.h @@ -0,0 +1,55 @@ +/* + * + * MIT License: + * Copyright (c) 2011 Adrian McEwen + * 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. + * + * adrianm@mcqn.com 1/1/2011 + */ + +#ifndef IPAddress_h +#define IPAddress_h + +// A class to make it easier to handle and pass around IP addresses + +class IPAddress { +private: + uint8_t _address[4]; // IPv4 address + +public: + // Constructors + IPAddress(); + IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); + IPAddress(uint32_t address); + IPAddress(const uint8_t *address); + + // Overloaded cast operator to allow IPAddress objects to be used where a pointer + // to a four-byte uint8_t array is expected + operator uint8_t*() { return _address; }; + + // Overloaded index operator to allow getting and setting individual octets of the address + uint8_t operator[](int index) const { return _address[index]; }; + uint8_t& operator[](int index) { return _address[index]; }; + + // Overloaded copy operators to allow initialisation of IPAddress objects from other types + IPAddress& operator=(const uint8_t *address); + IPAddress& operator=(uint32_t address); +}; + +#endif diff --git a/libraries/Ethernet/Udp.cpp b/libraries/Ethernet/Udp.cpp index 07c454df2..6ad8aca7e 100644 --- a/libraries/Ethernet/Udp.cpp +++ b/libraries/Ethernet/Udp.cpp @@ -56,97 +56,12 @@ uint8_t UDP::begin(uint16_t port) { return 1; } -/* Send packet contained in buf of length len to peer at specified ip, and port */ -/* Use this function to transmit binary data that might contain 0x00 bytes*/ -/* This function returns sent data size for success else -1. */ -uint16_t UDP::sendPacket(uint8_t * buf, uint16_t len, uint8_t * ip, uint16_t port){ - return sendto(_sock,(const uint8_t *)buf,len,ip,port); -} - -/* Send zero-terminated string str as packet to peer at specified ip, and port */ -/* This function returns sent data size for success else -1. */ -uint16_t UDP::sendPacket(const char str[], uint8_t * ip, uint16_t port){ - // compute strlen - const char *s; - for(s = str; *s; ++s); - uint16_t len = (s-str); - // send packet - return sendto(_sock,(const uint8_t *)str,len,ip,port); -} /* Is data available in rx buffer? Returns 0 if no, number of available bytes if yes. * returned value includes 8 byte UDP header!*/ int UDP::available() { return W5100.getRXReceivedSize(_sock); } - -/* Read a received packet into buffer buf (which is of maximum length len); */ -/* store calling ip and port as well. Call available() to make sure data is ready first. */ -/* NOTE: I don't believe len is ever checked in implementation of recvfrom(),*/ -/* so it's easy to overflow buffer. so we check and truncate. */ -/* returns number of bytes read, or negative number of bytes we would have needed if we truncated */ -int UDP::readPacket(uint8_t * buf, uint16_t bufLen, uint8_t *ip, uint16_t *port) { - int packetLen = available()-8; //skip UDP header; - if(packetLen < 0 ) return 0; // no real data here - if(packetLen > (int)bufLen) { - //packet is too large - truncate - //HACK - hand-parse the UDP packet using TCP recv method - uint8_t tmpBuf[8]; - int i; - //read 8 header bytes and get IP and port from it - recv(_sock,tmpBuf,8); - ip[0] = tmpBuf[0]; - ip[1] = tmpBuf[1]; - ip[2] = tmpBuf[2]; - ip[3] = tmpBuf[3]; - *port = tmpBuf[4]; - *port = (*port << 8) + tmpBuf[5]; - - //now copy first (bufLen) bytes into buf - for(i=0;i<(int)bufLen;i++) { - recv(_sock,tmpBuf,1); - buf[i]=tmpBuf[0]; - } - - //and just read the rest byte by byte and throw it away - while(available()) { - recv(_sock,tmpBuf,1); - } - - return (-1*packetLen); - - //ALTERNATIVE: requires stdlib - takes a bunch of space - /*//create new buffer and read everything into it - uint8_t * tmpBuf = (uint8_t *)malloc(packetLen); - recvfrom(_sock,tmpBuf,packetLen,ip,port); - if(!tmpBuf) return 0; //couldn't allocate - // copy first bufLen bytes - for(unsigned int i=0; i 0) + { + _remoteIP = tmpBuf; + _remotePort = tmpBuf[4]; + _remotePort = (_remotePort << 8) + tmpBuf[5]; + // When we get here, any remaining bytes are the data + ret = available(); + } + return ret; +} + +int UDP::read() +{ + uint8_t byte; + if (recv(_sock, &byte, 1) > 0) + { + // We read things without any problems + return byte; + } + // If we get here, there's no data available + return -1; +} + +int UDP::read(unsigned char* buffer, size_t len) +{ + /* In the readPacket that copes with truncating packets, the buffer was + filled with this code. Not sure why it loops round reading out a byte + at a time. + int i; + for(i=0;i<(int)bufLen;i++) { + recv(_sock,tmpBuf,1); + buf[i]=tmpBuf[0]; + } + */ + return recv(_sock, buffer, len); +} + +int UDP::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 UDP::flush() +{ + while (available()) + { + read(); + } +} + diff --git a/libraries/Ethernet/Udp.h b/libraries/Ethernet/Udp.h index c801ee277..3970a9662 100644 --- a/libraries/Ethernet/Udp.h +++ b/libraries/Ethernet/Udp.h @@ -37,28 +37,57 @@ #ifndef udp_h #define udp_h +#include +#include + #define UDP_TX_PACKET_MAX_SIZE 24 -class UDP { +class UDP : public Stream { 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 public: - UDP(); + UDP(); // Constructor uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - int available(); // has data been received? + void stop(); // Finish with the UDP socket - // C-style buffer-oriented functions - uint16_t sendPacket(uint8_t *, uint16_t, uint8_t *, uint16_t); //send a packet to specified peer - uint16_t sendPacket(const char[], uint8_t *, uint16_t); //send a string as a packet to specified peer - int readPacket(uint8_t *, uint16_t); // read a received packet - int readPacket(uint8_t *, uint16_t, uint8_t *, uint16_t *); // read a received packet, also return sender's ip and port - // readPacket that fills a character string buffer - int readPacket(char *, uint16_t, uint8_t *, uint16_t &); + // 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 + int beginPacket(IPAddress ip, uint16_t port); + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + int endPacket(); + // Write a single byte into the packet + virtual void write(uint8_t); + // Write a string of characters into the packet + virtual void write(const char *str); + // Write size bytes from buffer into the packet + virtual void write(const uint8_t *buffer, size_t size); - // Finish with the UDP socket - void stop(); + // Start processing the next available incoming packet + // Returns the size of the packet in bytes, or 0 if no packets are available + 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); + // 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 + IPAddress remoteIP() { return _remoteIP; }; + // Return the port of the host who sent the current incoming packet + uint16_t remotePort() { return _remotePort; }; }; #endif diff --git a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde index f27290f54..e23410139 100644 --- a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde +++ b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde @@ -22,15 +22,10 @@ // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -byte ip[] = { - 192,168,1,177 }; +IPAddress ip(192, 168, 1, 177); unsigned int localPort = 8888; // local port to listen on -// the next two variables are set when a packet is received -byte remoteIp[4]; // holds received packet's originating IP -unsigned int remotePort; // holds received packet's originating port - // 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 @@ -48,19 +43,33 @@ void setup() { void loop() { // if there's data available, read a packet - int packetSize = Udp.available(); // note that this includes the UDP header + int packetSize = Udp.parsePacket(); if(packetSize) { - packetSize = packetSize - 8; // subtract the 8 byte header 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 and get the senders IP addr and port number - Udp.readPacket(packetBuffer,UDP_TX_PACKET_MAX_SIZE, remoteIp, remotePort); + // read the packet into packetBufffer + Udp.read((byte*)packetBuffer,UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer); - Udp.sendPacket( ReplyBuffer, remoteIp, remotePort); + // 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); } diff --git a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde index 22bc754c5..cfb5a2bc1 100644 --- a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde +++ b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde @@ -24,14 +24,12 @@ // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -byte ip[] = { - 192,168,1,177 }; +IPAddress ip(192, 168, 1, 177); unsigned int localPort = 8888; // local port to listen for UDP packets -byte timeServer[] = { - 192, 43, 244, 18}; // time.nist.gov NTP server +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 @@ -55,8 +53,9 @@ void loop() // wait to see if a reply is available delay(1000); - if ( Udp.available() ) { - Udp.readPacket(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer + 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: @@ -118,7 +117,9 @@ unsigned long sendNTPpacket(byte *address) // all NTP fields have been given values, now // you can send a packet requesting a timestamp: - Udp.sendPacket( packetBuffer,NTP_PACKET_SIZE, address, 123); //NTP requests are to port 123 + Udp.beginPacket(address, 123); //NTP requests are to port 123 + Udp.write(packetBuffer,NTP_PACKET_SIZE); + Udp.endPacket(); } diff --git a/libraries/Ethernet/keywords.txt b/libraries/Ethernet/keywords.txt index ebc579363..7fdcedf09 100644 --- a/libraries/Ethernet/keywords.txt +++ b/libraries/Ethernet/keywords.txt @@ -9,6 +9,7 @@ Ethernet KEYWORD1 Client KEYWORD1 Server KEYWORD1 +IPAddress KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) @@ -19,10 +20,16 @@ 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/utility/socket.cpp b/libraries/Ethernet/utility/socket.cpp index cad54a5e3..487584511 100644 --- a/libraries/Ethernet/utility/socket.cpp +++ b/libraries/Ethernet/utility/socket.cpp @@ -344,3 +344,58 @@ uint16_t igmpsend(SOCKET s, const uint8_t * buf, uint16_t len) 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 index 48e2d877b..37ea93f3d 100755 --- a/libraries/Ethernet/utility/socket.h +++ b/libraries/Ethernet/utility/socket.h @@ -16,5 +16,26 @@ extern uint16_t recvfrom(SOCKET s, uint8_t * buf, uint16_t len, uint8_t * addr, 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 index aaf3071f7..aafabaeec 100644 --- a/libraries/Ethernet/utility/w5100.cpp +++ b/libraries/Ethernet/utility/w5100.cpp @@ -65,10 +65,16 @@ uint16_t W5100Class::getRXReceivedSize(SOCKET s) } -void W5100Class::send_data_processing(SOCKET s, uint8_t *data, uint16_t len) +void W5100Class::send_data_processing(SOCKET s, const uint8_t *data, uint16_t len) +{ + // This is same as having no offset in a call to send_data_processing_offset + send_data_processing_offset(s, 0, data, len); +} + +void W5100Class::send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len) { uint16_t ptr = readSnTX_WR(s); - + ptr += data_offset; uint16_t offset = ptr & SMASK; uint16_t dstAddr = offset + SBASE[s]; @@ -132,7 +138,7 @@ uint8_t W5100Class::write(uint16_t _addr, uint8_t _data) return 1; } -uint16_t W5100Class::write(uint16_t _addr, uint8_t *_buf, uint16_t _len) +uint16_t W5100Class::write(uint16_t _addr, const uint8_t *_buf, uint16_t _len) { for (int i=0; i<_len; i++) { diff --git a/libraries/Ethernet/utility/w5100.h b/libraries/Ethernet/utility/w5100.h index 118e5d80d..9872c7ccb 100755 --- a/libraries/Ethernet/utility/w5100.h +++ b/libraries/Ethernet/utility/w5100.h @@ -146,7 +146,19 @@ public: * 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, uint8_t *data, uint16_t len); + 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. @@ -182,7 +194,7 @@ public: // --------------- private: static uint8_t write(uint16_t _addr, uint8_t _data); - static uint16_t write(uint16_t addr, uint8_t *buf, uint16_t len); + 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); From 5caad5bdb4492c23f553ec94bd100ff78e87604f Mon Sep 17 00:00:00 2001 From: amcewen Date: Thu, 13 Jan 2011 17:55:08 +0000 Subject: [PATCH 02/29] Added a method to read data into a char buffer so that character-based (rather than byte-based) operations don't require a cast. As requested by Tom Igoe. Part of the fix to issue 439. --- libraries/Ethernet/Udp.h | 3 +++ .../examples/UDPSendReceiveString/UDPSendReceiveString.pde | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/libraries/Ethernet/Udp.h b/libraries/Ethernet/Udp.h index 3970a9662..8cd3b065a 100644 --- a/libraries/Ethernet/Udp.h +++ b/libraries/Ethernet/Udp.h @@ -80,6 +80,9 @@ public: // 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 diff --git a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde index e23410139..081d69114 100644 --- a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde +++ b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde @@ -62,7 +62,7 @@ void loop() { Serial.println(Udp.remotePort()); // read the packet into packetBufffer - Udp.read((byte*)packetBuffer,UDP_TX_PACKET_MAX_SIZE); + Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer); From a42dc0b455513b9cf3127b9720cc66d0db274b03 Mon Sep 17 00:00:00 2001 From: amcewen Date: Sun, 16 Jan 2011 20:11:50 +0000 Subject: [PATCH 03/29] Fix for issue 62, adding DHCP support. New begin() method added to EthernetClass which takes just a MAC address and gets the rest of its configuration information via DHCP. Examples updated to use the IPAddress class and some have been changed to get their config via DHCP. --- libraries/Ethernet/Client.cpp | 4 +- libraries/Ethernet/Client.h | 6 +- libraries/Ethernet/Dhcp.cpp | 341 ++++++++++++++++++ libraries/Ethernet/Dhcp.h | 158 ++++++++ libraries/Ethernet/Ethernet.cpp | 77 +++- libraries/Ethernet/Ethernet.h | 18 +- libraries/Ethernet/IPAddress.cpp | 5 + libraries/Ethernet/IPAddress.h | 15 +- libraries/Ethernet/Udp.cpp | 2 +- .../BarometricPressureWebServer.pde | 9 +- .../examples/ChatServer/ChatServer.pde | 8 +- .../examples/PachubeClient/PachubeClient.pde | 21 +- .../PachubeClientString.pde | 12 +- .../examples/TelnetClient/TelnetClient.pde | 6 +- .../examples/UdpNtpClient/UdpNtpClient.pde | 21 +- .../Ethernet/examples/WebClient/WebClient.pde | 16 +- .../Ethernet/examples/WebServer/WebServer.pde | 4 +- libraries/Ethernet/util.h | 13 + 18 files changed, 662 insertions(+), 74 deletions(-) create mode 100755 libraries/Ethernet/Dhcp.cpp create mode 100755 libraries/Ethernet/Dhcp.h create mode 100644 libraries/Ethernet/util.h diff --git a/libraries/Ethernet/Client.cpp b/libraries/Ethernet/Client.cpp index 96d5c7eed..7ae55d08d 100644 --- a/libraries/Ethernet/Client.cpp +++ b/libraries/Ethernet/Client.cpp @@ -16,7 +16,7 @@ uint16_t Client::_srcport = 1024; Client::Client(uint8_t sock) : _sock(sock) { } -Client::Client(uint8_t *ip, uint16_t port) : _ip(ip), _port(port), _sock(MAX_SOCK_NUM) { +Client::Client(IPAddress& ip, uint16_t port) : _ip(ip), _port(port), _sock(MAX_SOCK_NUM) { } uint8_t Client::connect() { @@ -38,7 +38,7 @@ uint8_t Client::connect() { if (_srcport == 0) _srcport = 1024; socket(_sock, SnMR::TCP, _srcport, 0); - if (!::connect(_sock, _ip, _port)) { + if (!::connect(_sock, _ip.raw_address(), _port)) { _sock = MAX_SOCK_NUM; return 0; } diff --git a/libraries/Ethernet/Client.h b/libraries/Ethernet/Client.h index 8725f158a..e92e90e33 100644 --- a/libraries/Ethernet/Client.h +++ b/libraries/Ethernet/Client.h @@ -7,8 +7,8 @@ class Client : public Stream { public: Client(); - Client(uint8_t); - Client(uint8_t *, uint16_t); + Client(uint8_t sock); + Client(IPAddress& ip, uint16_t port); uint8_t status(); uint8_t connect(); @@ -31,7 +31,7 @@ public: private: static uint16_t _srcport; uint8_t _sock; - uint8_t *_ip; + IPAddress _ip; uint16_t _port; }; diff --git a/libraries/Ethernet/Dhcp.cpp b/libraries/Ethernet/Dhcp.cpp new file mode 100755 index 000000000..8264b435b --- /dev/null +++ b/libraries/Ethernet/Dhcp.cpp @@ -0,0 +1,341 @@ +// DHCP Library v0.3 - April 25, 2009 +// Author: Jordan Terrell - blog.jordanterrell.com + +#include "w5100.h" + +#include +#include +#include "Dhcp.h" +#include "wiring.h" +#include "util.h" + +int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) +{ + uint8_t dhcp_state = STATE_DHCP_START; + uint8_t messageType = 0; + + // zero out _dhcpMacAddr, _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp + memset(_dhcpMacAddr, 0, 26); + + memcpy((void*)_dhcpMacAddr, (void*)mac, 6); + + // Pick an initial transaction ID + _dhcpTransactionId = random(1UL, 2000UL); + _dhcpInitialTransactionId = _dhcpTransactionId; + + 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_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; + } + 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) + 3; // length of hostname + last 3 bytes of mac address + strcpy((char*)&(buffer[18]), HOST_NAME); + + buffer[24] = _dhcpMacAddr[3]; + buffer[25] = _dhcpMacAddr[4]; + buffer[26] = _dhcpMacAddr[5]; + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 27); + + 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 - 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); + break; + + case dns : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read(_dhcpDnsServerIp, 4); + 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 dhcpIPaddrLeaseTime : + 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; +} + +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); +} + diff --git a/libraries/Ethernet/Dhcp.h b/libraries/Ethernet/Dhcp.h new file mode 100755 index 000000000..c0034940c --- /dev/null +++ b/libraries/Ethernet/Dhcp.h @@ -0,0 +1,158 @@ +// DHCP Library v0.3 - April 25, 2009 +// Author: Jordan Terrell - blog.jordanterrell.com + +#ifndef Dhcp_h +#define Dhcp_h + +#include "Udp.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" + +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]; + UDP _dhcpUdpSocket; + + void presend_DHCP(); + void send_DHCP_MESSAGE(uint8_t, uint16_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); +}; + +#endif diff --git a/libraries/Ethernet/Ethernet.cpp b/libraries/Ethernet/Ethernet.cpp index 91cbacd39..937f5b4f9 100644 --- a/libraries/Ethernet/Ethernet.cpp +++ b/libraries/Ethernet/Ethernet.cpp @@ -1,5 +1,6 @@ #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] = { @@ -7,30 +8,78 @@ uint8_t EthernetClass::_state[MAX_SOCK_NUM] = { uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = { 0, 0, 0, 0 }; -void EthernetClass::begin(uint8_t *mac, uint8_t *ip) +int EthernetClass::begin(uint8_t *mac_address) { - uint8_t gateway[4]; - gateway[0] = ip[0]; - gateway[1] = ip[1]; - gateway[2] = ip[2]; + DhcpClass 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 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, ip, gateway); + begin(mac_address, local_ip, gateway); } -void EthernetClass::begin(uint8_t *mac, uint8_t *ip, uint8_t *gateway) +void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress gateway) { - uint8_t subnet[] = { - 255, 255, 255, 0 }; - begin(mac, ip, gateway, subnet); + IPAddress subnet(255, 255, 255, 0); + begin(mac_address, local_ip, gateway, subnet); } -void EthernetClass::begin(uint8_t *mac, uint8_t *ip, uint8_t *gateway, uint8_t *subnet) +void EthernetClass::begin(uint8_t *mac, IPAddress local_ip, IPAddress gateway, IPAddress subnet) { W5100.init(); W5100.setMACAddress(mac); - W5100.setIPAddress(ip); - W5100.setGatewayIp(gateway); - W5100.setSubnetMask(subnet); + W5100.setIPAddress(local_ip._address); + W5100.setGatewayIp(gateway._address); + W5100.setSubnetMask(subnet._address); +} + +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 index a91f1aa17..fdf0b7f39 100644 --- a/libraries/Ethernet/Ethernet.h +++ b/libraries/Ethernet/Ethernet.h @@ -3,6 +3,7 @@ #include //#include "w5100.h" +#include "IPAddress.h" #include "Client.h" #include "Server.h" @@ -10,12 +11,23 @@ class EthernetClass { private: + IPAddress _dnsServerAddress; public: static uint8_t _state[MAX_SOCK_NUM]; static uint16_t _server_port[MAX_SOCK_NUM]; - void begin(uint8_t *, uint8_t *); - void begin(uint8_t *, uint8_t *, uint8_t *); - void begin(uint8_t *, uint8_t *, uint8_t *, uint8_t *); + // 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 gateway); + void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress gateway, IPAddress subnet); + + IPAddress localIP(); + IPAddress subnetMask(); + IPAddress gatewayIP(); + IPAddress dnsServerIP(); + friend class Client; friend class Server; }; diff --git a/libraries/Ethernet/IPAddress.cpp b/libraries/Ethernet/IPAddress.cpp index 389329de0..408d518a0 100644 --- a/libraries/Ethernet/IPAddress.cpp +++ b/libraries/Ethernet/IPAddress.cpp @@ -37,3 +37,8 @@ IPAddress& IPAddress::operator=(uint32_t address) return *this; } +bool IPAddress::operator==(const uint8_t* addr) +{ + return memcmp(addr, _address, sizeof(_address)) == 0; +} + diff --git a/libraries/Ethernet/IPAddress.h b/libraries/Ethernet/IPAddress.h index 586385320..1d19bbd22 100644 --- a/libraries/Ethernet/IPAddress.h +++ b/libraries/Ethernet/IPAddress.h @@ -31,6 +31,11 @@ class IPAddress { private: uint8_t _address[4]; // IPv4 address + // Access the raw byte array containing the address. Because this returns a pointer + // to the internal structure rather than a copy of the address this function should only + // be used when you know that the usage of the returned uint8_t* will be transient and not + // stored. + uint8_t* raw_address() { return _address; }; public: // Constructors @@ -41,7 +46,9 @@ public: // Overloaded cast operator to allow IPAddress objects to be used where a pointer // to a four-byte uint8_t array is expected - operator uint8_t*() { return _address; }; + operator uint32_t() { return *((uint32_t*)_address); }; + bool operator==(const IPAddress& addr) { return (*((uint32_t*)_address)) == (*((uint32_t*)addr._address)); }; + bool operator==(const uint8_t* addr); // Overloaded index operator to allow getting and setting individual octets of the address uint8_t operator[](int index) const { return _address[index]; }; @@ -50,6 +57,12 @@ public: // Overloaded copy operators to allow initialisation of IPAddress objects from other types IPAddress& operator=(const uint8_t *address); IPAddress& operator=(uint32_t address); + + friend class EthernetClass; + friend class UDP; + friend class Client; + friend class Server; + friend class DhcpClass; }; #endif diff --git a/libraries/Ethernet/Udp.cpp b/libraries/Ethernet/Udp.cpp index 6ad8aca7e..a8c98c3f4 100644 --- a/libraries/Ethernet/Udp.cpp +++ b/libraries/Ethernet/Udp.cpp @@ -77,7 +77,7 @@ void UDP::stop() int UDP::beginPacket(IPAddress ip, uint16_t port) { _offset = 0; - return startUDP(_sock, ip, port); + return startUDP(_sock, ip.raw_address(), port); } int UDP::endPacket() diff --git a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde index a58433fed..3f43d96db 100644 --- a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde +++ b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde @@ -31,12 +31,9 @@ byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // assign an IP address for the controller: -byte ip[] = { - 192,168,1,20 }; -byte gateway[] = { - 192,168,1,1}; -byte subnet[] = { - 255, 255, 255, 0 }; +IPAddress ip(192,168,1,20); +IPAddress gateway(192,168,1,1); +IPAddress subnet(255, 255, 255, 0); // Initialize the Ethernet server library diff --git a/libraries/Ethernet/examples/ChatServer/ChatServer.pde b/libraries/Ethernet/examples/ChatServer/ChatServer.pde index 50ae01408..8267a5dd4 100644 --- a/libraries/Ethernet/examples/ChatServer/ChatServer.pde +++ b/libraries/Ethernet/examples/ChatServer/ChatServer.pde @@ -24,9 +24,9 @@ // The IP address will be dependent on your local network. // gateway and subnet are optional: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -byte ip[] = { 192,168,1, 177 }; -byte gateway[] = { 192,168,1, 1 }; -byte subnet[] = { 255, 255, 0, 0 }; +IPAddress ip(192,168,1, 177); +IPAddress gateway(192,168,1, 1); +IPAddress subnet(255, 255, 0, 0); // telnet defaults to port 23 Server server(23); @@ -60,4 +60,4 @@ void loop() { // echo the bytes to the server as well: Serial.print(thisChar); } -} \ No newline at end of file +} diff --git a/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde b/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde index fe94541e1..687fa437e 100644 --- a/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde +++ b/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde @@ -23,20 +23,13 @@ #include // 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}; -// assign an IP address for the controller: -byte ip[] = { - 192,169,1,20 }; -byte gateway[] = { - 192,168,1,1}; -byte subnet[] = { - 255, 255, 255, 0 }; // The address of the server you want to connect to (pachube.com): -byte server[] = { - 209,40,205,190 }; +IPAddress server(209,40,205,190); // initialize the library instance: Client client(server, 80); @@ -46,9 +39,15 @@ boolean lastConnected = false; // state of the connection last time through const int postingInterval = 10000; //delay between updates to Pachube.com void setup() { - // start the ethernet connection and serial port: - Ethernet.begin(mac, ip); + // start serial port: Serial.begin(9600); + // start the Ethernet connection: + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // no point in carrying on, so do nothing forevermore: + for(;;) + ; + } // give the ethernet module time to boot up: delay(1000); } diff --git a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde index 225823ac1..0db6e219a 100644 --- a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde +++ b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde @@ -29,16 +29,12 @@ byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // assign an IP address for the controller: -byte ip[] = { - 192,169,1,20 }; -byte gateway[] = { - 192,168,1,1}; -byte subnet[] = { - 255, 255, 255, 0 }; +IPAddress ip(192,169,1,20); +IPAddress gateway(192,168,1,1); +IPAddress subnet(255, 255, 255, 0); // The address of the server you want to connect to (pachube.com): -byte server[] = { - 209,40,205,190 }; +IPAddress server(209,40,205,190); // initialize the library instance: Client client(server, 80); diff --git a/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde b/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde index aca1fa9ad..95756d076 100644 --- a/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde +++ b/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde @@ -24,12 +24,10 @@ // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -byte ip[] = { - 192,168,1,177 }; +IPAddress ip(192,168,1,177); // Enter the IP address of the server you're connecting to: -byte server[] = { - 1,1,1,1 }; +IPAddress server(1,1,1,1); // Initialize the Ethernet client library // with the IP address and port of the server diff --git a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde index cfb5a2bc1..7c2d3ea9e 100644 --- a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde +++ b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde @@ -20,13 +20,11 @@ #include #include -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network: +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; -IPAddress ip(192, 168, 1, 177); - unsigned int localPort = 8888; // local port to listen for UDP packets IPAddress timeServer(192, 43, 244, 18); // time.nist.gov NTP server @@ -40,11 +38,16 @@ UDP Udp; void setup() { - // start Ethernet and UDP - Ethernet.begin(mac,ip); - Udp.begin(localPort); - Serial.begin(9600); + + // 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() @@ -99,7 +102,7 @@ void loop() } // send an NTP request to the time server at the given address -unsigned long sendNTPpacket(byte *address) +unsigned long sendNTPpacket(IPAddress& address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); diff --git a/libraries/Ethernet/examples/WebClient/WebClient.pde b/libraries/Ethernet/examples/WebClient/WebClient.pde index a2d350311..74d34e0ce 100644 --- a/libraries/Ethernet/examples/WebClient/WebClient.pde +++ b/libraries/Ethernet/examples/WebClient/WebClient.pde @@ -15,11 +15,10 @@ #include #include -// Enter a MAC address and IP address for your controller below. -// The IP address will be dependent on your local network: +// 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 }; -byte ip[] = { 192,168,1,177 }; -byte server[] = { 173,194,33,104 }; // Google +IPAddress server(173,194,33,104); // Google // Initialize the Ethernet client library // with the IP address and port of the server @@ -27,10 +26,15 @@ byte server[] = { 173,194,33,104 }; // Google Client client(server, 80); void setup() { - // start the Ethernet connection: - Ethernet.begin(mac, ip); // start the serial library: Serial.begin(9600); + // start the Ethernet connection: + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // no point in carrying on, so do nothing forevermore: + for(;;) + ; + } // give the Ethernet shield a second to initialize: delay(1000); Serial.println("connecting..."); diff --git a/libraries/Ethernet/examples/WebServer/WebServer.pde b/libraries/Ethernet/examples/WebServer/WebServer.pde index 77bcb204e..c69a56a40 100644 --- a/libraries/Ethernet/examples/WebServer/WebServer.pde +++ b/libraries/Ethernet/examples/WebServer/WebServer.pde @@ -21,7 +21,7 @@ // 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 }; -byte ip[] = { 192,168,1, 177 }; +IPAddress ip(192,168,1, 177); // Initialize the Ethernet server library // with the IP address and port you want to use @@ -79,4 +79,4 @@ void loop() // close the connection: client.stop(); } -} \ No newline at end of file +} diff --git a/libraries/Ethernet/util.h b/libraries/Ethernet/util.h new file mode 100644 index 000000000..220011b8f --- /dev/null +++ b/libraries/Ethernet/util.h @@ -0,0 +1,13 @@ +#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 From a310cb8e4dad410af717e3fe9502fc3f98127892 Mon Sep 17 00:00:00 2001 From: amcewen Date: Tue, 25 Jan 2011 16:29:38 +0000 Subject: [PATCH 04/29] Proposed fix for issue 243, adding DNS to the Ethernet library. Uses a slightly modified version of the agreed API as the host/port parameters have been moved from the Client constructor to the Client::connect methods. This means it's possible for errors to be returned if the DNS lookup fails and also reduces the RAM footprint of the Client class as it no longer needs to store the host/port for later use in Client::connect. --- libraries/Ethernet/Client.cpp | 22 +- libraries/Ethernet/Client.h | 6 +- libraries/Ethernet/Dns.cpp | 423 ++++++++++++++++++ libraries/Ethernet/Dns.h | 41 ++ libraries/Ethernet/IPAddress.h | 4 + .../examples/PachubeClient/PachubeClient.pde | 7 +- .../PachubeClientString.pde | 18 +- .../examples/TelnetClient/TelnetClient.pde | 4 +- .../Ethernet/examples/WebClient/WebClient.pde | 4 +- 9 files changed, 503 insertions(+), 26 deletions(-) create mode 100644 libraries/Ethernet/Dns.cpp create mode 100644 libraries/Ethernet/Dns.h diff --git a/libraries/Ethernet/Client.cpp b/libraries/Ethernet/Client.cpp index 7ae55d08d..8a525ca7e 100644 --- a/libraries/Ethernet/Client.cpp +++ b/libraries/Ethernet/Client.cpp @@ -10,16 +10,32 @@ extern "C" { #include "Ethernet.h" #include "Client.h" #include "Server.h" +#include "Dns.h" uint16_t Client::_srcport = 1024; +Client::Client() : _sock(MAX_SOCK_NUM) { +} + Client::Client(uint8_t sock) : _sock(sock) { } -Client::Client(IPAddress& ip, uint16_t port) : _ip(ip), _port(port), _sock(MAX_SOCK_NUM) { +int Client::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; + } } -uint8_t Client::connect() { +int Client::connect(IPAddress ip, uint16_t port) { if (_sock != MAX_SOCK_NUM) return 0; @@ -38,7 +54,7 @@ uint8_t Client::connect() { if (_srcport == 0) _srcport = 1024; socket(_sock, SnMR::TCP, _srcport, 0); - if (!::connect(_sock, _ip.raw_address(), _port)) { + if (!::connect(_sock, ip.raw_address(), port)) { _sock = MAX_SOCK_NUM; return 0; } diff --git a/libraries/Ethernet/Client.h b/libraries/Ethernet/Client.h index e92e90e33..23a8f1860 100644 --- a/libraries/Ethernet/Client.h +++ b/libraries/Ethernet/Client.h @@ -8,10 +8,10 @@ class Client : public Stream { public: Client(); Client(uint8_t sock); - Client(IPAddress& ip, uint16_t port); uint8_t status(); - uint8_t connect(); + int connect(IPAddress ip, uint16_t port); + int connect(const char *host, uint16_t port); virtual void write(uint8_t); virtual void write(const char *str); virtual void write(const uint8_t *buf, size_t size); @@ -31,8 +31,6 @@ public: private: static uint16_t _srcport; uint8_t _sock; - IPAddress _ip; - uint16_t _port; }; #endif diff --git a/libraries/Ethernet/Dns.cpp b/libraries/Ethernet/Dns.cpp new file mode 100644 index 000000000..3a31e35a4 --- /dev/null +++ b/libraries/Ethernet/Dns.cpp @@ -0,0 +1,423 @@ +// Arduino DNS client for WizNet5100-based Ethernet shield +// (c) Copyright 2009-2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#include "w5100.h" +#include "Udp.h" +#include "util.h" + +#include "Dns.h" +#include +//#include +#include "wiring.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(int 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 != 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 (int 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 (int 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 (int 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 new file mode 100644 index 000000000..9582351f2 --- /dev/null +++ b/libraries/Ethernet/Dns.h @@ -0,0 +1,41 @@ +// Arduino DNS client for WizNet5100-based Ethernet shield +// (c) Copyright 2009-2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#ifndef DNSClient_h +#define DNSClient_h + +#include + +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(int aTimeout, IPAddress& aAddress); + + IPAddress iDNSServer; + uint16_t iRequestId; + UDP iUdp; +}; + +#endif diff --git a/libraries/Ethernet/IPAddress.h b/libraries/Ethernet/IPAddress.h index 1d19bbd22..487e420bd 100644 --- a/libraries/Ethernet/IPAddress.h +++ b/libraries/Ethernet/IPAddress.h @@ -63,6 +63,10 @@ public: friend class Client; friend class Server; friend class DhcpClass; + friend class DNSClient; }; +const IPAddress INADDR_NONE(0,0,0,0); + + #endif diff --git a/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde b/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde index 687fa437e..af9bf1f05 100644 --- a/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde +++ b/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde @@ -28,11 +28,8 @@ byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -// The address of the server you want to connect to (pachube.com): -IPAddress server(209,40,205,190); - // initialize the library instance: -Client client(server, 80); +Client client; 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 @@ -85,7 +82,7 @@ void loop() { // this method makes a HTTP connection to the server: void sendData(int thisData) { // if there's a successful connection: - if (client.connect()) { + if (client.connect("www.pachube.com", 80)) { Serial.println("connecting..."); // send the HTTP PUT request. // fill in your feed address here: diff --git a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde index 0db6e219a..e6dbf09ea 100644 --- a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde +++ b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde @@ -28,16 +28,9 @@ // fill in your address here: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -// assign an IP address for the controller: -IPAddress ip(192,169,1,20); -IPAddress gateway(192,168,1,1); -IPAddress subnet(255, 255, 255, 0); - -// The address of the server you want to connect to (pachube.com): -IPAddress server(209,40,205,190); // initialize the library instance: -Client client(server, 80); +Client client; 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 @@ -45,8 +38,13 @@ const int postingInterval = 10000; //delay between updates to Pachube.com void setup() { // start the ethernet connection and serial port: - Ethernet.begin(mac, ip); Serial.begin(9600); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // no point in carrying on, so do nothing forevermore: + for(;;) + ; + } // give the ethernet module time to boot up: delay(1000); } @@ -92,7 +90,7 @@ void loop() { // this method makes a HTTP connection to the server: void sendData(String thisData) { // if there's a successful connection: - if (client.connect()) { + if (client.connect("www.pachube.com", 80)) { Serial.println("connecting..."); // send the HTTP PUT request. // fill in your feed address here: diff --git a/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde b/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde index 95756d076..7502d218d 100644 --- a/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde +++ b/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde @@ -33,7 +33,7 @@ IPAddress server(1,1,1,1); // 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): -Client client(server, 10002); +Client client; void setup() { // start the Ethernet connection: @@ -45,7 +45,7 @@ void setup() { Serial.println("connecting..."); // if you get a connection, report back via serial: - if (client.connect()) { + if (client.connect(server, 10002)) { Serial.println("connected"); } else { diff --git a/libraries/Ethernet/examples/WebClient/WebClient.pde b/libraries/Ethernet/examples/WebClient/WebClient.pde index 74d34e0ce..646c3aadd 100644 --- a/libraries/Ethernet/examples/WebClient/WebClient.pde +++ b/libraries/Ethernet/examples/WebClient/WebClient.pde @@ -23,7 +23,7 @@ IPAddress server(173,194,33,104); // Google // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): -Client client(server, 80); +Client client; void setup() { // start the serial library: @@ -40,7 +40,7 @@ void setup() { Serial.println("connecting..."); // if you get a connection, report back via serial: - if (client.connect()) { + if (client.connect(server, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.0"); From 4000c9199b7f91907519a46d692d660012ade090 Mon Sep 17 00:00:00 2001 From: amcewen Date: Fri, 4 Feb 2011 21:15:42 +0000 Subject: [PATCH 05/29] Added new method to UDP to take a hostname rather than an IP address. Part of issue 243 --- libraries/Ethernet/Udp.cpp | 17 +++++++++++++++++ libraries/Ethernet/Udp.h | 3 +++ 2 files changed, 20 insertions(+) diff --git a/libraries/Ethernet/Udp.cpp b/libraries/Ethernet/Udp.cpp index a8c98c3f4..2c8b10332 100644 --- a/libraries/Ethernet/Udp.cpp +++ b/libraries/Ethernet/Udp.cpp @@ -30,6 +30,7 @@ #include "socket.h" #include "Ethernet.h" #include "Udp.h" +#include "Dns.h" /* Constructor */ UDP::UDP() : _sock(MAX_SOCK_NUM) {} @@ -74,6 +75,22 @@ void UDP::stop() _sock = MAX_SOCK_NUM; } +int UDP::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 UDP::beginPacket(IPAddress ip, uint16_t port) { _offset = 0; diff --git a/libraries/Ethernet/Udp.h b/libraries/Ethernet/Udp.h index 8cd3b065a..99df53f15 100644 --- a/libraries/Ethernet/Udp.h +++ b/libraries/Ethernet/Udp.h @@ -60,6 +60,9 @@ public: // 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 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 + 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 int endPacket(); From 7f18110b803609974a3897749d9d1f67ae614fff Mon Sep 17 00:00:00 2001 From: amcewen Date: Fri, 4 Feb 2011 21:44:51 +0000 Subject: [PATCH 06/29] Fixed bug in parsePacket where it could block indefinitely if called when no packets were available to be read. --- libraries/Ethernet/Udp.cpp | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/libraries/Ethernet/Udp.cpp b/libraries/Ethernet/Udp.cpp index 2c8b10332..aed5d983b 100644 --- a/libraries/Ethernet/Udp.cpp +++ b/libraries/Ethernet/Udp.cpp @@ -121,20 +121,25 @@ void UDP::write(const uint8_t *buffer, size_t size) int UDP::parsePacket() { - //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) + if (available() > 0) { - _remoteIP = tmpBuf; - _remotePort = tmpBuf[4]; - _remotePort = (_remotePort << 8) + tmpBuf[5]; - // When we get here, any remaining bytes are the data - ret = available(); + //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]; + // When we get here, any remaining bytes are the data + ret = available(); + } + return ret; } - return ret; + // There aren't any packets available + return 0; } int UDP::read() From a5f6a42dd7128ba3dc13d25a430f4a5a896d7528 Mon Sep 17 00:00:00 2001 From: amcewen Date: Mon, 28 Mar 2011 12:08:53 +0100 Subject: [PATCH 07/29] Pulled out Client API into a base class to allow multiple derived classes to use it, and moved it (plus IPAddress) out of the Ethernet library so that other libraries can find it. First steps in integrating the WiFly code so it's easier to switch between that and Ethernet --- .../arduino/cores/arduino}/IPAddress.cpp | 0 .../arduino/cores/arduino}/IPAddress.h | 0 hardware/arduino/cores/arduino/NetClient.h | 28 +++++++++++++++++++ libraries/Ethernet/Client.h | 18 ++++++------ 4 files changed, 38 insertions(+), 8 deletions(-) rename {libraries/Ethernet => hardware/arduino/cores/arduino}/IPAddress.cpp (100%) rename {libraries/Ethernet => hardware/arduino/cores/arduino}/IPAddress.h (100%) create mode 100644 hardware/arduino/cores/arduino/NetClient.h diff --git a/libraries/Ethernet/IPAddress.cpp b/hardware/arduino/cores/arduino/IPAddress.cpp similarity index 100% rename from libraries/Ethernet/IPAddress.cpp rename to hardware/arduino/cores/arduino/IPAddress.cpp diff --git a/libraries/Ethernet/IPAddress.h b/hardware/arduino/cores/arduino/IPAddress.h similarity index 100% rename from libraries/Ethernet/IPAddress.h rename to hardware/arduino/cores/arduino/IPAddress.h diff --git a/hardware/arduino/cores/arduino/NetClient.h b/hardware/arduino/cores/arduino/NetClient.h new file mode 100644 index 000000000..d8df9149a --- /dev/null +++ b/hardware/arduino/cores/arduino/NetClient.h @@ -0,0 +1,28 @@ +#ifndef netclient_h +#define netclient_h +#include "WProgram.h" +#include "Print.h" +#include "NetClient.h" +#include "IPAddress.h" + +class NetClient : public Stream { + +public: + virtual int connect(IPAddress ip, uint16_t port) =0; + virtual int connect(const char *host, uint16_t port) =0; + virtual void write(uint8_t) =0; + virtual void write(const char *str) =0; + virtual void write(const uint8_t *buf, size_t size) =0; + virtual int available() = 0; + virtual int read() = 0; + virtual int read(uint8_t *buf, size_t size) = 0; + virtual int peek() = 0; + virtual void flush() = 0; + virtual void stop() = 0; + virtual uint8_t connected() = 0; + virtual uint8_t operator==(int) = 0; + virtual uint8_t operator!=(int) = 0; + virtual operator bool() = 0; +}; + +#endif diff --git a/libraries/Ethernet/Client.h b/libraries/Ethernet/Client.h index 23a8f1860..a4d1589ff 100644 --- a/libraries/Ethernet/Client.h +++ b/libraries/Ethernet/Client.h @@ -2,16 +2,18 @@ #define client_h #include "WProgram.h" #include "Print.h" +#include "NetClient.h" +#include "IPAddress.h" -class Client : public Stream { +class Client : public NetClient { public: Client(); Client(uint8_t sock); uint8_t status(); - int connect(IPAddress ip, uint16_t port); - int connect(const char *host, uint16_t port); + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char *host, uint16_t port); virtual void write(uint8_t); virtual void write(const char *str); virtual void write(const uint8_t *buf, size_t size); @@ -20,11 +22,11 @@ public: virtual int read(uint8_t *buf, size_t size); virtual int peek(); virtual void flush(); - void stop(); - uint8_t connected(); - uint8_t operator==(int); - uint8_t operator!=(int); - operator bool(); + virtual void stop(); + virtual uint8_t connected(); + virtual uint8_t operator==(int); + virtual uint8_t operator!=(int); + virtual operator bool(); friend class Server; From 17d8fcb46d49fc284671d2f124a01e69ce86b0c8 Mon Sep 17 00:00:00 2001 From: amcewen Date: Thu, 31 Mar 2011 16:19:17 +0100 Subject: [PATCH 08/29] Pulled out Server API into the NetServer base class, and a few minor changes to get the NetClient API to work well with the WiFly library --- hardware/arduino/cores/arduino/NetClient.h | 2 -- hardware/arduino/cores/arduino/NetServer.h | 11 +++++++++++ libraries/Ethernet/Server.h | 6 +++--- 3 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 hardware/arduino/cores/arduino/NetServer.h diff --git a/hardware/arduino/cores/arduino/NetClient.h b/hardware/arduino/cores/arduino/NetClient.h index d8df9149a..ea64664e7 100644 --- a/hardware/arduino/cores/arduino/NetClient.h +++ b/hardware/arduino/cores/arduino/NetClient.h @@ -20,8 +20,6 @@ public: virtual void flush() = 0; virtual void stop() = 0; virtual uint8_t connected() = 0; - virtual uint8_t operator==(int) = 0; - virtual uint8_t operator!=(int) = 0; virtual operator bool() = 0; }; diff --git a/hardware/arduino/cores/arduino/NetServer.h b/hardware/arduino/cores/arduino/NetServer.h new file mode 100644 index 000000000..91f484895 --- /dev/null +++ b/hardware/arduino/cores/arduino/NetServer.h @@ -0,0 +1,11 @@ +#ifndef netserver_h +#define netserver_h + +class NetClient; + +class NetServer { +public: + virtual void begin() =0; +}; + +#endif diff --git a/libraries/Ethernet/Server.h b/libraries/Ethernet/Server.h index 6aa5d3aaf..4c3bd1b54 100644 --- a/libraries/Ethernet/Server.h +++ b/libraries/Ethernet/Server.h @@ -1,19 +1,19 @@ #ifndef server_h #define server_h -#include "Print.h" +#include "NetServer.h" class Client; class Server : -public Print { +public NetServer { private: uint16_t _port; void accept(); public: Server(uint16_t); Client available(); - void begin(); + virtual void begin(); virtual void write(uint8_t); virtual void write(const char *str); virtual void write(const uint8_t *buf, size_t size); From 3540d92eb2a8066eb4e8553f6eb72bd632335411 Mon Sep 17 00:00:00 2001 From: amcewen Date: Fri, 1 Apr 2011 21:10:38 +0100 Subject: [PATCH 09/29] Added Printable interface class to allow printing of classes such as IPAddress --- hardware/arduino/cores/arduino/Print.cpp | 11 ++++++++ hardware/arduino/cores/arduino/Print.h | 3 ++ hardware/arduino/cores/arduino/Printable.h | 32 ++++++++++++++++++++++ libraries/Ethernet/IPAddress.cpp | 10 +++++++ libraries/Ethernet/IPAddress.h | 6 +++- 5 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 hardware/arduino/cores/arduino/Printable.h diff --git a/hardware/arduino/cores/arduino/Print.cpp b/hardware/arduino/cores/arduino/Print.cpp index 4ee556dd8..f5e77e082 100755 --- a/hardware/arduino/cores/arduino/Print.cpp +++ b/hardware/arduino/cores/arduino/Print.cpp @@ -101,6 +101,11 @@ void Print::print(double n, int digits) printFloat(n, digits); } +void Print::print(const Printable& x) +{ + x.printTo(*this); +} + void Print::println(void) { print('\r'); @@ -161,6 +166,12 @@ void Print::println(double n, int digits) println(); } +void Print::println(const Printable& x) +{ + print(x); + println(); +} + // Private Methods ///////////////////////////////////////////////////////////// void Print::printNumber(unsigned long n, uint8_t base) diff --git a/hardware/arduino/cores/arduino/Print.h b/hardware/arduino/cores/arduino/Print.h index b092ae51d..d2014bf08 100755 --- a/hardware/arduino/cores/arduino/Print.h +++ b/hardware/arduino/cores/arduino/Print.h @@ -24,6 +24,7 @@ #include // for size_t #include "WString.h" +#include "Printable.h" #define DEC 10 #define HEX 16 @@ -50,6 +51,7 @@ class Print void print(long, int = DEC); void print(unsigned long, int = DEC); void print(double, int = 2); + void print(const Printable&); void println(const String &s); void println(const char[]); @@ -60,6 +62,7 @@ class Print void println(long, int = DEC); void println(unsigned long, int = DEC); void println(double, int = 2); + void println(const Printable&); void println(void); }; diff --git a/hardware/arduino/cores/arduino/Printable.h b/hardware/arduino/cores/arduino/Printable.h new file mode 100644 index 000000000..fc6485826 --- /dev/null +++ b/hardware/arduino/cores/arduino/Printable.h @@ -0,0 +1,32 @@ +/* + Printable.h - Interface class that allows printing of complex types + Copyright (c) 2011 Adrian McEwen. 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 Printable_h +#define Printable_h + +class Print; + +class Printable +{ + public: + virtual void printTo(Print& p) const =0; +}; + +#endif + diff --git a/libraries/Ethernet/IPAddress.cpp b/libraries/Ethernet/IPAddress.cpp index 408d518a0..c4fb75096 100644 --- a/libraries/Ethernet/IPAddress.cpp +++ b/libraries/Ethernet/IPAddress.cpp @@ -42,3 +42,13 @@ bool IPAddress::operator==(const uint8_t* addr) return memcmp(addr, _address, sizeof(_address)) == 0; } +void IPAddress::printTo(Print& p) const +{ + for (int i =0; i < 3; i++) + { + p.print(_address[i], DEC); + p.print('.'); + } + p.print(_address[3], DEC); +} + diff --git a/libraries/Ethernet/IPAddress.h b/libraries/Ethernet/IPAddress.h index 487e420bd..7dd520351 100644 --- a/libraries/Ethernet/IPAddress.h +++ b/libraries/Ethernet/IPAddress.h @@ -26,9 +26,11 @@ #ifndef IPAddress_h #define IPAddress_h +#include + // A class to make it easier to handle and pass around IP addresses -class IPAddress { +class IPAddress : public Printable { private: uint8_t _address[4]; // IPv4 address // Access the raw byte array containing the address. Because this returns a pointer @@ -58,6 +60,8 @@ public: IPAddress& operator=(const uint8_t *address); IPAddress& operator=(uint32_t address); + virtual void printTo(Print& p) const; + friend class EthernetClass; friend class UDP; friend class Client; From facbd279b67923bbabbc4540721280f652ae5726 Mon Sep 17 00:00:00 2001 From: amcewen Date: Sat, 2 Apr 2011 11:33:27 +0100 Subject: [PATCH 10/29] Added a brief explanation of how you'd use Printable --- hardware/arduino/cores/arduino/Printable.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/hardware/arduino/cores/arduino/Printable.h b/hardware/arduino/cores/arduino/Printable.h index fc6485826..e5d773261 100644 --- a/hardware/arduino/cores/arduino/Printable.h +++ b/hardware/arduino/cores/arduino/Printable.h @@ -22,6 +22,12 @@ class Print; +/** The Printable class provides a way for new classes to allow themselves to be printed. + By deriving from Printable and implementing the printTo method, it will then be possible + for users to print out instances of this class by passing them into the usual + Print::print and Print::println methods. +*/ + class Printable { public: From 35a78b15ea94014a475967b8414ad00d1a145f9c Mon Sep 17 00:00:00 2001 From: amcewen Date: Sun, 10 Apr 2011 11:34:40 +0100 Subject: [PATCH 11/29] Added virtual destructor to Printable, which also requires new and delete operators to be added --- hardware/arduino/cores/arduino/Printable.h | 3 +++ hardware/arduino/cores/arduino/new.cpp | 18 ++++++++++++++++++ hardware/arduino/cores/arduino/new.h | 22 ++++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 hardware/arduino/cores/arduino/new.cpp create mode 100644 hardware/arduino/cores/arduino/new.h diff --git a/hardware/arduino/cores/arduino/Printable.h b/hardware/arduino/cores/arduino/Printable.h index e5d773261..5ff607767 100644 --- a/hardware/arduino/cores/arduino/Printable.h +++ b/hardware/arduino/cores/arduino/Printable.h @@ -20,6 +20,8 @@ #ifndef Printable_h #define Printable_h +#include + class Print; /** The Printable class provides a way for new classes to allow themselves to be printed. @@ -31,6 +33,7 @@ class Print; class Printable { public: + virtual ~Printable() {}; virtual void printTo(Print& p) const =0; }; diff --git a/hardware/arduino/cores/arduino/new.cpp b/hardware/arduino/cores/arduino/new.cpp new file mode 100644 index 000000000..0f6d4220e --- /dev/null +++ b/hardware/arduino/cores/arduino/new.cpp @@ -0,0 +1,18 @@ +#include + +void * operator new(size_t size) +{ + return malloc(size); +} + +void operator delete(void * ptr) +{ + free(ptr); +} + +int __cxa_guard_acquire(__guard *g) {return !*(char *)(g);}; +void __cxa_guard_release (__guard *g) {*(char *)g = 1;}; +void __cxa_guard_abort (__guard *) {}; + +void __cxa_pure_virtual(void) {}; + diff --git a/hardware/arduino/cores/arduino/new.h b/hardware/arduino/cores/arduino/new.h new file mode 100644 index 000000000..cd940ce8b --- /dev/null +++ b/hardware/arduino/cores/arduino/new.h @@ -0,0 +1,22 @@ +/* Header to define new/delete operators as they aren't provided by avr-gcc by default + Taken from http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=59453 + */ + +#ifndef NEW_H +#define NEW_H + +#include + +void * operator new(size_t size); +void operator delete(void * ptr); + +__extension__ typedef int __guard __attribute__((mode (__DI__))); + +extern "C" int __cxa_guard_acquire(__guard *); +extern "C" void __cxa_guard_release (__guard *); +extern "C" void __cxa_guard_abort (__guard *); + +extern "C" void __cxa_pure_virtual(void); + +#endif + From 789e22add2f233d2ef8cbbc8ff747f1737972fe9 Mon Sep 17 00:00:00 2001 From: amcewen Date: Sun, 12 Jun 2011 22:02:25 +0100 Subject: [PATCH 12/29] Added a way to specify the DNS server to use with static IP --- libraries/Ethernet/Ethernet.cpp | 18 ++++++++++++++---- libraries/Ethernet/Ethernet.h | 5 +++-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/libraries/Ethernet/Ethernet.cpp b/libraries/Ethernet/Ethernet.cpp index 937f5b4f9..c298f3d17 100644 --- a/libraries/Ethernet/Ethernet.cpp +++ b/libraries/Ethernet/Ethernet.cpp @@ -33,27 +33,37 @@ int EthernetClass::begin(uint8_t *mac_address) } 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, gateway); + begin(mac_address, local_ip, dns_server, gateway); } -void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress 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, gateway, subnet); + begin(mac_address, local_ip, dns_server, gateway, subnet); } -void EthernetClass::begin(uint8_t *mac, IPAddress local_ip, IPAddress gateway, IPAddress 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; } IPAddress EthernetClass::localIP() diff --git a/libraries/Ethernet/Ethernet.h b/libraries/Ethernet/Ethernet.h index fdf0b7f39..b4d223fba 100644 --- a/libraries/Ethernet/Ethernet.h +++ b/libraries/Ethernet/Ethernet.h @@ -20,8 +20,9 @@ public: // 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 gateway); - void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress gateway, IPAddress subnet); + 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); IPAddress localIP(); IPAddress subnetMask(); From ffd2cec8a0d4e6755d7a0182ab3a32a411f8f240 Mon Sep 17 00:00:00 2001 From: amcewen Date: Thu, 16 Jun 2011 20:16:26 +0100 Subject: [PATCH 13/29] Tweak to defines to support a couple more AVRs - the ATmega32U4 and AT90USB1286, so it doesn't need to be patched for the Teensy boards. --- libraries/Ethernet/utility/w5100.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libraries/Ethernet/utility/w5100.h b/libraries/Ethernet/utility/w5100.h index 9872c7ccb..35d23ed41 100755 --- a/libraries/Ethernet/utility/w5100.h +++ b/libraries/Ethernet/utility/w5100.h @@ -324,6 +324,10 @@ private: 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__) || 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); }; From 6b2dec0d01217675daf124a9dea2d0650d88225b Mon Sep 17 00:00:00 2001 From: amcewen Date: Thu, 7 Jul 2011 21:59:35 +0100 Subject: [PATCH 14/29] Fixed bug where the DHCP client didn't correctly handle a response containing more than one DNS server address. Fixes issue 569. --- libraries/Ethernet/Dhcp.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/libraries/Ethernet/Dhcp.cpp b/libraries/Ethernet/Dhcp.cpp index c20d2e61d..29db89098 100755 --- a/libraries/Ethernet/Dhcp.cpp +++ b/libraries/Ethernet/Dhcp.cpp @@ -271,11 +271,19 @@ uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& tr 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 : From b7533c18393c2b6d0e1e4dba620d87215611ce6c Mon Sep 17 00:00:00 2001 From: amcewen Date: Sun, 28 Aug 2011 22:26:07 +0100 Subject: [PATCH 15/29] Final changes to integrate latest core updates to WiFly branch --- hardware/arduino/cores/arduino/NetClient.h | 7 +++---- libraries/Ethernet/Client.h | 2 -- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/hardware/arduino/cores/arduino/NetClient.h b/hardware/arduino/cores/arduino/NetClient.h index ea64664e7..35bfa0a7b 100644 --- a/hardware/arduino/cores/arduino/NetClient.h +++ b/hardware/arduino/cores/arduino/NetClient.h @@ -1,6 +1,5 @@ #ifndef netclient_h #define netclient_h -#include "WProgram.h" #include "Print.h" #include "NetClient.h" #include "IPAddress.h" @@ -10,9 +9,9 @@ class NetClient : public Stream { public: virtual int connect(IPAddress ip, uint16_t port) =0; virtual int connect(const char *host, uint16_t port) =0; - virtual void write(uint8_t) =0; - virtual void write(const char *str) =0; - virtual void write(const uint8_t *buf, size_t size) =0; + virtual size_t write(uint8_t) =0; + virtual size_t write(const char *str) =0; + virtual size_t write(const uint8_t *buf, size_t size) =0; virtual int available() = 0; virtual int read() = 0; virtual int read(uint8_t *buf, size_t size) = 0; diff --git a/libraries/Ethernet/Client.h b/libraries/Ethernet/Client.h index 1d360063a..6717cf128 100644 --- a/libraries/Ethernet/Client.h +++ b/libraries/Ethernet/Client.h @@ -24,8 +24,6 @@ public: virtual void flush(); virtual void stop(); virtual uint8_t connected(); - virtual uint8_t operator==(int); - virtual uint8_t operator!=(int); virtual operator bool(); friend class Server; From ad5dead85a2a32a1be79fec73a39dec67cf0a372 Mon Sep 17 00:00:00 2001 From: amcewen Date: Mon, 29 Aug 2011 22:36:28 +0100 Subject: [PATCH 16/29] Changed names of the Ethernet classes: Client -> EthernetClient, NetClient -> Client, and basic testing performed --- .../cores/arduino/{NetClient.h => Client.h} | 10 +++-- hardware/arduino/cores/arduino/NetServer.h | 11 ----- hardware/arduino/cores/arduino/Server.h | 9 ++++ libraries/Ethernet/Ethernet.h | 8 ++-- .../{Client.cpp => EthernetClient.cpp} | 42 +++++++++---------- .../Ethernet/{Client.h => EthernetClient.h} | 14 +++---- .../{Server.cpp => EthernetServer.cpp} | 28 ++++++------- .../Ethernet/{Server.h => EthernetServer.h} | 16 +++---- .../BarometricPressureWebServer.pde | 8 ++-- .../examples/ChatServer/ChatServer.pde | 4 +- .../DhcpAddressPrinter/DhcpAddressPrinter.ino | 2 +- .../DhcpChatServer/DhcpChatServer.ino | 4 +- .../examples/DnsWebClient/DnsWebClient.pde | 2 +- .../examples/PachubeClient/PachubeClient.pde | 2 +- .../PachubeClientString.pde | 2 +- .../examples/TelnetClient/TelnetClient.pde | 2 +- .../examples/TwitterClient/TwitterClient.ino | 2 +- .../Ethernet/examples/WebClient/WebClient.pde | 2 +- .../Ethernet/examples/WebServer/WebServer.pde | 6 +-- libraries/Ethernet/keywords.txt | 4 +- 20 files changed, 89 insertions(+), 89 deletions(-) rename hardware/arduino/cores/arduino/{NetClient.h => Client.h} (77%) delete mode 100644 hardware/arduino/cores/arduino/NetServer.h create mode 100644 hardware/arduino/cores/arduino/Server.h rename libraries/Ethernet/{Client.cpp => EthernetClient.cpp} (73%) rename libraries/Ethernet/{Client.h => EthernetClient.h} (76%) rename libraries/Ethernet/{Server.cpp => EthernetServer.cpp} (72%) rename libraries/Ethernet/{Server.h => EthernetServer.h} (53%) diff --git a/hardware/arduino/cores/arduino/NetClient.h b/hardware/arduino/cores/arduino/Client.h similarity index 77% rename from hardware/arduino/cores/arduino/NetClient.h rename to hardware/arduino/cores/arduino/Client.h index 35bfa0a7b..ed9e9b48c 100644 --- a/hardware/arduino/cores/arduino/NetClient.h +++ b/hardware/arduino/cores/arduino/Client.h @@ -1,10 +1,10 @@ -#ifndef netclient_h -#define netclient_h +#ifndef client_h +#define client_h #include "Print.h" -#include "NetClient.h" +#include "Stream.h" #include "IPAddress.h" -class NetClient : public Stream { +class Client : public Stream { public: virtual int connect(IPAddress ip, uint16_t port) =0; @@ -20,6 +20,8 @@ public: virtual void stop() = 0; virtual uint8_t connected() = 0; virtual operator bool() = 0; +protected: + uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); }; }; #endif diff --git a/hardware/arduino/cores/arduino/NetServer.h b/hardware/arduino/cores/arduino/NetServer.h deleted file mode 100644 index 91f484895..000000000 --- a/hardware/arduino/cores/arduino/NetServer.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef netserver_h -#define netserver_h - -class NetClient; - -class NetServer { -public: - virtual void begin() =0; -}; - -#endif diff --git a/hardware/arduino/cores/arduino/Server.h b/hardware/arduino/cores/arduino/Server.h new file mode 100644 index 000000000..edab726be --- /dev/null +++ b/hardware/arduino/cores/arduino/Server.h @@ -0,0 +1,9 @@ +#ifndef server_h +#define server_h + +class Server { +public: + virtual void begin() =0; +}; + +#endif diff --git a/libraries/Ethernet/Ethernet.h b/libraries/Ethernet/Ethernet.h index b4d223fba..c916ddae5 100644 --- a/libraries/Ethernet/Ethernet.h +++ b/libraries/Ethernet/Ethernet.h @@ -4,8 +4,8 @@ #include //#include "w5100.h" #include "IPAddress.h" -#include "Client.h" -#include "Server.h" +#include "EthernetClient.h" +#include "EthernetServer.h" #define MAX_SOCK_NUM 4 @@ -29,8 +29,8 @@ public: IPAddress gatewayIP(); IPAddress dnsServerIP(); - friend class Client; - friend class Server; + friend class EthernetClient; + friend class EthernetServer; }; extern EthernetClass Ethernet; diff --git a/libraries/Ethernet/Client.cpp b/libraries/Ethernet/EthernetClient.cpp similarity index 73% rename from libraries/Ethernet/Client.cpp rename to libraries/Ethernet/EthernetClient.cpp index 3c1c2503b..42c2c6cc1 100644 --- a/libraries/Ethernet/Client.cpp +++ b/libraries/Ethernet/EthernetClient.cpp @@ -8,19 +8,19 @@ extern "C" { #include "Arduino.h" #include "Ethernet.h" -#include "Client.h" -#include "Server.h" +#include "EthernetClient.h" +#include "EthernetServer.h" #include "Dns.h" -uint16_t Client::_srcport = 1024; +uint16_t EthernetClient::_srcport = 1024; -Client::Client() : _sock(MAX_SOCK_NUM) { +EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) { } -Client::Client(uint8_t sock) : _sock(sock) { +EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) { } -int Client::connect(const char* host, uint16_t port) { +int EthernetClient::connect(const char* host, uint16_t port) { // Look up the host first int ret = 0; DNSClient dns; @@ -35,7 +35,7 @@ int Client::connect(const char* host, uint16_t port) { } } -int Client::connect(IPAddress ip, uint16_t port) { +int EthernetClient::connect(IPAddress ip, uint16_t port) { if (_sock != MAX_SOCK_NUM) return 0; @@ -54,7 +54,7 @@ int Client::connect(IPAddress ip, uint16_t port) { if (_srcport == 0) _srcport = 1024; socket(_sock, SnMR::TCP, _srcport, 0); - if (!::connect(_sock, ip.raw_address(), port)) { + if (!::connect(_sock, rawIPAddress(ip), port)) { _sock = MAX_SOCK_NUM; return 0; } @@ -70,15 +70,15 @@ int Client::connect(IPAddress ip, uint16_t port) { return 1; } -size_t Client::write(uint8_t b) { +size_t EthernetClient::write(uint8_t b) { return write(&b, 1); } -size_t Client::write(const char *str) { +size_t EthernetClient::write(const char *str) { return write((const uint8_t *) str, strlen(str)); } -size_t Client::write(const uint8_t *buf, size_t size) { +size_t EthernetClient::write(const uint8_t *buf, size_t size) { if (_sock == MAX_SOCK_NUM) { setWriteError(); return 0; @@ -90,13 +90,13 @@ size_t Client::write(const uint8_t *buf, size_t size) { return size; } -int Client::available() { +int EthernetClient::available() { if (_sock != MAX_SOCK_NUM) return W5100.getRXReceivedSize(_sock); return 0; } -int Client::read() { +int EthernetClient::read() { uint8_t b; if ( recv(_sock, &b, 1) > 0 ) { @@ -110,11 +110,11 @@ int Client::read() { } } -int Client::read(uint8_t *buf, size_t size) { +int EthernetClient::read(uint8_t *buf, size_t size) { return recv(_sock, buf, size); } -int Client::peek() { +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()) @@ -123,12 +123,12 @@ int Client::peek() { return b; } -void Client::flush() { +void EthernetClient::flush() { while (available()) read(); } -void Client::stop() { +void EthernetClient::stop() { if (_sock == MAX_SOCK_NUM) return; @@ -148,7 +148,7 @@ void Client::stop() { _sock = MAX_SOCK_NUM; } -uint8_t Client::connected() { +uint8_t EthernetClient::connected() { if (_sock == MAX_SOCK_NUM) return 0; uint8_t s = status(); @@ -156,14 +156,14 @@ uint8_t Client::connected() { (s == SnSR::CLOSE_WAIT && !available())); } -uint8_t Client::status() { +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 -// Server::available() as the condition in an if-statement. +// EthernetServer::available() as the condition in an if-statement. -Client::operator bool() { +EthernetClient::operator bool() { return _sock != MAX_SOCK_NUM; } diff --git a/libraries/Ethernet/Client.h b/libraries/Ethernet/EthernetClient.h similarity index 76% rename from libraries/Ethernet/Client.h rename to libraries/Ethernet/EthernetClient.h index 6717cf128..f68a3b4d9 100644 --- a/libraries/Ethernet/Client.h +++ b/libraries/Ethernet/EthernetClient.h @@ -1,15 +1,15 @@ -#ifndef client_h -#define client_h +#ifndef ethernetclient_h +#define ethernetclient_h #include "Arduino.h" #include "Print.h" -#include "NetClient.h" +#include "Client.h" #include "IPAddress.h" -class Client : public NetClient { +class EthernetClient : public Client { public: - Client(); - Client(uint8_t sock); + EthernetClient(); + EthernetClient(uint8_t sock); uint8_t status(); virtual int connect(IPAddress ip, uint16_t port); @@ -26,7 +26,7 @@ public: virtual uint8_t connected(); virtual operator bool(); - friend class Server; + friend class EthernetServer; private: static uint16_t _srcport; diff --git a/libraries/Ethernet/Server.cpp b/libraries/Ethernet/EthernetServer.cpp similarity index 72% rename from libraries/Ethernet/Server.cpp rename to libraries/Ethernet/EthernetServer.cpp index 1ac75d507..9ae86f39e 100644 --- a/libraries/Ethernet/Server.cpp +++ b/libraries/Ethernet/EthernetServer.cpp @@ -5,18 +5,18 @@ extern "C" { } #include "Ethernet.h" -#include "Client.h" -#include "Server.h" +#include "EthernetClient.h" +#include "EthernetServer.h" -Server::Server(uint16_t port) +EthernetServer::EthernetServer(uint16_t port) { _port = port; } -void Server::begin() +void EthernetServer::begin() { for (int sock = 0; sock < MAX_SOCK_NUM; sock++) { - Client client(sock); + EthernetClient client(sock); if (client.status() == SnSR::CLOSED) { socket(sock, SnMR::TCP, _port, 0); listen(sock); @@ -26,12 +26,12 @@ void Server::begin() } } -void Server::accept() +void EthernetServer::accept() { int listening = 0; for (int sock = 0; sock < MAX_SOCK_NUM; sock++) { - Client client(sock); + EthernetClient client(sock); if (EthernetClass::_server_port[sock] == _port) { if (client.status() == SnSR::LISTEN) { @@ -48,12 +48,12 @@ void Server::accept() } } -Client Server::available() +EthernetClient EthernetServer::available() { accept(); for (int sock = 0; sock < MAX_SOCK_NUM; sock++) { - Client client(sock); + EthernetClient client(sock); if (EthernetClass::_server_port[sock] == _port && (client.status() == SnSR::ESTABLISHED || client.status() == SnSR::CLOSE_WAIT)) { @@ -64,27 +64,27 @@ Client Server::available() } } - return Client(MAX_SOCK_NUM); + return EthernetClient(MAX_SOCK_NUM); } -size_t Server::write(uint8_t b) +size_t EthernetServer::write(uint8_t b) { write(&b, 1); } -size_t Server::write(const char *str) +size_t EthernetServer::write(const char *str) { write((const uint8_t *)str, strlen(str)); } -size_t Server::write(const uint8_t *buffer, size_t size) +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++) { - Client client(sock); + EthernetClient client(sock); if (EthernetClass::_server_port[sock] == _port && client.status() == SnSR::ESTABLISHED) { diff --git a/libraries/Ethernet/Server.h b/libraries/Ethernet/EthernetServer.h similarity index 53% rename from libraries/Ethernet/Server.h rename to libraries/Ethernet/EthernetServer.h index 0febe4fee..ced5ed649 100644 --- a/libraries/Ethernet/Server.h +++ b/libraries/Ethernet/EthernetServer.h @@ -1,18 +1,18 @@ -#ifndef server_h -#define server_h +#ifndef ethernetserver_h +#define ethernetserver_h -#include "NetServer.h" +#include "Server.h" -class Client; +class EthernetClient; -class Server : -public NetServer { +class EthernetServer : +public Server { private: uint16_t _port; void accept(); public: - Server(uint16_t); - Client available(); + EthernetServer(uint16_t); + EthernetClient available(); virtual void begin(); virtual size_t write(uint8_t); virtual size_t write(const char *str); diff --git a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde index 3f43d96db..bfbcb6d4a 100644 --- a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde +++ b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde @@ -39,7 +39,7 @@ 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): -Server server(80); +EthernetServer server(80); //Sensor's memory register addresses: @@ -96,7 +96,7 @@ void loop() { } // listen for incoming Ethernet connections: - listenForClients(); + listenForEthernetClients(); } @@ -124,9 +124,9 @@ void getData() { Serial.println(" Pa"); } -void listenForClients() { +void listenForEthernetClients() { // listen for incoming clients - Client client = server.available(); + EthernetClient client = server.available(); if (client) { Serial.println("Got a client"); // an http request ends with a blank line diff --git a/libraries/Ethernet/examples/ChatServer/ChatServer.pde b/libraries/Ethernet/examples/ChatServer/ChatServer.pde index 8267a5dd4..9f819fd5a 100644 --- a/libraries/Ethernet/examples/ChatServer/ChatServer.pde +++ b/libraries/Ethernet/examples/ChatServer/ChatServer.pde @@ -29,7 +29,7 @@ IPAddress gateway(192,168,1, 1); IPAddress subnet(255, 255, 0, 0); // telnet defaults to port 23 -Server server(23); +EthernetServer server(23); boolean gotAMessage = false; // whether or not you got a message from the client yet void setup() { @@ -43,7 +43,7 @@ void setup() { void loop() { // wait for a new client: - Client client = server.available(); + EthernetClient client = server.available(); // when the client sends the first byte, say hello: if (client) { diff --git a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino index 8701568c0..a5787b91d 100644 --- a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino +++ b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino @@ -24,7 +24,7 @@ byte mac[] = { // 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): -Client client; +EthernetClient client; void setup() { // start the serial library: diff --git a/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino b/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino index c3e581387..50820542c 100644 --- a/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino +++ b/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino @@ -30,7 +30,7 @@ IPAddress gateway(192,168,1, 1); IPAddress subnet(255, 255, 0, 0); // telnet defaults to port 23 -Server server(23); +EthernetServer server(23); boolean gotAMessage = false; // whether or not you got a message from the client yet void setup() { @@ -59,7 +59,7 @@ void setup() { void loop() { // wait for a new client: - Client client = server.available(); + EthernetClient client = server.available(); // when the client sends the first byte, say hello: if (client) { diff --git a/libraries/Ethernet/examples/DnsWebClient/DnsWebClient.pde b/libraries/Ethernet/examples/DnsWebClient/DnsWebClient.pde index 7bec73a83..5c7a53a65 100644 --- a/libraries/Ethernet/examples/DnsWebClient/DnsWebClient.pde +++ b/libraries/Ethernet/examples/DnsWebClient/DnsWebClient.pde @@ -25,7 +25,7 @@ char serverName[] = "www.google.com"; // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): -Client client; +EthernetClient client; void setup() { // start the serial library: diff --git a/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde b/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde index af9bf1f05..e626113b0 100644 --- a/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde +++ b/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde @@ -29,7 +29,7 @@ byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // initialize the library instance: -Client client; +EthernetClient client; 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 diff --git a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde index e6dbf09ea..4b97c4175 100644 --- a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde +++ b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde @@ -30,7 +30,7 @@ byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // initialize the library instance: -Client client; +EthernetClient client; 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 diff --git a/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde b/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde index 7502d218d..5cf1ad875 100644 --- a/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde +++ b/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde @@ -33,7 +33,7 @@ IPAddress server(1,1,1,1); // 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): -Client client; +EthernetClient client; void setup() { // start the Ethernet connection: diff --git a/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino b/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino index 399e76bc3..f113e17b9 100644 --- a/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino +++ b/libraries/Ethernet/examples/TwitterClient/TwitterClient.ino @@ -33,7 +33,7 @@ byte mac[] = { IPAddress ip(192,168,1,20); // initialize the library instance: -Client client; +EthernetClient client; const int requestInterval = 60000; // delay between requests diff --git a/libraries/Ethernet/examples/WebClient/WebClient.pde b/libraries/Ethernet/examples/WebClient/WebClient.pde index 646c3aadd..18068541f 100644 --- a/libraries/Ethernet/examples/WebClient/WebClient.pde +++ b/libraries/Ethernet/examples/WebClient/WebClient.pde @@ -23,7 +23,7 @@ IPAddress server(173,194,33,104); // Google // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): -Client client; +EthernetClient client; void setup() { // start the serial library: diff --git a/libraries/Ethernet/examples/WebServer/WebServer.pde b/libraries/Ethernet/examples/WebServer/WebServer.pde index c69a56a40..6837f8320 100644 --- a/libraries/Ethernet/examples/WebServer/WebServer.pde +++ b/libraries/Ethernet/examples/WebServer/WebServer.pde @@ -1,5 +1,5 @@ /* - Web Server + Web Server A simple web server that shows the value of the analog input pins. using an Arduino Wiznet Ethernet shield. @@ -26,7 +26,7 @@ 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): -Server server(80); +EthernetServer server(80); void setup() { @@ -38,7 +38,7 @@ void setup() void loop() { // listen for incoming clients - Client client = server.available(); + EthernetClient client = server.available(); if (client) { // an http request ends with a blank line boolean currentLineIsBlank = true; diff --git a/libraries/Ethernet/keywords.txt b/libraries/Ethernet/keywords.txt index 7fdcedf09..6b37cbe05 100644 --- a/libraries/Ethernet/keywords.txt +++ b/libraries/Ethernet/keywords.txt @@ -7,8 +7,8 @@ ####################################### Ethernet KEYWORD1 -Client KEYWORD1 -Server KEYWORD1 +EthernetClient KEYWORD1 +EthernetServer KEYWORD1 IPAddress KEYWORD1 ####################################### From c49ba1831b5f2b96e0c0236c22f973c183994489 Mon Sep 17 00:00:00 2001 From: Ricklon Date: Mon, 29 Aug 2011 17:12:08 -0700 Subject: [PATCH 17/29] ArduinoTestSuite updates from Paul Stoffregen --- .../ArduinoTestSuite/ArduinoTestSuite.cpp | 92 ++++++++++++---- libraries/ArduinoTestSuite/ArduinoTestSuite.h | 18 ++-- .../examples/ATS_Constants/ATS_Constants.pde | 1 - .../examples/ATS_Delay/ATS_Delay.pde | 102 +++++++++++++++++- .../examples/ATS_General/ATS_General.pde | 10 +- .../examples/ATS_Skeleton/ATS_Skeleton.pde | 1 - .../ATS_StringIndexOfMemory.pde | 79 +++++++------- .../ATS_StringTest/ATS_StringTest.pde | 25 +++-- .../ATS_String_Addition.pde | 15 +-- .../examples/ATS_ToneTest/ATS_ToneTest.pde | 13 ++- 10 files changed, 251 insertions(+), 105 deletions(-) diff --git a/libraries/ArduinoTestSuite/ArduinoTestSuite.cpp b/libraries/ArduinoTestSuite/ArduinoTestSuite.cpp index 86a275ab7..44e75da4f 100644 --- a/libraries/ArduinoTestSuite/ArduinoTestSuite.cpp +++ b/libraries/ArduinoTestSuite/ArduinoTestSuite.cpp @@ -1,6 +1,7 @@ //************************************************************************ //* Arduino Test Suite //* (C) 2010 by Mark Sproul +//* (C) 2011 by Matthew Murdoch //* Open source as per standard Arduino code //* //* This library is free software; you can redistribute it and/or @@ -15,6 +16,7 @@ //************************************************************************ //* Aug 31, 2010 Started on TestArduino //* Oct 18, 2010 Added memory testing +//* Jun 10, 2011 Added free list to memory usage calculation //************************************************************************ #include @@ -26,11 +28,6 @@ #include "ArduinoTestSuite.h" -#include "Arduino.h" -#include "HardwareSerial.h" -#include "pins_arduino.h" - - #include "avr_cpunames.h" #if defined(USART3_RX_vect) @@ -58,6 +55,7 @@ enum }; unsigned long gTestStartTime; +unsigned long gTestTotalElapsedTime; short gTagIndent; int gYotalErrors; int gTestCount; @@ -176,9 +174,9 @@ char memoryMsg[48]; gTestCount = 0; Serial.begin(9600); - delay(1000); + delay(100); - gTestStartTime = millis(); + gTestTotalElapsedTime = 0; Serial.println(); Serial.println(); @@ -197,14 +195,17 @@ char memoryMsg[48]; randomSeed(analogRead(0)); + gTestStartTime = micros(); } //************************************************************************ void ATS_end() { -long seconds; -long milliSecs; +unsigned long seconds; +unsigned long microSecs; +char buf[8]; + gTestTotalElapsedTime += (micros() - gTestStartTime); Serial_println_P(gTextMsg_dashLine); @@ -212,14 +213,22 @@ long milliSecs; Serial.print("Ran "); Serial.print(gTestCount); Serial.print(" tests in "); + + seconds = gTestTotalElapsedTime / 1000000; + microSecs = gTestTotalElapsedTime % 1000000; - seconds = millis() / 1000; - milliSecs = millis() % 1000; Serial.print(seconds); - Serial.print('.'); - Serial.print(milliSecs); + ultoa(microSecs + 1000000, buf, 10); // add forces leading zeros + buf[0] = '.'; // replace leading '1' with decimal point + Serial.print(buf); Serial.print('s'); Serial.println(); + + int used = ATS_GetMaximumMemoryAllocated(); + if (used >= 0) { + Serial.print("Maximum heap memory: "); + Serial.println(used); + } Serial.println(); if (gYotalErrors == 0) @@ -245,6 +254,9 @@ void ATS_PrintTestStatus(char *testString, boolean passed) { int sLen; + // do not include time printing status in total test time + gTestTotalElapsedTime += (micros() - gTestStartTime); + Serial.print(testString); sLen = strlen(testString); while (sLen < 60) @@ -265,6 +277,9 @@ int sLen; Serial.println(); gTestCount++; + + // begin counting total test time again + gTestStartTime = micros(); } @@ -474,8 +489,15 @@ uint8_t helperpin; #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define kAnalogPinOffset 54 + #define DIGITAL_ANAPIN(a) ((a) + kAnalogPinOffset) +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) + #define kAnalogPinOffset 38 + #define DIGITAL_ANAPIN(a) ((a) + kAnalogPinOffset) +#elif defined(__AVR_ATmega32U4__) + #define DIGITAL_ANAPIN(a) ((a) < 11 ? 21 - (a) : 22) #else #define kAnalogPinOffset 14 + #define DIGITAL_ANAPIN(a) ((a) + kAnalogPinOffset) #endif @@ -490,7 +512,7 @@ int analogValueLow; //* first we have to set the ANALOG pin to INPUT - pinMode(analogPintoTest + kAnalogPinOffset, INPUT); + pinMode(DIGITAL_ANAPIN(analogPintoTest), INPUT); passedOK = true; @@ -532,15 +554,15 @@ boolean ATS_Test_AnalogInput(uint8_t analogPinToTest) boolean passedOK; uint8_t helperpin; - if ((analogPinToTest % 2) == 0) + if ((DIGITAL_ANAPIN(analogPinToTest) % 2) == 0) { //* if its EVEN, add 1 - helperpin = kAnalogPinOffset + analogPinToTest + 1; + helperpin = DIGITAL_ANAPIN(analogPinToTest) + 1; } else { //* if its ODD - helperpin = kAnalogPinOffset + analogPinToTest - 1; + helperpin = DIGITAL_ANAPIN(analogPinToTest) - 1; } passedOK = ATS_Test_AnalogInputWithHelper(analogPinToTest, helperpin); return(passedOK); @@ -551,7 +573,7 @@ uint8_t helperpin; #define kSerialTestDelay 3 -#if (SERIAL_PORT_COUNT > 1) && !defined(__AVR_ATmega32U4__) +#if (SERIAL_PORT_COUNT > 1) //************************************************************************ //* retunrs 0 if no errors, 1 if an error occured short ATS_TestSerialLoopback(HardwareSerial *theSerialPort, char *serialPortName) @@ -693,8 +715,32 @@ extern unsigned int __bss_start; extern unsigned int __bss_end; extern unsigned int __heap_start; extern void *__brkval; +char *__brkval_maximum __attribute__((weak)); +/* + * The free list structure as maintained by the avr-libc memory allocation routines. + */ +struct __freelist { + size_t sz; + struct __freelist *nx; +}; +/* The head of the free list structure */ +extern struct __freelist *__flp; + +/* Calculates the size of the free list */ +int ATS_FreeListSize() +{ +struct __freelist* current; +int total = 0; + + for (current = __flp; current; current = current->nx) { + total += 2; /* Add two bytes for the memory block's header */ + total += (int) current->sz; + } + + return total; +} //************************************************************************ int ATS_GetFreeMemory() @@ -703,13 +749,21 @@ int free_memory; if((int)__brkval == 0) { - free_memory = ((int)&free_memory) - ((int)&__bss_end); + free_memory = ((int)&free_memory) - ((int)&__heap_start); } else { free_memory = ((int)&free_memory) - ((int)__brkval); + free_memory += ATS_FreeListSize(); } return free_memory; } +int ATS_GetMaximumMemoryAllocated() +{ + if (__brkval_maximum) { + return (int)__brkval_maximum - (int)&__heap_start; + } + return -1; +} diff --git a/libraries/ArduinoTestSuite/ArduinoTestSuite.h b/libraries/ArduinoTestSuite/ArduinoTestSuite.h index af810e1eb..f2f00ca89 100644 --- a/libraries/ArduinoTestSuite/ArduinoTestSuite.h +++ b/libraries/ArduinoTestSuite/ArduinoTestSuite.h @@ -3,15 +3,12 @@ //* Aug 31, 2010 Started on TestArduino //************************************************************************ -#ifndef _AVR_IO_H_ - #include -#endif - -#ifndef Arduino_h - #include "Arduino.h" -#endif -#ifndef HardwareSerial_h - #include "HardwareSerial.h" +#if defined(ARDUINO) && ARDUINO >= 100 +#include "Arduino.h" +#include "pins_arduino.h" +#else +#include "WProgram.h" +#include "pins_arduino.h" #endif @@ -37,9 +34,12 @@ short ATS_TestSerialLoopback(HardwareSerial *theSerialPort, char *serialPortName int ATS_GetFreeMemory(); +int ATS_GetMaximumMemoryAllocated(); + //************************************************************************ //* this has to be an inline function because calling subroutines affects free memory +inline void ATS_ReportMemoryUsage(int _memoryUsageAtStart) __attribute__((always_inline, unused)); inline void ATS_ReportMemoryUsage(int _memoryUsageAtStart) { int freeMemoryAtEnd; diff --git a/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.pde b/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.pde index 3196923f5..fc3aab765 100644 --- a/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.pde +++ b/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.pde @@ -7,7 +7,6 @@ //* Oct 16, 2010 Test of Arduino Constants //************************************************************************ -#include "HardwareSerial.h" #include //************************************************************************ diff --git a/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.pde b/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.pde index c3235d273..111302e38 100644 --- a/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.pde +++ b/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.pde @@ -1 +1,101 @@ -//************************************************************************ //* Arduino Test Suite //* ATS_ToneTest //* //* Copyright (c) 2010 Mark Sproul 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 //************************************************************************ //* Aug 31, 2010 Started on TestArduino //* Oct 28, 2010 Started on Delay //************************************************************************ #include "HardwareSerial.h" #include //************************************************************************ void setup() { short ii; short testNum; int startMemoryUsage; unsigned long startMillis; unsigned long endMillis; unsigned long deltaMillis; unsigned long errMillis; boolean passed; char testNameString[80]; startMemoryUsage = ATS_GetFreeMemory(); ATS_begin("Arduino", "DelayTest"); testNum = 1; //* we start at 2 because 0/1 are RXD/TXD for (ii=0; ii<1000; ii+= 15) { startMillis = millis(); delay(ii); endMillis = millis(); deltaMillis = endMillis - startMillis; if (deltaMillis >= ii) { errMillis = deltaMillis - ii; } else { errMillis = ii - deltaMillis; } if (errMillis <= 1) { passed = true; } else { passed = false; } sprintf(testNameString, "DelayTest.%02d (delay= %4d actual delay=%ld err=%ld)", testNum, ii, deltaMillis, errMillis); ATS_PrintTestStatus(testNameString, passed); testNum++; } ATS_ReportMemoryUsage(startMemoryUsage); ATS_end(); } //************************************************************************ void loop() { } \ No newline at end of file +//************************************************************************ +//* Arduino Test Suite +//* ATS_ToneTest +//* +//* Copyright (c) 2010 Mark Sproul 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 +//************************************************************************ +//* Aug 31, 2010 Started on TestArduino +//* Oct 28, 2010 Started on Delay +//************************************************************************ + +#include + +//************************************************************************ +void setup() +{ +short ii; +short testNum; +int startMemoryUsage; +unsigned long startMillis; +unsigned long endMillis; +unsigned long deltaMillis; +unsigned long errMillis; +boolean passed; +char testNameString[80]; + + + startMemoryUsage = ATS_GetFreeMemory(); + + ATS_begin("Arduino", "DelayTest"); + + testNum = 1; + //* we start at 2 because 0/1 are RXD/TXD + for (ii=0; ii<1000; ii+= 15) + { + startMillis = millis(); + + delay(ii); + + endMillis = millis(); + + deltaMillis = endMillis - startMillis; + + if (deltaMillis >= ii) + { + errMillis = deltaMillis - ii; + } + else + { + errMillis = ii - deltaMillis; + } + + if (errMillis <= 1) + { + passed = true; + } + else + { + passed = false; + } + sprintf(testNameString, "DelayTest.%02d (delay= %4d actual delay=%ld err=%ld)", testNum, ii, deltaMillis, errMillis); + + ATS_PrintTestStatus(testNameString, passed); + + + testNum++; + } + + + + + ATS_ReportMemoryUsage(startMemoryUsage); + + ATS_end(); + +} + + +//************************************************************************ +void loop() +{ + + +} + + + + diff --git a/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.pde b/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.pde index 3c219bc13..588342dca 100644 --- a/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.pde +++ b/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.pde @@ -8,11 +8,7 @@ //* Oct 18, 2010 Added memory testing //************************************************************************ -#include "HardwareSerial.h" -#include "pins_arduino.h" #include -#include "avr_cpunames.h" - #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) #define kBoard_PinCount 20 @@ -20,6 +16,12 @@ #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define kBoard_PinCount 70 #define kBoard_AnalogCount 16 + +#elif defined(CORE_TEENSY) +#define kBoard_PinCount CORE_NUM_TOTAL_PINS +#define kBoard_AnalogCount CORE_NUM_ANALOG +#define SERIAL_PORT_COUNT 2 +HardwareSerial Serial1 = HardwareSerial(); #endif diff --git a/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.pde b/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.pde index e7fc4fa08..58ecaff6c 100644 --- a/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.pde +++ b/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.pde @@ -7,7 +7,6 @@ //* Oct 16, 2010 Started on String Test //************************************************************************ -#include "HardwareSerial.h" #include //************************************************************************ diff --git a/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.pde b/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.pde index 000976104..2de273ece 100644 --- a/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.pde +++ b/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.pde @@ -7,19 +7,12 @@ //* Oct 16, 2010 Started on String Test //************************************************************************ -#include "HardwareSerial.h" #include //************************************************************************ -void setup() + +void do_string_operations(int startMemoryUsage) { - char testName[64]; - int startMemoryUsage; - /* - * Create variable for the tests. - */ - - String stringOne; int firstClosingBracket; int firstOpeningBracket; @@ -31,67 +24,77 @@ void setup() int lastOpeningBracket; int lastListItem; int lastParagraph; - int secondLastGraf; - - /*; - * initiate the test run - */ - startMemoryUsage = ATS_GetFreeMemory(); - ATS_begin("Arduino", "String Memory Test"); - // indexOf() returns the position (i.e. index) of a particular character - // in a string. For example, if you were parsing HTML tags, you could use it: + int secondLastParagraph; + int thirdLastParagraph; + + // 1111111111 + // 01234567890123456789 stringOne = ""; firstClosingBracket = stringOne.indexOf('>'); - Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket); + ATS_PrintTestStatus("firstClosingBracket", firstClosingBracket == 5); + // 1111111111 + // 01234567890123456789 stringOne = ""; secondOpeningBracket = firstClosingBracket + 1; secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket ); - Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket); + ATS_PrintTestStatus("secondClosingBracket", secondClosingBracket == 11); // you can also use indexOf() to search for Strings: + // 1111111111 + // 01234567890123456789 stringOne = ""; bodyTag = stringOne.indexOf(""); - Serial.println("The index of the body tag in the string " + stringOne + " is " + bodyTag); + ATS_PrintTestStatus("bodyTag", bodyTag == 12); + // 111111111122222222223333333333 + // 0123456789012345678901234567890123456789 stringOne = "
  • item
  • item
  • item
"; firstListItem = stringOne.indexOf("
  • "); - secondListItem = stringOne.indexOf("item", firstListItem + 1 ); - Serial.println("The index of the second list item in the string " + stringOne + " is " + secondClosingBracket); + secondListItem = stringOne.indexOf("
  • ", firstListItem + 1 ); + + ATS_PrintTestStatus("firstListItem", firstListItem == 4); + ATS_PrintTestStatus("secondListItem", secondListItem == 12); // lastIndexOf() gives you the last occurrence of a character or string: lastOpeningBracket = stringOne.lastIndexOf('<'); - Serial.println("The index of the last < in the string " + stringOne + " is " + lastOpeningBracket); - + ATS_PrintTestStatus("lastOpeningBracket", lastOpeningBracket == 28); + lastListItem = stringOne.lastIndexOf("
  • "); - Serial.println("The index of the last list item in the string " + stringOne + " is " + lastListItem); - + ATS_PrintTestStatus("lastListItem", lastListItem == 20); // lastIndexOf() can also search for a string: + // 11111111112222222222333333333344444444445555555555 + // 012345678901234567890123456789012345678901234567890123456789 stringOne = "

    Lorem ipsum dolor sit amet

    Ipsem

    Quod

    "; lastParagraph = stringOne.lastIndexOf(" Started on String Test //************************************************************************ -#include "HardwareSerial.h" #include //************************************************************************ @@ -101,10 +100,14 @@ void setup() // or perhaps you want to ignore case: ATS_PrintTestStatus("11. EqualsIgnoreCase() method equals", stringOne.equalsIgnoreCase(stringTwo)); +#if ARDUINO < 100 || defined(CORE_TEENSY) +// David Mellis decided not to keep implicit string to number comparison operators +// in Arduino 1.0. Only run this test on older version, or if using Teensy // a numeric string compared to the number it represents: stringOne = "1"; int numberOne = 1; ATS_PrintTestStatus("12. A numeric string compared to the number it represents", stringOne == numberOne); +#endif // two numeric strings compared: stringOne = "2"; @@ -129,18 +132,18 @@ void setup() ATS_PrintTestStatus("18. The compareTo() operator also allows you to compare strings", stringOne.compareTo(stringTwo) < 0); + // These two tests assume the string compare parses numbers + // within strings, but it does not actually do any such thing // compareTo() String with numnber > String with number: - stringOne = "Sensor: 50"; - stringTwo= "Sensor: 150"; - ATS_PrintTestStatus("19. The compareTo() String with integers", stringOne.compareTo(stringTwo) < 0); - - + //stringOne = "Sensor: 50"; + //stringTwo= "Sensor: 150"; + //ATS_PrintTestStatus("19. The compareTo() String with integers", stringOne.compareTo(stringTwo) < 0); // compareTo() String with numnber > String with number append integer, matches example code: - stringOne = "Sensor: "; - stringTwo= "Sensor: "; - stringOne += 50; - stringTwo += 150; - ATS_PrintTestStatus("20. The compareTo() compare strings with appended integers", stringOne.compareTo(stringTwo) < 0); + //stringOne = "Sensor: "; + //stringTwo= "Sensor: "; + //stringOne += 50; + //stringTwo += 150; + //ATS_PrintTestStatus("20. The compareTo() compare strings with appended integers", stringOne.compareTo(stringTwo) < 0); /* diff --git a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.pde b/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.pde index 3c35627ba..fc611bb67 100644 --- a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.pde +++ b/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.pde @@ -1,18 +1,5 @@ #include - -void Test_Equal(char *testString, char *expected, const String &actual) -{ - char buf[100]; actual.toCharArray(buf, 100); - boolean b = (strcmp(buf, expected) == 0); - ATS_PrintTestStatus(testString, b); - if (!b) { - Serial.print("expected '"); - Serial.print(expected); - Serial.print("', actual '"); - Serial.print(actual); - Serial.println("'"); - } -} +#include "Test_Equal.h" void setup() { diff --git a/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.pde b/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.pde index b244081e5..195a3ca18 100644 --- a/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.pde +++ b/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.pde @@ -22,11 +22,7 @@ //* Oct 23, 2010 Started on ToneTest //************************************************************************ - - - - -#include "HardwareSerial.h" +#include #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) #define kBoard_PinCount 20 @@ -34,10 +30,11 @@ #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define kBoard_PinCount 70 #define kBoard_AnalogCount 16 +#elif defined(CORE_TEENSY) + #define kBoard_PinCount CORE_NUM_TOTAL_PINS + #define kBoard_AnalogCount CORE_NUM_ANALOG #endif -#include - //************************************************************************ void TestTonePin(uint8_t toneOutputPinNumber) { @@ -63,6 +60,7 @@ long deltaFreq; //* if its ODD helperpin = toneOutputPinNumber - 1; } + if (helperpin >= kBoard_PinCount) return; //* dont set the mode of the OUTPUT pin, the tone command does that @@ -143,6 +141,7 @@ long durationTime; //* if its ODD helperpin = toneOutputPinNumber - 1; } + if (helperpin >= kBoard_PinCount) return; //* dont set the mode of the OUTPUT pin, the tone command does that From 35777612c0ce0a3f28eb374574da40d35f6b9f97 Mon Sep 17 00:00:00 2001 From: Tom Igoe Date: Tue, 30 Aug 2011 15:33:32 -0400 Subject: [PATCH 18/29] Changed all .pde examples to .ino All examples in /build/shared/examples/ and /libraries/ have had their extensions changed to .ino --- .../AnalogReadSerial/AnalogReadSerial.ino | 15 ++ .../{BareMinimum.pde => BareMinimum.ino} | 0 .../1.Basics/Blink/{Blink.pde => Blink.ino} | 0 .../DigitalReadSerial/DigitalReadSerial.ino | 19 ++ .../1.Basics/Fade/{Fade.pde => Fade.ino} | 0 ...WithoutDelay.pde => BlinkWithoutDelay.ino} | 0 .../examples/2.Digital/Button/Button.ino | 56 +++++ .../examples/2.Digital/Debounce/Debounce.ino | 75 +++++++ .../StateChangeDetection.ino | 92 ++++++++ .../2.Digital/toneKeyboard/toneKeyboard.ino | 45 ++++ .../2.Digital/toneMelody/toneMelody.ino | 49 ++++ .../{toneMultiple.pde => toneMultiple.ino} | 0 .../tonePitchFollower/tonePitchFollower.ino | 46 ++++ .../AnalogInOutSerial/AnalogInOutSerial.ino | 53 +++++ .../3.Analog/AnalogInput/AnalogInput.ino | 50 +++++ ...nalogWriteMega.pde => AnalogWriteMega.ino} | 0 .../3.Analog/Calibration/Calibration.ino | 75 +++++++ .../examples/3.Analog/Fading/Fading.ino | 45 ++++ .../examples/3.Analog/Smoothing/Smoothing.ino | 67 ++++++ .../4.Communication/ASCIITable/ASCIITable.ino | 76 +++++++ .../4.Communication/Dimmer/Dimmer.ino | 112 ++++++++++ .../examples/4.Communication/Graph/Graph.ino | 149 +++++++++++++ .../examples/4.Communication/MIDI/Midi.ino | 49 ++++ ...ultiSerialMega.pde => MultiSerialMega.ino} | 0 .../PhysicalPixel/PhysicalPixel.ino | 170 ++++++++++++++ .../SerialCallResponse/SerialCallResponse.ino | 211 ++++++++++++++++++ .../SerialCallResponseASCII.ino | 211 ++++++++++++++++++ .../VirtualColorMixer/VirtualColorMixer.ino | 130 +++++++++++ .../examples/5.Control/Arrays/Arrays.ino | 57 +++++ .../ForLoopIteration/ForLoopIteration.ino | 47 ++++ .../IfStatementConditional.ino | 56 +++++ .../WhileStatementConditional.ino | 88 ++++++++ .../5.Control/switchCase/switchCase.ino | 62 +++++ .../{switchCase2.pde => switchCase2.ino} | 0 .../examples/6.Sensors/ADXL3xx/ADXL3xx.ino | 64 ++++++ .../shared/examples/6.Sensors/Knock/Knock.ino | 55 +++++ .../6.Sensors/Memsic2125/Memsic2125.ino | 63 ++++++ build/shared/examples/6.Sensors/Ping/Ping.ino | 84 +++++++ .../RowColumnScanning/RowColumnScanning.ino | 114 ++++++++++ .../barGraph/{barGraph.pde => barGraph.ino} | 0 ...cterAnalysis.pde => CharacterAnalysis.ino} | 0 .../StringAdditionOperator.ino | 61 +++++ .../StringAppendOperator.ino | 64 ++++++ ...gCaseChanges.pde => StringCaseChanges.ino} | 0 ...ingCharacters.pde => StringCharacters.ino} | 0 .../StringComparisonOperators.ino | 124 ++++++++++ .../StringConstructors/StringConstructors.ino | 64 ++++++ .../{StringIndexOf.pde => StringIndexOf.ino} | 0 .../{StringLength.pde => StringLength.ino} | 0 ...ingLengthTrim.pde => StringLengthTrim.ino} | 0 .../{StringReplace.pde => StringReplace.ino} | 0 .../StringStartsWithEndsWith.ino | 49 ++++ ...tringSubstring.pde => StringSubstring.ino} | 0 .../{StringToInt.pde => StringToInt.ino} | 0 ...{StringToIntRGB.pde => StringToIntRGB.ino} | 0 .../{ArduinoISP.pde => ArduinoISP.ino} | 0 .../{ATS_Constants.pde => ATS_Constants.ino} | 0 .../{ATS_Delay.pde => ATS_Delay.ino} | 0 .../{ATS_General.pde => ATS_General.ino} | 0 .../{ATS_SD_File.pde => ATS_SD_File.ino} | 0 .../{ATS_SD_Files.pde => ATS_SD_Files.ino} | 0 .../{ATS_SD_Seek.pde => ATS_SD_Seek.ino} | 0 .../{ATS_Skeleton.pde => ATS_Skeleton.ino} | 0 ...Memory.pde => ATS_StringIndexOfMemory.ino} | 0 ...{ATS_StringTest.pde => ATS_StringTest.ino} | 0 ...g_Addition.pde => ATS_String_Addition.ino} | 0 .../{ATS_ToneTest.pde => ATS_ToneTest.ino} | 0 .../{eeprom_clear.pde => eeprom_clear.ino} | 0 .../{eeprom_read.pde => eeprom_read.ino} | 0 .../{eeprom_write.pde => eeprom_write.ino} | 0 ...er.pde => BarometricPressureWebServer.ino} | 0 .../{ChatServer.pde => ChatServer.ino} | 0 .../DhcpAddressPrinter/DhcpAddressPrinter.ino | 7 +- .../DhcpAddressPrinter/DhcpAddressPrinter.pde | 53 ----- .../{DnsWebClient.pde => DnsWebClient.ino} | 0 .../{PachubeClient.pde => PachubeClient.ino} | 0 ...ientString.pde => PachubeClientString.ino} | 0 .../{TelnetClient.pde => TelnetClient.ino} | 0 ...iveString.pde => UDPSendReceiveString.ino} | 0 .../{UdpNtpClient.pde => UdpNtpClient.ino} | 0 .../{WebClient.pde => WebClient.ino} | 0 .../{WebServer.pde => WebServer.ino} | 0 ...InputsFirmata.pde => AllInputsFirmata.ino} | 0 .../{AnalogFirmata.pde => AnalogFirmata.ino} | 0 .../{EchoString.pde => EchoString.ino} | 0 .../{I2CFirmata.pde => I2CFirmata.ino} | 0 ...dardFirmata.pde => OldStandardFirmata.ino} | 0 .../{ServoFirmata.pde => ServoFirmata.ino} | 0 ...logFirmata.pde => SimpleAnalogFirmata.ino} | 0 ...alFirmata.pde => SimpleDigitalFirmata.ino} | 0 ...tandardFirmata.pde => StandardFirmata.ino} | 0 ...pde => StandardFirmata_2_2_forUNO_0_3.ino} | 0 .../{Autoscroll.pde => Autoscroll.ino} | 0 .../examples/Blink/{Blink.pde => Blink.ino} | 0 .../Cursor/{Cursor.pde => Cursor.ino} | 0 ...ustomCharacter.pde => CustomCharacter.ino} | 0 .../Display/{Display.pde => Display.ino} | 0 .../{HelloWorld.pde => HelloWorld.ino} | 0 .../Scroll/{Scroll.pde => Scroll.ino} | 0 .../{SerialDisplay.pde => SerialDisplay.ino} | 0 .../{TextDirection.pde => TextDirection.ino} | 0 .../{setCursor.pde => setCursor.ino} | 0 .../CardInfo/{CardInfo.pde => CardInfo.ino} | 0 .../{Datalogger.pde => Datalogger.ino} | 0 .../DumpFile/{DumpFile.pde => DumpFile.ino} | 0 .../examples/Files/{Files.pde => Files.ino} | 0 .../{ReadWrite.pde => ReadWrite.ino} | 0 .../{listfiles.pde => listfiles.ino} | 0 ...ensor.pde => BarometricPressureSensor.ino} | 0 ...ensor.pde => BarometricPressureSensor.ino} | 0 ...alPotControl.pde => DigitalPotControl.ino} | 0 .../examples/Knob/{Knob.pde => Knob.ino} | 0 .../examples/Sweep/{Sweep.pde => Sweep.ino} | 0 ...PortRXExample.pde => TwoPortRXExample.ino} | 0 .../{MotorKnob.pde => MotorKnob.ino} | 0 ...volution.pde => stepper_oneRevolution.ino} | 0 ...AtATime.pde => stepper_oneStepAtATime.ino} | 0 ...edControl.pde => stepper_speedControl.ino} | 0 ...Ranger_reader.pde => SFRRanger_reader.ino} | 0 ...tiometer.pde => digital_potentiometer.ino} | 0 .../{master_reader.pde => master_reader.ino} | 0 .../{master_writer.pde => master_writer.ino} | 0 ...{slave_receiver.pde => slave_receiver.ino} | 0 .../{slave_sender.pde => slave_sender.ino} | 0 124 files changed, 2850 insertions(+), 57 deletions(-) create mode 100644 build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.ino rename build/shared/examples/1.Basics/BareMinimum/{BareMinimum.pde => BareMinimum.ino} (100%) rename build/shared/examples/1.Basics/Blink/{Blink.pde => Blink.ino} (100%) create mode 100644 build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.ino rename build/shared/examples/1.Basics/Fade/{Fade.pde => Fade.ino} (100%) rename build/shared/examples/2.Digital/BlinkWithoutDelay/{BlinkWithoutDelay.pde => BlinkWithoutDelay.ino} (100%) create mode 100644 build/shared/examples/2.Digital/Button/Button.ino create mode 100644 build/shared/examples/2.Digital/Debounce/Debounce.ino create mode 100644 build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.ino create mode 100644 build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.ino create mode 100644 build/shared/examples/2.Digital/toneMelody/toneMelody.ino rename build/shared/examples/2.Digital/toneMultiple/{toneMultiple.pde => toneMultiple.ino} (100%) create mode 100644 build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.ino create mode 100644 build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.ino create mode 100644 build/shared/examples/3.Analog/AnalogInput/AnalogInput.ino rename build/shared/examples/3.Analog/AnalogWriteMega/{AnalogWriteMega.pde => AnalogWriteMega.ino} (100%) create mode 100644 build/shared/examples/3.Analog/Calibration/Calibration.ino create mode 100644 build/shared/examples/3.Analog/Fading/Fading.ino create mode 100644 build/shared/examples/3.Analog/Smoothing/Smoothing.ino create mode 100644 build/shared/examples/4.Communication/ASCIITable/ASCIITable.ino create mode 100644 build/shared/examples/4.Communication/Dimmer/Dimmer.ino create mode 100644 build/shared/examples/4.Communication/Graph/Graph.ino create mode 100644 build/shared/examples/4.Communication/MIDI/Midi.ino rename build/shared/examples/4.Communication/MultiSerialMega/{MultiSerialMega.pde => MultiSerialMega.ino} (100%) create mode 100644 build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.ino create mode 100644 build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.ino create mode 100644 build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino create mode 100644 build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.ino create mode 100644 build/shared/examples/5.Control/Arrays/Arrays.ino create mode 100644 build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.ino create mode 100644 build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.ino create mode 100644 build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.ino create mode 100644 build/shared/examples/5.Control/switchCase/switchCase.ino rename build/shared/examples/5.Control/switchCase2/{switchCase2.pde => switchCase2.ino} (100%) create mode 100644 build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.ino create mode 100644 build/shared/examples/6.Sensors/Knock/Knock.ino create mode 100644 build/shared/examples/6.Sensors/Memsic2125/Memsic2125.ino create mode 100644 build/shared/examples/6.Sensors/Ping/Ping.ino create mode 100644 build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.ino rename build/shared/examples/7.Display/barGraph/{barGraph.pde => barGraph.ino} (100%) rename build/shared/examples/8.Strings/CharacterAnalysis/{CharacterAnalysis.pde => CharacterAnalysis.ino} (100%) create mode 100644 build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.ino create mode 100644 build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.ino rename build/shared/examples/8.Strings/StringCaseChanges/{StringCaseChanges.pde => StringCaseChanges.ino} (100%) rename build/shared/examples/8.Strings/StringCharacters/{StringCharacters.pde => StringCharacters.ino} (100%) create mode 100644 build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.ino create mode 100644 build/shared/examples/8.Strings/StringConstructors/StringConstructors.ino rename build/shared/examples/8.Strings/StringIndexOf/{StringIndexOf.pde => StringIndexOf.ino} (100%) rename build/shared/examples/8.Strings/StringLength/{StringLength.pde => StringLength.ino} (100%) rename build/shared/examples/8.Strings/StringLengthTrim/{StringLengthTrim.pde => StringLengthTrim.ino} (100%) rename build/shared/examples/8.Strings/StringReplace/{StringReplace.pde => StringReplace.ino} (100%) create mode 100644 build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino rename build/shared/examples/8.Strings/StringSubstring/{StringSubstring.pde => StringSubstring.ino} (100%) rename build/shared/examples/8.Strings/StringToInt/{StringToInt.pde => StringToInt.ino} (100%) rename build/shared/examples/8.Strings/StringToIntRGB/{StringToIntRGB.pde => StringToIntRGB.ino} (100%) rename build/shared/examples/ArduinoISP/{ArduinoISP.pde => ArduinoISP.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_Constants/{ATS_Constants.pde => ATS_Constants.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_Delay/{ATS_Delay.pde => ATS_Delay.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_General/{ATS_General.pde => ATS_General.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_SD_File/{ATS_SD_File.pde => ATS_SD_File.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_SD_Files/{ATS_SD_Files.pde => ATS_SD_Files.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_SD_Seek/{ATS_SD_Seek.pde => ATS_SD_Seek.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_Skeleton/{ATS_Skeleton.pde => ATS_Skeleton.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/{ATS_StringIndexOfMemory.pde => ATS_StringIndexOfMemory.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_StringTest/{ATS_StringTest.pde => ATS_StringTest.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_String_Addition/{ATS_String_Addition.pde => ATS_String_Addition.ino} (100%) rename libraries/ArduinoTestSuite/examples/ATS_ToneTest/{ATS_ToneTest.pde => ATS_ToneTest.ino} (100%) rename libraries/EEPROM/examples/eeprom_clear/{eeprom_clear.pde => eeprom_clear.ino} (100%) rename libraries/EEPROM/examples/eeprom_read/{eeprom_read.pde => eeprom_read.ino} (100%) rename libraries/EEPROM/examples/eeprom_write/{eeprom_write.pde => eeprom_write.ino} (100%) rename libraries/Ethernet/examples/BarometricPressureWebServer/{BarometricPressureWebServer.pde => BarometricPressureWebServer.ino} (100%) rename libraries/Ethernet/examples/ChatServer/{ChatServer.pde => ChatServer.ino} (100%) delete mode 100644 libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.pde rename libraries/Ethernet/examples/DnsWebClient/{DnsWebClient.pde => DnsWebClient.ino} (100%) rename libraries/Ethernet/examples/PachubeClient/{PachubeClient.pde => PachubeClient.ino} (100%) rename libraries/Ethernet/examples/PachubeClientString/{PachubeClientString.pde => PachubeClientString.ino} (100%) rename libraries/Ethernet/examples/TelnetClient/{TelnetClient.pde => TelnetClient.ino} (100%) rename libraries/Ethernet/examples/UDPSendReceiveString/{UDPSendReceiveString.pde => UDPSendReceiveString.ino} (100%) rename libraries/Ethernet/examples/UdpNtpClient/{UdpNtpClient.pde => UdpNtpClient.ino} (100%) rename libraries/Ethernet/examples/WebClient/{WebClient.pde => WebClient.ino} (100%) rename libraries/Ethernet/examples/WebServer/{WebServer.pde => WebServer.ino} (100%) rename libraries/Firmata/examples/AllInputsFirmata/{AllInputsFirmata.pde => AllInputsFirmata.ino} (100%) rename libraries/Firmata/examples/AnalogFirmata/{AnalogFirmata.pde => AnalogFirmata.ino} (100%) rename libraries/Firmata/examples/EchoString/{EchoString.pde => EchoString.ino} (100%) rename libraries/Firmata/examples/I2CFirmata/{I2CFirmata.pde => I2CFirmata.ino} (100%) rename libraries/Firmata/examples/OldStandardFirmata/{OldStandardFirmata.pde => OldStandardFirmata.ino} (100%) rename libraries/Firmata/examples/ServoFirmata/{ServoFirmata.pde => ServoFirmata.ino} (100%) rename libraries/Firmata/examples/SimpleAnalogFirmata/{SimpleAnalogFirmata.pde => SimpleAnalogFirmata.ino} (100%) rename libraries/Firmata/examples/SimpleDigitalFirmata/{SimpleDigitalFirmata.pde => SimpleDigitalFirmata.ino} (100%) rename libraries/Firmata/examples/StandardFirmata/{StandardFirmata.pde => StandardFirmata.ino} (100%) rename libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/{StandardFirmata_2_2_forUNO_0_3.pde => StandardFirmata_2_2_forUNO_0_3.ino} (100%) rename libraries/LiquidCrystal/examples/Autoscroll/{Autoscroll.pde => Autoscroll.ino} (100%) rename libraries/LiquidCrystal/examples/Blink/{Blink.pde => Blink.ino} (100%) rename libraries/LiquidCrystal/examples/Cursor/{Cursor.pde => Cursor.ino} (100%) rename libraries/LiquidCrystal/examples/CustomCharacter/{CustomCharacter.pde => CustomCharacter.ino} (100%) rename libraries/LiquidCrystal/examples/Display/{Display.pde => Display.ino} (100%) rename libraries/LiquidCrystal/examples/HelloWorld/{HelloWorld.pde => HelloWorld.ino} (100%) rename libraries/LiquidCrystal/examples/Scroll/{Scroll.pde => Scroll.ino} (100%) rename libraries/LiquidCrystal/examples/SerialDisplay/{SerialDisplay.pde => SerialDisplay.ino} (100%) rename libraries/LiquidCrystal/examples/TextDirection/{TextDirection.pde => TextDirection.ino} (100%) rename libraries/LiquidCrystal/examples/setCursor/{setCursor.pde => setCursor.ino} (100%) rename libraries/SD/examples/CardInfo/{CardInfo.pde => CardInfo.ino} (100%) rename libraries/SD/examples/Datalogger/{Datalogger.pde => Datalogger.ino} (100%) rename libraries/SD/examples/DumpFile/{DumpFile.pde => DumpFile.ino} (100%) rename libraries/SD/examples/Files/{Files.pde => Files.ino} (100%) rename libraries/SD/examples/ReadWrite/{ReadWrite.pde => ReadWrite.ino} (100%) rename libraries/SD/examples/listfiles/{listfiles.pde => listfiles.ino} (100%) rename libraries/SPI/examples/BarometricPressureSensor/{BarometricPressureSensor.pde => BarometricPressureSensor.ino} (100%) rename libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/{BarometricPressureSensor.pde => BarometricPressureSensor.ino} (100%) rename libraries/SPI/examples/DigitalPotControl/{DigitalPotControl.pde => DigitalPotControl.ino} (100%) rename libraries/Servo/examples/Knob/{Knob.pde => Knob.ino} (100%) rename libraries/Servo/examples/Sweep/{Sweep.pde => Sweep.ino} (100%) rename libraries/SoftwareSerial/examples/TwoPortRXExample/{TwoPortRXExample.pde => TwoPortRXExample.ino} (100%) rename libraries/Stepper/examples/MotorKnob/{MotorKnob.pde => MotorKnob.ino} (100%) rename libraries/Stepper/examples/stepper_oneRevolution/{stepper_oneRevolution.pde => stepper_oneRevolution.ino} (100%) rename libraries/Stepper/examples/stepper_oneStepAtATime/{stepper_oneStepAtATime.pde => stepper_oneStepAtATime.ino} (100%) rename libraries/Stepper/examples/stepper_speedControl/{stepper_speedControl.pde => stepper_speedControl.ino} (100%) rename libraries/Wire/examples/SFRRanger_reader/{SFRRanger_reader.pde => SFRRanger_reader.ino} (100%) rename libraries/Wire/examples/digital_potentiometer/{digital_potentiometer.pde => digital_potentiometer.ino} (100%) rename libraries/Wire/examples/master_reader/{master_reader.pde => master_reader.ino} (100%) rename libraries/Wire/examples/master_writer/{master_writer.pde => master_writer.ino} (100%) rename libraries/Wire/examples/slave_receiver/{slave_receiver.pde => slave_receiver.ino} (100%) rename libraries/Wire/examples/slave_sender/{slave_sender.pde => slave_sender.ino} (100%) diff --git a/build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.ino b/build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.ino new file mode 100644 index 000000000..2ba6fa73b --- /dev/null +++ b/build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.ino @@ -0,0 +1,15 @@ +/* + AnalogReadSerial + Reads an analog input on pin 0, prints the result to the serial monitor + + This example code is in the public domain. + */ + +void setup() { + Serial.begin(9600); +} + +void loop() { + int sensorValue = analogRead(A0); + Serial.println(sensorValue); +} diff --git a/build/shared/examples/1.Basics/BareMinimum/BareMinimum.pde b/build/shared/examples/1.Basics/BareMinimum/BareMinimum.ino similarity index 100% rename from build/shared/examples/1.Basics/BareMinimum/BareMinimum.pde rename to build/shared/examples/1.Basics/BareMinimum/BareMinimum.ino diff --git a/build/shared/examples/1.Basics/Blink/Blink.pde b/build/shared/examples/1.Basics/Blink/Blink.ino similarity index 100% rename from build/shared/examples/1.Basics/Blink/Blink.pde rename to build/shared/examples/1.Basics/Blink/Blink.ino diff --git a/build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.ino b/build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.ino new file mode 100644 index 000000000..68e4dc966 --- /dev/null +++ b/build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.ino @@ -0,0 +1,19 @@ +/* + DigitalReadSerial + Reads a digital input on pin 2, prints the result to the serial monitor + + This example code is in the public domain. + */ + +void setup() { + Serial.begin(9600); + pinMode(2, INPUT); +} + +void loop() { + int sensorValue = digitalRead(2); + Serial.println(sensorValue); +} + + + diff --git a/build/shared/examples/1.Basics/Fade/Fade.pde b/build/shared/examples/1.Basics/Fade/Fade.ino similarity index 100% rename from build/shared/examples/1.Basics/Fade/Fade.pde rename to build/shared/examples/1.Basics/Fade/Fade.ino diff --git a/build/shared/examples/2.Digital/BlinkWithoutDelay/BlinkWithoutDelay.pde b/build/shared/examples/2.Digital/BlinkWithoutDelay/BlinkWithoutDelay.ino similarity index 100% rename from build/shared/examples/2.Digital/BlinkWithoutDelay/BlinkWithoutDelay.pde rename to build/shared/examples/2.Digital/BlinkWithoutDelay/BlinkWithoutDelay.ino diff --git a/build/shared/examples/2.Digital/Button/Button.ino b/build/shared/examples/2.Digital/Button/Button.ino new file mode 100644 index 000000000..e019fca31 --- /dev/null +++ b/build/shared/examples/2.Digital/Button/Button.ino @@ -0,0 +1,56 @@ +/* + Button + + Turns on and off a light emitting diode(LED) connected to digital + pin 13, when pressing a pushbutton attached to pin 2. + + + The circuit: + * LED attached from pin 13 to ground + * pushbutton attached to pin 2 from +5V + * 10K resistor attached to pin 2 from ground + + * Note: on most Arduinos there is already an LED on the board + attached to pin 13. + + + created 2005 + by DojoDave + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Button + */ + +// constants won't change. They're used here to +// set pin numbers: +const int buttonPin = 2; // the number of the pushbutton pin +const int ledPin = 13; // the number of the LED pin + +// variables will change: +int buttonState = 0; // variable for reading the pushbutton status + +void setup() { + // initialize the LED pin as an output: + pinMode(ledPin, OUTPUT); + // initialize the pushbutton pin as an input: + pinMode(buttonPin, INPUT); +} + +void loop(){ + // read the state of the pushbutton value: + buttonState = digitalRead(buttonPin); + + // check if the pushbutton is pressed. + // if it is, the buttonState is HIGH: + if (buttonState == HIGH) { + // turn LED on: + digitalWrite(ledPin, HIGH); + } + else { + // turn LED off: + digitalWrite(ledPin, LOW); + } +} \ No newline at end of file diff --git a/build/shared/examples/2.Digital/Debounce/Debounce.ino b/build/shared/examples/2.Digital/Debounce/Debounce.ino new file mode 100644 index 000000000..89416b269 --- /dev/null +++ b/build/shared/examples/2.Digital/Debounce/Debounce.ino @@ -0,0 +1,75 @@ +/* + Debounce + + Each time the input pin goes from LOW to HIGH (e.g. because of a push-button + press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's + a minimum delay between toggles to debounce the circuit (i.e. to ignore + noise). + + The circuit: + * LED attached from pin 13 to ground + * pushbutton attached from pin 2 to +5V + * 10K resistor attached from pin 2 to ground + + * Note: On most Arduino boards, there is already an LED on the board + connected to pin 13, so you don't need any extra components for this example. + + + created 21 November 2006 + by David A. Mellis + modified 30 Aug 2011 + by Limor Fried + +This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Debounce + */ + +// constants won't change. They're used here to +// set pin numbers: +const int buttonPin = 2; // the number of the pushbutton pin +const int ledPin = 13; // the number of the LED pin + +// Variables will change: +int ledState = HIGH; // the current state of the output pin +int buttonState; // the current reading from the input pin +int lastButtonState = LOW; // the previous reading from the input pin + +// the following variables are long's because the time, measured in miliseconds, +// will quickly become a bigger number than can be stored in an int. +long lastDebounceTime = 0; // the last time the output pin was toggled +long debounceDelay = 50; // the debounce time; increase if the output flickers + +void setup() { + pinMode(buttonPin, INPUT); + pinMode(ledPin, OUTPUT); +} + +void loop() { + // read the state of the switch into a local variable: + int reading = digitalRead(buttonPin); + + // check to see if you just pressed the button + // (i.e. the input went from LOW to HIGH), and you've waited + // long enough since the last press to ignore any noise: + + // If the switch changed, due to noise or pressing: + if (reading != lastButtonState) { + // reset the debouncing timer + lastDebounceTime = millis(); + } + + if ((millis() - lastDebounceTime) > debounceDelay) { + // whatever the reading is at, it's been there for longer + // than the debounce delay, so take it as the actual current state: + buttonState = reading; + } + + // set the LED using the state of the button: + digitalWrite(ledPin, buttonState); + + // save the reading. Next time through the loop, + // it'll be the lastButtonState: + lastButtonState = reading; +} + diff --git a/build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.ino b/build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.ino new file mode 100644 index 000000000..30bb3c405 --- /dev/null +++ b/build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.ino @@ -0,0 +1,92 @@ +/* + State change detection (edge detection) + + Often, you don't need to know the state of a digital input all the time, + but you just need to know when the input changes from one state to another. + For example, you want to know when a button goes from OFF to ON. This is called + state change detection, or edge detection. + + This example shows how to detect when a button or button changes from off to on + and on to off. + + The circuit: + * pushbutton attached to pin 2 from +5V + * 10K resistor attached to pin 2 from ground + * LED attached from pin 13 to ground (or use the built-in LED on + most Arduino boards) + + created 27 Sep 2005 + modified 30 Aug 2011 + by Tom Igoe + +This example code is in the public domain. + + http://arduino.cc/en/Tutorial/ButtonStateChange + + */ + +// this constant won't change: +const int buttonPin = 2; // the pin that the pushbutton is attached to +const int ledPin = 13; // the pin that the LED is attached to + +// Variables will change: +int buttonPushCounter = 0; // counter for the number of button presses +int buttonState = 0; // current state of the button +int lastButtonState = 0; // previous state of the button + +void setup() { + // initialize the button pin as a input: + pinMode(buttonPin, INPUT); + // initialize the LED as an output: + pinMode(ledPin, OUTPUT); + // initialize serial communication: + Serial.begin(9600); +} + + +void loop() { + // read the pushbutton input pin: + buttonState = digitalRead(buttonPin); + + // compare the buttonState to its previous state + if (buttonState != lastButtonState) { + // if the state has changed, increment the counter + if (buttonState == HIGH) { + // if the current state is HIGH then the button + // wend from off to on: + buttonPushCounter++; + Serial.println("on"); + Serial.print("number of button pushes: "); + Serial.println(buttonPushCounter); + } + else { + // if the current state is LOW then the button + // wend from on to off: + Serial.println("off"); + } + } + // save the current state as the last state, + //for next time through the loop + lastButtonState = buttonState; + + + // turns on the LED every four button pushes by + // checking the modulo of the button push counter. + // the modulo function gives you the remainder of + // the division of two numbers: + if (buttonPushCounter % 4 == 0) { + digitalWrite(ledPin, HIGH); + } else { + digitalWrite(ledPin, LOW); + } + +} + + + + + + + + + diff --git a/build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.ino b/build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.ino new file mode 100644 index 000000000..9decdd752 --- /dev/null +++ b/build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.ino @@ -0,0 +1,45 @@ +/* + keyboard + + Plays a pitch that changes based on a changing analog input + + circuit: + * 3 force-sensing resistors from +5V to analog in 0 through 5 + * 3 10K resistors from analog in 0 through 5 to ground + * 8-ohm speaker on digital pin 8 + + created 21 Jan 2010 + modified 30 Aug 2011 + by Tom Igoe + +This example code is in the public domain. + + http://arduino.cc/en/Tutorial/Tone3 + + */ + +#include "pitches.h" + +const int threshold = 10; // minimum reading of the sensors that generates a note + +// notes to play, corresponding to the 3 sensors: +int notes[] = { + NOTE_A4, NOTE_B4,NOTE_C3 }; + +void setup() { + +} + +void loop() { + for (int thisSensor = 0; thisSensor < 3; thisSensor++) { + // get a sensor reading: + int sensorReading = analogRead(thisSensor); + + // if the sensor is pressed hard enough: + if (sensorReading > threshold) { + // play the note corresponding to this sensor: + tone(8, notes[thisSensor], 20); + } + } + Serial.println(); +} diff --git a/build/shared/examples/2.Digital/toneMelody/toneMelody.ino b/build/shared/examples/2.Digital/toneMelody/toneMelody.ino new file mode 100644 index 000000000..8593ab770 --- /dev/null +++ b/build/shared/examples/2.Digital/toneMelody/toneMelody.ino @@ -0,0 +1,49 @@ +/* + Melody + + Plays a melody + + circuit: + * 8-ohm speaker on digital pin 8 + + created 21 Jan 2010 + modified 30 Aug 2011 + by Tom Igoe + +This example code is in the public domain. + + http://arduino.cc/en/Tutorial/Tone + + */ + #include "pitches.h" + +// notes in the melody: +int melody[] = { + NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4}; + +// note durations: 4 = quarter note, 8 = eighth note, etc.: +int noteDurations[] = { + 4, 8, 8, 4,4,4,4,4 }; + +void setup() { + // iterate over the notes of the melody: + for (int thisNote = 0; thisNote < 8; thisNote++) { + + // to calculate the note duration, take one second + // divided by the note type. + //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. + int noteDuration = 1000/noteDurations[thisNote]; + tone(8, melody[thisNote],noteDuration); + + // to distinguish the notes, set a minimum time between them. + // the note's duration + 30% seems to work well: + int pauseBetweenNotes = noteDuration * 1.30; + delay(pauseBetweenNotes); + // stop the tone playing: + noTone(8); + } +} + +void loop() { + // no need to repeat the melody. +} diff --git a/build/shared/examples/2.Digital/toneMultiple/toneMultiple.pde b/build/shared/examples/2.Digital/toneMultiple/toneMultiple.ino similarity index 100% rename from build/shared/examples/2.Digital/toneMultiple/toneMultiple.pde rename to build/shared/examples/2.Digital/toneMultiple/toneMultiple.ino diff --git a/build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.ino b/build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.ino new file mode 100644 index 000000000..beb28b2bd --- /dev/null +++ b/build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.ino @@ -0,0 +1,46 @@ +/* + Pitch follower + + Plays a pitch that changes based on a changing analog input + + circuit: + * 8-ohm speaker on digital pin 8 + * photoresistor on analog 0 to 5V + * 4.7K resistor on analog 0 to ground + + created 21 Jan 2010 + modified 30 Aug 2011 + by Tom Igoe + +This example code is in the public domain. + + http://arduino.cc/en/Tutorial/Tone2 + + */ + + +void setup() { + // initialize serial communications (for debugging only): + Serial.begin(9600); +} + +void loop() { + // read the sensor: + int sensorReading = analogRead(A0); + // print the sensor reading so you know its range + Serial.println(sensorReading); + // map the pitch to the range of the analog input. + // change the minimum and maximum input numbers below + // depending on the range your sensor's giving: + int thisPitch = map(sensorReading, 400, 1000, 100, 1000); + + // play the pitch: + tone(9, thisPitch, 10); + +} + + + + + + diff --git a/build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.ino b/build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.ino new file mode 100644 index 000000000..e142f690e --- /dev/null +++ b/build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.ino @@ -0,0 +1,53 @@ +/* + Analog input, analog output, serial output + + Reads an analog input pin, maps the result to a range from 0 to 255 + and uses the result to set the pulsewidth modulation (PWM) of an output pin. + Also prints the results to the serial monitor. + + The circuit: + * potentiometer connected to analog pin 0. + Center pin of the potentiometer goes to the analog pin. + side pins of the potentiometer go to +5V and ground + * LED connected from digital pin 9 to ground + + created 29 Dec. 2008 + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + */ + +// These constants won't change. They're used to give names +// to the pins used: +const int analogInPin = A0; // Analog input pin that the potentiometer is attached to +const int analogOutPin = 9; // Analog output pin that the LED is attached to + +int sensorValue = 0; // value read from the pot +int outputValue = 0; // value output to the PWM (analog out) + +void setup() { + // initialize serial communications at 9600 bps: + Serial.begin(9600); +} + +void loop() { + // read the analog in value: + sensorValue = analogRead(analogInPin); + // map it to the range of the analog out: + outputValue = map(sensorValue, 0, 1023, 0, 255); + // change the analog out value: + analogWrite(analogOutPin, outputValue); + + // print the results to the serial monitor: + Serial.print("sensor = " ); + Serial.print(sensorValue); + Serial.print("\t output = "); + Serial.println(outputValue); + + // wait 10 milliseconds before the next loop + // for the analog-to-digital converter to settle + // after the last reading: + delay(10); +} diff --git a/build/shared/examples/3.Analog/AnalogInput/AnalogInput.ino b/build/shared/examples/3.Analog/AnalogInput/AnalogInput.ino new file mode 100644 index 000000000..5d685883b --- /dev/null +++ b/build/shared/examples/3.Analog/AnalogInput/AnalogInput.ino @@ -0,0 +1,50 @@ +/* + Analog Input + Demonstrates analog input by reading an analog sensor on analog pin 0 and + turning on and off a light emitting diode(LED) connected to digital pin 13. + The amount of time the LED will be on and off depends on + the value obtained by analogRead(). + + The circuit: + * Potentiometer attached to analog input 0 + * center pin of the potentiometer to the analog pin + * one side pin (either one) to ground + * the other side pin to +5V + * LED anode (long leg) attached to digital output 13 + * LED cathode (short leg) attached to ground + + * Note: because most Arduinos have a built-in LED attached + to pin 13 on the board, the LED is optional. + + + Created by David Cuartielles + modified 30 Aug 2011 + By Tom Igoe + + This example code is in the public domain. + + http://arduino.cc/en/Tutorial/AnalogInput + + */ + +int sensorPin = A0; // select the input pin for the potentiometer +int ledPin = 13; // select the pin for the LED +int sensorValue = 0; // variable to store the value coming from the sensor + +void setup() { + // declare the ledPin as an OUTPUT: + pinMode(ledPin, OUTPUT); +} + +void loop() { + // read the value from the sensor: + sensorValue = analogRead(sensorPin); + // turn the ledPin on + digitalWrite(ledPin, HIGH); + // stop the program for milliseconds: + delay(sensorValue); + // turn the ledPin off: + digitalWrite(ledPin, LOW); + // stop the program for for milliseconds: + delay(sensorValue); +} \ No newline at end of file diff --git a/build/shared/examples/3.Analog/AnalogWriteMega/AnalogWriteMega.pde b/build/shared/examples/3.Analog/AnalogWriteMega/AnalogWriteMega.ino similarity index 100% rename from build/shared/examples/3.Analog/AnalogWriteMega/AnalogWriteMega.pde rename to build/shared/examples/3.Analog/AnalogWriteMega/AnalogWriteMega.ino diff --git a/build/shared/examples/3.Analog/Calibration/Calibration.ino b/build/shared/examples/3.Analog/Calibration/Calibration.ino new file mode 100644 index 000000000..c3f88fdf0 --- /dev/null +++ b/build/shared/examples/3.Analog/Calibration/Calibration.ino @@ -0,0 +1,75 @@ +/* + Calibration + + Demonstrates one technique for calibrating sensor input. The + sensor readings during the first five seconds of the sketch + execution define the minimum and maximum of expected values + attached to the sensor pin. + + The sensor minimum and maximum initial values may seem backwards. + Initially, you set the minimum high and listen for anything + lower, saving it as the new minimum. Likewise, you set the + maximum low and listen for anything higher as the new maximum. + + The circuit: + * Analog sensor (potentiometer will do) attached to analog input 0 + * LED attached from digital pin 9 to ground + + created 29 Oct 2008 + By David A Mellis + modified 30 Aug 2011 + By Tom Igoe + + http://arduino.cc/en/Tutorial/Calibration + + This example code is in the public domain. + + */ + +// These constants won't change: +const int sensorPin = A0; // pin that the sensor is attached to +const int ledPin = 9; // pin that the LED is attached to + +// variables: +int sensorValue = 0; // the sensor value +int sensorMin = 1023; // minimum sensor value +int sensorMax = 0; // maximum sensor value + + +void setup() { + // turn on LED to signal the start of the calibration period: + pinMode(13, OUTPUT); + digitalWrite(13, HIGH); + + // calibrate during the first five seconds + while (millis() < 5000) { + sensorValue = analogRead(sensorPin); + + // record the maximum sensor value + if (sensorValue > sensorMax) { + sensorMax = sensorValue; + } + + // record the minimum sensor value + if (sensorValue < sensorMin) { + sensorMin = sensorValue; + } + } + + // signal the end of the calibration period + digitalWrite(13, LOW); +} + +void loop() { + // read the sensor: + sensorValue = analogRead(sensorPin); + + // apply the calibration to the sensor reading + sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255); + + // in case the sensor value is outside the range seen during calibration + sensorValue = constrain(sensorValue, 0, 255); + + // fade the LED using the calibrated value: + analogWrite(ledPin, sensorValue); +} diff --git a/build/shared/examples/3.Analog/Fading/Fading.ino b/build/shared/examples/3.Analog/Fading/Fading.ino new file mode 100644 index 000000000..858d3616c --- /dev/null +++ b/build/shared/examples/3.Analog/Fading/Fading.ino @@ -0,0 +1,45 @@ +/* + Fading + + This example shows how to fade an LED using the analogWrite() function. + + The circuit: + * LED attached from digital pin 9 to ground. + + Created 1 Nov 2008 + By David A. Mellis + modified 30 Aug 2011 + By Tom Igoe + + http://arduino.cc/en/Tutorial/Fading + + This example code is in the public domain. + + */ + + +int ledPin = 9; // LED connected to digital pin 9 + +void setup() { + // nothing happens in setup +} + +void loop() { + // fade in from min to max in increments of 5 points: + for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) { + // sets the value (range from 0 to 255): + analogWrite(ledPin, fadeValue); + // wait for 30 milliseconds to see the dimming effect + delay(30); + } + + // fade out from max to min in increments of 5 points: + for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { + // sets the value (range from 0 to 255): + analogWrite(ledPin, fadeValue); + // wait for 30 milliseconds to see the dimming effect + delay(30); + } +} + + diff --git a/build/shared/examples/3.Analog/Smoothing/Smoothing.ino b/build/shared/examples/3.Analog/Smoothing/Smoothing.ino new file mode 100644 index 000000000..e33a0dd16 --- /dev/null +++ b/build/shared/examples/3.Analog/Smoothing/Smoothing.ino @@ -0,0 +1,67 @@ +/* + + Smoothing + + Reads repeatedly from an analog input, calculating a running average + and printing it to the computer. Keeps ten readings in an array and + continually averages them. + + The circuit: + * Analog sensor (potentiometer will do) attached to analog input 0 + + Created 22 April 2007 + modified 30 Aug 2011 + By David A. Mellis + + http://www.arduino.cc/en/Tutorial/Smoothing + + This example code is in the public domain. + + +*/ + + +// Define the number of samples to keep track of. The higher the number, +// the more the readings will be smoothed, but the slower the output will +// respond to the input. Using a constant rather than a normal variable lets +// use this value to determine the size of the readings array. +const int numReadings = 10; + +int readings[numReadings]; // the readings from the analog input +int index = 0; // the index of the current reading +int total = 0; // the running total +int average = 0; // the average + +int inputPin = A0; + +void setup() +{ + // initialize serial communication with computer: + Serial.begin(9600); + // initialize all the readings to 0: + for (int thisReading = 0; thisReading < numReadings; thisReading++) + readings[thisReading] = 0; +} + +void loop() { + // subtract the last reading: + total= total - readings[index]; + // read from the sensor: + readings[index] = analogRead(inputPin); + // add the reading to the total: + total= total + readings[index]; + // advance to the next position in the array: + index = index + 1; + + // if we're at the end of the array... + if (index >= numReadings) + // ...wrap around to the beginning: + index = 0; + + // calculate the average: + average = total / numReadings; + // send it to the computer as ASCII digits + Serial.println(average); +} + + diff --git a/build/shared/examples/4.Communication/ASCIITable/ASCIITable.ino b/build/shared/examples/4.Communication/ASCIITable/ASCIITable.ino new file mode 100644 index 000000000..5a111027d --- /dev/null +++ b/build/shared/examples/4.Communication/ASCIITable/ASCIITable.ino @@ -0,0 +1,76 @@ +/* + ASCII table + + Prints out byte values in all possible formats: + * as raw binary values + * as ASCII-encoded decimal, hex, octal, and binary values + + For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII + + The circuit: No external hardware needed. + + created 2006 + by Nicholas Zambetti + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + + + */ +void setup() +{ + Serial.begin(9600); + + // prints title with ending line break + Serial.println("ASCII Table ~ Character Map"); +} + +// first visible ASCIIcharacter '!' is number 33: +int thisByte = 33; +// you can also write ASCII characters in single quotes. +// for example. '!' is the same as 33, so you could also use this: +//int thisByte = '!'; + +void loop() +{ + // prints value unaltered, i.e. the raw binary version of the + // byte. The serial monitor interprets all bytes as + // ASCII, so 33, the first number, will show up as '!' + Serial.write(thisByte); + + Serial.print(", dec: "); + // prints value as string as an ASCII-encoded decimal (base 10). + // Decimal is the default format for Serial.print() and Serial.println(), + // so no modifier is needed: + Serial.print(thisByte); + // But you can declare the modifier for decimal if you want to. + //this also works if you uncomment it: + + // Serial.print(thisByte, DEC); + + + Serial.print(", hex: "); + // prints value as string in hexadecimal (base 16): + Serial.print(thisByte, HEX); + + Serial.print(", oct: "); + // prints value as string in octal (base 8); + Serial.print(thisByte, OCT); + + Serial.print(", bin: "); + // prints value as string in binary (base 2) + // also prints ending line break: + Serial.println(thisByte, BIN); + + // if printed last visible character '~' or 126, stop: + if(thisByte == 126) { // you could also use if (thisByte == '~') { + // This loop loops forever and does nothing + while(true) { + continue; + } + } + // go on to the next character + thisByte++; +} diff --git a/build/shared/examples/4.Communication/Dimmer/Dimmer.ino b/build/shared/examples/4.Communication/Dimmer/Dimmer.ino new file mode 100644 index 000000000..78849c2c9 --- /dev/null +++ b/build/shared/examples/4.Communication/Dimmer/Dimmer.ino @@ -0,0 +1,112 @@ +/* + Dimmer + + Demonstrates the sending data from the computer to the Arduino board, + in this case to control the brightness of an LED. The data is sent + in individual bytes, each of which ranges from 0 to 255. Arduino + reads these bytes and uses them to set the brightness of the LED. + + The circuit: + LED attached from digital pin 9 to ground. + Serial connection to Processing, Max/MSP, or another serial application + + created 2006 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe and Scott Fitzgerald + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Dimmer + + */ + +const int ledPin = 9; // the pin that the LED is attached to + +void setup() +{ + // initialize the serial communication: + Serial.begin(9600); + // initialize the ledPin as an output: + pinMode(ledPin, OUTPUT); +} + +void loop() { + byte brightness; + + // check if data has been sent from the computer: + if (Serial.available()) { + // read the most recent byte (which will be from 0 to 255): + brightness = Serial.read(); + // set the brightness of the LED: + analogWrite(ledPin, brightness); + } +} + +/* Processing code for this example + // Dimmer - sends bytes over a serial port + // by David A. Mellis + //This example code is in the public domain. + + import processing.serial.*; + Serial port; + + void setup() { + size(256, 150); + + println("Available serial ports:"); + println(Serial.list()); + + // Uses the first port in this list (number 0). Change this to + // select the port corresponding to your Arduino board. The last + // parameter (e.g. 9600) is the speed of the communication. It + // has to correspond to the value passed to Serial.begin() in your + // Arduino sketch. + port = new Serial(this, Serial.list()[0], 9600); + + // If you know the name of the port used by the Arduino board, you + // can specify it directly like this. + //port = new Serial(this, "COM1", 9600); + } + + void draw() { + // draw a gradient from black to white + for (int i = 0; i < 256; i++) { + stroke(i); + line(i, 0, i, 150); + } + + // write the current X-position of the mouse to the serial port as + // a single byte + port.write(mouseX); + } + */ + +/* Max/MSP v5 patch for this example + +----------begin_max5_patcher---------- +1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M +YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC +ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBLXiP +xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK +rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.W +sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui +FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+owv +AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK +z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu +xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqueG2 +uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j1Ykj +jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKdA +4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn95Izr +TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS +xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5KTa6 +WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG2v9 +FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ+zS7 +3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo8qHc +cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ ++wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x +D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8 +ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS +xqZqbd3ZLdera1iPqYxOm++v7SUSz +-----------end_max5_patcher----------- + */ diff --git a/build/shared/examples/4.Communication/Graph/Graph.ino b/build/shared/examples/4.Communication/Graph/Graph.ino new file mode 100644 index 000000000..92256ab00 --- /dev/null +++ b/build/shared/examples/4.Communication/Graph/Graph.ino @@ -0,0 +1,149 @@ +/* + Graph + + A simple example of communication from the Arduino board to the computer: + the value of analog input 0 is sent out the serial port. We call this "serial" + communication because the connection appears to both the Arduino and the + computer as a serial port, even though it may actually use + a USB cable. Bytes are sent one after another (serially) from the Arduino + to the computer. + + You can use the Arduino serial monitor to view the sent data, or it can + be read by Processing, PD, Max/MSP, or any other program capable of reading + data from a serial port. The Processing code below graphs the data received + so you can see the value of the analog input changing over time. + + The circuit: + Any analog input sensor is attached to analog in pin 0. + + created 2006 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe and Scott Fitzgerald + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Graph + */ + +void setup() { + // initialize the serial communication: + Serial.begin(9600); +} + +void loop() { + // send the value of analog input 0: + Serial.println(analogRead(A0)); + // wait a bit for the analog-to-digital converter + // to stabilize after the last reading: + delay(10); +} + +/* Processing code for this example + + // Graphing sketch + + + // This program takes ASCII-encoded strings + // from the serial port at 9600 baud and graphs them. It expects values in the + // range 0 to 1023, followed by a newline, or newline and carriage return + + // Created 20 Apr 2005 + // Updated 18 Jan 2008 + // by Tom Igoe + // This example code is in the public domain. + + import processing.serial.*; + + Serial myPort; // The serial port + int xPos = 1; // horizontal position of the graph + + void setup () { + // set the window size: + size(400, 300); + + // List all the available serial ports + println(Serial.list()); + // I know that the first port in the serial list on my mac + // is always my Arduino, so I open Serial.list()[0]. + // Open whatever port is the one you're using. + myPort = new Serial(this, Serial.list()[0], 9600); + // don't generate a serialEvent() unless you get a newline character: + myPort.bufferUntil('\n'); + // set inital background: + background(0); + } + void draw () { + // everything happens in the serialEvent() + } + + void serialEvent (Serial myPort) { + // get the ASCII string: + String inString = myPort.readStringUntil('\n'); + + if (inString != null) { + // trim off any whitespace: + inString = trim(inString); + // convert to an int and map to the screen height: + float inByte = float(inString); + inByte = map(inByte, 0, 1023, 0, height); + + // draw the line: + stroke(127,34,255); + line(xPos, height, xPos, height - inByte); + + // at the edge of the screen, go back to the beginning: + if (xPos >= width) { + xPos = 0; + background(0); + } + else { + // increment the horizontal position: + xPos++; + } + } + } + + */ + +/* Max/MSP v5 patch for this example + ----------begin_max5_patcher---------- +1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJIT +RTxj+6AOHkoTDooroUs0AQPR73a+1cwtK3WtZxzEpOwqlB9YveAlL4KWMYh6 +Q1GLo99ISKXeJMmU451zTUQAWpmNy+NM+SZ2y+sR1l02JuU9t0hJvFlNcMPy +dOuBv.U5Rgb0LPpRpYBooM3529latArTUVvzZdFPtsXAuDrrTU.f.sBffXxL +vGE50lIHkUVJXq3fRtdaoDvjYfbgjujaFJSCzq4.tLaN.bi1tJefWpqbO0uz +1IjIABoluxrJ1guxh2JfPO2B5zRNyBCLDFcqbwNvuv9fHCb8bvevyyEU2JKT +YhkBSWPAfq2TZ6YhqmuMUo0feUn+rYpY4YtY+cFw3lUJdCMYAapZqzwUHX8S +crjAd+SIOU6UBAwIygy.Q1+HAA1KH6EveWOFQlitUK92ehfal9kFhUxJ3tWc +sgpxadigWExbt1o7Ps5dk3yttivyg20W0VcSmg1G90qtx92rAZbH4ez.ruy1 +nhmaDPidE07J+5n2sg6E6oKXxUSmc20o6E3SPRDbrkXnPGUYE.i5nCNB9TxQ +jG.G0kCTZtH88f07Rt0ZMMWUw8VvbKVAaTk6GyoraPdZff7rQTejBN54lgyv +HE0Ft7AvIvvgvIwO23jBdUkYOuSvIFSiNcjFhiSsUBwsUCh1AgfNSBAeNDBZ +DIDqY.f8.YjfjV1HAn9XDTxyNFYatVTkKx3kcK9GraZpI5jv7GOx+Z37Xh82 +LSKHIDmDXaESoXRngIZQDKVkpxUkMCyXCQhcCK1z.G457gi3TzMz4RFD515F +G3bIQQwcP3SOF0zlkGhiCBQ1kOHHFFlXaEBQIQnCwv9QF1LxPZ.A4jR5cyQs +vbvHMJsLll01We+rE2LazX6zYmCraRrsPFwKg1ANBZFY.IAihr8Ox.aH0oAL +hB8nQVw0FSJiZeunOykbT6t3r.NP8.iL+bnwNiXuVMNJH9H9YCm89CFXPBER +bz422p8.O4dg6kRxdyjDqRwMIHTbT3QFLskxJ8tbmQK4tm0XGeZWF7wKKtYY +aTAF.XPNFaaQBinQMJ4QLF0aNHF0JtYuHSxoUZfZY6.UU2ejJTb8lQw8Fo5k +Rv6e2PI+fOM71o2ecY1VgTYdCSxxUqLokuYq9jYJi6lxPgD2NIPePLB0mwbG +YA9Rgxdiu1k5xiLlSU6JVnx6wzg3sYHwTesB8Z5D7RiGZpXyvDNJY.DQX3.H +hvmcUN4bP1yCkhpTle2P37jtBsKrLWcMScEmltOPv22ZfAqQAdKr9HzATQwZ +q18PrUGt6Tst2XMCRUfGuhXs6ccn23YloomMqcTiC5iMGPsHsHRWhWFlaenV +XcqwgCQiGGJzptyS2ZMODBz6fGza0bzmXBj7+DA94bvpR01MffAlueO7HwcI +pWCwmzJdvi9ILgflLAFmyXB6O7ML0YbD26lenmcGxjVsZUN+A6pUK7AtTrPg +M+eRYG0qD9j4I7eEbco8Xh6WcO.or9XDC6UCiewbXHkh6xm5LiPEkzpJDRTu +mEB44Fgz4NCtJvX.SM1vo2SlTCZGAe7GZu6ahdRyzFOhYZ+mbVVSYptBw.K1 +tboIkatIA7c1cTKD1u.honLYV04VkluHsXe0szv9pQCE9Ro3jaVB1o15pz2X +zYoBvO5KXCAe0LCYJybE8ZODf4fV8t9qW0zYxq.YJfTosj1bv0xc.SaC0+AV +9V9L.KKyV3SyTcRtmzi6rO.O16USvts4B5xe9EymDvebK0eMfW6+NIsNlE2m +eqRyJ0utRq13+RjmqYKN1e.4d61jjdsauXe3.2p6jgi9hsNIv97CoyJ01xzl +c3ZhUCtSHx3UZgjoEJYqNY+hYs5zZQVFW19L3JDYaTlMLqAAt1G2yXlnFg9a +53L1FJVcv.cOX0dh7mCVGCLce7GFcQwDdH5Ta3nyAS0pQbHxegr+tGIZORgM +RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES +1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd. +HJ5hhnng3h9HPj4lud02.1bxGw. +-----------end_max5_patcher----------- + + */ diff --git a/build/shared/examples/4.Communication/MIDI/Midi.ino b/build/shared/examples/4.Communication/MIDI/Midi.ino new file mode 100644 index 000000000..a10548673 --- /dev/null +++ b/build/shared/examples/4.Communication/MIDI/Midi.ino @@ -0,0 +1,49 @@ +/* + MIDI note player + + This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data. + If this circuit is connected to a MIDI synth, it will play + the notes F#-0 (0x1E) to F#-5 (0x5A) in sequence. + + + The circuit: + * digital in 1 connected to MIDI jack pin 5 + * MIDI jack pin 2 connected to ground + * MIDI jack pin 4 connected to +5V through 220-ohm resistor + Attach a MIDI cable to the jack, then to a MIDI synth, and play music. + + created 13 Jun 2006 + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/MIDI + + */ + +void setup() { + // Set MIDI baud rate: + Serial.begin(31250); +} + +void loop() { + // play notes from F#-0 (0x1E) to F#-5 (0x5A): + for (int note = 0x1E; note < 0x5A; note ++) { + //Note on channel 1 (0x90), some note value (note), middle velocity (0x45): + noteOn(0x90, note, 0x45); + delay(100); + //Note on channel 1 (0x90), some note value (note), silent velocity (0x00): + noteOn(0x90, note, 0x00); + delay(100); + } +} + +// plays a MIDI note. Doesn't check to see that +// cmd is greater than 127, or that data values are less than 127: +void noteOn(int cmd, int pitch, int velocity) { + Serial.write(cmd); + Serial.write(pitch); + Serial.write(velocity); +} + diff --git a/build/shared/examples/4.Communication/MultiSerialMega/MultiSerialMega.pde b/build/shared/examples/4.Communication/MultiSerialMega/MultiSerialMega.ino similarity index 100% rename from build/shared/examples/4.Communication/MultiSerialMega/MultiSerialMega.pde rename to build/shared/examples/4.Communication/MultiSerialMega/MultiSerialMega.ino diff --git a/build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.ino b/build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.ino new file mode 100644 index 000000000..7ac8231a6 --- /dev/null +++ b/build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.ino @@ -0,0 +1,170 @@ +/* + Physical Pixel + + An example of using the Arduino board to receive data from the + computer. In this case, the Arduino boards turns on an LED when + it receives the character 'H', and turns off the LED when it + receives the character 'L'. + + The data can be sent from the Arduino serial monitor, or another + program like Processing (see code below), Flash (via a serial-net + proxy), PD, or Max/MSP. + + The circuit: + * LED connected from digital pin 13 to ground + + created 2006 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe and Scott Fitzgerald + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/PhysicalPixel + */ + +const int ledPin = 13; // the pin that the LED is attached to +int incomingByte; // a variable to read incoming serial data into + +void setup() { + // initialize serial communication: + Serial.begin(9600); + // initialize the LED pin as an output: + pinMode(ledPin, OUTPUT); +} + +void loop() { + // see if there's incoming serial data: + if (Serial.available() > 0) { + // read the oldest byte in the serial buffer: + incomingByte = Serial.read(); + // if it's a capital H (ASCII 72), turn on the LED: + if (incomingByte == 'H') { + digitalWrite(ledPin, HIGH); + } + // if it's an L (ASCII 76) turn off the LED: + if (incomingByte == 'L') { + digitalWrite(ledPin, LOW); + } + } +} + +/* Processing code for this example + + // mouseover serial + + // Demonstrates how to send data to the Arduino I/O board, in order to + // turn ON a light if the mouse is over a square and turn it off + // if the mouse is not. + + // created 2003-4 + // based on examples by Casey Reas and Hernando Barragan + // modified 30 Aug 2011 + // by Tom Igoe + // This example code is in the public domain. + + + + import processing.serial.*; + + float boxX; + float boxY; + int boxSize = 20; + boolean mouseOverBox = false; + + Serial port; + + void setup() { + size(200, 200); + boxX = width/2.0; + boxY = height/2.0; + rectMode(RADIUS); + + // List all the available serial ports in the output pane. + // You will need to choose the port that the Arduino board is + // connected to from this list. The first port in the list is + // port #0 and the third port in the list is port #2. + println(Serial.list()); + + // Open the port that the Arduino board is connected to (in this case #0) + // Make sure to open the port at the same speed Arduino is using (9600bps) + port = new Serial(this, Serial.list()[0], 9600); + + } + + void draw() + { + background(0); + + // Test if the cursor is over the box + if (mouseX > boxX-boxSize && mouseX < boxX+boxSize && + mouseY > boxY-boxSize && mouseY < boxY+boxSize) { + mouseOverBox = true; + // draw a line around the box and change its color: + stroke(255); + fill(153); + // send an 'H' to indicate mouse is over square: + port.write('H'); + } + else { + // return the box to it's inactive state: + stroke(153); + fill(153); + // send an 'L' to turn the LED off: + port.write('L'); + mouseOverBox = false; + } + + // Draw the box + rect(boxX, boxY, boxSize, boxSize); + } + + + */ + +/* +Max/MSP version 5 patch to run with this example: + +----------begin_max5_patcher---------- +1672.3oc2ZszaaiCD9ryuBBebQVCQRYao8xhf1cQCPVfBzh8RRQ.sDsM2HSZ +HQmlzh9eu7gjsjsEk7y0oWjiHoHm4aluYHGlueUmtiDuPy5B9Cv8fNc99Uc5 +XZR2Pm726zcF4knDRlYXciDylQ4xtWa6SReQZZ+iSeMiEQR.ej8BM4A9C7OO +kkAlSjQSAYTdbFfvA27o2c6sfO.Doqd6NfXgDHmRUCKkolg4hT06BfbQJGH3 +5Qd2e8d.QJIQSow5tzebZ7BFW.FIHow8.2JAQpVIIYByxo9KIMkSjL9D0BRT +sbGHZJIkDoZOSMuQT.8YZ5qpgGI3locF4IpQRzq2nDF+odZMIJkRjpEF44M3 +A9nWAum7LKFbSOv+PSRXYOvmIhYiYpg.8A2LOUOxPyH+TjPJA+MS9sIzTRRr +QP9rXF31IBZAHpVHkHrfaPRHLuUCzoj9GSoQRqIB52y6Z.tu8o4EX+fddfuj ++MrXiwPL5+9cXwrOVvkbxLpomazHbQO7EyX7DpzXYgkFdF6algCQpkX4XUlo +hA6oa7GWck9w0Gnmy6RXQOoQeCfWwlzsdnHLTq8n9PCHLv7Cxa6PAN3RCKjh +ISRVZ+sSl704Tqt0kocE9R8J+P+RJOZ4ysp6gN0vppBbOTEN8qp0YCq5bq47 +PUwfA5e766z7NbGMuncw7VgNRSyQhbnPMGrDsGaFSvKM5NcWoIVdZn44.eOi +9DTRUT.7jDQzSTiF4UzXLc7tLGh4T9pwaFQkGUGIiOOkpBSJUwGsBd40krHQ +9XEvwq2V6eLIhV6GuzP7uzzXBmzsXPSRYwBtVLp7s5lKVv6UN2VW7xRtYDbx +7s7wRgHYDI8YVFaTBshkP49R3rYpH3RlUhTQmK5jMadJyF3cYaTNQMGSyhRE +IIUlJaOOukdhoOyhnekEKmZlqU3UkLrk7bpPrpztKBVUR1uorLddk6xIOqNt +lBOroRrNVFJGLrDxudpET4kzkstNp2lzuUHVMgk5TDZx9GWumnoQTbhXsEtF +tzCcM+z0QKXsngCUtTOEIN0SX2iHTTIIz968.Kf.uhfzUCUuAd3UKd.OKt.N +HTynxTQyjpQD9jlwEXeKQxfHCBahUge6RprSa2V4m3aYOMyaP6gah2Yf1zbD +jVwZVGFZHHxINFxpjr5CiTS9JiZn6e6nTlXQZTAFj6QCppQwzL0AxVtoi6WE +QXsANkEGWMEuwNvhmKTnat7A9RqLq6pXuEwY6xM5xRraoTiurj51J1vKLzFs +CvM7HI14Mpje6YRxHOSieTsJpvJORjxT1nERK6s7YTN7sr6rylNwf5zMiHI4 +meZ4rTYt2PpVettZERbjJ6PjfqN2loPSrUcusH01CegsGEE5467rnCdqT1ES +QxtCvFq.cvGz+BaAHXKzRSfP+2Jf.KCvj5ZLJRAhwi+SWHvPyN3vXiaPn6JR +3eoA.0TkFhTvpsDMIrL20nAkCI4EoYfSHAuiPBdmJRyd.IynYYjIzMvjOTKf +3DLvnvRLDLpWeEOYXMfAZqfQ0.qsnlUdmA33t8CNJ7MZEb.u7fiZHLYzDkJp +R7CqEVLGN75U+1JXxFUY.xEEBcRCqhOEkz2bENEWnh4pbh0wY25EefbD6EmW +UA6Ip8wFLyuFXx+Wrp8m6iff1B86W7bqJO9+mx8er4E3.abCLrYdA16sBuHx +vKT6BlpIGQIhL55W7oicf3ayv3ixQCm4aQuY1HZUPQWY+cASx2WZ3f1fICuz +vj5R5ZbM1y8gXYN4dIXaYGq4NhQvS5MmcDADy+S.j8CQ78vk7Q7gtPDX3kFh +3NGaAsYBUAO.8N1U4WKycxbQdrWxJdXd10gNIO+hkUMmm.CZwknu7JbNUYUq +0sOsTsI1QudDtjw0t+xZ85wWZd80tMCiiMADNX4UzrcSeK23su87IANqmA7j +tiRzoXi2YRh67ldAk79gPmTe3YKuoY0qdEDV3X8xylCJMTN45JIakB7uY8XW +uVr3PO8wWwEoTW8lsfraX7ZqzZDDXCRqNkztHsGCYpIDDAOqxDpMVUMKcOrp +942acPvx2NPocMC1wQZ8glRn3myTykVaEUNLoEeJjVaAevA4EAZnsNgkeyO+ +3rEZB7f0DTazDcQTNmdt8aACGi1QOWnMmd+.6YjMHH19OB5gKsMF877x8wsJ +hN97JSnSfLUXGUoj6ujWXd6Pk1SAC+Pkogm.tZ.1lX1qL.pe6PE11DPeMMZ2 +.P0K+3peBt3NskC +-----------end_max5_patcher----------- + + + */ diff --git a/build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.ino b/build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.ino new file mode 100644 index 000000000..e15031e8b --- /dev/null +++ b/build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.ino @@ -0,0 +1,211 @@ +/* + Serial Call and Response + Language: Wiring/Arduino + + This program sends an ASCII A (byte of value 65) on startup + and repeats that until it gets some data in. + Then it waits for a byte in the serial port, and + sends three sensor values whenever it gets a byte in. + + Thanks to Greg Shakar and Scott Fitzgerald for the improvements + + The circuit: + * potentiometers attached to analog inputs 0 and 1 + * pushbutton attached to digital I/O 2 + + Created 26 Sept. 2005 + by Tom Igoe + modified 30 Aug 2011 + by Tom Igoe and Scott Fitzgerald + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/SerialCallResponse + + */ + +int firstSensor = 0; // first analog sensor +int secondSensor = 0; // second analog sensor +int thirdSensor = 0; // digital sensor +int inByte = 0; // incoming serial byte + +void setup() +{ + // start serial port at 9600 bps: + Serial.begin(9600); + pinMode(2, INPUT); // digital sensor is on digital pin 2 + establishContact(); // send a byte to establish contact until receiver responds +} + +void loop() +{ + // if we get a valid byte, read analog ins: + if (Serial.available() > 0) { + // get incoming byte: + inByte = Serial.read(); + // read first analog input, divide by 4 to make the range 0-255: + firstSensor = analogRead(A0)/4; + // delay 10ms to let the ADC recover: + delay(10); + // read second analog input, divide by 4 to make the range 0-255: + secondSensor = analogRead(1)/4; + // read switch, map it to 0 or 255L + thirdSensor = map(digitalRead(2), 0, 1, 0, 255); + // send sensor values: + Serial.write(firstSensor); + Serial.write(secondSensor); + Serial.write(thirdSensor); + } +} + +void establishContact() { + while (Serial.available() <= 0) { + Serial.print('A'); // send a capital A + delay(300); + } +} + +/* +Processing sketch to run with this example: + +// This example code is in the public domain. + +import processing.serial.*; + +int bgcolor; // Background color +int fgcolor; // Fill color +Serial myPort; // The serial port +int[] serialInArray = new int[3]; // Where we'll put what we receive +int serialCount = 0; // A count of how many bytes we receive +int xpos, ypos; // Starting position of the ball +boolean firstContact = false; // Whether we've heard from the microcontroller + +void setup() { + size(256, 256); // Stage size + noStroke(); // No border on the next thing drawn + + // Set the starting position of the ball (middle of the stage) + xpos = width/2; + ypos = height/2; + + // Print a list of the serial ports, for debugging purposes: + println(Serial.list()); + + // I know that the first port in the serial list on my mac + // is always my FTDI adaptor, so I open Serial.list()[0]. + // On Windows machines, this generally opens COM1. + // Open whatever port is the one you're using. + String portName = Serial.list()[0]; + myPort = new Serial(this, portName, 9600); +} + +void draw() { + background(bgcolor); + fill(fgcolor); + // Draw the shape + ellipse(xpos, ypos, 20, 20); +} + +void serialEvent(Serial myPort) { + // read a byte from the serial port: + int inByte = myPort.read(); + // if this is the first byte received, and it's an A, + // clear the serial buffer and note that you've + // had first contact from the microcontroller. + // Otherwise, add the incoming byte to the array: + if (firstContact == false) { + if (inByte == 'A') { + myPort.clear(); // clear the serial port buffer + firstContact = true; // you've had first contact from the microcontroller + myPort.write('A'); // ask for more + } + } + else { + // Add the latest byte from the serial port to array: + serialInArray[serialCount] = inByte; + serialCount++; + + // If we have 3 bytes: + if (serialCount > 2 ) { + xpos = serialInArray[0]; + ypos = serialInArray[1]; + fgcolor = serialInArray[2]; + + // print the values (for debugging purposes only): + println(xpos + "\t" + ypos + "\t" + fgcolor); + + // Send a capital A to request new sensor readings: + myPort.write('A'); + // Reset serialCount: + serialCount = 0; + } + } +} +*/ + +/* +Max/MSP version 5 patch to run with this example: + +----------begin_max5_patcher---------- +2569.3oc2as0jiZqD9YO+Jzw09PRc75BIAX671TaUop8gy4gLoNmG1YqsjAY +rxhAGPLW1T4+dZIAd.aCFeiEuYqXFABQqu9qa0Rp0ec2fgyiegmND8KnOgFL +3utav.8sT2XPd4ACWwdwKjkpq1vU7zTV.e3Hyyj7Wj5665Tbq3LYHWJecM2z +tCGh9b9iVyjdKEQAeIg6IMOkRmM1ZDx10UcgRF6LBgmN1Zy6H70se77+38yJ +9DKhijQrU5Ovv6SDrvhmDksRDAedsvRJU8Tw2zUGSfuyl5ZjUckwpa922cm5 +mQsDLh3OCx0NXQJODgqENlyhBFNpkvBchFVzfCwZ+vh60DVHm.r3EuZEORtC +t7.WISnOvBCe+uwSWGGkxQnGidL5AdjeJhgl+pjifuNRtjiRMUecbhbDhE4i +R3LnVTcsRQhnwHzCfXhVDmvChyfZ3EGFmLB8x53Tyq7J7Wn3EPS6IR7B4nrT +.n0M+SrvLnYR3xrjHtOZQR7ps+tiMh2+MVx+EzuuTjhz5JDzSy.KAn5Lir5y +eR3AhdjtTL7SBB5SpO8VMIBZjfXsPDC2GpCCojIP1L89EFIC45f9o6e3Ce7i +n6+YUCmJYIxr0iA4.ZvuxUxwyLgo+ajDUCLR8AizsLfnQn7l.8LbW9SfXIjv +qAZdzJ.1P9LIartS5AvqDvArM590I.ayZ1iQyeE8fWrTh9Ug7aA7DVnuFW+c +.q9XP7F+.ghHtGnBzJZLtdhsskshK6PLV85BXmZL3cNRlM9XX1VWPlsLQD.n +C5m.Mwmje9mUpDOE4RDrT99P9BIPMidBdUAP5AV08ggFdSB6YEWPgoqShg2Q +yOeV.OeIa8ZPSNmq32n+C6Efq9m.kETcfimb96Xz+WotkJtYgTrPjvA9Onn2 +gE.bNV5WQ2m3mIhh0LmRs0d0lz5UlDiWJGKGs1jXtTixz8lQalvEQBIHVvGM +UqlBXJONOqQZi2BvfjosuWrWPiTOngmXo8oatfoZPiZWCnYeq.ZdK4desvWD +GXYdBQtmLvk1iCu+wgJ12bdfHBLF.QNyioLGTVCKjJGSFPW8vUYQBySUtKWw +70t0f+bdXr2WQoKy.i.+3miNZJqsqA8czvNgRajxR6aneMQbrF.XkqDMzaFo +6wgmV.YDrNjCWaC.4psvwypAfH6Ef9e7DeVDauPDcePjUcAkUVN4I4.SNx.s +gHTMjVJvSJU6ACeq23nGfYlsoKYYT1khiBv6.Ekhq6SVE2zmu3XZiXvO8a0W +WiJ+Tslhn0f+YvFRSv296xxBkeY+fS0muf4wq8kqQULXXPhvONRIFUdW0sK9 +f.Gvn6cJK45ZDwVumWVFGGNmk7jHULOjWQS.rYVjXE39TJLRDDWQwCEqVmHL +VratGOhAswxTuj3vvJMk4IOsmmXB95YgubotsdCupL8lRLmJ1YUteiS2opQ2 +hjf4.H4T7+kqT81b0Fw+DGSrPZRyro5Bk7Kssom8jxeuZ8OUa3+6ZDhG6LyA +OcR0Wb6oHMnvok4OFcs.VK0+NOHkjCoF5ryrCBot2zPZkwF1cFoJVZy.ZwLS +2YFp0xYsLwvXtXlBOA2..6TK.ukep5FYsgQW2C5R6FzcMChIw5RvXMF+4DV7 +TqCBnzSFPsOE.sinq+afR0HPpG03PV+UHm1GFKImLVR9QGKycj1ZnDe6BkMM +vDDVMKYDZMCvrXXtMn2gQuifdGE8N6KhgewExAGpx5ldnJs7b1rRmIpUKNmN +taHqauXRSqETZfYU5IEy7U0fC6cfAlT137vnwrenQCp0QgFtV8Tzv74FdfQ5 +HSGSg+y1dj9uaWWF2pXs1ZIKNht7aScTs1L0LKLcuQ878iEowYIdE58h.dPU +6S97ToHZybo+zaNH2phKE99Um4pFtE9qiAJUt.h9bqzdGsb6zV41s+I231H2 +S5WxMts3shPQ5OxM4XjaZuQtUCt1d415FTtw8K4d1wf23aP4lzqvaWq1J2N8 +K+fsUtc6W768LL3sgbO46gbmeSnCX1tjT1Sb+u.eFHDwuvjxDw7LoIDrxaex +4uaBM9vCsYFAgwyYg4asylVoRauiTscac2aHwkYmzrpcWyJOsi8NkCb995N8 +sLYptT1wYxMRpL8udeCYxzAQjolDBf51BDw4FAQToB.LfJ9DS2MCjju8ylcV +rVHwtuAIx3ffP9YyGLoKhY8JpsySabC1u1pWqSS8hM6RrcqTuV2PoyXCo2Y6 +xmwbduYKMroMAL1S6aIzXnmesc+PQpT08KtpLBF0xbrXV9pz3t4x9vC5rivT +v9xo2kpTPLrQq8Qsydvwjze1js23fJcSmiNWRveuxj0mXga7OsuEl1jTWtlt +sIGdqqaiut85SJIixVMmmbHEu1tuIkus6jRnfiaiJ+aJcOoAcusILPWyfbGP +2Os+o7anaianaSlRZc2lX8CKmmZWFFZlySH8OR+EBFJFfKGFbZDF5g190LhX +Vzao5wgvnRWZAR4XxF37zsrVnZ10EpnWNn5agnfj3r0HZ8QR2xnGrMAMNA23 +.HG+3njuSrHHdZnKBbnCeFgZWr0XSbU4YgEooXqoVWyLZldIym7PAXpsjmvU +oMtWXbJe6iRSCCGQMo4MYlgzX03Anh3dyjj8U.EUh3dLXxz7T51oMXxj9FlT +2IOTSMNwUiI2xwvRn6jfnU.Dbea550AH5SYF6TONl1k3H13lPDbu67XVmYyG +pX1DvA3Aolut5joTx1Isov5yWzJCIgXMoQim9lsyYtvcDhwzHOPNRwu6kUf+ +9rvc+4JtLI9sjcrlAUaQ2rXfTmlTwXxMi6.8Yr3z7FjuBlFRuYY7q0a.8lY4 +L0F7LzLWKqyZ0sx4KTrloLswU6EeUOHeWx02323L+Buhhn0YRz7rEKTmm4m3 +IuBFXnUhPv6I2KNxO8nO8iTy4IKeo.sZ5vOhuYNwnlAXTGna0gztokIwrj.X +WCLfabXDbmECl9qWMO8Lvw16+cNnry9dWIsNpYKuUl.kpzNa2892p6czPsUj +bnsPlbONQhByHUkxwTr5B0d5lRmov51BYcVmBeTbKDIpS2JSUxFwZjIxrtWl +tzTehEUwrbLqlH1rP5UKkmgyDplCpKctFLSZQOYKqpCawfmYRR+7oXYuoz4h +6VsQZmzstbZCWvw9z74XN+h1NlSrdkRTmxnqtTW37zoas9IsxgNoakIRakIb +24QpshDoyDI21.Szt0w8V1g0jNmS6TYBa2VGHGAcpXHByvG1jYaJ0INIrNM2 +cj7kmjtozYJsaoJuLCuctHXaFDaqHw5GbPqN0klNltCF3WG65uMy4gP6dYhb +H9T2RmZ07HNRmD4tzv4KbOAuozkHpxCQzvc7LLZiSBR25jffuBy5IWORw5KE +CagO+YWiuFKOA0VOzDY5zRRqtz4Jszqgz5ZjVWqxRqpTWXei6VWyXx0d4nfB ++8c+C81VE7B +-----------end_max5_patcher----------- + + +*/ diff --git a/build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino b/build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino new file mode 100644 index 000000000..acf400051 --- /dev/null +++ b/build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.ino @@ -0,0 +1,211 @@ +/* + Serial Call and Response in ASCII + Language: Wiring/Arduino + + This program sends an ASCII A (byte of value 65) on startup + and repeats that until it gets some data in. + Then it waits for a byte in the serial port, and + sends three ASCII-encoded, comma-separated sensor values, + truncated by a linefeed and carriage return, + whenever it gets a byte in. + + Thanks to Greg Shakar and Scott Fitzgerald for the improvements + + The circuit: + * potentiometers attached to analog inputs 0 and 1 + * pushbutton attached to digital I/O 2 + + + + Created 26 Sept. 2005 + by Tom Igoe + modified 30 Aug 2011 + by Tom Igoe and Scott Fitzgerald + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII + + */ + +int firstSensor = 0; // first analog sensor +int secondSensor = 0; // second analog sensor +int thirdSensor = 0; // digital sensor +int inByte = 0; // incoming serial byte + +void setup() +{ + // start serial port at 9600 bps: + Serial.begin(9600); + pinMode(2, INPUT); // digital sensor is on digital pin 2 + establishContact(); // send a byte to establish contact until receiver responds +} + +void loop() +{ + // if we get a valid byte, read analog ins: + if (Serial.available() > 0) { + // get incoming byte: + inByte = Serial.read(); + // read first analog input, divide by 4 to make the range 0-255: + firstSensor = analogRead(A0)/4; + // delay 10ms to let the ADC recover: + delay(10); + // read second analog input, divide by 4 to make the range 0-255: + secondSensor = analogRead(A1)/4; + // read switch, map it to 0 or 255L + thirdSensor = map(digitalRead(2), 0, 1, 0, 255); + // send sensor values: + Serial.print(firstSensor); + Serial.print(","); + Serial.print(secondSensor); + Serial.print(","); + Serial.println(thirdSensor); + } +} + +void establishContact() { + while (Serial.available() <= 0) { + Serial.println("0,0,0"); // send an initial string + delay(300); + } +} + + +/* +Processing code to run with this example: + +// This example code is in the public domain. + +import processing.serial.*; // import the Processing serial library +Serial myPort; // The serial port + +float bgcolor; // Background color +float fgcolor; // Fill color +float xpos, ypos; // Starting position of the ball + +void setup() { + size(640,480); + + // List all the available serial ports + println(Serial.list()); + + // I know that the first port in the serial list on my mac + // is always my Arduino module, so I open Serial.list()[0]. + // Change the 0 to the appropriate number of the serial port + // that your microcontroller is attached to. + myPort = new Serial(this, Serial.list()[0], 9600); + + // read bytes into a buffer until you get a linefeed (ASCII 10): + myPort.bufferUntil('\n'); + + // draw with smooth edges: + smooth(); +} + +void draw() { + background(bgcolor); + fill(fgcolor); + // Draw the shape + ellipse(xpos, ypos, 20, 20); +} + +// serialEvent method is run automatically by the Processing applet +// whenever the buffer reaches the byte value set in the bufferUntil() +// method in the setup(): + +void serialEvent(Serial myPort) { + // read the serial buffer: + String myString = myPort.readStringUntil('\n'); + // if you got any bytes other than the linefeed: + myString = trim(myString); + + // split the string at the commas + // and convert the sections into integers: + int sensors[] = int(split(myString, ',')); + + // print out the values you got: + for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) { + print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t"); + } + // add a linefeed after all the sensor values are printed: + println(); + if (sensors.length > 1) { + xpos = map(sensors[0], 0,1023,0,width); + ypos = map(sensors[1], 0,1023,0,height); + fgcolor = sensors[2]; + } + // send a byte to ask for more data: + myPort.write("A"); + } + +*/ + +/* + +Max/MSP version 5 patch to run with this example: + +----------begin_max5_patcher---------- +2726.3oc2bkziaiiE9bU+J3XjCciwo.WzZeqPCL.4vLG5zXlCIAAzRz1bhrj +aI5pRkF8+89QRIWR1VxxqQNoPrL0B0G+dK7QxG8ed+cilj8UQwHzuf9.5t69 +y6u6Nyozm3txx2MZA+qQI7BysMJU7b1j++nw1KoDeUYN8z7rEEurXRVR0kxV +oRDJ0KKE1pezHzmJuzRtJZtLc1myEQJ6UodtOfGibCLG7czeRwOfW+LxXy6A +d2u0u5ULMKUkxWXdAidLWxW+xixRxxs0LQWU3GBBwjPO82vkeiTq1SWsPlBv +0zFI0p9B42LUOgBUy56011r2r9j+082q+X7owgRUFuU1Slp5EA5oAJxwqKBL +3BSfruSD32RPyxyVsrcUvw8TMjEZOzEK5reVrAqPODVgd9XkBQBz9PDLhvZk +YlvSmoYmpicyRXK8fMpF9tcwRD7ARSGj0G6HnoEhhB9LwV7jm6w45h4Z7V4D +XXCF8AWvzHX2rQ3kTmgbV0YPj8przKZw03Ph0oCIugloTT1hEBvi6l7x6EZL +g9UdRxa+MQwxrzBA5w2+qu6cnOl9wz2KRiKPbzjWTBD.AjZt.UXelkY4pwHd +ZLJWvg6hU9bhzrXQ7Xj9UxgadIOmqDwHjLcLRkuJMxTbxKP8lHSESEh3GPuy +T2ov8qJPSyxEyxVAUsws8XzWWlUXeWu.eCkMEd1HYdTh.sp.DSFb8DOYkn.P +iZUdJ7FzcguIfe.YZW+mLk3WP+9bYAxHoQ.OsBrifamaajwhmjQPaN0TJC9H +GZYw5W8FUIBpjYYFPjAmGtGnUCEArYosoVjg7bQ+jkhd7m0UbghmqVs7A.GP +E9EgFGOyk11uEI5JXbEwXDEokr7inmgyJdBfkTAOFn2fV.zFJlq3OXZjQfbQ +yzDGziKyAcUb3GSAZ+8QYJE5eIUealHmmDa30eG3p2MKasWDsjIBDAJqpX6l +ENVmld9FOnNX8AhOc21EtWRem3yncgJWNCXGzOARhOn9zOqEIQZkK4r4p2lH +lp.UyzmfGUBlLfV0iIIV8lb9yZcAMmtLOCdFi94yR35y4KWBRxIBs9M5ey+J +nq9GfJKH5.2Vk5uOf9eZwsRqaVghoxbAn+CB5szB.cNdwWPOlGuRllYzbpUW +6TZx5niPqONOpoKPmxCs3626lQZlKjoRE.K3kVXDSy.KiBiIDpzaAXPxM12S +2Io0gE.wFiOydfvrkbZgzbtUHsn4hnuT4KR.ZYQRYomLvkFnjo4Gs92DwLYp +wc+pTI3bGrHzFDSUZeSVdu4U0dLWviMd1fuNIIK5Knh4q.6f3rmSOXsVGaDa +LeiyGZU3KsH.XCMAPKgrrD8wQZuIF121Y2GGcjCFkYhYw2NX.pmIZWRXKDDc +mDz+UjGyS4i583ivsEUWcbJxKIlRlApCYhtWsBPOo1ce2nWaMV4an0SksCGm +fZAhA78LsJkvzlvUmLVL8PpiLvU8q2O1NlwZez7NkoKAWzfYjQAey2KeUh5y +6lbZd8o7HQqObKhh6FMKWFmkpgQimUe5pWn10t03nNxM2QJe4NdXUVVxDd9S +xB4jDQCIAnMySkK.OnJoEQPnEUWTtXYtzZwt9bhTNTGyKhxyRRZTU1q7zNth +M9qmkwp4l55U9pwL7TSyogcViy243k1bZelMAHI2p+W+lZ2lq0gLXcLQbMJM +gAlB07Ks0Hv8q+9Z0+TqieXaiPxCtgtj.+lO3liw5tJmV1uL9RQrX8emFkRK +oTq5ra3doTuaZJsQeCaOjVsVZ2DZqyCRq5rXaH71Cd1g4R5ffcakf2vOUa8r +1QuqsMCIWd1cIGhIAeNzXsF+kJrj.7dIT1QSnNGCgdkTW+mHR2DY8IDt8Ipq +txoy94R5Qykzez4xRGo8lJI2tTYWcLAgUyyGiVxANKCFdC5MDzann2vPuw4r +X3Wcft2tpv2zcUYvyIqU55qmt4R0wsCYcy4SJnURoCMqZWoZvu5JbzfiLHz5 +Fm6mMB+glMX3ChM7vCT1v95Fsmd5nAOvf+43L17890jI8JVqMlxhCnI+5PG0 +yMSKiByzZzWe2bQQ1p7nJ4d0ndPMaSwhBkLc8Xo+vqMuMtw4x33lib0P2x3k +YfJUI.QepWRuCF2d2n3Feahau9ha8PRFP3V6Vte3ldihaXDKHxvA2A8E2CK8 +69ia1vxeB8PvMa3faxgfa5vA2taYt0Bt8GV5It8ku8FV3l0WbiOi3t7jPCvt +bIE7mDweFdMPHhelqT4xIqT1Pvpu7Im9pIz4E22hYLKIaBOobocVWKMp6sP0 +l008uxDmmURCezIgHyFyMKj8ZpP0VN+35eijKT+i21QpPsOFwobPXtjdvHt2 +HLhNa..Opjia0UKojxke1syT800YnQIprYyRDmr9fclJd8yc13Yct.6WZwK9 +HW7baxg5zKwK9VJeHwmVBQVo2acN5zctEGLzxHxjn3Va9IxBkt4WcTaDLte4 +XQ.obVZ7VeXW7AK7.LEbNexckNKDS5zZumIKsG0llMzMW3fFMS2CNWRHeuRE +1m3Iq8OsqIl1l779kQD32UylbYa0GURFsZwDQ99D7F69Ns4Cn0XAWuNE92Tx +dZGx9xDgrex9fgmvuilMoilMMzu2MaJ9GVcdlqeu04ozgmR+YhFpRhvRZvsS +ZX.Z62ROhqRqmpGH793oVOzCtyKDWKALak7Burjm6YeqXg6wdqoe6wFZoSFW +aHFcERIavsQrZMSpSjfF1bQtIcoiRxJDatIR5vKbYRDxvk63nN23QTualzKu +Aony+zCfSJG5AsLap1Cm3Oz3j11wdFUiibS6YsbJ0RXakWjMHDxPaTpsQHl8 +WE+HYDmvZ5HNjtXDxfaeL1lYyu1vrYlPY1EcEJ8dxnlsSQmQyVeeRPw9cZ7L +zrcNw4qh53X2gZVNfV84N0JHeelup+XgPkms24moGMypNR6dGMSuYbGX1ZAG +m2fxXtrJ81cuaqdCX2LyhmwfmiB8v3SaRcr5KLlwrHnyI4jbQ2Bamyg0+aBd +bkWQY5xUJzjUSmp2IuOIxeQ+KHvBYB38TDkkFWbn66uxrxpz+IA2019ibyrW +Iscvn2Jy5smbWyNfusKUe61ZgzY2HjqVLXl2dyzSyRGatrukjxVK2qd3WutZ ++srTuzF47v1Ky6tWh2sDQGDlb1ClXWUHwZjEBsQSgWeZBuOLcc4IWbOvDAeU +wjeOfDy8vfD02QuVvdjx.OBVW5DAaPO.q+Uk9b5AhBtpHhzGkLmCTfZEgtzP +yZ7aEulRmCvROyfsDdkKGUsRmJXo8w7045JsI8ASW2dnHrK.Ow7Cr5dtlCtr +0kNUzFdIPqqAsLLqFZMkN0t0HWBzBiARiOpWczpKcpAFzGeQazjt3Aqf6QvJ +jvgmUL6.CLnxFobZ.sxXSoSEs8oSO2lz7EOzJVewzAvfNXS+cN1ILrrSPSoq +BC5bXLXkcqcIJcbbVW5DQqWe52iccsX5i31fa50aDGz9hoqmYAs27DdfYp5d +cwjaeMHOB2G1ewWc7Br4NX8RL6OpBk2ooz0nKW2q6fjb6yfLcYGZPKFGbNj5 +Lnoz4X1LN2gXUMHX2xYa1lC.MJwpRWPqabh6o63tGMjvgmsu2Q1KsMHVO15R +mHXCGdC2yI3BXIcpxz9DLiyoLIHPg+59+Fv1JXFJ +-----------end_max5_patcher----------- +*/ diff --git a/build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.ino b/build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.ino new file mode 100644 index 000000000..39e4b5761 --- /dev/null +++ b/build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.ino @@ -0,0 +1,130 @@ +/* + This example reads three analog sensors (potentiometers are easiest) + and sends their values serially. The Processing and Max/MSP programs at the bottom + take those three values and use them to change the background color of the screen. + + The circuit: + * potentiometers attached to analog inputs 0, 1, and 2 + + http://www.arduino.cc/en/Tutorial/VirtualColorMixer + + created 2 Dec 2006 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe and Scott Fitzgerald + + This example code is in the public domain. + */ + +const int redPin = A0; // sensor to control red color +const int greenPin = A1; // sensor to control green color +const int bluePin = A2; // sensor to control blue color + +void setup() +{ + Serial.begin(9600); +} + +void loop() +{ + Serial.print(analogRead(redPin)); + Serial.print(","); + Serial.print(analogRead(greenPin)); + Serial.print(","); + Serial.println(analogRead(bluePin)); +} + +/* Processing code for this example + +// This example code is in the public domain. + + import processing.serial.*; + + float redValue = 0; // red value + float greenValue = 0; // green value + float blueValue = 0; // blue value + + Serial myPort; + + void setup() { + size(200, 200); + + // List all the available serial ports + println(Serial.list()); + // I know that the first port in the serial list on my mac + // is always my Arduino, so I open Serial.list()[0]. + // Open whatever port is the one you're using. + myPort = new Serial(this, Serial.list()[0], 9600); + // don't generate a serialEvent() unless you get a newline character: + myPort.bufferUntil('\n'); + } + + void draw() { + // set the background color with the color values: + background(redValue, greenValue, blueValue); + } + + void serialEvent(Serial myPort) { + // get the ASCII string: + String inString = myPort.readStringUntil('\n'); + + if (inString != null) { + // trim off any whitespace: + inString = trim(inString); + // split the string on the commas and convert the + // resulting substrings into an integer array: + float[] colors = float(split(inString, ",")); + // if the array has at least three elements, you know + // you got the whole thing. Put the numbers in the + // color variables: + if (colors.length >=3) { + // map them to the range 0-255: + redValue = map(colors[0], 0, 1023, 0, 255); + greenValue = map(colors[1], 0, 1023, 0, 255); + blueValue = map(colors[2], 0, 1023, 0, 255); + } + } + } + */ + +/* Max/MSP patch for this example + + ----------begin_max5_patcher---------- +1512.3oc4Z00aaaCE8YmeED9ktB35xOjrj1aAsXX4g8xZQeYoXfVh1gqRjdT +TsIsn+2K+PJUovVVJ1VMdCAvxThV7bO7b48dIyWtXxzkxaYkSA+J3u.Sl7kK +lLwcK6MlT2dxzB5so4zRW2lJXeRt7elNy+HM6Vs61uDDzbOYkNmo02sg4euS +4BSede8S2P0o2vEq+aEKU66PPP7b3LPHDauPvyCmAvv4v6+M7L2XXF2WfCaF +lURgVPKbCxzKUbZdySDUEbgABN.ia08R9mccGYGn66qGutNir27qWbg8iY+7 +HDRx.Hjf+OPHCQgPdpQHoxhBlwB+QF4cbkthlCRk4REnfeKScs3ZwaugWBbj +.PS+.qDPAkZkgPlY5oPS4By2A5aTLFv9pounjsgpnZVF3x27pqtBrRpJnZaa +C3WxTkfUJYA.BzR.BhIy.ehquw7dSoJCsrlATLckR.nhLPNWvVwL+Vp1LHL. +SjMG.tRaG7OxT5R2c8Hx9B8.wLCxVaGI6qnpj45Ug84kL+6YIM8CqUxJyycF +7bqsBRULGvwfWyRMyovElat7NvqoejaLm4f+fkmyKuVTHy3q3ldhB.WtQY6Z +x0BSOeSpTqA+FW+Yy3SyybH3sFy8p0RVCmaMpTyX6HdDZ2JsPbfSogbBMueH +JLd6RMBdfRMzPjZvimuWIK2XgFA.ZmtfKoh0Sm88qc6OF4bDQ3P6kEtF6xej +.OkjD4H5OllyS+.3FlhY0so4xRlWqyrXErQpt+2rsnXgQNZHZgmMVzEofW7T +S4zORQtgIdDbRHrObRzSMNofUVZVcbKbhQZrSOo934TqRHIN2ncr7BF8TKR1 +tHDqL.PejLRRPKMR.pKFAkbtDa+UOvsYsIFH0DYsTCjqZ66T1CmGeDILLpSm +myk0SdkOKh5LUr4GbWwRYdW7fm.BvDmzHnSdH3biGpSbxxDNJoGDAD1ChH7L +I0DaloOTBLvkO7zPs5HJnKNoGAXbol5eytUhfyiSfnjE1uAq+Fp0a+wygGwR +q3ZI8.psJpkpJnyPzwmXBj7Sh.+bNvVZxlcKAm0OYHIxcIjzEKdRChgO5UMf +LkMPNN0MfiS7Ev6TYQct.F5IWcCZ4504rGsiVswGWWSYyma01QcZgmL+f+sf +oU18Hn6o6dXkMkFF14TL9rIAWE+6wvGV.p.TPqz3HK5L+VxYxl4UmBKEjr.B +6zinuKI3C+D2Y7azIM6N7QL6t+jQyZxymK1ToAKqVsxjlGyjz2c1kTK3180h +kJEYkacWpv6lyp2VJTjWK47wHA6fyBOWxH9pUf6jUtZkLpNKW.9EeUBH3ymY +XSQlaqGrkQMGzp20adYSmIOGjIABo1xZyAWJtCX9tg6+HMuhMCPyx76ao+Us +UxmzUE79H8d2ZB1m1ztbnOa1mGeAq0awyK8a9UqBUc6pZolpzurTK232e5gp +aInVw8QIIcpaiNSJfY4Z+92Cs+Mc+mgg2cEsvGlLY6V+1kMuioxnB5VM+fsY +9vSu4WI1PMBGXye6KXvNuzmZTh7U9h5j6vvASdngPdgOFxycNL6ia1axUMmT +JIzebXcQCn3SKMf+4QCMmOZung+6xBCPLfwO8ngcEI52YJ1y7mx3CN9xKUYU +bg7Y1yXjlKW6SrZnguQdsSfOSSDItqv2jwJFjavc1vO7OigyBr2+gDYorRk1 +HXZpVFfu2FxXkZtfp4RQqNkX5y2sya3YYL2iavWAOaizH+pw.Ibg8f1I9h3Z +2B79sNeOHvBOtfEalWsvyu0KMf015.AaROvZ7vv5AhnndfHLbTgjcCK1KlHv +gOk5B26OqrXjcJ005.QqCHn8fVTxnxfj93SfQiJlv8YV0VT9fVUwOOhSV3uD +eeqCUClbBPa.j3vWDoMZssNTzRNEnE6gYPXazZaMF921syaLWyAeBXvCESA8 +ASi6Zyw8.RQi65J8ZsNx3ho93OhGWENtWpowepae4YhCFeLErOLENtXJrOSc +iadi39rf4hwc8xdhHz3gn3dBI7iDRlFe8huAfIZhq +-----------end_max5_patcher----------- + + + */ diff --git a/build/shared/examples/5.Control/Arrays/Arrays.ino b/build/shared/examples/5.Control/Arrays/Arrays.ino new file mode 100644 index 000000000..f5154770c --- /dev/null +++ b/build/shared/examples/5.Control/Arrays/Arrays.ino @@ -0,0 +1,57 @@ +/* + Arrays + + Demonstrates the use of an array to hold pin numbers + in order to iterate over the pins in a sequence. + Lights multiple LEDs in sequence, then in reverse. + + Unlike the For Loop tutorial, where the pins have to be + contiguous, here the pins can be in any random order. + + The circuit: + * LEDs from pins 2 through 7 to ground + + created 2006 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe + +This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Array + */ + +int timer = 100; // The higher the number, the slower the timing. +int ledPins[] = { + 2, 7, 4, 6, 5, 3 }; // an array of pin numbers to which LEDs are attached +int pinCount = 6; // the number of pins (i.e. the length of the array) + +void setup() { + int thisPin; + // the array elements are numbered from 0 to (pinCount - 1). + // use a for loop to initialize each pin as an output: + for (int thisPin = 0; thisPin < pinCount; thisPin++) { + pinMode(ledPins[thisPin], OUTPUT); + } +} + +void loop() { + // loop from the lowest pin to the highest: + for (int thisPin = 0; thisPin < pinCount; thisPin++) { + // turn the pin on: + digitalWrite(ledPins[thisPin], HIGH); + delay(timer); + // turn the pin off: + digitalWrite(ledPins[thisPin], LOW); + + } + + // loop from the highest pin to the lowest: + for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { + // turn the pin on: + digitalWrite(ledPins[thisPin], HIGH); + delay(timer); + // turn the pin off: + digitalWrite(ledPins[thisPin], LOW); + } +} diff --git a/build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.ino b/build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.ino new file mode 100644 index 000000000..d9ce32b8f --- /dev/null +++ b/build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.ino @@ -0,0 +1,47 @@ +/* + For Loop Iteration + + Demonstrates the use of a for() loop. + Lights multiple LEDs in sequence, then in reverse. + + The circuit: + * LEDs from pins 2 through 7 to ground + + created 2006 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe + +This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ForLoop + */ + +int timer = 100; // The higher the number, the slower the timing. + +void setup() { + // use a for loop to initialize each pin as an output: + for (int thisPin = 2; thisPin < 8; thisPin++) { + pinMode(thisPin, OUTPUT); + } +} + +void loop() { + // loop from the lowest pin to the highest: + for (int thisPin = 2; thisPin < 8; thisPin++) { + // turn the pin on: + digitalWrite(thisPin, HIGH); + delay(timer); + // turn the pin off: + digitalWrite(thisPin, LOW); + } + + // loop from the highest pin to the lowest: + for (int thisPin = 7; thisPin >= 2; thisPin--) { + // turn the pin on: + digitalWrite(thisPin, HIGH); + delay(timer); + // turn the pin off: + digitalWrite(thisPin, LOW); + } +} diff --git a/build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.ino b/build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.ino new file mode 100644 index 000000000..8346f2cbb --- /dev/null +++ b/build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.ino @@ -0,0 +1,56 @@ +/* + Conditionals - If statement + + This example demonstrates the use of if() statements. + It reads the state of a potentiometer (an analog input) and turns on an LED + only if the LED goes above a certain threshold level. It prints the analog value + regardless of the level. + + The circuit: + * potentiometer connected to analog pin 0. + Center pin of the potentiometer goes to the analog pin. + side pins of the potentiometer go to +5V and ground + * LED connected from digital pin 13 to ground + + * Note: On most Arduino boards, there is already an LED on the board + connected to pin 13, so you don't need any extra components for this example. + + created 17 Jan 2009 + modified 30 Aug 2011 + by Tom Igoe + +This example code is in the public domain. + +http://arduino.cc/en/Tutorial/IfStatement + + */ + +// These constants won't change: +const int analogPin = A0; // pin that the sensor is attached to +const int ledPin = 13; // pin that the LED is attached to +const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input + +void setup() { + // initialize the LED pin as an output: + pinMode(ledPin, OUTPUT); + // initialize serial communications: + Serial.begin(9600); +} + +void loop() { + // read the value of the potentiometer: + int analogValue = analogRead(analogPin); + + // if the analog value is high enough, turn on the LED: + if (analogValue > threshold) { + digitalWrite(ledPin, HIGH); + } + else { + digitalWrite(ledPin,LOW); + } + + // print the analog value: + Serial.println(analogValue); + +} + diff --git a/build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.ino b/build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.ino new file mode 100644 index 000000000..9cffeef22 --- /dev/null +++ b/build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.ino @@ -0,0 +1,88 @@ +/* + Conditionals - while statement + + This example demonstrates the use of while() statements. + + While the pushbutton is pressed, the sketch runs the calibration routine. + The sensor readings during the while loop define the minimum and maximum + of expected values from the photo resistor. + + This is a variation on the calibrate example. + + The circuit: + * photo resistor connected from +5V to analog in pin 0 + * 10K resistor connected from ground to analog in pin 0 + * LED connected from digital pin 9 to ground through 220 ohm resistor + * pushbutton attached from pin 2 to +5V + * 10K resistor attached from pin 2 to ground + + created 17 Jan 2009 + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + http://arduino.cc/en/Tutorial/WhileLoop + + */ + + +// These constants won't change: +const int sensorPin = A2; // pin that the sensor is attached to +const int ledPin = 9; // pin that the LED is attached to +const int indicatorLedPin = 13; // pin that the built-in LED is attached to +const int buttonPin = 2; // pin that the button is attached to + + +// These variables will change: +int sensorMin = 1023; // minimum sensor value +int sensorMax = 0; // maximum sensor value +int sensorValue = 0; // the sensor value + + +void setup() { + // set the LED pins as outputs and the switch pin as input: + pinMode(indicatorLedPin, OUTPUT); + pinMode (ledPin, OUTPUT); + pinMode (buttonPin, INPUT); +} + +void loop() { + // while the button is pressed, take calibration readings: + while (digitalRead(buttonPin) == HIGH) { + calibrate(); + } + // signal the end of the calibration period + digitalWrite(indicatorLedPin, LOW); + + // read the sensor: + sensorValue = analogRead(sensorPin); + + // apply the calibration to the sensor reading + sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255); + + // in case the sensor value is outside the range seen during calibration + sensorValue = constrain(sensorValue, 0, 255); + + // fade the LED using the calibrated value: + analogWrite(ledPin, sensorValue); +} + +void calibrate() { + // turn on the indicator LED to indicate that calibration is happening: + digitalWrite(indicatorLedPin, HIGH); + // read the sensor: + sensorValue = analogRead(sensorPin); + + // record the maximum sensor value + if (sensorValue > sensorMax) { + sensorMax = sensorValue; + } + + // record the minimum sensor value + if (sensorValue < sensorMin) { + sensorMin = sensorValue; + } +} + + diff --git a/build/shared/examples/5.Control/switchCase/switchCase.ino b/build/shared/examples/5.Control/switchCase/switchCase.ino new file mode 100644 index 000000000..87eb3f340 --- /dev/null +++ b/build/shared/examples/5.Control/switchCase/switchCase.ino @@ -0,0 +1,62 @@ +/* + Switch statement + + Demonstrates the use of a switch statement. The switch + statement allows you to choose from among a set of discrete values + of a variable. It's like a series of if statements. + + To see this sketch in action, but the board and sensor in a well-lit + room, open the serial monitor, and and move your hand gradually + down over the sensor. + + The circuit: + * photoresistor from analog in 0 to +5V + * 10K resistor from analog in 0 to ground + + created 1 Jul 2009 + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/SwitchCase + */ + +// these constants won't change: +const int sensorMin = 0; // sensor minimum, discovered through experiment +const int sensorMax = 600; // sensor maximum, discovered through experiment + +void setup() { + // initialize serial communication: + Serial.begin(9600); +} + +void loop() { + // read the sensor: + int sensorReading = analogRead(A0); + // map the sensor range to a range of four options: + int range = map(sensorReading, sensorMin, sensorMax, 0, 3); + + // do something different depending on the + // range value: + switch (range) { + case 0: // your hand is on the sensor + Serial.println("dark"); + break; + case 1: // your hand is close to the sensor + Serial.println("dim"); + break; + case 2: // your hand is a few inches from the sensor + Serial.println("medium"); + break; + case 3: // your hand is nowhere near the sensor + Serial.println("bright"); + break; + } + +} + + + + + diff --git a/build/shared/examples/5.Control/switchCase2/switchCase2.pde b/build/shared/examples/5.Control/switchCase2/switchCase2.ino similarity index 100% rename from build/shared/examples/5.Control/switchCase2/switchCase2.pde rename to build/shared/examples/5.Control/switchCase2/switchCase2.ino diff --git a/build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.ino b/build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.ino new file mode 100644 index 000000000..a55cc016a --- /dev/null +++ b/build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.ino @@ -0,0 +1,64 @@ + +/* + ADXL3xx + + Reads an Analog Devices ADXL3xx accelerometer and communicates the + acceleration to the computer. The pins used are designed to be easily + compatible with the breakout boards from Sparkfun, available from: + http://www.sparkfun.com/commerce/categories.php?c=80 + + http://www.arduino.cc/en/Tutorial/ADXL3xx + + The circuit: + analog 0: accelerometer self test + analog 1: z-axis + analog 2: y-axis + analog 3: x-axis + analog 4: ground + analog 5: vcc + + created 2 Jul 2008 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + +*/ + +// these constants describe the pins. They won't change: +const int groundpin = 18; // analog input pin 4 -- ground +const int powerpin = 19; // analog input pin 5 -- voltage +const int xpin = A3; // x-axis of the accelerometer +const int ypin = A2; // y-axis +const int zpin = A1; // z-axis (only on 3-axis models) + +void setup() +{ + // initialize the serial communications: + Serial.begin(9600); + + // Provide ground and power by using the analog inputs as normal + // digital pins. This makes it possible to directly connect the + // breakout board to the Arduino. If you use the normal 5V and + // GND pins on the Arduino, you can remove these lines. + pinMode(groundpin, OUTPUT); + pinMode(powerpin, OUTPUT); + digitalWrite(groundpin, LOW); + digitalWrite(powerpin, HIGH); +} + +void loop() +{ + // print the sensor values: + Serial.print(analogRead(xpin)); + // print a tab between values: + Serial.print("\t"); + Serial.print(analogRead(ypin)); + // print a tab between values: + Serial.print("\t"); + Serial.print(analogRead(zpin)); + Serial.println(); + // delay before next reading: + delay(100); +} diff --git a/build/shared/examples/6.Sensors/Knock/Knock.ino b/build/shared/examples/6.Sensors/Knock/Knock.ino new file mode 100644 index 000000000..6f8c2c55a --- /dev/null +++ b/build/shared/examples/6.Sensors/Knock/Knock.ino @@ -0,0 +1,55 @@ +/* Knock Sensor + + This sketch reads a piezo element to detect a knocking sound. + It reads an analog pin and compares the result to a set threshold. + If the result is greater than the threshold, it writes + "knock" to the serial port, and toggles the LED on pin 13. + + The circuit: + * + connection of the piezo attached to analog in 0 + * - connection of the piezo attached to ground + * 1-megohm resistor attached from analog in 0 to ground + + http://www.arduino.cc/en/Tutorial/Knock + + created 25 Mar 2007 + by David Cuartielles + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + */ + + +// these constants won't change: +const int ledPin = 13; // led connected to digital pin 13 +const int knockSensor = A0; // the piezo is connected to analog pin 0 +const int threshold = 100; // threshold value to decide when the detected sound is a knock or not + + +// these variables will change: +int sensorReading = 0; // variable to store the value read from the sensor pin +int ledState = LOW; // variable used to store the last LED status, to toggle the light + +void setup() { + pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT + Serial.begin(9600); // use the serial port +} + +void loop() { + // read the sensor and store it in the variable sensorReading: + sensorReading = analogRead(knockSensor); + + // if the sensor reading is greater than the threshold: + if (sensorReading >= threshold) { + // toggle the status of the ledPin: + ledState = !ledState; + // update the LED pin itself: + digitalWrite(ledPin, ledState); + // send the string "Knock!" back to the computer, followed by newline + Serial.println("Knock!"); + } + delay(100); // delay to avoid overloading the serial port buffer +} + diff --git a/build/shared/examples/6.Sensors/Memsic2125/Memsic2125.ino b/build/shared/examples/6.Sensors/Memsic2125/Memsic2125.ino new file mode 100644 index 000000000..974ccb52f --- /dev/null +++ b/build/shared/examples/6.Sensors/Memsic2125/Memsic2125.ino @@ -0,0 +1,63 @@ +/* + Memsic2125 + + Read the Memsic 2125 two-axis accelerometer. Converts the + pulses output by the 2125 into milli-g's (1/1000 of earth's + gravity) and prints them over the serial connection to the + computer. + + The circuit: + * X output of accelerometer to digital pin 2 + * Y output of accelerometer to digital pin 3 + * +V of accelerometer to +5V + * GND of accelerometer to ground + + http://www.arduino.cc/en/Tutorial/Memsic2125 + + created 6 Nov 2008 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + */ + +// these constants won't change: +const int xPin = 2; // X output of the accelerometer +const int yPin = 3; // Y output of the accelerometer + +void setup() { + // initialize serial communications: + Serial.begin(9600); + // initialize the pins connected to the accelerometer + // as inputs: + pinMode(xPin, INPUT); + pinMode(yPin, INPUT); +} + +void loop() { + // variables to read the pulse widths: + int pulseX, pulseY; + // variables to contain the resulting accelerations + int accelerationX, accelerationY; + + // read pulse from x- and y-axes: + pulseX = pulseIn(xPin,HIGH); + pulseY = pulseIn(yPin,HIGH); + + // convert the pulse width into acceleration + // accelerationX and accelerationY are in milli-g's: + // earth's gravity is 1000 milli-g's, or 1g. + accelerationX = ((pulseX / 10) - 500) * 8; + accelerationY = ((pulseY / 10) - 500) * 8; + + // print the acceleration + Serial.print(accelerationX); + // print a tab character: + Serial.print("\t"); + Serial.print(accelerationY); + Serial.println(); + + delay(100); +} diff --git a/build/shared/examples/6.Sensors/Ping/Ping.ino b/build/shared/examples/6.Sensors/Ping/Ping.ino new file mode 100644 index 000000000..5de46d603 --- /dev/null +++ b/build/shared/examples/6.Sensors/Ping/Ping.ino @@ -0,0 +1,84 @@ +/* Ping))) Sensor + + This sketch reads a PING))) ultrasonic rangefinder and returns the + distance to the closest object in range. To do this, it sends a pulse + to the sensor to initiate a reading, then listens for a pulse + to return. The length of the returning pulse is proportional to + the distance of the object from the sensor. + + The circuit: + * +V connection of the PING))) attached to +5V + * GND connection of the PING))) attached to ground + * SIG connection of the PING))) attached to digital pin 7 + + http://www.arduino.cc/en/Tutorial/Ping + + created 3 Nov 2008 + by David A. Mellis + modified 30 Aug 2011 + by Tom Igoe + + This example code is in the public domain. + + */ + +// this constant won't change. It's the pin number +// of the sensor's output: +const int pingPin = 7; + +void setup() { + // initialize serial communication: + Serial.begin(9600); +} + +void loop() +{ + // establish variables for duration of the ping, + // and the distance result in inches and centimeters: + long duration, inches, cm; + + // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. + // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: + pinMode(pingPin, OUTPUT); + digitalWrite(pingPin, LOW); + delayMicroseconds(2); + digitalWrite(pingPin, HIGH); + delayMicroseconds(5); + digitalWrite(pingPin, LOW); + + // The same pin is used to read the signal from the PING))): a HIGH + // pulse whose duration is the time (in microseconds) from the sending + // of the ping to the reception of its echo off of an object. + pinMode(pingPin, INPUT); + duration = pulseIn(pingPin, HIGH); + + // convert the time into a distance + inches = microsecondsToInches(duration); + cm = microsecondsToCentimeters(duration); + + Serial.print(inches); + Serial.print("in, "); + Serial.print(cm); + Serial.print("cm"); + Serial.println(); + + delay(100); +} + +long microsecondsToInches(long microseconds) +{ + // According to Parallax's datasheet for the PING))), there are + // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per + // second). This gives the distance travelled by the ping, outbound + // and return, so we divide by 2 to get the distance of the obstacle. + // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf + return microseconds / 74 / 2; +} + +long microsecondsToCentimeters(long microseconds) +{ + // The speed of sound is 340 m/s or 29 microseconds per centimeter. + // The ping travels out and back, so to find the distance of the + // object we take half of the distance travelled. + return microseconds / 29 / 2; +} diff --git a/build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.ino b/build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.ino new file mode 100644 index 000000000..6be347295 --- /dev/null +++ b/build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.ino @@ -0,0 +1,114 @@ +/* + Row-Column Scanning an 8x8 LED matrix with X-Y input + + This example controls an 8x8 LED matrix using two analog inputs + + created 27 May 2009 + modified 30 Aug 2011 + by Tom Igoe + + This example works for the Lumex LDM-24488NI Matrix. See + http://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf + for the pin connections + + For other LED cathode column matrixes, you should only need to change + the pin numbers in the row[] and column[] arrays + + rows are the anodes + cols are the cathodes + --------- + + Pin numbers: + Matrix: + * Digital pins 2 through 13, + * analog pins 2 through 5 used as digital 16 through 19 + Potentiometers: + * center pins are attached to analog pins 0 and 1, respectively + * side pins attached to +5V and ground, respectively. + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/RowColumnScanning + + see also http://www.tigoe.net/pcomp/code/category/arduinowiring/514 for more + */ + + +// 2-dimensional array of row pin numbers: +const int row[8] = { + 2,7,19,5,13,18,12,16 }; + +// 2-dimensional array of column pin numbers: +const int col[8] = { + 6,11,10,3,17,4,8,9 }; + +// 2-dimensional array of pixels: +int pixels[8][8]; + +// cursor position: +int x = 5; +int y = 5; + +void setup() { + Serial.begin(9600); + // initialize the I/O pins as outputs: + + // iterate over the pins: + for (int thisPin = 0; thisPin < 8; thisPin++) { + // initialize the output pins: + pinMode(col[thisPin], OUTPUT); + pinMode(row[thisPin], OUTPUT); + // take the col pins (i.e. the cathodes) high to ensure that + // the LEDS are off: + digitalWrite(col[thisPin], HIGH); + } + + // initialize the pixel matrix: + for (int x = 0; x < 8; x++) { + for (int y = 0; y < 8; y++) { + pixels[x][y] = HIGH; + } + } +} + +void loop() { + // read input: + readSensors(); + + // draw the screen: + refreshScreen(); +} + +void readSensors() { + // turn off the last position: + pixels[x][y] = HIGH; + // read the sensors for X and Y values: + x = 7 - map(analogRead(A0), 0, 1023, 0, 7); + y = map(analogRead(A1), 0, 1023, 0, 7); + // set the new pixel position low so that the LED will turn on + // in the next screen refresh: + pixels[x][y] = LOW; + +} + +void refreshScreen() { + // iterate over the rows (anodes): + for (int thisRow = 0; thisRow < 8; thisRow++) { + // take the row pin (anode) high: + digitalWrite(row[thisRow], HIGH); + // iterate over the cols (cathodes): + for (int thisCol = 0; thisCol < 8; thisCol++) { + // get the state of the current pixel; + int thisPixel = pixels[thisRow][thisCol]; + // when the row is HIGH and the col is LOW, + // the LED where they meet turns on: + digitalWrite(col[thisCol], thisPixel); + // turn the pixel off: + if (thisPixel == LOW) { + digitalWrite(col[thisCol], HIGH); + } + } + // take the row pin low to turn off the whole row: + digitalWrite(row[thisRow], LOW); + } +} diff --git a/build/shared/examples/7.Display/barGraph/barGraph.pde b/build/shared/examples/7.Display/barGraph/barGraph.ino similarity index 100% rename from build/shared/examples/7.Display/barGraph/barGraph.pde rename to build/shared/examples/7.Display/barGraph/barGraph.ino diff --git a/build/shared/examples/8.Strings/CharacterAnalysis/CharacterAnalysis.pde b/build/shared/examples/8.Strings/CharacterAnalysis/CharacterAnalysis.ino similarity index 100% rename from build/shared/examples/8.Strings/CharacterAnalysis/CharacterAnalysis.pde rename to build/shared/examples/8.Strings/CharacterAnalysis/CharacterAnalysis.ino diff --git a/build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.ino b/build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.ino new file mode 100644 index 000000000..88938e864 --- /dev/null +++ b/build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.ino @@ -0,0 +1,61 @@ +/* + Adding Strings together + + Examples of how to add strings together + You can also add several different data types to string, as shown here: + + created 27 July 2010 + modified 30 Aug 2011 + by Tom Igoe + + http://arduino.cc/en/Tutorial/StringAdditionOperator + + This example code is in the public domain. + */ + +// declare three strings: +String stringOne, stringTwo, stringThree; + +void setup() { + Serial.begin(9600); + stringOne = String("stringThree = "); + stringTwo = String("this string"); + stringThree = String (); + Serial.println("\n\nAdding strings together (concatenation):"); +} + +void loop() { + // adding a constant integer to a string: + stringThree = stringOne + 123; + Serial.println(stringThree); // prints "stringThree = 123" + + // adding a constant long interger to a string: + stringThree = stringOne + 123456789; + Serial.println(stringThree); // prints " You added 123456789" + + // adding a constant character to a string: + stringThree = stringOne + 'A'; + Serial.println(stringThree); // prints "You added A" + + // adding a constant string to a string: + stringThree = stringOne + "abc"; + Serial.println(stringThree); // prints "You added abc" + + stringThree = stringOne + stringTwo; + Serial.println(stringThree); // prints "You added this string" + + // adding a variable integer to a string: + int sensorValue = analogRead(A0); + stringOne = "Sensor value: "; + stringThree = stringOne + sensorValue; + Serial.println(stringThree); // prints "Sensor Value: 401" or whatever value analogRead(A0) has + + // adding a variable long integer to a string: + long currentTime = millis(); + stringOne="millis() value: "; + stringThree = stringOne + millis(); + Serial.println(stringThree); // prints "The millis: 345345" or whatever value currentTime has + + // do nothing while true: + while(true); +} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.ino b/build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.ino new file mode 100644 index 000000000..cb902ca6b --- /dev/null +++ b/build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.ino @@ -0,0 +1,64 @@ +/* + Appending to Strings using the += operator and concat() + + Examples of how to append different data types to strings + + created 27 July 2010 + modified 30 Aug 2011 + by Tom Igoe + + http://arduino.cc/en/Tutorial/StringAppendOperator + + This example code is in the public domain. + */ +String stringOne, stringTwo; + +void setup() { + Serial.begin(9600); + stringOne = String("Sensor "); + stringTwo = String("value"); + Serial.println("\n\nAppending to a string:"); +} + +void loop() { + Serial.println(stringOne); // prints "Sensor " + + // adding a string to a string: + stringOne += stringTwo; + Serial.println(stringOne); // prints "Sensor value" + + // adding a constant string to a string: + stringOne += " for input "; + Serial.println(stringOne); // prints "Sensor value for input" + + // adding a constant character to a string: + stringOne += 'A'; + Serial.println(stringOne); // prints "Sensor value for input A" + + // adding a constant integer to a string: + stringOne += 0; + Serial.println(stringOne); // prints "Sensor value for input A0" + + // adding a constant string to a string: + stringOne += ": "; + Serial.println(stringOne); // prints "Sensor value for input" + + // adding a variable integer to a string: + stringOne += analogRead(A0); + Serial.println(stringOne); // prints "Sensor value for input A0: 456" or whatever analogRead(A0) is + + Serial.println("\n\nchanging the Strings' values"); + stringOne = "A long integer: "; + stringTwo = "The millis(): "; + + // adding a constant long integer to a string: + stringOne += 123456789; + Serial.println(stringOne); // prints "A long integer: 123456789" + + // using concat() to add a long variable to a string: + stringTwo.concat(millis()); + Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is + + // do nothing while true: + while(true); +} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringCaseChanges/StringCaseChanges.pde b/build/shared/examples/8.Strings/StringCaseChanges/StringCaseChanges.ino similarity index 100% rename from build/shared/examples/8.Strings/StringCaseChanges/StringCaseChanges.pde rename to build/shared/examples/8.Strings/StringCaseChanges/StringCaseChanges.ino diff --git a/build/shared/examples/8.Strings/StringCharacters/StringCharacters.pde b/build/shared/examples/8.Strings/StringCharacters/StringCharacters.ino similarity index 100% rename from build/shared/examples/8.Strings/StringCharacters/StringCharacters.pde rename to build/shared/examples/8.Strings/StringCharacters/StringCharacters.ino diff --git a/build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.ino b/build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.ino new file mode 100644 index 000000000..53c7492e5 --- /dev/null +++ b/build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.ino @@ -0,0 +1,124 @@ +/* + Comparing Strings + + Examples of how to compare strings using the comparison operators + + created 27 July 2010 + modified 30 Aug 2011 + by Tom Igoe + + http://arduino.cc/en/Tutorial/StringComparisonOperators + + This example code is in the public domain. + */ + +String stringOne, stringTwo; + +void setup() { + Serial.begin(9600); + stringOne = String("this"); + stringTwo = String("that"); + Serial.println("\n\nComparing Strings:"); + +} + +void loop() { + // two strings equal: + if (stringOne == "this") { + Serial.println("StringOne == \"this\""); + } + // two strings not equal: + if (stringOne != stringTwo) { + Serial.println(stringOne + " =! " + stringTwo); + } + + // two strings not equal (case sensitivity matters): + stringOne = "This"; + stringTwo = "this"; + if (stringOne != stringTwo) { + Serial.println(stringOne + " =! " + stringTwo); + } + // you can also use equals() to see if two strings are the same: + if (stringOne.equals(stringTwo)) { + Serial.println(stringOne + " equals " + stringTwo); + } + else { + Serial.println(stringOne + " does not equal " + stringTwo); + } + + // or perhaps you want to ignore case: + if (stringOne.equalsIgnoreCase(stringTwo)) { + Serial.println(stringOne + " equals (ignoring case) " + stringTwo); + } + else { + Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo); + } + + // a numeric string compared to the number it represents: + stringOne = "1"; + int numberOne = 1; + if (stringOne == numberOne) { + Serial.println(stringOne + " = " + numberOne); + } + + + + // two numeric strings compared: + stringOne = "2"; + stringTwo = "1"; + if (stringOne >= stringTwo) { + Serial.println(stringOne + " >= " + stringTwo); + } + + // comparison operators can be used to compare strings for alphabetic sorting too: + stringOne = String("Brown"); + if (stringOne < "Charles") { + Serial.println(stringOne + " < Charles"); + } + + if (stringOne > "Adams") { + Serial.println(stringOne + " > Adams"); + } + + if (stringOne <= "Browne") { + Serial.println(stringOne + " <= Browne"); + } + + + if (stringOne >= "Brow") { + Serial.println(stringOne + " >= Brow"); + } + + // the compareTo() operator also allows you to compare strings + // it evaluates on the first character that's different. + // if the first character of the string you're comparing to + // comes first in alphanumeric order, then compareTo() is greater than 0: + stringOne = "Cucumber"; + stringTwo = "Cucuracha"; + if (stringOne.compareTo(stringTwo) < 0 ) { + Serial.println(stringOne + " comes before " + stringTwo); + } + else { + Serial.println(stringOne + " comes after " + stringTwo); + } + + delay(10000); // because the next part is a loop: + + // compareTo() is handy when you've got strings with numbers in them too: + + while (true) { + stringOne = "Sensor: "; + stringTwo= "Sensor: "; + + stringOne += analogRead(A0); + stringTwo += analogRead(A5); + + if (stringOne.compareTo(stringTwo) < 0 ) { + Serial.println(stringOne + " comes before " + stringTwo); + } + else { + Serial.println(stringOne + " comes after " + stringTwo); + + } + } +} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringConstructors/StringConstructors.ino b/build/shared/examples/8.Strings/StringConstructors/StringConstructors.ino new file mode 100644 index 000000000..ee7e8701c --- /dev/null +++ b/build/shared/examples/8.Strings/StringConstructors/StringConstructors.ino @@ -0,0 +1,64 @@ +/* + String constructors + + Examples of how to create strings from other data types + + created 27 July 2010 + modified 30 Aug 2011 + by Tom Igoe + + http://arduino.cc/en/Tutorial/StringConstructors + + This example code is in the public domain. + */ + +void setup() { + Serial.begin(9600); +} + +void loop() { + // using a constant String: + String stringOne = "Hello String"; + Serial.println(stringOne); // prints "Hello String" + + // converting a constant char into a String: + stringOne = String('a'); + Serial.println(stringOne); // prints "a" + + // converting a constant string into a String object: + String stringTwo = String("This is a string"); + Serial.println(stringTwo); // prints "This is a string" + + // concatenating two strings: + stringOne = String(stringTwo + " with more"); + // prints "This is a string with more": + Serial.println(stringOne); + + // using a constant integer: + stringOne = String(13); + Serial.println(stringOne); // prints "13" + + // using an int and a base: + stringOne = String(analogRead(A0), DEC); + // prints "453" or whatever the value of analogRead(A0) is + Serial.println(stringOne); + + // using an int and a base (hexadecimal): + stringOne = String(45, HEX); + // prints "2d", which is the hexadecimal version of decimal 45: + Serial.println(stringOne); + + // using an int and a base (binary) + stringOne = String(255, BIN); + // prints "11111111" which is the binary value of 255 + Serial.println(stringOne); + + // using a long and a base: + stringOne = String(millis(), DEC); + // prints "123456" or whatever the value of millis() is: + Serial.println(stringOne); + + // do nothing while true: + while(true); + +} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringIndexOf/StringIndexOf.pde b/build/shared/examples/8.Strings/StringIndexOf/StringIndexOf.ino similarity index 100% rename from build/shared/examples/8.Strings/StringIndexOf/StringIndexOf.pde rename to build/shared/examples/8.Strings/StringIndexOf/StringIndexOf.ino diff --git a/build/shared/examples/8.Strings/StringLength/StringLength.pde b/build/shared/examples/8.Strings/StringLength/StringLength.ino similarity index 100% rename from build/shared/examples/8.Strings/StringLength/StringLength.pde rename to build/shared/examples/8.Strings/StringLength/StringLength.ino diff --git a/build/shared/examples/8.Strings/StringLengthTrim/StringLengthTrim.pde b/build/shared/examples/8.Strings/StringLengthTrim/StringLengthTrim.ino similarity index 100% rename from build/shared/examples/8.Strings/StringLengthTrim/StringLengthTrim.pde rename to build/shared/examples/8.Strings/StringLengthTrim/StringLengthTrim.ino diff --git a/build/shared/examples/8.Strings/StringReplace/StringReplace.pde b/build/shared/examples/8.Strings/StringReplace/StringReplace.ino similarity index 100% rename from build/shared/examples/8.Strings/StringReplace/StringReplace.pde rename to build/shared/examples/8.Strings/StringReplace/StringReplace.ino diff --git a/build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino b/build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino new file mode 100644 index 000000000..429ec60d9 --- /dev/null +++ b/build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.ino @@ -0,0 +1,49 @@ +/* + String startWith() and endsWith() + + Examples of how to use startsWith() and endsWith() in a String + + created 27 July 2010 + modified 30 Aug 2011 + by Tom Igoe + + http://arduino.cc/en/Tutorial/StringStartsWithEndsWith + + This example code is in the public domain. + */ + +void setup() { + Serial.begin(9600); + Serial.println("\n\nString startsWith() and endsWith():"); + +} + +void loop() { +// startsWith() checks to see if a String starts with a particular substring: + String stringOne = "HTTP/1.1 200 OK"; + Serial.println(stringOne); + if (stringOne.startsWith("HTTP/1.1")) { + Serial.println("Server's using http version 1.1"); + } + + // you can also look for startsWith() at an offset position in the string: + stringOne = "HTTP/1.1 200 OK"; + if (stringOne.startsWith("200 OK", 9)) { + Serial.println("Got an OK from the server"); + } + + // endsWith() checks to see if a String ends with a particular character: + String sensorReading = "sensor = "; + sensorReading += analogRead(A0); + Serial.print (sensorReading); + if (sensorReading.endsWith(0)) { + Serial.println(". This reading is divisible by ten"); + } + else { + Serial.println(". This reading is not divisible by ten"); + + } + +// do nothing while true: + while(true); +} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringSubstring/StringSubstring.pde b/build/shared/examples/8.Strings/StringSubstring/StringSubstring.ino similarity index 100% rename from build/shared/examples/8.Strings/StringSubstring/StringSubstring.pde rename to build/shared/examples/8.Strings/StringSubstring/StringSubstring.ino diff --git a/build/shared/examples/8.Strings/StringToInt/StringToInt.pde b/build/shared/examples/8.Strings/StringToInt/StringToInt.ino similarity index 100% rename from build/shared/examples/8.Strings/StringToInt/StringToInt.pde rename to build/shared/examples/8.Strings/StringToInt/StringToInt.ino diff --git a/build/shared/examples/8.Strings/StringToIntRGB/StringToIntRGB.pde b/build/shared/examples/8.Strings/StringToIntRGB/StringToIntRGB.ino similarity index 100% rename from build/shared/examples/8.Strings/StringToIntRGB/StringToIntRGB.pde rename to build/shared/examples/8.Strings/StringToIntRGB/StringToIntRGB.ino diff --git a/build/shared/examples/ArduinoISP/ArduinoISP.pde b/build/shared/examples/ArduinoISP/ArduinoISP.ino similarity index 100% rename from build/shared/examples/ArduinoISP/ArduinoISP.pde rename to build/shared/examples/ArduinoISP/ArduinoISP.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.pde b/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.pde rename to libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.pde b/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.pde rename to libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.pde b/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.pde rename to libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.pde b/libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.pde rename to libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.pde b/libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.pde rename to libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.pde b/libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.pde rename to libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.pde b/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.pde rename to libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.pde b/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.pde rename to libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_StringTest/ATS_StringTest.pde b/libraries/ArduinoTestSuite/examples/ATS_StringTest/ATS_StringTest.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_StringTest/ATS_StringTest.pde rename to libraries/ArduinoTestSuite/examples/ATS_StringTest/ATS_StringTest.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.pde b/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.pde rename to libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.ino diff --git a/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.pde b/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.ino similarity index 100% rename from libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.pde rename to libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.ino diff --git a/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.pde b/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino similarity index 100% rename from libraries/EEPROM/examples/eeprom_clear/eeprom_clear.pde rename to libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino diff --git a/libraries/EEPROM/examples/eeprom_read/eeprom_read.pde b/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino similarity index 100% rename from libraries/EEPROM/examples/eeprom_read/eeprom_read.pde rename to libraries/EEPROM/examples/eeprom_read/eeprom_read.ino diff --git a/libraries/EEPROM/examples/eeprom_write/eeprom_write.pde b/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino similarity index 100% rename from libraries/EEPROM/examples/eeprom_write/eeprom_write.pde rename to libraries/EEPROM/examples/eeprom_write/eeprom_write.ino diff --git a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino similarity index 100% rename from libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.pde rename to libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino diff --git a/libraries/Ethernet/examples/ChatServer/ChatServer.pde b/libraries/Ethernet/examples/ChatServer/ChatServer.ino similarity index 100% rename from libraries/Ethernet/examples/ChatServer/ChatServer.pde rename to libraries/Ethernet/examples/ChatServer/ChatServer.ino diff --git a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino index 8701568c0..50a557dcc 100644 --- a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino +++ b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino @@ -30,18 +30,17 @@ void setup() { // start the serial library: Serial.begin(9600); // start the Ethernet connection: - Serial.println("Trying to get an IP address using DHCP");z if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: - while(true); + for(;;) + ; } // print your local IP address: Serial.print("My IP address: "); - IPAddress myIPAddress = Ethernet.localIP(); for (byte thisByte = 0; thisByte < 4; thisByte++) { // print the value of each byte of the IP address: - Serial.print(myIPAddress[thisByte], DEC); + Serial.print(Ethernet.localIP()[thisByte], DEC); Serial.print("."); } Serial.println(); diff --git a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.pde b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.pde deleted file mode 100644 index 50a557dcc..000000000 --- a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.pde +++ /dev/null @@ -1,53 +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 - 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): -Client client; - -void setup() { - // start the serial library: - Serial.begin(9600); - // 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/DnsWebClient/DnsWebClient.pde b/libraries/Ethernet/examples/DnsWebClient/DnsWebClient.ino similarity index 100% rename from libraries/Ethernet/examples/DnsWebClient/DnsWebClient.pde rename to libraries/Ethernet/examples/DnsWebClient/DnsWebClient.ino diff --git a/libraries/Ethernet/examples/PachubeClient/PachubeClient.pde b/libraries/Ethernet/examples/PachubeClient/PachubeClient.ino similarity index 100% rename from libraries/Ethernet/examples/PachubeClient/PachubeClient.pde rename to libraries/Ethernet/examples/PachubeClient/PachubeClient.ino diff --git a/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde b/libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino similarity index 100% rename from libraries/Ethernet/examples/PachubeClientString/PachubeClientString.pde rename to libraries/Ethernet/examples/PachubeClientString/PachubeClientString.ino diff --git a/libraries/Ethernet/examples/TelnetClient/TelnetClient.pde b/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino similarity index 100% rename from libraries/Ethernet/examples/TelnetClient/TelnetClient.pde rename to libraries/Ethernet/examples/TelnetClient/TelnetClient.ino diff --git a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino similarity index 100% rename from libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde rename to libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino diff --git a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino similarity index 100% rename from libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde rename to libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino diff --git a/libraries/Ethernet/examples/WebClient/WebClient.pde b/libraries/Ethernet/examples/WebClient/WebClient.ino similarity index 100% rename from libraries/Ethernet/examples/WebClient/WebClient.pde rename to libraries/Ethernet/examples/WebClient/WebClient.ino diff --git a/libraries/Ethernet/examples/WebServer/WebServer.pde b/libraries/Ethernet/examples/WebServer/WebServer.ino similarity index 100% rename from libraries/Ethernet/examples/WebServer/WebServer.pde rename to libraries/Ethernet/examples/WebServer/WebServer.ino diff --git a/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.pde b/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino similarity index 100% rename from libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.pde rename to libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino diff --git a/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.pde b/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino similarity index 100% rename from libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.pde rename to libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino diff --git a/libraries/Firmata/examples/EchoString/EchoString.pde b/libraries/Firmata/examples/EchoString/EchoString.ino similarity index 100% rename from libraries/Firmata/examples/EchoString/EchoString.pde rename to libraries/Firmata/examples/EchoString/EchoString.ino diff --git a/libraries/Firmata/examples/I2CFirmata/I2CFirmata.pde b/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino similarity index 100% rename from libraries/Firmata/examples/I2CFirmata/I2CFirmata.pde rename to libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino diff --git a/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.pde b/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino similarity index 100% rename from libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.pde rename to libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino diff --git a/libraries/Firmata/examples/ServoFirmata/ServoFirmata.pde b/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino similarity index 100% rename from libraries/Firmata/examples/ServoFirmata/ServoFirmata.pde rename to libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino diff --git a/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.pde b/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino similarity index 100% rename from libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.pde rename to libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino diff --git a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.pde b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino similarity index 100% rename from libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.pde rename to libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino diff --git a/libraries/Firmata/examples/StandardFirmata/StandardFirmata.pde b/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmata/StandardFirmata.pde rename to libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino diff --git a/libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.pde b/libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.pde rename to libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.ino diff --git a/libraries/LiquidCrystal/examples/Autoscroll/Autoscroll.pde b/libraries/LiquidCrystal/examples/Autoscroll/Autoscroll.ino similarity index 100% rename from libraries/LiquidCrystal/examples/Autoscroll/Autoscroll.pde rename to libraries/LiquidCrystal/examples/Autoscroll/Autoscroll.ino diff --git a/libraries/LiquidCrystal/examples/Blink/Blink.pde b/libraries/LiquidCrystal/examples/Blink/Blink.ino similarity index 100% rename from libraries/LiquidCrystal/examples/Blink/Blink.pde rename to libraries/LiquidCrystal/examples/Blink/Blink.ino diff --git a/libraries/LiquidCrystal/examples/Cursor/Cursor.pde b/libraries/LiquidCrystal/examples/Cursor/Cursor.ino similarity index 100% rename from libraries/LiquidCrystal/examples/Cursor/Cursor.pde rename to libraries/LiquidCrystal/examples/Cursor/Cursor.ino diff --git a/libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.pde b/libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.ino similarity index 100% rename from libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.pde rename to libraries/LiquidCrystal/examples/CustomCharacter/CustomCharacter.ino diff --git a/libraries/LiquidCrystal/examples/Display/Display.pde b/libraries/LiquidCrystal/examples/Display/Display.ino similarity index 100% rename from libraries/LiquidCrystal/examples/Display/Display.pde rename to libraries/LiquidCrystal/examples/Display/Display.ino diff --git a/libraries/LiquidCrystal/examples/HelloWorld/HelloWorld.pde b/libraries/LiquidCrystal/examples/HelloWorld/HelloWorld.ino similarity index 100% rename from libraries/LiquidCrystal/examples/HelloWorld/HelloWorld.pde rename to libraries/LiquidCrystal/examples/HelloWorld/HelloWorld.ino diff --git a/libraries/LiquidCrystal/examples/Scroll/Scroll.pde b/libraries/LiquidCrystal/examples/Scroll/Scroll.ino similarity index 100% rename from libraries/LiquidCrystal/examples/Scroll/Scroll.pde rename to libraries/LiquidCrystal/examples/Scroll/Scroll.ino diff --git a/libraries/LiquidCrystal/examples/SerialDisplay/SerialDisplay.pde b/libraries/LiquidCrystal/examples/SerialDisplay/SerialDisplay.ino similarity index 100% rename from libraries/LiquidCrystal/examples/SerialDisplay/SerialDisplay.pde rename to libraries/LiquidCrystal/examples/SerialDisplay/SerialDisplay.ino diff --git a/libraries/LiquidCrystal/examples/TextDirection/TextDirection.pde b/libraries/LiquidCrystal/examples/TextDirection/TextDirection.ino similarity index 100% rename from libraries/LiquidCrystal/examples/TextDirection/TextDirection.pde rename to libraries/LiquidCrystal/examples/TextDirection/TextDirection.ino diff --git a/libraries/LiquidCrystal/examples/setCursor/setCursor.pde b/libraries/LiquidCrystal/examples/setCursor/setCursor.ino similarity index 100% rename from libraries/LiquidCrystal/examples/setCursor/setCursor.pde rename to libraries/LiquidCrystal/examples/setCursor/setCursor.ino diff --git a/libraries/SD/examples/CardInfo/CardInfo.pde b/libraries/SD/examples/CardInfo/CardInfo.ino similarity index 100% rename from libraries/SD/examples/CardInfo/CardInfo.pde rename to libraries/SD/examples/CardInfo/CardInfo.ino diff --git a/libraries/SD/examples/Datalogger/Datalogger.pde b/libraries/SD/examples/Datalogger/Datalogger.ino similarity index 100% rename from libraries/SD/examples/Datalogger/Datalogger.pde rename to libraries/SD/examples/Datalogger/Datalogger.ino diff --git a/libraries/SD/examples/DumpFile/DumpFile.pde b/libraries/SD/examples/DumpFile/DumpFile.ino similarity index 100% rename from libraries/SD/examples/DumpFile/DumpFile.pde rename to libraries/SD/examples/DumpFile/DumpFile.ino diff --git a/libraries/SD/examples/Files/Files.pde b/libraries/SD/examples/Files/Files.ino similarity index 100% rename from libraries/SD/examples/Files/Files.pde rename to libraries/SD/examples/Files/Files.ino diff --git a/libraries/SD/examples/ReadWrite/ReadWrite.pde b/libraries/SD/examples/ReadWrite/ReadWrite.ino similarity index 100% rename from libraries/SD/examples/ReadWrite/ReadWrite.pde rename to libraries/SD/examples/ReadWrite/ReadWrite.ino diff --git a/libraries/SD/examples/listfiles/listfiles.pde b/libraries/SD/examples/listfiles/listfiles.ino similarity index 100% rename from libraries/SD/examples/listfiles/listfiles.pde rename to libraries/SD/examples/listfiles/listfiles.ino diff --git a/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.pde b/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino similarity index 100% rename from libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.pde rename to libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino diff --git a/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.pde b/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.ino similarity index 100% rename from libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.pde rename to libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor/BarometricPressureSensor.ino diff --git a/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.pde b/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino similarity index 100% rename from libraries/SPI/examples/DigitalPotControl/DigitalPotControl.pde rename to libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino diff --git a/libraries/Servo/examples/Knob/Knob.pde b/libraries/Servo/examples/Knob/Knob.ino similarity index 100% rename from libraries/Servo/examples/Knob/Knob.pde rename to libraries/Servo/examples/Knob/Knob.ino diff --git a/libraries/Servo/examples/Sweep/Sweep.pde b/libraries/Servo/examples/Sweep/Sweep.ino similarity index 100% rename from libraries/Servo/examples/Sweep/Sweep.pde rename to libraries/Servo/examples/Sweep/Sweep.ino diff --git a/libraries/SoftwareSerial/examples/TwoPortRXExample/TwoPortRXExample.pde b/libraries/SoftwareSerial/examples/TwoPortRXExample/TwoPortRXExample.ino similarity index 100% rename from libraries/SoftwareSerial/examples/TwoPortRXExample/TwoPortRXExample.pde rename to libraries/SoftwareSerial/examples/TwoPortRXExample/TwoPortRXExample.ino diff --git a/libraries/Stepper/examples/MotorKnob/MotorKnob.pde b/libraries/Stepper/examples/MotorKnob/MotorKnob.ino similarity index 100% rename from libraries/Stepper/examples/MotorKnob/MotorKnob.pde rename to libraries/Stepper/examples/MotorKnob/MotorKnob.ino diff --git a/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.pde b/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino similarity index 100% rename from libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.pde rename to libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino diff --git a/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.pde b/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino similarity index 100% rename from libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.pde rename to libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino diff --git a/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.pde b/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino similarity index 100% rename from libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.pde rename to libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino diff --git a/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.pde b/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino similarity index 100% rename from libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.pde rename to libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino diff --git a/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.pde b/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino similarity index 100% rename from libraries/Wire/examples/digital_potentiometer/digital_potentiometer.pde rename to libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino diff --git a/libraries/Wire/examples/master_reader/master_reader.pde b/libraries/Wire/examples/master_reader/master_reader.ino similarity index 100% rename from libraries/Wire/examples/master_reader/master_reader.pde rename to libraries/Wire/examples/master_reader/master_reader.ino diff --git a/libraries/Wire/examples/master_writer/master_writer.pde b/libraries/Wire/examples/master_writer/master_writer.ino similarity index 100% rename from libraries/Wire/examples/master_writer/master_writer.pde rename to libraries/Wire/examples/master_writer/master_writer.ino diff --git a/libraries/Wire/examples/slave_receiver/slave_receiver.pde b/libraries/Wire/examples/slave_receiver/slave_receiver.ino similarity index 100% rename from libraries/Wire/examples/slave_receiver/slave_receiver.pde rename to libraries/Wire/examples/slave_receiver/slave_receiver.ino diff --git a/libraries/Wire/examples/slave_sender/slave_sender.pde b/libraries/Wire/examples/slave_sender/slave_sender.ino similarity index 100% rename from libraries/Wire/examples/slave_sender/slave_sender.pde rename to libraries/Wire/examples/slave_sender/slave_sender.ino From a6093a8d91a2f94569394999e9f6a0b2d99637c9 Mon Sep 17 00:00:00 2001 From: amcewen Date: Tue, 30 Aug 2011 21:27:31 +0100 Subject: [PATCH 19/29] Created an abstract base class UDP to match the Client and Server classes, and reworked the Ethernet library to use it and derive EthernetUDP. --- hardware/arduino/cores/arduino/Udp.h | 90 +++++++++++++++++++ libraries/Ethernet/Dhcp.h | 4 +- libraries/Ethernet/Dns.cpp | 2 +- libraries/Ethernet/Dns.h | 4 +- .../Ethernet/{Udp.cpp => EthernetUdp.cpp} | 36 ++++---- libraries/Ethernet/{Udp.h => EthernetUdp.h} | 27 +++--- .../UDPSendReceiveString.pde | 6 +- .../examples/UdpNtpClient/UdpNtpClient.pde | 4 +- 8 files changed, 131 insertions(+), 42 deletions(-) create mode 100644 hardware/arduino/cores/arduino/Udp.h rename libraries/Ethernet/{Udp.cpp => EthernetUdp.cpp} (83%) rename libraries/Ethernet/{Udp.h => EthernetUdp.h} (87%) diff --git a/hardware/arduino/cores/arduino/Udp.h b/hardware/arduino/cores/arduino/Udp.h new file mode 100644 index 000000000..1fb9cd3cf --- /dev/null +++ b/hardware/arduino/cores/arduino/Udp.h @@ -0,0 +1,90 @@ +/* + * Udp.cpp: Library to send/receive UDP packets. + * + * 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 udp_h +#define udp_h + +#include +#include + +class UDP : public Stream { + +public: + virtual uint8_t begin(uint16_t) =0; // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use + virtual void stop() =0; // 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) =0; + // 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) =0; + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket() =0; + // Write a single byte into the packet + virtual size_t write(uint8_t) =0; + // Write a string of characters into the packet + virtual size_t write(const char *str) =0; + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size) =0; + + // 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() =0; + // Number of bytes remaining in the current packet + virtual int available() =0; + // Read a single byte from the current packet + virtual int read() =0; + // 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) =0; + // 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) =0; + // Return the next byte from the current packet without moving on to the next byte + virtual int peek() =0; + virtual void flush() =0; // Finish reading the current packet + + // Return the IP address of the host who sent the current incoming packet + virtual IPAddress remoteIP() =0; + // Return the port of the host who sent the current incoming packet + virtual uint16_t remotePort() =0; +protected: + uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); }; +}; + +#endif diff --git a/libraries/Ethernet/Dhcp.h b/libraries/Ethernet/Dhcp.h index c0034940c..f87719959 100755 --- a/libraries/Ethernet/Dhcp.h +++ b/libraries/Ethernet/Dhcp.h @@ -4,7 +4,7 @@ #ifndef Dhcp_h #define Dhcp_h -#include "Udp.h" +#include "EthernetUdp.h" /* DHCP state machine. */ #define STATE_DHCP_START 0 @@ -139,7 +139,7 @@ private: uint8_t _dhcpGatewayIp[4]; uint8_t _dhcpDhcpServerIp[4]; uint8_t _dhcpDnsServerIp[4]; - UDP _dhcpUdpSocket; + EthernetUDP _dhcpUdpSocket; void presend_DHCP(); void send_DHCP_MESSAGE(uint8_t, uint16_t); diff --git a/libraries/Ethernet/Dns.cpp b/libraries/Ethernet/Dns.cpp index a049c7633..86fd0177a 100644 --- a/libraries/Ethernet/Dns.cpp +++ b/libraries/Ethernet/Dns.cpp @@ -3,7 +3,7 @@ // Released under Apache License, version 2.0 #include "w5100.h" -#include "Udp.h" +#include "EthernetUdp.h" #include "util.h" #include "Dns.h" diff --git a/libraries/Ethernet/Dns.h b/libraries/Ethernet/Dns.h index 9582351f2..d4f49769b 100644 --- a/libraries/Ethernet/Dns.h +++ b/libraries/Ethernet/Dns.h @@ -5,7 +5,7 @@ #ifndef DNSClient_h #define DNSClient_h -#include +#include class DNSClient { @@ -35,7 +35,7 @@ protected: IPAddress iDNSServer; uint16_t iRequestId; - UDP iUdp; + EthernetUDP iUdp; }; #endif diff --git a/libraries/Ethernet/Udp.cpp b/libraries/Ethernet/EthernetUdp.cpp similarity index 83% rename from libraries/Ethernet/Udp.cpp rename to libraries/Ethernet/EthernetUdp.cpp index a1244ffb9..9ca650986 100644 --- a/libraries/Ethernet/Udp.cpp +++ b/libraries/Ethernet/EthernetUdp.cpp @@ -33,10 +33,10 @@ #include "Dns.h" /* Constructor */ -UDP::UDP() : _sock(MAX_SOCK_NUM) {} +EthernetUDP::EthernetUDP() : _sock(MAX_SOCK_NUM) {} -/* Start UDP socket, listening at local port PORT */ -uint8_t UDP::begin(uint16_t port) { +/* Start EthernetUDP socket, listening at local port PORT */ +uint8_t EthernetUDP::begin(uint16_t port) { if (_sock != MAX_SOCK_NUM) return 0; @@ -59,12 +59,12 @@ uint8_t UDP::begin(uint16_t port) { /* Is data available in rx buffer? Returns 0 if no, number of available bytes if yes. * returned value includes 8 byte UDP header!*/ -int UDP::available() { +int EthernetUDP::available() { return W5100.getRXReceivedSize(_sock); } -/* Release any resources being used by this UDP instance */ -void UDP::stop() +/* Release any resources being used by this EthernetUDP instance */ +void EthernetUDP::stop() { if (_sock == MAX_SOCK_NUM) return; @@ -75,7 +75,7 @@ void UDP::stop() _sock = MAX_SOCK_NUM; } -int UDP::beginPacket(const char *host, uint16_t port) +int EthernetUDP::beginPacket(const char *host, uint16_t port) { // Look up the host first int ret = 0; @@ -91,36 +91,36 @@ int UDP::beginPacket(const char *host, uint16_t port) } } -int UDP::beginPacket(IPAddress ip, uint16_t port) +int EthernetUDP::beginPacket(IPAddress ip, uint16_t port) { _offset = 0; - return startUDP(_sock, ip.raw_address(), port); + return startUDP(_sock, rawIPAddress(ip), port); } -int UDP::endPacket() +int EthernetUDP::endPacket() { return sendUDP(_sock); } -size_t UDP::write(uint8_t byte) +size_t EthernetUDP::write(uint8_t byte) { return write(&byte, 1); } -size_t UDP::write(const char *str) +size_t EthernetUDP::write(const char *str) { size_t len = strlen(str); return write((const uint8_t *)str, len); } -size_t UDP::write(const uint8_t *buffer, size_t size) +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 UDP::parsePacket() +int EthernetUDP::parsePacket() { if (available() > 0) { @@ -143,7 +143,7 @@ int UDP::parsePacket() return 0; } -int UDP::read() +int EthernetUDP::read() { uint8_t byte; if (recv(_sock, &byte, 1) > 0) @@ -155,7 +155,7 @@ int UDP::read() return -1; } -int UDP::read(unsigned char* buffer, size_t len) +int EthernetUDP::read(unsigned char* buffer, size_t len) { /* In the readPacket that copes with truncating packets, the buffer was filled with this code. Not sure why it loops round reading out a byte @@ -169,7 +169,7 @@ int UDP::read(unsigned char* buffer, size_t len) return recv(_sock, buffer, len); } -int UDP::peek() +int EthernetUDP::peek() { uint8_t b; // Unlike recv, peek doesn't check to see if there's any data available, so we must @@ -179,7 +179,7 @@ int UDP::peek() return b; } -void UDP::flush() +void EthernetUDP::flush() { while (available()) { diff --git a/libraries/Ethernet/Udp.h b/libraries/Ethernet/EthernetUdp.h similarity index 87% rename from libraries/Ethernet/Udp.h rename to libraries/Ethernet/EthernetUdp.h index 59238c1ae..64e30275f 100644 --- a/libraries/Ethernet/Udp.h +++ b/libraries/Ethernet/EthernetUdp.h @@ -34,15 +34,14 @@ * bjoern@cs.stanford.edu 12/30/2008 */ -#ifndef udp_h -#define udp_h +#ifndef ethernetudp_h +#define ethernetudp_h -#include -#include +#include #define UDP_TX_PACKET_MAX_SIZE 24 -class UDP : public Stream { +class EthernetUDP : public UDP { private: uint8_t _sock; // socket ID for Wiz5100 uint16_t _port; // local port to listen on @@ -51,21 +50,21 @@ private: uint16_t _offset; // offset into the packet being sent public: - UDP(); // Constructor - uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - void stop(); // Finish with the UDP socket + 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 - int beginPacket(IPAddress ip, uint16_t 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 - int beginPacket(const char *host, uint16_t 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 - int endPacket(); + virtual int endPacket(); // Write a single byte into the packet virtual size_t write(uint8_t); // Write a string of characters into the packet @@ -75,7 +74,7 @@ public: // Start processing the next available incoming packet // Returns the size of the packet in bytes, or 0 if no packets are available - int parsePacket(); + virtual int parsePacket(); // Number of bytes remaining in the current packet virtual int available(); // Read a single byte from the current packet @@ -91,9 +90,9 @@ public: virtual void flush(); // Finish reading the current packet // Return the IP address of the host who sent the current incoming packet - IPAddress remoteIP() { return _remoteIP; }; + virtual IPAddress remoteIP() { return _remoteIP; }; // Return the port of the host who sent the current incoming packet - uint16_t remotePort() { return _remotePort; }; + virtual uint16_t remotePort() { return _remotePort; }; }; #endif diff --git a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde index 081d69114..4d4045cac 100644 --- a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde +++ b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.pde @@ -15,7 +15,7 @@ #include // needed for Arduino versions later than 0018 #include -#include // UDP library from: bjoern@cs.stanford.edu 12/30/2008 +#include // UDP library from: bjoern@cs.stanford.edu 12/30/2008 // Enter a MAC address and IP address for your controller below. @@ -30,8 +30,8 @@ unsigned int localPort = 8888; // local port to listen on char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, char ReplyBuffer[] = "acknowledged"; // a string to send back -// A UDP instance to let us send and receive packets over UDP -UDP Udp; +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; void setup() { // start the Ethernet and UDP: diff --git a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde index 7c2d3ea9e..b4e24b8ce 100644 --- a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde +++ b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.pde @@ -18,7 +18,7 @@ #include #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 @@ -34,7 +34,7 @@ const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets // A UDP instance to let us send and receive packets over UDP -UDP Udp; +EthernetUDP Udp; void setup() { From b21b43c591ef5b7bfdc5294d89482b7cccdc2b1a Mon Sep 17 00:00:00 2001 From: Tom Igoe Date: Tue, 30 Aug 2011 17:02:55 -0400 Subject: [PATCH 20/29] deleted .pde examples --- .../AnalogReadSerial/AnalogReadSerial.pde | 15 -- .../DigitalReadSerial/DigitalReadSerial.pde | 19 -- .../examples/2.Digital/Button/Button.pde | 56 ----- .../examples/2.Digital/Debounce/Debounce.pde | 75 ------- .../StateChangeDetection.pde | 92 -------- .../2.Digital/toneKeyboard/toneKeyboard.pde | 45 ---- .../2.Digital/toneMelody/toneMelody.pde | 49 ---- .../tonePitchFollower/tonePitchFollower.pde | 46 ---- .../AnalogInOutSerial/AnalogInOutSerial.pde | 53 ----- .../3.Analog/AnalogInput/AnalogInput.pde | 50 ----- .../3.Analog/Calibration/Calibration.pde | 75 ------- .../examples/3.Analog/Fading/Fading.pde | 45 ---- .../examples/3.Analog/Smoothing/Smoothing.pde | 66 ------ .../4.Communication/ASCIITable/ASCIITable.pde | 76 ------- .../4.Communication/Dimmer/Dimmer.pde | 112 ---------- .../examples/4.Communication/Graph/Graph.pde | 149 ------------- .../examples/4.Communication/MIDI/Midi.pde | 49 ---- .../PhysicalPixel/PhysicalPixel.pde | 170 -------------- .../SerialCallResponse/SerialCallResponse.pde | 211 ------------------ .../SerialCallResponseASCII.pde | 211 ------------------ .../VirtualColorMixer/VirtualColorMixer.pde | 130 ----------- .../examples/5.Control/Arrays/Arrays.pde | 57 ----- .../ForLoopIteration/ForLoopIteration.pde | 47 ---- .../IfStatementConditional.pde | 56 ----- .../WhileStatementConditional.pde | 88 -------- .../5.Control/switchCase/switchCase.pde | 62 ----- .../examples/6.Sensors/ADXL3xx/ADXL3xx.pde | 64 ------ .../shared/examples/6.Sensors/Knock/Knock.pde | 55 ----- .../6.Sensors/Memsic2125/Memsic2125.pde | 63 ------ build/shared/examples/6.Sensors/Ping/Ping.pde | 84 ------- .../RowColumnScanning/RowColumnScanning.pde | 114 ---------- .../StringAdditionOperator.pde | 61 ----- .../StringAppendOperator.pde | 64 ------ .../StringComparisonOperators.pde | 124 ---------- .../StringConstructors/StringConstructors.pde | 64 ------ .../StringStartsWithEndsWith.pde | 49 ---- 36 files changed, 2846 deletions(-) delete mode 100644 build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.pde delete mode 100644 build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.pde delete mode 100644 build/shared/examples/2.Digital/Button/Button.pde delete mode 100644 build/shared/examples/2.Digital/Debounce/Debounce.pde delete mode 100644 build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.pde delete mode 100644 build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.pde delete mode 100644 build/shared/examples/2.Digital/toneMelody/toneMelody.pde delete mode 100644 build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.pde delete mode 100644 build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.pde delete mode 100644 build/shared/examples/3.Analog/AnalogInput/AnalogInput.pde delete mode 100644 build/shared/examples/3.Analog/Calibration/Calibration.pde delete mode 100644 build/shared/examples/3.Analog/Fading/Fading.pde delete mode 100644 build/shared/examples/3.Analog/Smoothing/Smoothing.pde delete mode 100644 build/shared/examples/4.Communication/ASCIITable/ASCIITable.pde delete mode 100644 build/shared/examples/4.Communication/Dimmer/Dimmer.pde delete mode 100644 build/shared/examples/4.Communication/Graph/Graph.pde delete mode 100644 build/shared/examples/4.Communication/MIDI/Midi.pde delete mode 100644 build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.pde delete mode 100644 build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.pde delete mode 100644 build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.pde delete mode 100644 build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.pde delete mode 100644 build/shared/examples/5.Control/Arrays/Arrays.pde delete mode 100644 build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.pde delete mode 100644 build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.pde delete mode 100644 build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.pde delete mode 100644 build/shared/examples/5.Control/switchCase/switchCase.pde delete mode 100644 build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.pde delete mode 100644 build/shared/examples/6.Sensors/Knock/Knock.pde delete mode 100644 build/shared/examples/6.Sensors/Memsic2125/Memsic2125.pde delete mode 100644 build/shared/examples/6.Sensors/Ping/Ping.pde delete mode 100644 build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.pde delete mode 100644 build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.pde delete mode 100644 build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.pde delete mode 100644 build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.pde delete mode 100644 build/shared/examples/8.Strings/StringConstructors/StringConstructors.pde delete mode 100644 build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.pde diff --git a/build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.pde b/build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.pde deleted file mode 100644 index 97243f325..000000000 --- a/build/shared/examples/1.Basics/AnalogReadSerial/AnalogReadSerial.pde +++ /dev/null @@ -1,15 +0,0 @@ -/* - AnalogReadSerial - Reads an analog input on pin 0, prints the result to the serial monitor - - This example code is in the public domain. - */ - -void setup() { - Serial.begin(9600); -} - -void loop() { - int sensorValue = analogRead(A0); - Serial.println(sensorValue, DEC); -} diff --git a/build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.pde b/build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.pde deleted file mode 100644 index 7651a8fae..000000000 --- a/build/shared/examples/1.Basics/DigitalReadSerial/DigitalReadSerial.pde +++ /dev/null @@ -1,19 +0,0 @@ -/* - DigitalReadSerial - Reads a digital input on pin 2, prints the result to the serial monitor - - This example code is in the public domain. - */ - -void setup() { - Serial.begin(9600); - pinMode(2, INPUT); -} - -void loop() { - int sensorValue = digitalRead(2); - Serial.println(sensorValue, DEC); -} - - - diff --git a/build/shared/examples/2.Digital/Button/Button.pde b/build/shared/examples/2.Digital/Button/Button.pde deleted file mode 100644 index a56ea14eb..000000000 --- a/build/shared/examples/2.Digital/Button/Button.pde +++ /dev/null @@ -1,56 +0,0 @@ -/* - Button - - Turns on and off a light emitting diode(LED) connected to digital - pin 13, when pressing a pushbutton attached to pin 2. - - - The circuit: - * LED attached from pin 13 to ground - * pushbutton attached to pin 2 from +5V - * 10K resistor attached to pin 2 from ground - - * Note: on most Arduinos there is already an LED on the board - attached to pin 13. - - - created 2005 - by DojoDave - modified 28 Oct 2010 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/Button - */ - -// constants won't change. They're used here to -// set pin numbers: -const int buttonPin = 2; // the number of the pushbutton pin -const int ledPin = 13; // the number of the LED pin - -// variables will change: -int buttonState = 0; // variable for reading the pushbutton status - -void setup() { - // initialize the LED pin as an output: - pinMode(ledPin, OUTPUT); - // initialize the pushbutton pin as an input: - pinMode(buttonPin, INPUT); -} - -void loop(){ - // read the state of the pushbutton value: - buttonState = digitalRead(buttonPin); - - // check if the pushbutton is pressed. - // if it is, the buttonState is HIGH: - if (buttonState == HIGH) { - // turn LED on: - digitalWrite(ledPin, HIGH); - } - else { - // turn LED off: - digitalWrite(ledPin, LOW); - } -} \ No newline at end of file diff --git a/build/shared/examples/2.Digital/Debounce/Debounce.pde b/build/shared/examples/2.Digital/Debounce/Debounce.pde deleted file mode 100644 index 6f184eccc..000000000 --- a/build/shared/examples/2.Digital/Debounce/Debounce.pde +++ /dev/null @@ -1,75 +0,0 @@ -/* - Debounce - - Each time the input pin goes from LOW to HIGH (e.g. because of a push-button - press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's - a minimum delay between toggles to debounce the circuit (i.e. to ignore - noise). - - The circuit: - * LED attached from pin 13 to ground - * pushbutton attached from pin 2 to +5V - * 10K resistor attached from pin 2 to ground - - * Note: On most Arduino boards, there is already an LED on the board - connected to pin 13, so you don't need any extra components for this example. - - - created 21 November 2006 - by David A. Mellis - modified 3 Jul 2009 - by Limor Fried - -This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/Debounce - */ - -// constants won't change. They're used here to -// set pin numbers: -const int buttonPin = 2; // the number of the pushbutton pin -const int ledPin = 13; // the number of the LED pin - -// Variables will change: -int ledState = HIGH; // the current state of the output pin -int buttonState; // the current reading from the input pin -int lastButtonState = LOW; // the previous reading from the input pin - -// the following variables are long's because the time, measured in miliseconds, -// will quickly become a bigger number than can be stored in an int. -long lastDebounceTime = 0; // the last time the output pin was toggled -long debounceDelay = 50; // the debounce time; increase if the output flickers - -void setup() { - pinMode(buttonPin, INPUT); - pinMode(ledPin, OUTPUT); -} - -void loop() { - // read the state of the switch into a local variable: - int reading = digitalRead(buttonPin); - - // check to see if you just pressed the button - // (i.e. the input went from LOW to HIGH), and you've waited - // long enough since the last press to ignore any noise: - - // If the switch changed, due to noise or pressing: - if (reading != lastButtonState) { - // reset the debouncing timer - lastDebounceTime = millis(); - } - - if ((millis() - lastDebounceTime) > debounceDelay) { - // whatever the reading is at, it's been there for longer - // than the debounce delay, so take it as the actual current state: - buttonState = reading; - } - - // set the LED using the state of the button: - digitalWrite(ledPin, buttonState); - - // save the reading. Next time through the loop, - // it'll be the lastButtonState: - lastButtonState = reading; -} - diff --git a/build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.pde b/build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.pde deleted file mode 100644 index 33f997c6b..000000000 --- a/build/shared/examples/2.Digital/StateChangeDetection/StateChangeDetection.pde +++ /dev/null @@ -1,92 +0,0 @@ -/* - State change detection (edge detection) - - Often, you don't need to know the state of a digital input all the time, - but you just need to know when the input changes from one state to another. - For example, you want to know when a button goes from OFF to ON. This is called - state change detection, or edge detection. - - This example shows how to detect when a button or button changes from off to on - and on to off. - - The circuit: - * pushbutton attached to pin 2 from +5V - * 10K resistor attached to pin 2 from ground - * LED attached from pin 13 to ground (or use the built-in LED on - most Arduino boards) - - created 27 Sep 2005 - modified 14 Oct 2010 - by Tom Igoe - -This example code is in the public domain. - - http://arduino.cc/en/Tutorial/ButtonStateChange - - */ - -// this constant won't change: -const int buttonPin = 2; // the pin that the pushbutton is attached to -const int ledPin = 13; // the pin that the LED is attached to - -// Variables will change: -int buttonPushCounter = 0; // counter for the number of button presses -int buttonState = 0; // current state of the button -int lastButtonState = 0; // previous state of the button - -void setup() { - // initialize the button pin as a input: - pinMode(buttonPin, INPUT); - // initialize the LED as an output: - pinMode(ledPin, OUTPUT); - // initialize serial communication: - Serial.begin(9600); -} - - -void loop() { - // read the pushbutton input pin: - buttonState = digitalRead(buttonPin); - - // compare the buttonState to its previous state - if (buttonState != lastButtonState) { - // if the state has changed, increment the counter - if (buttonState == HIGH) { - // if the current state is HIGH then the button - // wend from off to on: - buttonPushCounter++; - Serial.println("on"); - Serial.print("number of button pushes: "); - Serial.println(buttonPushCounter, DEC); - } - else { - // if the current state is LOW then the button - // wend from on to off: - Serial.println("off"); - } - } - // save the current state as the last state, - //for next time through the loop - lastButtonState = buttonState; - - - // turns on the LED every four button pushes by - // checking the modulo of the button push counter. - // the modulo function gives you the remainder of - // the division of two numbers: - if (buttonPushCounter % 4 == 0) { - digitalWrite(ledPin, HIGH); - } else { - digitalWrite(ledPin, LOW); - } - -} - - - - - - - - - diff --git a/build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.pde b/build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.pde deleted file mode 100644 index b1a5364a7..000000000 --- a/build/shared/examples/2.Digital/toneKeyboard/toneKeyboard.pde +++ /dev/null @@ -1,45 +0,0 @@ -/* - keyboard - - Plays a pitch that changes based on a changing analog input - - circuit: - * 3 force-sensing resistors from +5V to analog in 0 through 5 - * 3 10K resistors from analog in 0 through 5 to ground - * 8-ohm speaker on digital pin 8 - - created 21 Jan 2010 - Modified 4 Sep 2010 - by Tom Igoe - -This example code is in the public domain. - - http://arduino.cc/en/Tutorial/Tone3 - - */ - -#include "pitches.h" - -const int threshold = 10; // minimum reading of the sensors that generates a note - -// notes to play, corresponding to the 3 sensors: -int notes[] = { - NOTE_A4, NOTE_B4,NOTE_C3 }; - -void setup() { - -} - -void loop() { - for (int thisSensor = 0; thisSensor < 3; thisSensor++) { - // get a sensor reading: - int sensorReading = analogRead(thisSensor); - - // if the sensor is pressed hard enough: - if (sensorReading > threshold) { - // play the note corresponding to this sensor: - tone(8, notes[thisSensor], 20); - } - } - Serial.println(); -} diff --git a/build/shared/examples/2.Digital/toneMelody/toneMelody.pde b/build/shared/examples/2.Digital/toneMelody/toneMelody.pde deleted file mode 100644 index debcebd6b..000000000 --- a/build/shared/examples/2.Digital/toneMelody/toneMelody.pde +++ /dev/null @@ -1,49 +0,0 @@ -/* - Melody - - Plays a melody - - circuit: - * 8-ohm speaker on digital pin 8 - - created 21 Jan 2010 - modified 14 Oct 2010 - by Tom Igoe - -This example code is in the public domain. - - http://arduino.cc/en/Tutorial/Tone - - */ - #include "pitches.h" - -// notes in the melody: -int melody[] = { - NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4}; - -// note durations: 4 = quarter note, 8 = eighth note, etc.: -int noteDurations[] = { - 4, 8, 8, 4,4,4,4,4 }; - -void setup() { - // iterate over the notes of the melody: - for (int thisNote = 0; thisNote < 8; thisNote++) { - - // to calculate the note duration, take one second - // divided by the note type. - //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. - int noteDuration = 1000/noteDurations[thisNote]; - tone(8, melody[thisNote],noteDuration); - - // to distinguish the notes, set a minimum time between them. - // the note's duration + 30% seems to work well: - int pauseBetweenNotes = noteDuration * 1.30; - delay(pauseBetweenNotes); - // stop the tone playing: - noTone(8); - } -} - -void loop() { - // no need to repeat the melody. -} diff --git a/build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.pde b/build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.pde deleted file mode 100644 index bcc4b6327..000000000 --- a/build/shared/examples/2.Digital/tonePitchFollower/tonePitchFollower.pde +++ /dev/null @@ -1,46 +0,0 @@ -/* - Pitch follower - - Plays a pitch that changes based on a changing analog input - - circuit: - * 8-ohm speaker on digital pin 8 - * photoresistor on analog 0 to 5V - * 4.7K resistor on analog 0 to ground - - created 21 Jan 2010 - Modified 4 Sep 2010 - by Tom Igoe - -This example code is in the public domain. - - http://arduino.cc/en/Tutorial/Tone2 - - */ - - -void setup() { - // initialize serial communications (for debugging only): - Serial.begin(9600); -} - -void loop() { - // read the sensor: - int sensorReading = analogRead(A0); - // print the sensor reading so you know its range - Serial.println(sensorReading); - // map the pitch to the range of the analog input. - // change the minimum and maximum input numbers below - // depending on the range your sensor's giving: - int thisPitch = map(sensorReading, 400, 1000, 100, 1000); - - // play the pitch: - tone(9, thisPitch, 10); - -} - - - - - - diff --git a/build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.pde b/build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.pde deleted file mode 100644 index 57c14219d..000000000 --- a/build/shared/examples/3.Analog/AnalogInOutSerial/AnalogInOutSerial.pde +++ /dev/null @@ -1,53 +0,0 @@ -/* - Analog input, analog output, serial output - - Reads an analog input pin, maps the result to a range from 0 to 255 - and uses the result to set the pulsewidth modulation (PWM) of an output pin. - Also prints the results to the serial monitor. - - The circuit: - * potentiometer connected to analog pin 0. - Center pin of the potentiometer goes to the analog pin. - side pins of the potentiometer go to +5V and ground - * LED connected from digital pin 9 to ground - - created 29 Dec. 2008 - Modified 4 Sep 2010 - by Tom Igoe - - This example code is in the public domain. - - */ - -// These constants won't change. They're used to give names -// to the pins used: -const int analogInPin = A0; // Analog input pin that the potentiometer is attached to -const int analogOutPin = 9; // Analog output pin that the LED is attached to - -int sensorValue = 0; // value read from the pot -int outputValue = 0; // value output to the PWM (analog out) - -void setup() { - // initialize serial communications at 9600 bps: - Serial.begin(9600); -} - -void loop() { - // read the analog in value: - sensorValue = analogRead(analogInPin); - // map it to the range of the analog out: - outputValue = map(sensorValue, 0, 1023, 0, 255); - // change the analog out value: - analogWrite(analogOutPin, outputValue); - - // print the results to the serial monitor: - Serial.print("sensor = " ); - Serial.print(sensorValue); - Serial.print("\t output = "); - Serial.println(outputValue); - - // wait 10 milliseconds before the next loop - // for the analog-to-digital converter to settle - // after the last reading: - delay(10); -} diff --git a/build/shared/examples/3.Analog/AnalogInput/AnalogInput.pde b/build/shared/examples/3.Analog/AnalogInput/AnalogInput.pde deleted file mode 100644 index 18a005524..000000000 --- a/build/shared/examples/3.Analog/AnalogInput/AnalogInput.pde +++ /dev/null @@ -1,50 +0,0 @@ -/* - Analog Input - Demonstrates analog input by reading an analog sensor on analog pin 0 and - turning on and off a light emitting diode(LED) connected to digital pin 13. - The amount of time the LED will be on and off depends on - the value obtained by analogRead(). - - The circuit: - * Potentiometer attached to analog input 0 - * center pin of the potentiometer to the analog pin - * one side pin (either one) to ground - * the other side pin to +5V - * LED anode (long leg) attached to digital output 13 - * LED cathode (short leg) attached to ground - - * Note: because most Arduinos have a built-in LED attached - to pin 13 on the board, the LED is optional. - - - Created by David Cuartielles - Modified 4 Sep 2010 - By Tom Igoe - - This example code is in the public domain. - - http://arduino.cc/en/Tutorial/AnalogInput - - */ - -int sensorPin = A0; // select the input pin for the potentiometer -int ledPin = 13; // select the pin for the LED -int sensorValue = 0; // variable to store the value coming from the sensor - -void setup() { - // declare the ledPin as an OUTPUT: - pinMode(ledPin, OUTPUT); -} - -void loop() { - // read the value from the sensor: - sensorValue = analogRead(sensorPin); - // turn the ledPin on - digitalWrite(ledPin, HIGH); - // stop the program for milliseconds: - delay(sensorValue); - // turn the ledPin off: - digitalWrite(ledPin, LOW); - // stop the program for for milliseconds: - delay(sensorValue); -} \ No newline at end of file diff --git a/build/shared/examples/3.Analog/Calibration/Calibration.pde b/build/shared/examples/3.Analog/Calibration/Calibration.pde deleted file mode 100644 index c5734df4e..000000000 --- a/build/shared/examples/3.Analog/Calibration/Calibration.pde +++ /dev/null @@ -1,75 +0,0 @@ -/* - Calibration - - Demonstrates one technique for calibrating sensor input. The - sensor readings during the first five seconds of the sketch - execution define the minimum and maximum of expected values - attached to the sensor pin. - - The sensor minimum and maximum initial values may seem backwards. - Initially, you set the minimum high and listen for anything - lower, saving it as the new minimum. Likewise, you set the - maximum low and listen for anything higher as the new maximum. - - The circuit: - * Analog sensor (potentiometer will do) attached to analog input 0 - * LED attached from digital pin 9 to ground - - created 29 Oct 2008 - By David A Mellis - Modified 4 Sep 2010 - By Tom Igoe - - http://arduino.cc/en/Tutorial/Calibration - - This example code is in the public domain. - - */ - -// These constants won't change: -const int sensorPin = A0; // pin that the sensor is attached to -const int ledPin = 9; // pin that the LED is attached to - -// variables: -int sensorValue = 0; // the sensor value -int sensorMin = 1023; // minimum sensor value -int sensorMax = 0; // maximum sensor value - - -void setup() { - // turn on LED to signal the start of the calibration period: - pinMode(13, OUTPUT); - digitalWrite(13, HIGH); - - // calibrate during the first five seconds - while (millis() < 5000) { - sensorValue = analogRead(sensorPin); - - // record the maximum sensor value - if (sensorValue > sensorMax) { - sensorMax = sensorValue; - } - - // record the minimum sensor value - if (sensorValue < sensorMin) { - sensorMin = sensorValue; - } - } - - // signal the end of the calibration period - digitalWrite(13, LOW); -} - -void loop() { - // read the sensor: - sensorValue = analogRead(sensorPin); - - // apply the calibration to the sensor reading - sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255); - - // in case the sensor value is outside the range seen during calibration - sensorValue = constrain(sensorValue, 0, 255); - - // fade the LED using the calibrated value: - analogWrite(ledPin, sensorValue); -} diff --git a/build/shared/examples/3.Analog/Fading/Fading.pde b/build/shared/examples/3.Analog/Fading/Fading.pde deleted file mode 100644 index 46959ad26..000000000 --- a/build/shared/examples/3.Analog/Fading/Fading.pde +++ /dev/null @@ -1,45 +0,0 @@ -/* - Fading - - This example shows how to fade an LED using the analogWrite() function. - - The circuit: - * LED attached from digital pin 9 to ground. - - Created 1 Nov 2008 - By David A. Mellis - Modified 17 June 2009 - By Tom Igoe - - http://arduino.cc/en/Tutorial/Fading - - This example code is in the public domain. - - */ - - -int ledPin = 9; // LED connected to digital pin 9 - -void setup() { - // nothing happens in setup -} - -void loop() { - // fade in from min to max in increments of 5 points: - for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) { - // sets the value (range from 0 to 255): - analogWrite(ledPin, fadeValue); - // wait for 30 milliseconds to see the dimming effect - delay(30); - } - - // fade out from max to min in increments of 5 points: - for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { - // sets the value (range from 0 to 255): - analogWrite(ledPin, fadeValue); - // wait for 30 milliseconds to see the dimming effect - delay(30); - } -} - - diff --git a/build/shared/examples/3.Analog/Smoothing/Smoothing.pde b/build/shared/examples/3.Analog/Smoothing/Smoothing.pde deleted file mode 100644 index 5de30e8d7..000000000 --- a/build/shared/examples/3.Analog/Smoothing/Smoothing.pde +++ /dev/null @@ -1,66 +0,0 @@ -/* - - Smoothing - - Reads repeatedly from an analog input, calculating a running average - and printing it to the computer. Keeps ten readings in an array and - continually averages them. - - The circuit: - * Analog sensor (potentiometer will do) attached to analog input 0 - - Created 22 April 2007 - By David A. Mellis - - http://www.arduino.cc/en/Tutorial/Smoothing - - This example code is in the public domain. - - -*/ - - -// Define the number of samples to keep track of. The higher the number, -// the more the readings will be smoothed, but the slower the output will -// respond to the input. Using a constant rather than a normal variable lets -// use this value to determine the size of the readings array. -const int numReadings = 10; - -int readings[numReadings]; // the readings from the analog input -int index = 0; // the index of the current reading -int total = 0; // the running total -int average = 0; // the average - -int inputPin = A0; - -void setup() -{ - // initialize serial communication with computer: - Serial.begin(9600); - // initialize all the readings to 0: - for (int thisReading = 0; thisReading < numReadings; thisReading++) - readings[thisReading] = 0; -} - -void loop() { - // subtract the last reading: - total= total - readings[index]; - // read from the sensor: - readings[index] = analogRead(inputPin); - // add the reading to the total: - total= total + readings[index]; - // advance to the next position in the array: - index = index + 1; - - // if we're at the end of the array... - if (index >= numReadings) - // ...wrap around to the beginning: - index = 0; - - // calculate the average: - average = total / numReadings; - // send it to the computer (as ASCII digits) - Serial.println(average, DEC); -} - - diff --git a/build/shared/examples/4.Communication/ASCIITable/ASCIITable.pde b/build/shared/examples/4.Communication/ASCIITable/ASCIITable.pde deleted file mode 100644 index c92b0d023..000000000 --- a/build/shared/examples/4.Communication/ASCIITable/ASCIITable.pde +++ /dev/null @@ -1,76 +0,0 @@ -/* - ASCII table - - Prints out byte values in all possible formats: - * as raw binary values - * as ASCII-encoded decimal, hex, octal, and binary values - - For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII - - The circuit: No external hardware needed. - - created 2006 - by Nicholas Zambetti - modified 18 Jan 2009 - by Tom Igoe - - This example code is in the public domain. - - - - */ -void setup() -{ - Serial.begin(9600); - - // prints title with ending line break - Serial.println("ASCII Table ~ Character Map"); -} - -// first visible ASCIIcharacter '!' is number 33: -int thisByte = 33; -// you can also write ASCII characters in single quotes. -// for example. '!' is the same as 33, so you could also use this: -//int thisByte = '!'; - -void loop() -{ - // prints value unaltered, i.e. the raw binary version of the - // byte. The serial monitor interprets all bytes as - // ASCII, so 33, the first number, will show up as '!' - Serial.write(thisByte); - - Serial.print(", dec: "); - // prints value as string as an ASCII-encoded decimal (base 10). - // Decimal is the default format for Serial.print() and Serial.println(), - // so no modifier is needed: - Serial.print(thisByte); - // But you can declare the modifier for decimal if you want to. - //this also works if you uncomment it: - - // Serial.print(thisByte, DEC); - - - Serial.print(", hex: "); - // prints value as string in hexadecimal (base 16): - Serial.print(thisByte, HEX); - - Serial.print(", oct: "); - // prints value as string in octal (base 8); - Serial.print(thisByte, OCT); - - Serial.print(", bin: "); - // prints value as string in binary (base 2) - // also prints ending line break: - Serial.println(thisByte, BIN); - - // if printed last visible character '~' or 126, stop: - if(thisByte == 126) { // you could also use if (thisByte == '~') { - // This loop loops forever and does nothing - while(true) { - continue; - } - } - // go on to the next character - thisByte++; -} diff --git a/build/shared/examples/4.Communication/Dimmer/Dimmer.pde b/build/shared/examples/4.Communication/Dimmer/Dimmer.pde deleted file mode 100644 index 2985ddaee..000000000 --- a/build/shared/examples/4.Communication/Dimmer/Dimmer.pde +++ /dev/null @@ -1,112 +0,0 @@ -/* - Dimmer - - Demonstrates the sending data from the computer to the Arduino board, - in this case to control the brightness of an LED. The data is sent - in individual bytes, each of which ranges from 0 to 255. Arduino - reads these bytes and uses them to set the brightness of the LED. - - The circuit: - LED attached from digital pin 9 to ground. - Serial connection to Processing, Max/MSP, or another serial application - - created 2006 - by David A. Mellis - modified 14 Apr 2009 - by Tom Igoe and Scott Fitzgerald - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/Dimmer - - */ - -const int ledPin = 9; // the pin that the LED is attached to - -void setup() -{ - // initialize the serial communication: - Serial.begin(9600); - // initialize the ledPin as an output: - pinMode(ledPin, OUTPUT); -} - -void loop() { - byte brightness; - - // check if data has been sent from the computer: - if (Serial.available()) { - // read the most recent byte (which will be from 0 to 255): - brightness = Serial.read(); - // set the brightness of the LED: - analogWrite(ledPin, brightness); - } -} - -/* Processing code for this example - // Dimmer - sends bytes over a serial port - // by David A. Mellis - //This example code is in the public domain. - - import processing.serial.*; - Serial port; - - void setup() { - size(256, 150); - - println("Available serial ports:"); - println(Serial.list()); - - // Uses the first port in this list (number 0). Change this to - // select the port corresponding to your Arduino board. The last - // parameter (e.g. 9600) is the speed of the communication. It - // has to correspond to the value passed to Serial.begin() in your - // Arduino sketch. - port = new Serial(this, Serial.list()[0], 9600); - - // If you know the name of the port used by the Arduino board, you - // can specify it directly like this. - //port = new Serial(this, "COM1", 9600); - } - - void draw() { - // draw a gradient from black to white - for (int i = 0; i < 256; i++) { - stroke(i); - line(i, 0, i, 150); - } - - // write the current X-position of the mouse to the serial port as - // a single byte - port.write(mouseX); - } - */ - -/* Max/MSP v5 patch for this example - -----------begin_max5_patcher---------- -1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M -YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC -ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBLXiP -xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK -rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.W -sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui -FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+owv -AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK -z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu -xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqueG2 -uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j1Ykj -jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKdA -4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn95Izr -TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS -xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5KTa6 -WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG2v9 -FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ+zS7 -3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo8qHc -cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ -+wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x -D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8 -ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS -xqZqbd3ZLdera1iPqYxOm++v7SUSz ------------end_max5_patcher----------- - */ diff --git a/build/shared/examples/4.Communication/Graph/Graph.pde b/build/shared/examples/4.Communication/Graph/Graph.pde deleted file mode 100644 index 03e868b9b..000000000 --- a/build/shared/examples/4.Communication/Graph/Graph.pde +++ /dev/null @@ -1,149 +0,0 @@ -/* - Graph - - A simple example of communication from the Arduino board to the computer: - the value of analog input 0 is sent out the serial port. We call this "serial" - communication because the connection appears to both the Arduino and the - computer as a serial port, even though it may actually use - a USB cable. Bytes are sent one after another (serially) from the Arduino - to the computer. - - You can use the Arduino serial monitor to view the sent data, or it can - be read by Processing, PD, Max/MSP, or any other program capable of reading - data from a serial port. The Processing code below graphs the data received - so you can see the value of the analog input changing over time. - - The circuit: - Any analog input sensor is attached to analog in pin 0. - - created 2006 - by David A. Mellis - modified 14 Apr 2009 - by Tom Igoe and Scott Fitzgerald - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/Graph - */ - -void setup() { - // initialize the serial communication: - Serial.begin(9600); -} - -void loop() { - // send the value of analog input 0: - Serial.println(analogRead(A0)); - // wait a bit for the analog-to-digital converter - // to stabilize after the last reading: - delay(10); -} - -/* Processing code for this example - - // Graphing sketch - - - // This program takes ASCII-encoded strings - // from the serial port at 9600 baud and graphs them. It expects values in the - // range 0 to 1023, followed by a newline, or newline and carriage return - - // Created 20 Apr 2005 - // Updated 18 Jan 2008 - // by Tom Igoe - // This example code is in the public domain. - - import processing.serial.*; - - Serial myPort; // The serial port - int xPos = 1; // horizontal position of the graph - - void setup () { - // set the window size: - size(400, 300); - - // List all the available serial ports - println(Serial.list()); - // I know that the first port in the serial list on my mac - // is always my Arduino, so I open Serial.list()[0]. - // Open whatever port is the one you're using. - myPort = new Serial(this, Serial.list()[0], 9600); - // don't generate a serialEvent() unless you get a newline character: - myPort.bufferUntil('\n'); - // set inital background: - background(0); - } - void draw () { - // everything happens in the serialEvent() - } - - void serialEvent (Serial myPort) { - // get the ASCII string: - String inString = myPort.readStringUntil('\n'); - - if (inString != null) { - // trim off any whitespace: - inString = trim(inString); - // convert to an int and map to the screen height: - float inByte = float(inString); - inByte = map(inByte, 0, 1023, 0, height); - - // draw the line: - stroke(127,34,255); - line(xPos, height, xPos, height - inByte); - - // at the edge of the screen, go back to the beginning: - if (xPos >= width) { - xPos = 0; - background(0); - } - else { - // increment the horizontal position: - xPos++; - } - } - } - - */ - -/* Max/MSP v5 patch for this example - ----------begin_max5_patcher---------- -1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJIT -RTxj+6AOHkoTDooroUs0AQPR73a+1cwtK3WtZxzEpOwqlB9YveAlL4KWMYh6 -Q1GLo99ISKXeJMmU451zTUQAWpmNy+NM+SZ2y+sR1l02JuU9t0hJvFlNcMPy -dOuBv.U5Rgb0LPpRpYBooM3529latArTUVvzZdFPtsXAuDrrTU.f.sBffXxL -vGE50lIHkUVJXq3fRtdaoDvjYfbgjujaFJSCzq4.tLaN.bi1tJefWpqbO0uz -1IjIABoluxrJ1guxh2JfPO2B5zRNyBCLDFcqbwNvuv9fHCb8bvevyyEU2JKT -YhkBSWPAfq2TZ6YhqmuMUo0feUn+rYpY4YtY+cFw3lUJdCMYAapZqzwUHX8S -crjAd+SIOU6UBAwIygy.Q1+HAA1KH6EveWOFQlitUK92ehfal9kFhUxJ3tWc -sgpxadigWExbt1o7Ps5dk3yttivyg20W0VcSmg1G90qtx92rAZbH4ez.ruy1 -nhmaDPidE07J+5n2sg6E6oKXxUSmc20o6E3SPRDbrkXnPGUYE.i5nCNB9TxQ -jG.G0kCTZtH88f07Rt0ZMMWUw8VvbKVAaTk6GyoraPdZff7rQTejBN54lgyv -HE0Ft7AvIvvgvIwO23jBdUkYOuSvIFSiNcjFhiSsUBwsUCh1AgfNSBAeNDBZ -DIDqY.f8.YjfjV1HAn9XDTxyNFYatVTkKx3kcK9GraZpI5jv7GOx+Z37Xh82 -LSKHIDmDXaESoXRngIZQDKVkpxUkMCyXCQhcCK1z.G457gi3TzMz4RFD515F -G3bIQQwcP3SOF0zlkGhiCBQ1kOHHFFlXaEBQIQnCwv9QF1LxPZ.A4jR5cyQs -vbvHMJsLll01We+rE2LazX6zYmCraRrsPFwKg1ANBZFY.IAihr8Ox.aH0oAL -hB8nQVw0FSJiZeunOykbT6t3r.NP8.iL+bnwNiXuVMNJH9H9YCm89CFXPBER -bz422p8.O4dg6kRxdyjDqRwMIHTbT3QFLskxJ8tbmQK4tm0XGeZWF7wKKtYY -aTAF.XPNFaaQBinQMJ4QLF0aNHF0JtYuHSxoUZfZY6.UU2ejJTb8lQw8Fo5k -Rv6e2PI+fOM71o2ecY1VgTYdCSxxUqLokuYq9jYJi6lxPgD2NIPePLB0mwbG -YA9Rgxdiu1k5xiLlSU6JVnx6wzg3sYHwTesB8Z5D7RiGZpXyvDNJY.DQX3.H -hvmcUN4bP1yCkhpTle2P37jtBsKrLWcMScEmltOPv22ZfAqQAdKr9HzATQwZ -q18PrUGt6Tst2XMCRUfGuhXs6ccn23YloomMqcTiC5iMGPsHsHRWhWFlaenV -XcqwgCQiGGJzptyS2ZMODBz6fGza0bzmXBj7+DA94bvpR01MffAlueO7HwcI -pWCwmzJdvi9ILgflLAFmyXB6O7ML0YbD26lenmcGxjVsZUN+A6pUK7AtTrPg -M+eRYG0qD9j4I7eEbco8Xh6WcO.or9XDC6UCiewbXHkh6xm5LiPEkzpJDRTu -mEB44Fgz4NCtJvX.SM1vo2SlTCZGAe7GZu6ahdRyzFOhYZ+mbVVSYptBw.K1 -tboIkatIA7c1cTKD1u.honLYV04VkluHsXe0szv9pQCE9Ro3jaVB1o15pz2X -zYoBvO5KXCAe0LCYJybE8ZODf4fV8t9qW0zYxq.YJfTosj1bv0xc.SaC0+AV -9V9L.KKyV3SyTcRtmzi6rO.O16USvts4B5xe9EymDvebK0eMfW6+NIsNlE2m -eqRyJ0utRq13+RjmqYKN1e.4d61jjdsauXe3.2p6jgi9hsNIv97CoyJ01xzl -c3ZhUCtSHx3UZgjoEJYqNY+hYs5zZQVFW19L3JDYaTlMLqAAt1G2yXlnFg9a -53L1FJVcv.cOX0dh7mCVGCLce7GFcQwDdH5Ta3nyAS0pQbHxegr+tGIZORgM -RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES -1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd. -HJ5hhnng3h9HPj4lud02.1bxGw. ------------end_max5_patcher----------- - - */ diff --git a/build/shared/examples/4.Communication/MIDI/Midi.pde b/build/shared/examples/4.Communication/MIDI/Midi.pde deleted file mode 100644 index cdeaeea11..000000000 --- a/build/shared/examples/4.Communication/MIDI/Midi.pde +++ /dev/null @@ -1,49 +0,0 @@ -/* - MIDI note player - - This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data. - If this circuit is connected to a MIDI synth, it will play - the notes F#-0 (0x1E) to F#-5 (0x5A) in sequence. - - - The circuit: - * digital in 1 connected to MIDI jack pin 5 - * MIDI jack pin 2 connected to ground - * MIDI jack pin 4 connected to +5V through 220-ohm resistor - Attach a MIDI cable to the jack, then to a MIDI synth, and play music. - - created 13 Jun 2006 - modified 2 Jul 2009 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/MIDI - - */ - -void setup() { - // Set MIDI baud rate: - Serial.begin(31250); -} - -void loop() { - // play notes from F#-0 (0x1E) to F#-5 (0x5A): - for (int note = 0x1E; note < 0x5A; note ++) { - //Note on channel 1 (0x90), some note value (note), middle velocity (0x45): - noteOn(0x90, note, 0x45); - delay(100); - //Note on channel 1 (0x90), some note value (note), silent velocity (0x00): - noteOn(0x90, note, 0x00); - delay(100); - } -} - -// plays a MIDI note. Doesn't check to see that -// cmd is greater than 127, or that data values are less than 127: -void noteOn(int cmd, int pitch, int velocity) { - Serial.write(cmd); - Serial.write(pitch); - Serial.write(velocity); -} - diff --git a/build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.pde b/build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.pde deleted file mode 100644 index 8c1f780d3..000000000 --- a/build/shared/examples/4.Communication/PhysicalPixel/PhysicalPixel.pde +++ /dev/null @@ -1,170 +0,0 @@ -/* - Physical Pixel - - An example of using the Arduino board to receive data from the - computer. In this case, the Arduino boards turns on an LED when - it receives the character 'H', and turns off the LED when it - receives the character 'L'. - - The data can be sent from the Arduino serial monitor, or another - program like Processing (see code below), Flash (via a serial-net - proxy), PD, or Max/MSP. - - The circuit: - * LED connected from digital pin 13 to ground - - created 2006 - by David A. Mellis - modified 14 Apr 2009 - by Tom Igoe and Scott Fitzgerald - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/PhysicalPixel - */ - -const int ledPin = 13; // the pin that the LED is attached to -int incomingByte; // a variable to read incoming serial data into - -void setup() { - // initialize serial communication: - Serial.begin(9600); - // initialize the LED pin as an output: - pinMode(ledPin, OUTPUT); -} - -void loop() { - // see if there's incoming serial data: - if (Serial.available() > 0) { - // read the oldest byte in the serial buffer: - incomingByte = Serial.read(); - // if it's a capital H (ASCII 72), turn on the LED: - if (incomingByte == 'H') { - digitalWrite(ledPin, HIGH); - } - // if it's an L (ASCII 76) turn off the LED: - if (incomingByte == 'L') { - digitalWrite(ledPin, LOW); - } - } -} - -/* Processing code for this example - - // mouseover serial - - // Demonstrates how to send data to the Arduino I/O board, in order to - // turn ON a light if the mouse is over a square and turn it off - // if the mouse is not. - - // created 2003-4 - // based on examples by Casey Reas and Hernando Barragan - // modified 18 Jan 2009 - // by Tom Igoe - // This example code is in the public domain. - - - - import processing.serial.*; - - float boxX; - float boxY; - int boxSize = 20; - boolean mouseOverBox = false; - - Serial port; - - void setup() { - size(200, 200); - boxX = width/2.0; - boxY = height/2.0; - rectMode(RADIUS); - - // List all the available serial ports in the output pane. - // You will need to choose the port that the Arduino board is - // connected to from this list. The first port in the list is - // port #0 and the third port in the list is port #2. - println(Serial.list()); - - // Open the port that the Arduino board is connected to (in this case #0) - // Make sure to open the port at the same speed Arduino is using (9600bps) - port = new Serial(this, Serial.list()[0], 9600); - - } - - void draw() - { - background(0); - - // Test if the cursor is over the box - if (mouseX > boxX-boxSize && mouseX < boxX+boxSize && - mouseY > boxY-boxSize && mouseY < boxY+boxSize) { - mouseOverBox = true; - // draw a line around the box and change its color: - stroke(255); - fill(153); - // send an 'H' to indicate mouse is over square: - port.write('H'); - } - else { - // return the box to it's inactive state: - stroke(153); - fill(153); - // send an 'L' to turn the LED off: - port.write('L'); - mouseOverBox = false; - } - - // Draw the box - rect(boxX, boxY, boxSize, boxSize); - } - - - */ - -/* -Max/MSP version 5 patch to run with this example: - -----------begin_max5_patcher---------- -1672.3oc2ZszaaiCD9ryuBBebQVCQRYao8xhf1cQCPVfBzh8RRQ.sDsM2HSZ -HQmlzh9eu7gjsjsEk7y0oWjiHoHm4aluYHGlueUmtiDuPy5B9Cv8fNc99Uc5 -XZR2Pm726zcF4knDRlYXciDylQ4xtWa6SReQZZ+iSeMiEQR.ej8BM4A9C7OO -kkAlSjQSAYTdbFfvA27o2c6sfO.Doqd6NfXgDHmRUCKkolg4hT06BfbQJGH3 -5Qd2e8d.QJIQSow5tzebZ7BFW.FIHow8.2JAQpVIIYByxo9KIMkSjL9D0BRT -sbGHZJIkDoZOSMuQT.8YZ5qpgGI3locF4IpQRzq2nDF+odZMIJkRjpEF44M3 -A9nWAum7LKFbSOv+PSRXYOvmIhYiYpg.8A2LOUOxPyH+TjPJA+MS9sIzTRRr -QP9rXF31IBZAHpVHkHrfaPRHLuUCzoj9GSoQRqIB52y6Z.tu8o4EX+fddfuj -+MrXiwPL5+9cXwrOVvkbxLpomazHbQO7EyX7DpzXYgkFdF6algCQpkX4XUlo -hA6oa7GWck9w0Gnmy6RXQOoQeCfWwlzsdnHLTq8n9PCHLv7Cxa6PAN3RCKjh -ISRVZ+sSl704Tqt0kocE9R8J+P+RJOZ4ysp6gN0vppBbOTEN8qp0YCq5bq47 -PUwfA5e766z7NbGMuncw7VgNRSyQhbnPMGrDsGaFSvKM5NcWoIVdZn44.eOi -9DTRUT.7jDQzSTiF4UzXLc7tLGh4T9pwaFQkGUGIiOOkpBSJUwGsBd40krHQ -9XEvwq2V6eLIhV6GuzP7uzzXBmzsXPSRYwBtVLp7s5lKVv6UN2VW7xRtYDbx -7s7wRgHYDI8YVFaTBshkP49R3rYpH3RlUhTQmK5jMadJyF3cYaTNQMGSyhRE -IIUlJaOOukdhoOyhnekEKmZlqU3UkLrk7bpPrpztKBVUR1uorLddk6xIOqNt -lBOroRrNVFJGLrDxudpET4kzkstNp2lzuUHVMgk5TDZx9GWumnoQTbhXsEtF -tzCcM+z0QKXsngCUtTOEIN0SX2iHTTIIz968.Kf.uhfzUCUuAd3UKd.OKt.N -HTynxTQyjpQD9jlwEXeKQxfHCBahUge6RprSa2V4m3aYOMyaP6gah2Yf1zbD -jVwZVGFZHHxINFxpjr5CiTS9JiZn6e6nTlXQZTAFj6QCppQwzL0AxVtoi6WE -QXsANkEGWMEuwNvhmKTnat7A9RqLq6pXuEwY6xM5xRraoTiurj51J1vKLzFs -CvM7HI14Mpje6YRxHOSieTsJpvJORjxT1nERK6s7YTN7sr6rylNwf5zMiHI4 -meZ4rTYt2PpVettZERbjJ6PjfqN2loPSrUcusH01CegsGEE5467rnCdqT1ES -QxtCvFq.cvGz+BaAHXKzRSfP+2Jf.KCvj5ZLJRAhwi+SWHvPyN3vXiaPn6JR -3eoA.0TkFhTvpsDMIrL20nAkCI4EoYfSHAuiPBdmJRyd.IynYYjIzMvjOTKf -3DLvnvRLDLpWeEOYXMfAZqfQ0.qsnlUdmA33t8CNJ7MZEb.u7fiZHLYzDkJp -R7CqEVLGN75U+1JXxFUY.xEEBcRCqhOEkz2bENEWnh4pbh0wY25EefbD6EmW -UA6Ip8wFLyuFXx+Wrp8m6iff1B86W7bqJO9+mx8er4E3.abCLrYdA16sBuHx -vKT6BlpIGQIhL55W7oicf3ayv3ixQCm4aQuY1HZUPQWY+cASx2WZ3f1fICuz -vj5R5ZbM1y8gXYN4dIXaYGq4NhQvS5MmcDADy+S.j8CQ78vk7Q7gtPDX3kFh -3NGaAsYBUAO.8N1U4WKycxbQdrWxJdXd10gNIO+hkUMmm.CZwknu7JbNUYUq -0sOsTsI1QudDtjw0t+xZ85wWZd80tMCiiMADNX4UzrcSeK23su87IANqmA7j -tiRzoXi2YRh67ldAk79gPmTe3YKuoY0qdEDV3X8xylCJMTN45JIakB7uY8XW -uVr3PO8wWwEoTW8lsfraX7ZqzZDDXCRqNkztHsGCYpIDDAOqxDpMVUMKcOrp -942acPvx2NPocMC1wQZ8glRn3myTykVaEUNLoEeJjVaAevA4EAZnsNgkeyO+ -3rEZB7f0DTazDcQTNmdt8aACGi1QOWnMmd+.6YjMHH19OB5gKsMF877x8wsJ -hN97JSnSfLUXGUoj6ujWXd6Pk1SAC+Pkogm.tZ.1lX1qL.pe6PE11DPeMMZ2 -.P0K+3peBt3NskC ------------end_max5_patcher----------- - - - */ diff --git a/build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.pde b/build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.pde deleted file mode 100644 index 3a6e01300..000000000 --- a/build/shared/examples/4.Communication/SerialCallResponse/SerialCallResponse.pde +++ /dev/null @@ -1,211 +0,0 @@ -/* - Serial Call and Response - Language: Wiring/Arduino - - This program sends an ASCII A (byte of value 65) on startup - and repeats that until it gets some data in. - Then it waits for a byte in the serial port, and - sends three sensor values whenever it gets a byte in. - - Thanks to Greg Shakar and Scott Fitzgerald for the improvements - - The circuit: - * potentiometers attached to analog inputs 0 and 1 - * pushbutton attached to digital I/O 2 - - Created 26 Sept. 2005 - by Tom Igoe - Modified 4 Sep 2010 - by Tom Igoe and Scott Fitzgerald - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/SerialCallResponse - - */ - -int firstSensor = 0; // first analog sensor -int secondSensor = 0; // second analog sensor -int thirdSensor = 0; // digital sensor -int inByte = 0; // incoming serial byte - -void setup() -{ - // start serial port at 9600 bps: - Serial.begin(9600); - pinMode(2, INPUT); // digital sensor is on digital pin 2 - establishContact(); // send a byte to establish contact until receiver responds -} - -void loop() -{ - // if we get a valid byte, read analog ins: - if (Serial.available() > 0) { - // get incoming byte: - inByte = Serial.read(); - // read first analog input, divide by 4 to make the range 0-255: - firstSensor = analogRead(A0)/4; - // delay 10ms to let the ADC recover: - delay(10); - // read second analog input, divide by 4 to make the range 0-255: - secondSensor = analogRead(1)/4; - // read switch, map it to 0 or 255L - thirdSensor = map(digitalRead(2), 0, 1, 0, 255); - // send sensor values: - Serial.write(firstSensor); - Serial.write(secondSensor); - Serial.write(thirdSensor); - } -} - -void establishContact() { - while (Serial.available() <= 0) { - Serial.print('A'); // send a capital A - delay(300); - } -} - -/* -Processing sketch to run with this example: - -// This example code is in the public domain. - -import processing.serial.*; - -int bgcolor; // Background color -int fgcolor; // Fill color -Serial myPort; // The serial port -int[] serialInArray = new int[3]; // Where we'll put what we receive -int serialCount = 0; // A count of how many bytes we receive -int xpos, ypos; // Starting position of the ball -boolean firstContact = false; // Whether we've heard from the microcontroller - -void setup() { - size(256, 256); // Stage size - noStroke(); // No border on the next thing drawn - - // Set the starting position of the ball (middle of the stage) - xpos = width/2; - ypos = height/2; - - // Print a list of the serial ports, for debugging purposes: - println(Serial.list()); - - // I know that the first port in the serial list on my mac - // is always my FTDI adaptor, so I open Serial.list()[0]. - // On Windows machines, this generally opens COM1. - // Open whatever port is the one you're using. - String portName = Serial.list()[0]; - myPort = new Serial(this, portName, 9600); -} - -void draw() { - background(bgcolor); - fill(fgcolor); - // Draw the shape - ellipse(xpos, ypos, 20, 20); -} - -void serialEvent(Serial myPort) { - // read a byte from the serial port: - int inByte = myPort.read(); - // if this is the first byte received, and it's an A, - // clear the serial buffer and note that you've - // had first contact from the microcontroller. - // Otherwise, add the incoming byte to the array: - if (firstContact == false) { - if (inByte == 'A') { - myPort.clear(); // clear the serial port buffer - firstContact = true; // you've had first contact from the microcontroller - myPort.write('A'); // ask for more - } - } - else { - // Add the latest byte from the serial port to array: - serialInArray[serialCount] = inByte; - serialCount++; - - // If we have 3 bytes: - if (serialCount > 2 ) { - xpos = serialInArray[0]; - ypos = serialInArray[1]; - fgcolor = serialInArray[2]; - - // print the values (for debugging purposes only): - println(xpos + "\t" + ypos + "\t" + fgcolor); - - // Send a capital A to request new sensor readings: - myPort.write('A'); - // Reset serialCount: - serialCount = 0; - } - } -} -*/ - -/* -Max/MSP version 5 patch to run with this example: - -----------begin_max5_patcher---------- -2569.3oc2as0jiZqD9YO+Jzw09PRc75BIAX671TaUop8gy4gLoNmG1YqsjAY -rxhAGPLW1T4+dZIAd.aCFeiEuYqXFABQqu9qa0Rp0ec2fgyiegmND8KnOgFL -3utav.8sT2XPd4ACWwdwKjkpq1vU7zTV.e3Hyyj7Wj5665Tbq3LYHWJecM2z -tCGh9b9iVyjdKEQAeIg6IMOkRmM1ZDx10UcgRF6LBgmN1Zy6H70se77+38yJ -9DKhijQrU5Ovv6SDrvhmDksRDAedsvRJU8Tw2zUGSfuyl5ZjUckwpa922cm5 -mQsDLh3OCx0NXQJODgqENlyhBFNpkvBchFVzfCwZ+vh60DVHm.r3EuZEORtC -t7.WISnOvBCe+uwSWGGkxQnGidL5AdjeJhgl+pjifuNRtjiRMUecbhbDhE4i -R3LnVTcsRQhnwHzCfXhVDmvChyfZ3EGFmLB8x53Tyq7J7Wn3EPS6IR7B4nrT -.n0M+SrvLnYR3xrjHtOZQR7ps+tiMh2+MVx+EzuuTjhz5JDzSy.KAn5Lir5y -eR3AhdjtTL7SBB5SpO8VMIBZjfXsPDC2GpCCojIP1L89EFIC45f9o6e3Ce7i -n6+YUCmJYIxr0iA4.ZvuxUxwyLgo+ajDUCLR8AizsLfnQn7l.8LbW9SfXIjv -qAZdzJ.1P9LIartS5AvqDvArM590I.ayZ1iQyeE8fWrTh9Ug7aA7DVnuFW+c -.q9XP7F+.ghHtGnBzJZLtdhsskshK6PLV85BXmZL3cNRlM9XX1VWPlsLQD.n -C5m.Mwmje9mUpDOE4RDrT99P9BIPMidBdUAP5AV08ggFdSB6YEWPgoqShg2Q -yOeV.OeIa8ZPSNmq32n+C6Efq9m.kETcfimb96Xz+WotkJtYgTrPjvA9Onn2 -gE.bNV5WQ2m3mIhh0LmRs0d0lz5UlDiWJGKGs1jXtTixz8lQalvEQBIHVvGM -UqlBXJONOqQZi2BvfjosuWrWPiTOngmXo8oatfoZPiZWCnYeq.ZdK4desvWD -GXYdBQtmLvk1iCu+wgJ12bdfHBLF.QNyioLGTVCKjJGSFPW8vUYQBySUtKWw -70t0f+bdXr2WQoKy.i.+3miNZJqsqA8czvNgRajxR6aneMQbrF.XkqDMzaFo -6wgmV.YDrNjCWaC.4psvwypAfH6Ef9e7DeVDauPDcePjUcAkUVN4I4.SNx.s -gHTMjVJvSJU6ACeq23nGfYlsoKYYT1khiBv6.Ekhq6SVE2zmu3XZiXvO8a0W -WiJ+Tslhn0f+YvFRSv296xxBkeY+fS0muf4wq8kqQULXXPhvONRIFUdW0sK9 -f.Gvn6cJK45ZDwVumWVFGGNmk7jHULOjWQS.rYVjXE39TJLRDDWQwCEqVmHL -VratGOhAswxTuj3vvJMk4IOsmmXB95YgubotsdCupL8lRLmJ1YUteiS2opQ2 -hjf4.H4T7+kqT81b0Fw+DGSrPZRyro5Bk7Kssom8jxeuZ8OUa3+6ZDhG6LyA -OcR0Wb6oHMnvok4OFcs.VK0+NOHkjCoF5ryrCBot2zPZkwF1cFoJVZy.ZwLS -2YFp0xYsLwvXtXlBOA2..6TK.ukep5FYsgQW2C5R6FzcMChIw5RvXMF+4DV7 -TqCBnzSFPsOE.sinq+afR0HPpG03PV+UHm1GFKImLVR9QGKycj1ZnDe6BkMM -vDDVMKYDZMCvrXXtMn2gQuifdGE8N6KhgewExAGpx5ldnJs7b1rRmIpUKNmN -taHqauXRSqETZfYU5IEy7U0fC6cfAlT137vnwrenQCp0QgFtV8Tzv74FdfQ5 -HSGSg+y1dj9uaWWF2pXs1ZIKNht7aScTs1L0LKLcuQ878iEowYIdE58h.dPU -6S97ToHZybo+zaNH2phKE99Um4pFtE9qiAJUt.h9bqzdGsb6zV41s+I231H2 -S5WxMts3shPQ5OxM4XjaZuQtUCt1d415FTtw8K4d1wf23aP4lzqvaWq1J2N8 -K+fsUtc6W768LL3sgbO46gbmeSnCX1tjT1Sb+u.eFHDwuvjxDw7LoIDrxaex -4uaBM9vCsYFAgwyYg4asylVoRauiTscac2aHwkYmzrpcWyJOsi8NkCb995N8 -sLYptT1wYxMRpL8udeCYxzAQjolDBf51BDw4FAQToB.LfJ9DS2MCjju8ylcV -rVHwtuAIx3ffP9YyGLoKhY8JpsySabC1u1pWqSS8hM6RrcqTuV2PoyXCo2Y6 -xmwbduYKMroMAL1S6aIzXnmesc+PQpT08KtpLBF0xbrXV9pz3t4x9vC5rivT -v9xo2kpTPLrQq8Qsydvwjze1js23fJcSmiNWRveuxj0mXga7OsuEl1jTWtlt -sIGdqqaiut85SJIixVMmmbHEu1tuIkus6jRnfiaiJ+aJcOoAcusILPWyfbGP -2Os+o7anaianaSlRZc2lX8CKmmZWFFZlySH8OR+EBFJFfKGFbZDF5g190LhX -Vzao5wgvnRWZAR4XxF37zsrVnZ10EpnWNn5agnfj3r0HZ8QR2xnGrMAMNA23 -.HG+3njuSrHHdZnKBbnCeFgZWr0XSbU4YgEooXqoVWyLZldIym7PAXpsjmvU -oMtWXbJe6iRSCCGQMo4MYlgzX03Anh3dyjj8U.EUh3dLXxz7T51oMXxj9FlT -2IOTSMNwUiI2xwvRn6jfnU.Dbea550AH5SYF6TONl1k3H13lPDbu67XVmYyG -pX1DvA3Aolut5joTx1Isov5yWzJCIgXMoQim9lsyYtvcDhwzHOPNRwu6kUf+ -9rvc+4JtLI9sjcrlAUaQ2rXfTmlTwXxMi6.8Yr3z7FjuBlFRuYY7q0a.8lY4 -L0F7LzLWKqyZ0sx4KTrloLswU6EeUOHeWx02323L+Buhhn0YRz7rEKTmm4m3 -IuBFXnUhPv6I2KNxO8nO8iTy4IKeo.sZ5vOhuYNwnlAXTGna0gztokIwrj.X -WCLfabXDbmECl9qWMO8Lvw16+cNnry9dWIsNpYKuUl.kpzNa2892p6czPsUj -bnsPlbONQhByHUkxwTr5B0d5lRmov51BYcVmBeTbKDIpS2JSUxFwZjIxrtWl -tzTehEUwrbLqlH1rP5UKkmgyDplCpKctFLSZQOYKqpCawfmYRR+7oXYuoz4h -6VsQZmzstbZCWvw9z74XN+h1NlSrdkRTmxnqtTW37zoas9IsxgNoakIRakIb -24QpshDoyDI21.Szt0w8V1g0jNmS6TYBa2VGHGAcpXHByvG1jYaJ0INIrNM2 -cj7kmjtozYJsaoJuLCuctHXaFDaqHw5GbPqN0klNltCF3WG65uMy4gP6dYhb -H9T2RmZ07HNRmD4tzv4KbOAuozkHpxCQzvc7LLZiSBR25jffuBy5IWORw5KE -CagO+YWiuFKOA0VOzDY5zRRqtz4Jszqgz5ZjVWqxRqpTWXei6VWyXx0d4nfB -+8c+C81VE7B ------------end_max5_patcher----------- - - -*/ diff --git a/build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.pde b/build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.pde deleted file mode 100644 index 76a6ffe2b..000000000 --- a/build/shared/examples/4.Communication/SerialCallResponseASCII/SerialCallResponseASCII.pde +++ /dev/null @@ -1,211 +0,0 @@ -/* - Serial Call and Response in ASCII - Language: Wiring/Arduino - - This program sends an ASCII A (byte of value 65) on startup - and repeats that until it gets some data in. - Then it waits for a byte in the serial port, and - sends three ASCII-encoded, comma-separated sensor values, - truncated by a linefeed and carriage return, - whenever it gets a byte in. - - Thanks to Greg Shakar and Scott Fitzgerald for the improvements - - The circuit: - * potentiometers attached to analog inputs 0 and 1 - * pushbutton attached to digital I/O 2 - - - - Created 26 Sept. 2005 - by Tom Igoe - Modified 4 Sep 2010 - by Tom Igoe and Scott Fitzgerald - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII - - */ - -int firstSensor = 0; // first analog sensor -int secondSensor = 0; // second analog sensor -int thirdSensor = 0; // digital sensor -int inByte = 0; // incoming serial byte - -void setup() -{ - // start serial port at 9600 bps: - Serial.begin(9600); - pinMode(2, INPUT); // digital sensor is on digital pin 2 - establishContact(); // send a byte to establish contact until receiver responds -} - -void loop() -{ - // if we get a valid byte, read analog ins: - if (Serial.available() > 0) { - // get incoming byte: - inByte = Serial.read(); - // read first analog input, divide by 4 to make the range 0-255: - firstSensor = analogRead(A0)/4; - // delay 10ms to let the ADC recover: - delay(10); - // read second analog input, divide by 4 to make the range 0-255: - secondSensor = analogRead(1)/4; - // read switch, map it to 0 or 255L - thirdSensor = map(digitalRead(2), 0, 1, 0, 255); - // send sensor values: - Serial.print(firstSensor, DEC); - Serial.print(","); - Serial.print(secondSensor, DEC); - Serial.print(","); - Serial.println(thirdSensor, DEC); - } -} - -void establishContact() { - while (Serial.available() <= 0) { - Serial.println("0,0,0"); // send an initial string - delay(300); - } -} - - -/* -Processing code to run with this example: - -// This example code is in the public domain. - -import processing.serial.*; // import the Processing serial library -Serial myPort; // The serial port - -float bgcolor; // Background color -float fgcolor; // Fill color -float xpos, ypos; // Starting position of the ball - -void setup() { - size(640,480); - - // List all the available serial ports - println(Serial.list()); - - // I know that the first port in the serial list on my mac - // is always my Arduino module, so I open Serial.list()[0]. - // Change the 0 to the appropriate number of the serial port - // that your microcontroller is attached to. - myPort = new Serial(this, Serial.list()[0], 9600); - - // read bytes into a buffer until you get a linefeed (ASCII 10): - myPort.bufferUntil('\n'); - - // draw with smooth edges: - smooth(); -} - -void draw() { - background(bgcolor); - fill(fgcolor); - // Draw the shape - ellipse(xpos, ypos, 20, 20); -} - -// serialEvent method is run automatically by the Processing applet -// whenever the buffer reaches the byte value set in the bufferUntil() -// method in the setup(): - -void serialEvent(Serial myPort) { - // read the serial buffer: - String myString = myPort.readStringUntil('\n'); - // if you got any bytes other than the linefeed: - myString = trim(myString); - - // split the string at the commas - // and convert the sections into integers: - int sensors[] = int(split(myString, ',')); - - // print out the values you got: - for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) { - print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t"); - } - // add a linefeed after all the sensor values are printed: - println(); - if (sensors.length > 1) { - xpos = map(sensors[0], 0,1023,0,width); - ypos = map(sensors[1], 0,1023,0,height); - fgcolor = sensors[2]; - } - // send a byte to ask for more data: - myPort.write("A"); - } - -*/ - -/* - -Max/MSP version 5 patch to run with this example: - -----------begin_max5_patcher---------- -2726.3oc2bkziaiiE9bU+J3XjCciwo.WzZeqPCL.4vLG5zXlCIAAzRz1bhrj -aI5pRkF8+89QRIWR1VxxqQNoPrL0B0G+dK7QxG8ed+cilj8UQwHzuf9.5t69 -y6u6Nyozm3txx2MZA+qQI7BysMJU7b1j++nw1KoDeUYN8z7rEEurXRVR0kxV -oRDJ0KKE1pezHzmJuzRtJZtLc1myEQJ6UodtOfGibCLG7czeRwOfW+LxXy6A -d2u0u5ULMKUkxWXdAidLWxW+xixRxxs0LQWU3GBBwjPO82vkeiTq1SWsPlBv -0zFI0p9B42LUOgBUy56011r2r9j+082q+X7owgRUFuU1Slp5EA5oAJxwqKBL -3BSfruSD32RPyxyVsrcUvw8TMjEZOzEK5reVrAqPODVgd9XkBQBz9PDLhvZk -YlvSmoYmpicyRXK8fMpF9tcwRD7ARSGj0G6HnoEhhB9LwV7jm6w45h4Z7V4D -XXCF8AWvzHX2rQ3kTmgbV0YPj8przKZw03Ph0oCIugloTT1hEBvi6l7x6EZL -g9UdRxa+MQwxrzBA5w2+qu6cnOl9wz2KRiKPbzjWTBD.AjZt.UXelkY4pwHd -ZLJWvg6hU9bhzrXQ7Xj9UxgadIOmqDwHjLcLRkuJMxTbxKP8lHSESEh3GPuy -T2ov8qJPSyxEyxVAUsws8XzWWlUXeWu.eCkMEd1HYdTh.sp.DSFb8DOYkn.P -iZUdJ7FzcguIfe.YZW+mLk3WP+9bYAxHoQ.OsBrifamaajwhmjQPaN0TJC9H -GZYw5W8FUIBpjYYFPjAmGtGnUCEArYosoVjg7bQ+jkhd7m0UbghmqVs7A.GP -E9EgFGOyk11uEI5JXbEwXDEokr7inmgyJdBfkTAOFn2fV.zFJlq3OXZjQfbQ -yzDGziKyAcUb3GSAZ+8QYJE5eIUealHmmDa30eG3p2MKasWDsjIBDAJqpX6l -ENVmld9FOnNX8AhOc21EtWRem3yncgJWNCXGzOARhOn9zOqEIQZkK4r4p2lH -lp.UyzmfGUBlLfV0iIIV8lb9yZcAMmtLOCdFi94yR35y4KWBRxIBs9M5ey+J -nq9GfJKH5.2Vk5uOf9eZwsRqaVghoxbAn+CB5szB.cNdwWPOlGuRllYzbpUW -6TZx5niPqONOpoKPmxCs3626lQZlKjoRE.K3kVXDSy.KiBiIDpzaAXPxM12S -2Io0gE.wFiOydfvrkbZgzbtUHsn4hnuT4KR.ZYQRYomLvkFnjo4Gs92DwLYp -wc+pTI3bGrHzFDSUZeSVdu4U0dLWviMd1fuNIIK5Knh4q.6f3rmSOXsVGaDa -LeiyGZU3KsH.XCMAPKgrrD8wQZuIF121Y2GGcjCFkYhYw2NX.pmIZWRXKDDc -mDz+UjGyS4i583ivsEUWcbJxKIlRlApCYhtWsBPOo1ce2nWaMV4an0SksCGm -fZAhA78LsJkvzlvUmLVL8PpiLvU8q2O1NlwZez7NkoKAWzfYjQAey2KeUh5y -6lbZd8o7HQqObKhh6FMKWFmkpgQimUe5pWn10t03nNxM2QJe4NdXUVVxDd9S -xB4jDQCIAnMySkK.OnJoEQPnEUWTtXYtzZwt9bhTNTGyKhxyRRZTU1q7zNth -M9qmkwp4l55U9pwL7TSyogcViy243k1bZelMAHI2p+W+lZ2lq0gLXcLQbMJM -gAlB07Ks0Hv8q+9Z0+TqieXaiPxCtgtj.+lO3liw5tJmV1uL9RQrX8emFkRK -oTq5ra3doTuaZJsQeCaOjVsVZ2DZqyCRq5rXaH71Cd1g4R5ffcakf2vOUa8r -1QuqsMCIWd1cIGhIAeNzXsF+kJrj.7dIT1QSnNGCgdkTW+mHR2DY8IDt8Ipq -txoy94R5Qykzez4xRGo8lJI2tTYWcLAgUyyGiVxANKCFdC5MDzann2vPuw4r -X3Wcft2tpv2zcUYvyIqU55qmt4R0wsCYcy4SJnURoCMqZWoZvu5JbzfiLHz5 -Fm6mMB+glMX3ChM7vCT1v95Fsmd5nAOvf+43L17890jI8JVqMlxhCnI+5PG0 -yMSKiByzZzWe2bQQ1p7nJ4d0ndPMaSwhBkLc8Xo+vqMuMtw4x33lib0P2x3k -YfJUI.QepWRuCF2d2n3Feahau9ha8PRFP3V6Vte3ldihaXDKHxvA2A8E2CK8 -69ia1vxeB8PvMa3faxgfa5vA2taYt0Bt8GV5It8ku8FV3l0WbiOi3t7jPCvt -bIE7mDweFdMPHhelqT4xIqT1Pvpu7Im9pIz4E22hYLKIaBOobocVWKMp6sP0 -l008uxDmmURCezIgHyFyMKj8ZpP0VN+35eijKT+i21QpPsOFwobPXtjdvHt2 -HLhNa..Opjia0UKojxke1syT800YnQIprYyRDmr9fclJd8yc13Yct.6WZwK9 -HW7baxg5zKwK9VJeHwmVBQVo2acN5zctEGLzxHxjn3Va9IxBkt4WcTaDLte4 -XQ.obVZ7VeXW7AK7.LEbNexckNKDS5zZumIKsG0llMzMW3fFMS2CNWRHeuRE -1m3Iq8OsqIl1l779kQD32UylbYa0GURFsZwDQ99D7F69Ns4Cn0XAWuNE92Tx -dZGx9xDgrex9fgmvuilMoilMMzu2MaJ9GVcdlqeu04ozgmR+YhFpRhvRZvsS -ZX.Z62ROhqRqmpGH793oVOzCtyKDWKALak7Burjm6YeqXg6wdqoe6wFZoSFW -aHFcERIavsQrZMSpSjfF1bQtIcoiRxJDatIR5vKbYRDxvk63nN23QTualzKu -Aony+zCfSJG5AsLap1Cm3Oz3j11wdFUiibS6YsbJ0RXakWjMHDxPaTpsQHl8 -WE+HYDmvZ5HNjtXDxfaeL1lYyu1vrYlPY1EcEJ8dxnlsSQmQyVeeRPw9cZ7L -zrcNw4qh53X2gZVNfV84N0JHeelup+XgPkms24moGMypNR6dGMSuYbGX1ZAG -m2fxXtrJ81cuaqdCX2LyhmwfmiB8v3SaRcr5KLlwrHnyI4jbQ2Bamyg0+aBd -bkWQY5xUJzjUSmp2IuOIxeQ+KHvBYB38TDkkFWbn66uxrxpz+IA2019ibyrW -Iscvn2Jy5smbWyNfusKUe61ZgzY2HjqVLXl2dyzSyRGatrukjxVK2qd3WutZ -+srTuzF47v1Ky6tWh2sDQGDlb1ClXWUHwZjEBsQSgWeZBuOLcc4IWbOvDAeU -wjeOfDy8vfD02QuVvdjx.OBVW5DAaPO.q+Uk9b5AhBtpHhzGkLmCTfZEgtzP -yZ7aEulRmCvROyfsDdkKGUsRmJXo8w7045JsI8ASW2dnHrK.Ow7Cr5dtlCtr -0kNUzFdIPqqAsLLqFZMkN0t0HWBzBiARiOpWczpKcpAFzGeQazjt3Aqf6QvJ -jvgmUL6.CLnxFobZ.sxXSoSEs8oSO2lz7EOzJVewzAvfNXS+cN1ILrrSPSoq -BC5bXLXkcqcIJcbbVW5DQqWe52iccsX5i31fa50aDGz9hoqmYAs27DdfYp5d -cwjaeMHOB2G1ewWc7Br4NX8RL6OpBk2ooz0nKW2q6fjb6yfLcYGZPKFGbNj5 -Lnoz4X1LN2gXUMHX2xYa1lC.MJwpRWPqabh6o63tGMjvgmsu2Q1KsMHVO15R -mHXCGdC2yI3BXIcpxz9DLiyoLIHPg+59+Fv1JXFJ ------------end_max5_patcher----------- -*/ diff --git a/build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.pde b/build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.pde deleted file mode 100644 index e931262a9..000000000 --- a/build/shared/examples/4.Communication/VirtualColorMixer/VirtualColorMixer.pde +++ /dev/null @@ -1,130 +0,0 @@ -/* - This example reads three analog sensors (potentiometers are easiest) - and sends their values serially. The Processing and Max/MSP programs at the bottom - take those three values and use them to change the background color of the screen. - - The circuit: - * potentiometers attached to analog inputs 0, 1, and 2 - - http://www.arduino.cc/en/Tutorial/VirtualColorMixer - - created 2 Dec 2006 - by David A. Mellis - modified 4 Sep 2010 - by Tom Igoe and Scott Fitzgerald - - This example code is in the public domain. - */ - -const int redPin = A0; // sensor to control red color -const int greenPin = A1; // sensor to control green color -const int bluePin = A2; // sensor to control blue color - -void setup() -{ - Serial.begin(9600); -} - -void loop() -{ - Serial.print(analogRead(redPin)); - Serial.print(","); - Serial.print(analogRead(greenPin)); - Serial.print(","); - Serial.println(analogRead(bluePin)); -} - -/* Processing code for this example - -// This example code is in the public domain. - - import processing.serial.*; - - float redValue = 0; // red value - float greenValue = 0; // green value - float blueValue = 0; // blue value - - Serial myPort; - - void setup() { - size(200, 200); - - // List all the available serial ports - println(Serial.list()); - // I know that the first port in the serial list on my mac - // is always my Arduino, so I open Serial.list()[0]. - // Open whatever port is the one you're using. - myPort = new Serial(this, Serial.list()[0], 9600); - // don't generate a serialEvent() unless you get a newline character: - myPort.bufferUntil('\n'); - } - - void draw() { - // set the background color with the color values: - background(redValue, greenValue, blueValue); - } - - void serialEvent(Serial myPort) { - // get the ASCII string: - String inString = myPort.readStringUntil('\n'); - - if (inString != null) { - // trim off any whitespace: - inString = trim(inString); - // split the string on the commas and convert the - // resulting substrings into an integer array: - float[] colors = float(split(inString, ",")); - // if the array has at least three elements, you know - // you got the whole thing. Put the numbers in the - // color variables: - if (colors.length >=3) { - // map them to the range 0-255: - redValue = map(colors[0], 0, 1023, 0, 255); - greenValue = map(colors[1], 0, 1023, 0, 255); - blueValue = map(colors[2], 0, 1023, 0, 255); - } - } - } - */ - -/* Max/MSP patch for this example - - ----------begin_max5_patcher---------- -1512.3oc4Z00aaaCE8YmeED9ktB35xOjrj1aAsXX4g8xZQeYoXfVh1gqRjdT -TsIsn+2K+PJUovVVJ1VMdCAvxThV7bO7b48dIyWtXxzkxaYkSA+J3u.Sl7kK -lLwcK6MlT2dxzB5so4zRW2lJXeRt7elNy+HM6Vs61uDDzbOYkNmo02sg4euS -4BSede8S2P0o2vEq+aEKU66PPP7b3LPHDauPvyCmAvv4v6+M7L2XXF2WfCaF -lURgVPKbCxzKUbZdySDUEbgABN.ia08R9mccGYGn66qGutNir27qWbg8iY+7 -HDRx.Hjf+OPHCQgPdpQHoxhBlwB+QF4cbkthlCRk4REnfeKScs3ZwaugWBbj -.PS+.qDPAkZkgPlY5oPS4By2A5aTLFv9pounjsgpnZVF3x27pqtBrRpJnZaa -C3WxTkfUJYA.BzR.BhIy.ehquw7dSoJCsrlATLckR.nhLPNWvVwL+Vp1LHL. -SjMG.tRaG7OxT5R2c8Hx9B8.wLCxVaGI6qnpj45Ug84kL+6YIM8CqUxJyycF -7bqsBRULGvwfWyRMyovElat7NvqoejaLm4f+fkmyKuVTHy3q3ldhB.WtQY6Z -x0BSOeSpTqA+FW+Yy3SyybH3sFy8p0RVCmaMpTyX6HdDZ2JsPbfSogbBMueH -JLd6RMBdfRMzPjZvimuWIK2XgFA.ZmtfKoh0Sm88qc6OF4bDQ3P6kEtF6xej -.OkjD4H5OllyS+.3FlhY0so4xRlWqyrXErQpt+2rsnXgQNZHZgmMVzEofW7T -S4zORQtgIdDbRHrObRzSMNofUVZVcbKbhQZrSOo934TqRHIN2ncr7BF8TKR1 -tHDqL.PejLRRPKMR.pKFAkbtDa+UOvsYsIFH0DYsTCjqZ66T1CmGeDILLpSm -myk0SdkOKh5LUr4GbWwRYdW7fm.BvDmzHnSdH3biGpSbxxDNJoGDAD1ChH7L -I0DaloOTBLvkO7zPs5HJnKNoGAXbol5eytUhfyiSfnjE1uAq+Fp0a+wygGwR -q3ZI8.psJpkpJnyPzwmXBj7Sh.+bNvVZxlcKAm0OYHIxcIjzEKdRChgO5UMf -LkMPNN0MfiS7Ev6TYQct.F5IWcCZ4504rGsiVswGWWSYyma01QcZgmL+f+sf -oU18Hn6o6dXkMkFF14TL9rIAWE+6wvGV.p.TPqz3HK5L+VxYxl4UmBKEjr.B -6zinuKI3C+D2Y7azIM6N7QL6t+jQyZxymK1ToAKqVsxjlGyjz2c1kTK3180h -kJEYkacWpv6lyp2VJTjWK47wHA6fyBOWxH9pUf6jUtZkLpNKW.9EeUBH3ymY -XSQlaqGrkQMGzp20adYSmIOGjIABo1xZyAWJtCX9tg6+HMuhMCPyx76ao+Us -UxmzUE79H8d2ZB1m1ztbnOa1mGeAq0awyK8a9UqBUc6pZolpzurTK232e5gp -aInVw8QIIcpaiNSJfY4Z+92Cs+Mc+mgg2cEsvGlLY6V+1kMuioxnB5VM+fsY -9vSu4WI1PMBGXye6KXvNuzmZTh7U9h5j6vvASdngPdgOFxycNL6ia1axUMmT -JIzebXcQCn3SKMf+4QCMmOZung+6xBCPLfwO8ngcEI52YJ1y7mx3CN9xKUYU -bg7Y1yXjlKW6SrZnguQdsSfOSSDItqv2jwJFjavc1vO7OigyBr2+gDYorRk1 -HXZpVFfu2FxXkZtfp4RQqNkX5y2sya3YYL2iavWAOaizH+pw.Ibg8f1I9h3Z -2B79sNeOHvBOtfEalWsvyu0KMf015.AaROvZ7vv5AhnndfHLbTgjcCK1KlHv -gOk5B26OqrXjcJ005.QqCHn8fVTxnxfj93SfQiJlv8YV0VT9fVUwOOhSV3uD -eeqCUClbBPa.j3vWDoMZssNTzRNEnE6gYPXazZaMF921syaLWyAeBXvCESA8 -ASi6Zyw8.RQi65J8ZsNx3ho93OhGWENtWpowepae4YhCFeLErOLENtXJrOSc -iadi39rf4hwc8xdhHz3gn3dBI7iDRlFe8huAfIZhq ------------end_max5_patcher----------- - - - */ diff --git a/build/shared/examples/5.Control/Arrays/Arrays.pde b/build/shared/examples/5.Control/Arrays/Arrays.pde deleted file mode 100644 index cf83ccfb2..000000000 --- a/build/shared/examples/5.Control/Arrays/Arrays.pde +++ /dev/null @@ -1,57 +0,0 @@ -/* - Arrays - - Demonstrates the use of an array to hold pin numbers - in order to iterate over the pins in a sequence. - Lights multiple LEDs in sequence, then in reverse. - - Unlike the For Loop tutorial, where the pins have to be - contiguous, here the pins can be in any random order. - - The circuit: - * LEDs from pins 2 through 7 to ground - - created 2006 - by David A. Mellis - modified 5 Jul 2009 - by Tom Igoe - -This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/Array - */ - -int timer = 100; // The higher the number, the slower the timing. -int ledPins[] = { - 2, 7, 4, 6, 5, 3 }; // an array of pin numbers to which LEDs are attached -int pinCount = 6; // the number of pins (i.e. the length of the array) - -void setup() { - int thisPin; - // the array elements are numbered from 0 to (pinCount - 1). - // use a for loop to initialize each pin as an output: - for (int thisPin = 0; thisPin < pinCount; thisPin++) { - pinMode(ledPins[thisPin], OUTPUT); - } -} - -void loop() { - // loop from the lowest pin to the highest: - for (int thisPin = 0; thisPin < pinCount; thisPin++) { - // turn the pin on: - digitalWrite(ledPins[thisPin], HIGH); - delay(timer); - // turn the pin off: - digitalWrite(ledPins[thisPin], LOW); - - } - - // loop from the highest pin to the lowest: - for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { - // turn the pin on: - digitalWrite(ledPins[thisPin], HIGH); - delay(timer); - // turn the pin off: - digitalWrite(ledPins[thisPin], LOW); - } -} diff --git a/build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.pde b/build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.pde deleted file mode 100644 index ec60ec9a0..000000000 --- a/build/shared/examples/5.Control/ForLoopIteration/ForLoopIteration.pde +++ /dev/null @@ -1,47 +0,0 @@ -/* - For Loop Iteration - - Demonstrates the use of a for() loop. - Lights multiple LEDs in sequence, then in reverse. - - The circuit: - * LEDs from pins 2 through 7 to ground - - created 2006 - by David A. Mellis - modified 5 Jul 2009 - by Tom Igoe - -This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/ForLoop - */ - -int timer = 100; // The higher the number, the slower the timing. - -void setup() { - // use a for loop to initialize each pin as an output: - for (int thisPin = 2; thisPin < 8; thisPin++) { - pinMode(thisPin, OUTPUT); - } -} - -void loop() { - // loop from the lowest pin to the highest: - for (int thisPin = 2; thisPin < 8; thisPin++) { - // turn the pin on: - digitalWrite(thisPin, HIGH); - delay(timer); - // turn the pin off: - digitalWrite(thisPin, LOW); - } - - // loop from the highest pin to the lowest: - for (int thisPin = 7; thisPin >= 2; thisPin--) { - // turn the pin on: - digitalWrite(thisPin, HIGH); - delay(timer); - // turn the pin off: - digitalWrite(thisPin, LOW); - } -} diff --git a/build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.pde b/build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.pde deleted file mode 100644 index 5bc0dff3b..000000000 --- a/build/shared/examples/5.Control/IfStatementConditional/IfStatementConditional.pde +++ /dev/null @@ -1,56 +0,0 @@ -/* - Conditionals - If statement - - This example demonstrates the use of if() statements. - It reads the state of a potentiometer (an analog input) and turns on an LED - only if the LED goes above a certain threshold level. It prints the analog value - regardless of the level. - - The circuit: - * potentiometer connected to analog pin 0. - Center pin of the potentiometer goes to the analog pin. - side pins of the potentiometer go to +5V and ground - * LED connected from digital pin 13 to ground - - * Note: On most Arduino boards, there is already an LED on the board - connected to pin 13, so you don't need any extra components for this example. - - created 17 Jan 2009 - modified 4 Sep 2010 - by Tom Igoe - -This example code is in the public domain. - -http://arduino.cc/en/Tutorial/IfStatement - - */ - -// These constants won't change: -const int analogPin = A0; // pin that the sensor is attached to -const int ledPin = 13; // pin that the LED is attached to -const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input - -void setup() { - // initialize the LED pin as an output: - pinMode(ledPin, OUTPUT); - // initialize serial communications: - Serial.begin(9600); -} - -void loop() { - // read the value of the potentiometer: - int analogValue = analogRead(analogPin); - - // if the analog value is high enough, turn on the LED: - if (analogValue > threshold) { - digitalWrite(ledPin, HIGH); - } - else { - digitalWrite(ledPin,LOW); - } - - // print the analog value: - Serial.println(analogValue, DEC); - -} - diff --git a/build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.pde b/build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.pde deleted file mode 100644 index 69c6fc83b..000000000 --- a/build/shared/examples/5.Control/WhileStatementConditional/WhileStatementConditional.pde +++ /dev/null @@ -1,88 +0,0 @@ -/* - Conditionals - while statement - - This example demonstrates the use of while() statements. - - While the pushbutton is pressed, the sketch runs the calibration routine. - The sensor readings during the while loop define the minimum and maximum - of expected values from the photo resistor. - - This is a variation on the calibrate example. - - The circuit: - * photo resistor connected from +5V to analog in pin 0 - * 10K resistor connected from ground to analog in pin 0 - * LED connected from digital pin 9 to ground through 220 ohm resistor - * pushbutton attached from pin 2 to +5V - * 10K resistor attached from pin 2 to ground - - created 17 Jan 2009 - modified 4 Sep 2010 - by Tom Igoe - - This example code is in the public domain. - - http://arduino.cc/en/Tutorial/WhileLoop - - */ - - -// These constants won't change: -const int sensorPin = A2; // pin that the sensor is attached to -const int ledPin = 9; // pin that the LED is attached to -const int indicatorLedPin = 13; // pin that the built-in LED is attached to -const int buttonPin = 2; // pin that the button is attached to - - -// These variables will change: -int sensorMin = 1023; // minimum sensor value -int sensorMax = 0; // maximum sensor value -int sensorValue = 0; // the sensor value - - -void setup() { - // set the LED pins as outputs and the switch pin as input: - pinMode(indicatorLedPin, OUTPUT); - pinMode (ledPin, OUTPUT); - pinMode (buttonPin, INPUT); -} - -void loop() { - // while the button is pressed, take calibration readings: - while (digitalRead(buttonPin) == HIGH) { - calibrate(); - } - // signal the end of the calibration period - digitalWrite(indicatorLedPin, LOW); - - // read the sensor: - sensorValue = analogRead(sensorPin); - - // apply the calibration to the sensor reading - sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255); - - // in case the sensor value is outside the range seen during calibration - sensorValue = constrain(sensorValue, 0, 255); - - // fade the LED using the calibrated value: - analogWrite(ledPin, sensorValue); -} - -void calibrate() { - // turn on the indicator LED to indicate that calibration is happening: - digitalWrite(indicatorLedPin, HIGH); - // read the sensor: - sensorValue = analogRead(sensorPin); - - // record the maximum sensor value - if (sensorValue > sensorMax) { - sensorMax = sensorValue; - } - - // record the minimum sensor value - if (sensorValue < sensorMin) { - sensorMin = sensorValue; - } -} - - diff --git a/build/shared/examples/5.Control/switchCase/switchCase.pde b/build/shared/examples/5.Control/switchCase/switchCase.pde deleted file mode 100644 index 1b76e5fb6..000000000 --- a/build/shared/examples/5.Control/switchCase/switchCase.pde +++ /dev/null @@ -1,62 +0,0 @@ -/* - Switch statement - - Demonstrates the use of a switch statement. The switch - statement allows you to choose from among a set of discrete values - of a variable. It's like a series of if statements. - - To see this sketch in action, but the board and sensor in a well-lit - room, open the serial monitor, and and move your hand gradually - down over the sensor. - - The circuit: - * photoresistor from analog in 0 to +5V - * 10K resistor from analog in 0 to ground - - created 1 Jul 2009 - modified 4 Sep 2010 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/SwitchCase - */ - -// these constants won't change: -const int sensorMin = 0; // sensor minimum, discovered through experiment -const int sensorMax = 600; // sensor maximum, discovered through experiment - -void setup() { - // initialize serial communication: - Serial.begin(9600); -} - -void loop() { - // read the sensor: - int sensorReading = analogRead(A0); - // map the sensor range to a range of four options: - int range = map(sensorReading, sensorMin, sensorMax, 0, 3); - - // do something different depending on the - // range value: - switch (range) { - case 0: // your hand is on the sensor - Serial.println("dark"); - break; - case 1: // your hand is close to the sensor - Serial.println("dim"); - break; - case 2: // your hand is a few inches from the sensor - Serial.println("medium"); - break; - case 3: // your hand is nowhere near the sensor - Serial.println("bright"); - break; - } - -} - - - - - diff --git a/build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.pde b/build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.pde deleted file mode 100644 index 58ea129d2..000000000 --- a/build/shared/examples/6.Sensors/ADXL3xx/ADXL3xx.pde +++ /dev/null @@ -1,64 +0,0 @@ - -/* - ADXL3xx - - Reads an Analog Devices ADXL3xx accelerometer and communicates the - acceleration to the computer. The pins used are designed to be easily - compatible with the breakout boards from Sparkfun, available from: - http://www.sparkfun.com/commerce/categories.php?c=80 - - http://www.arduino.cc/en/Tutorial/ADXL3xx - - The circuit: - analog 0: accelerometer self test - analog 1: z-axis - analog 2: y-axis - analog 3: x-axis - analog 4: ground - analog 5: vcc - - created 2 Jul 2008 - by David A. Mellis - modified 4 Sep 2010 - by Tom Igoe - - This example code is in the public domain. - -*/ - -// these constants describe the pins. They won't change: -const int groundpin = 18; // analog input pin 4 -- ground -const int powerpin = 19; // analog input pin 5 -- voltage -const int xpin = A3; // x-axis of the accelerometer -const int ypin = A2; // y-axis -const int zpin = A1; // z-axis (only on 3-axis models) - -void setup() -{ - // initialize the serial communications: - Serial.begin(9600); - - // Provide ground and power by using the analog inputs as normal - // digital pins. This makes it possible to directly connect the - // breakout board to the Arduino. If you use the normal 5V and - // GND pins on the Arduino, you can remove these lines. - pinMode(groundpin, OUTPUT); - pinMode(powerpin, OUTPUT); - digitalWrite(groundpin, LOW); - digitalWrite(powerpin, HIGH); -} - -void loop() -{ - // print the sensor values: - Serial.print(analogRead(xpin)); - // print a tab between values: - Serial.print("\t"); - Serial.print(analogRead(ypin)); - // print a tab between values: - Serial.print("\t"); - Serial.print(analogRead(zpin)); - Serial.println(); - // delay before next reading: - delay(100); -} diff --git a/build/shared/examples/6.Sensors/Knock/Knock.pde b/build/shared/examples/6.Sensors/Knock/Knock.pde deleted file mode 100644 index 985f032b9..000000000 --- a/build/shared/examples/6.Sensors/Knock/Knock.pde +++ /dev/null @@ -1,55 +0,0 @@ -/* Knock Sensor - - This sketch reads a piezo element to detect a knocking sound. - It reads an analog pin and compares the result to a set threshold. - If the result is greater than the threshold, it writes - "knock" to the serial port, and toggles the LED on pin 13. - - The circuit: - * + connection of the piezo attached to analog in 0 - * - connection of the piezo attached to ground - * 1-megohm resistor attached from analog in 0 to ground - - http://www.arduino.cc/en/Tutorial/Knock - - created 25 Mar 2007 - by David Cuartielles - modified 4 Sep 2010 - by Tom Igoe - - This example code is in the public domain. - - */ - - -// these constants won't change: -const int ledPin = 13; // led connected to digital pin 13 -const int knockSensor = A0; // the piezo is connected to analog pin 0 -const int threshold = 100; // threshold value to decide when the detected sound is a knock or not - - -// these variables will change: -int sensorReading = 0; // variable to store the value read from the sensor pin -int ledState = LOW; // variable used to store the last LED status, to toggle the light - -void setup() { - pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT - Serial.begin(9600); // use the serial port -} - -void loop() { - // read the sensor and store it in the variable sensorReading: - sensorReading = analogRead(knockSensor); - - // if the sensor reading is greater than the threshold: - if (sensorReading >= threshold) { - // toggle the status of the ledPin: - ledState = !ledState; - // update the LED pin itself: - digitalWrite(ledPin, ledState); - // send the string "Knock!" back to the computer, followed by newline - Serial.println("Knock!"); - } - delay(100); // delay to avoid overloading the serial port buffer -} - diff --git a/build/shared/examples/6.Sensors/Memsic2125/Memsic2125.pde b/build/shared/examples/6.Sensors/Memsic2125/Memsic2125.pde deleted file mode 100644 index cf5e81c33..000000000 --- a/build/shared/examples/6.Sensors/Memsic2125/Memsic2125.pde +++ /dev/null @@ -1,63 +0,0 @@ -/* - Memsic2125 - - Read the Memsic 2125 two-axis accelerometer. Converts the - pulses output by the 2125 into milli-g's (1/1000 of earth's - gravity) and prints them over the serial connection to the - computer. - - The circuit: - * X output of accelerometer to digital pin 2 - * Y output of accelerometer to digital pin 3 - * +V of accelerometer to +5V - * GND of accelerometer to ground - - http://www.arduino.cc/en/Tutorial/Memsic2125 - - created 6 Nov 2008 - by David A. Mellis - modified 30 Jun 2009 - by Tom Igoe - - This example code is in the public domain. - - */ - -// these constants won't change: -const int xPin = 2; // X output of the accelerometer -const int yPin = 3; // Y output of the accelerometer - -void setup() { - // initialize serial communications: - Serial.begin(9600); - // initialize the pins connected to the accelerometer - // as inputs: - pinMode(xPin, INPUT); - pinMode(yPin, INPUT); -} - -void loop() { - // variables to read the pulse widths: - int pulseX, pulseY; - // variables to contain the resulting accelerations - int accelerationX, accelerationY; - - // read pulse from x- and y-axes: - pulseX = pulseIn(xPin,HIGH); - pulseY = pulseIn(yPin,HIGH); - - // convert the pulse width into acceleration - // accelerationX and accelerationY are in milli-g's: - // earth's gravity is 1000 milli-g's, or 1g. - accelerationX = ((pulseX / 10) - 500) * 8; - accelerationY = ((pulseY / 10) - 500) * 8; - - // print the acceleration - Serial.print(accelerationX); - // print a tab character: - Serial.print("\t"); - Serial.print(accelerationY); - Serial.println(); - - delay(100); -} diff --git a/build/shared/examples/6.Sensors/Ping/Ping.pde b/build/shared/examples/6.Sensors/Ping/Ping.pde deleted file mode 100644 index 70bab93a7..000000000 --- a/build/shared/examples/6.Sensors/Ping/Ping.pde +++ /dev/null @@ -1,84 +0,0 @@ -/* Ping))) Sensor - - This sketch reads a PING))) ultrasonic rangefinder and returns the - distance to the closest object in range. To do this, it sends a pulse - to the sensor to initiate a reading, then listens for a pulse - to return. The length of the returning pulse is proportional to - the distance of the object from the sensor. - - The circuit: - * +V connection of the PING))) attached to +5V - * GND connection of the PING))) attached to ground - * SIG connection of the PING))) attached to digital pin 7 - - http://www.arduino.cc/en/Tutorial/Ping - - created 3 Nov 2008 - by David A. Mellis - modified 30 Jun 2009 - by Tom Igoe - - This example code is in the public domain. - - */ - -// this constant won't change. It's the pin number -// of the sensor's output: -const int pingPin = 7; - -void setup() { - // initialize serial communication: - Serial.begin(9600); -} - -void loop() -{ - // establish variables for duration of the ping, - // and the distance result in inches and centimeters: - long duration, inches, cm; - - // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. - // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: - pinMode(pingPin, OUTPUT); - digitalWrite(pingPin, LOW); - delayMicroseconds(2); - digitalWrite(pingPin, HIGH); - delayMicroseconds(5); - digitalWrite(pingPin, LOW); - - // The same pin is used to read the signal from the PING))): a HIGH - // pulse whose duration is the time (in microseconds) from the sending - // of the ping to the reception of its echo off of an object. - pinMode(pingPin, INPUT); - duration = pulseIn(pingPin, HIGH); - - // convert the time into a distance - inches = microsecondsToInches(duration); - cm = microsecondsToCentimeters(duration); - - Serial.print(inches); - Serial.print("in, "); - Serial.print(cm); - Serial.print("cm"); - Serial.println(); - - delay(100); -} - -long microsecondsToInches(long microseconds) -{ - // According to Parallax's datasheet for the PING))), there are - // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per - // second). This gives the distance travelled by the ping, outbound - // and return, so we divide by 2 to get the distance of the obstacle. - // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf - return microseconds / 74 / 2; -} - -long microsecondsToCentimeters(long microseconds) -{ - // The speed of sound is 340 m/s or 29 microseconds per centimeter. - // The ping travels out and back, so to find the distance of the - // object we take half of the distance travelled. - return microseconds / 29 / 2; -} diff --git a/build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.pde b/build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.pde deleted file mode 100644 index bcda4c78d..000000000 --- a/build/shared/examples/7.Display/RowColumnScanning/RowColumnScanning.pde +++ /dev/null @@ -1,114 +0,0 @@ -/* - Row-Column Scanning an 8x8 LED matrix with X-Y input - - This example controls an 8x8 LED matrix using two analog inputs - - created 27 May 2009 - modified 4 Sep 2010 - by Tom Igoe - - This example works for the Lumex LDM-24488NI Matrix. See - http://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf - for the pin connections - - For other LED cathode column matrixes, you should only need to change - the pin numbers in the row[] and column[] arrays - - rows are the anodes - cols are the cathodes - --------- - - Pin numbers: - Matrix: - * Digital pins 2 through 13, - * analog pins 2 through 5 used as digital 16 through 19 - Potentiometers: - * center pins are attached to analog pins 0 and 1, respectively - * side pins attached to +5V and ground, respectively. - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/RowColumnScanning - - see also http://www.tigoe.net/pcomp/code/category/arduinowiring/514 for more - */ - - -// 2-dimensional array of row pin numbers: -const int row[8] = { - 2,7,19,5,13,18,12,16 }; - -// 2-dimensional array of column pin numbers: -const int col[8] = { - 6,11,10,3,17,4,8,9 }; - -// 2-dimensional array of pixels: -int pixels[8][8]; - -// cursor position: -int x = 5; -int y = 5; - -void setup() { - Serial.begin(9600); - // initialize the I/O pins as outputs: - - // iterate over the pins: - for (int thisPin = 0; thisPin < 8; thisPin++) { - // initialize the output pins: - pinMode(col[thisPin], OUTPUT); - pinMode(row[thisPin], OUTPUT); - // take the col pins (i.e. the cathodes) high to ensure that - // the LEDS are off: - digitalWrite(col[thisPin], HIGH); - } - - // initialize the pixel matrix: - for (int x = 0; x < 8; x++) { - for (int y = 0; y < 8; y++) { - pixels[x][y] = HIGH; - } - } -} - -void loop() { - // read input: - readSensors(); - - // draw the screen: - refreshScreen(); -} - -void readSensors() { - // turn off the last position: - pixels[x][y] = HIGH; - // read the sensors for X and Y values: - x = 7 - map(analogRead(A0), 0, 1023, 0, 7); - y = map(analogRead(A1), 0, 1023, 0, 7); - // set the new pixel position low so that the LED will turn on - // in the next screen refresh: - pixels[x][y] = LOW; - -} - -void refreshScreen() { - // iterate over the rows (anodes): - for (int thisRow = 0; thisRow < 8; thisRow++) { - // take the row pin (anode) high: - digitalWrite(row[thisRow], HIGH); - // iterate over the cols (cathodes): - for (int thisCol = 0; thisCol < 8; thisCol++) { - // get the state of the current pixel; - int thisPixel = pixels[thisRow][thisCol]; - // when the row is HIGH and the col is LOW, - // the LED where they meet turns on: - digitalWrite(col[thisCol], thisPixel); - // turn the pixel off: - if (thisPixel == LOW) { - digitalWrite(col[thisCol], HIGH); - } - } - // take the row pin low to turn off the whole row: - digitalWrite(row[thisRow], LOW); - } -} diff --git a/build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.pde b/build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.pde deleted file mode 100644 index fe631b9c7..000000000 --- a/build/shared/examples/8.Strings/StringAdditionOperator/StringAdditionOperator.pde +++ /dev/null @@ -1,61 +0,0 @@ -/* - Adding Strings together - - Examples of how to add strings together - You can also add several different data types to string, as shown here: - - created 27 July 2010 - modified 4 Sep 2010 - by Tom Igoe - - http://arduino.cc/en/Tutorial/StringAdditionOperator - - This example code is in the public domain. - */ - -// declare three strings: -String stringOne, stringTwo, stringThree; - -void setup() { - Serial.begin(9600); - stringOne = String("stringThree = "); - stringTwo = String("this string"); - stringThree = String (); - Serial.println("\n\nAdding strings together (concatenation):"); -} - -void loop() { - // adding a constant integer to a string: - stringThree = stringOne + 123; - Serial.println(stringThree); // prints "stringThree = 123" - - // adding a constant long interger to a string: - stringThree = stringOne + 123456789; - Serial.println(stringThree); // prints " You added 123456789" - - // adding a constant character to a string: - stringThree = stringOne + 'A'; - Serial.println(stringThree); // prints "You added A" - - // adding a constant string to a string: - stringThree = stringOne + "abc"; - Serial.println(stringThree); // prints "You added abc" - - stringThree = stringOne + stringTwo; - Serial.println(stringThree); // prints "You added this string" - - // adding a variable integer to a string: - int sensorValue = analogRead(A0); - stringOne = "Sensor value: "; - stringThree = stringOne + sensorValue; - Serial.println(stringThree); // prints "Sensor Value: 401" or whatever value analogRead(A0) has - - // adding a variable long integer to a string: - long currentTime = millis(); - stringOne="millis() value: "; - stringThree = stringOne + millis(); - Serial.println(stringThree); // prints "The millis: 345345" or whatever value currentTime has - - // do nothing while true: - while(true); -} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.pde b/build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.pde deleted file mode 100644 index 680738142..000000000 --- a/build/shared/examples/8.Strings/StringAppendOperator/StringAppendOperator.pde +++ /dev/null @@ -1,64 +0,0 @@ -/* - Appending to Strings using the += operator and concat() - - Examples of how to append different data types to strings - - created 27 July 2010 - modified 4 Sep 2010 - by Tom Igoe - - http://arduino.cc/en/Tutorial/StringAppendOperator - - This example code is in the public domain. - */ -String stringOne, stringTwo; - -void setup() { - Serial.begin(9600); - stringOne = String("Sensor "); - stringTwo = String("value"); - Serial.println("\n\nAppending to a string:"); -} - -void loop() { - Serial.println(stringOne); // prints "Sensor " - - // adding a string to a string: - stringOne += stringTwo; - Serial.println(stringOne); // prints "Sensor value" - - // adding a constant string to a string: - stringOne += " for input "; - Serial.println(stringOne); // prints "Sensor value for input" - - // adding a constant character to a string: - stringOne += 'A'; - Serial.println(stringOne); // prints "Sensor value for input A" - - // adding a constant integer to a string: - stringOne += 0; - Serial.println(stringOne); // prints "Sensor value for input A0" - - // adding a constant string to a string: - stringOne += ": "; - Serial.println(stringOne); // prints "Sensor value for input" - - // adding a variable integer to a string: - stringOne += analogRead(A0); - Serial.println(stringOne); // prints "Sensor value for input A0: 456" or whatever analogRead(A0) is - - Serial.println("\n\nchanging the Strings' values"); - stringOne = "A long integer: "; - stringTwo = "The millis(): "; - - // adding a constant long integer to a string: - stringOne += 123456789; - Serial.println(stringOne); // prints "A long integer: 123456789" - - // using concat() to add a long variable to a string: - stringTwo.concat(millis()); - Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is - - // do nothing while true: - while(true); -} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.pde b/build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.pde deleted file mode 100644 index 3122b0bee..000000000 --- a/build/shared/examples/8.Strings/StringComparisonOperators/StringComparisonOperators.pde +++ /dev/null @@ -1,124 +0,0 @@ -/* - Comparing Strings - - Examples of how to compare strings using the comparison operators - - created 27 July 2010 - modified 4 Sep 2010 - by Tom Igoe - - http://arduino.cc/en/Tutorial/StringComparisonOperators - - This example code is in the public domain. - */ - -String stringOne, stringTwo; - -void setup() { - Serial.begin(9600); - stringOne = String("this"); - stringTwo = String("that"); - Serial.println("\n\nComparing Strings:"); - -} - -void loop() { - // two strings equal: - if (stringOne == "this") { - Serial.println("StringOne == \"this\""); - } - // two strings not equal: - if (stringOne != stringTwo) { - Serial.println(stringOne + " =! " + stringTwo); - } - - // two strings not equal (case sensitivity matters): - stringOne = "This"; - stringTwo = "this"; - if (stringOne != stringTwo) { - Serial.println(stringOne + " =! " + stringTwo); - } - // you can also use equals() to see if two strings are the same: - if (stringOne.equals(stringTwo)) { - Serial.println(stringOne + " equals " + stringTwo); - } - else { - Serial.println(stringOne + " does not equal " + stringTwo); - } - - // or perhaps you want to ignore case: - if (stringOne.equalsIgnoreCase(stringTwo)) { - Serial.println(stringOne + " equals (ignoring case) " + stringTwo); - } - else { - Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo); - } - - // a numeric string compared to the number it represents: - stringOne = "1"; - int numberOne = 1; - if (stringOne == numberOne) { - Serial.println(stringOne + " = " + numberOne); - } - - - - // two numeric strings compared: - stringOne = "2"; - stringTwo = "1"; - if (stringOne >= stringTwo) { - Serial.println(stringOne + " >= " + stringTwo); - } - - // comparison operators can be used to compare strings for alphabetic sorting too: - stringOne = String("Brown"); - if (stringOne < "Charles") { - Serial.println(stringOne + " < Charles"); - } - - if (stringOne > "Adams") { - Serial.println(stringOne + " > Adams"); - } - - if (stringOne <= "Browne") { - Serial.println(stringOne + " <= Browne"); - } - - - if (stringOne >= "Brow") { - Serial.println(stringOne + " >= Brow"); - } - - // the compareTo() operator also allows you to compare strings - // it evaluates on the first character that's different. - // if the first character of the string you're comparing to - // comes first in alphanumeric order, then compareTo() is greater than 0: - stringOne = "Cucumber"; - stringTwo = "Cucuracha"; - if (stringOne.compareTo(stringTwo) < 0 ) { - Serial.println(stringOne + " comes before " + stringTwo); - } - else { - Serial.println(stringOne + " comes after " + stringTwo); - } - - delay(10000); // because the next part is a loop: - - // compareTo() is handy when you've got strings with numbers in them too: - - while (true) { - stringOne = "Sensor: "; - stringTwo= "Sensor: "; - - stringOne += analogRead(A0); - stringTwo += analogRead(A5); - - if (stringOne.compareTo(stringTwo) < 0 ) { - Serial.println(stringOne + " comes before " + stringTwo); - } - else { - Serial.println(stringOne + " comes after " + stringTwo); - - } - } -} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringConstructors/StringConstructors.pde b/build/shared/examples/8.Strings/StringConstructors/StringConstructors.pde deleted file mode 100644 index 94ae2dc7a..000000000 --- a/build/shared/examples/8.Strings/StringConstructors/StringConstructors.pde +++ /dev/null @@ -1,64 +0,0 @@ -/* - String constructors - - Examples of how to create strings from other data types - - created 27 July 2010 - modified 4 Sep 2010 - by Tom Igoe - - http://arduino.cc/en/Tutorial/StringConstructors - - This example code is in the public domain. - */ - -void setup() { - Serial.begin(9600); -} - -void loop() { - // using a constant String: - String stringOne = "Hello String"; - Serial.println(stringOne); // prints "Hello String" - - // converting a constant char into a String: - stringOne = String('a'); - Serial.println(stringOne); // prints "a" - - // converting a constant string into a String object: - String stringTwo = String("This is a string"); - Serial.println(stringTwo); // prints "This is a string" - - // concatenating two strings: - stringOne = String(stringTwo + " with more"); - // prints "This is a string with more": - Serial.println(stringOne); - - // using a constant integer: - stringOne = String(13); - Serial.println(stringOne); // prints "13" - - // using an int and a base: - stringOne = String(analogRead(A0), DEC); - // prints "453" or whatever the value of analogRead(A0) is - Serial.println(stringOne); - - // using an int and a base (hexadecimal): - stringOne = String(45, HEX); - // prints "2d", which is the hexadecimal version of decimal 45: - Serial.println(stringOne); - - // using an int and a base (binary) - stringOne = String(255, BIN); - // prints "11111111" which is the binary value of 255 - Serial.println(stringOne); - - // using a long and a base: - stringOne = String(millis(), DEC); - // prints "123456" or whatever the value of millis() is: - Serial.println(stringOne); - - // do nothing while true: - while(true); - -} \ No newline at end of file diff --git a/build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.pde b/build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.pde deleted file mode 100644 index b18b67684..000000000 --- a/build/shared/examples/8.Strings/StringStartsWithEndsWith/StringStartsWithEndsWith.pde +++ /dev/null @@ -1,49 +0,0 @@ -/* - String startWith() and endsWith() - - Examples of how to use startsWith() and endsWith() in a String - - created 27 July 2010 - modified 4 Sep 2010 - by Tom Igoe - - http://arduino.cc/en/Tutorial/StringStartsWithEndsWith - - This example code is in the public domain. - */ - -void setup() { - Serial.begin(9600); - Serial.println("\n\nString startsWith() and endsWith():"); - -} - -void loop() { -// startsWith() checks to see if a String starts with a particular substring: - String stringOne = "HTTP/1.1 200 OK"; - Serial.println(stringOne); - if (stringOne.startsWith("HTTP/1.1")) { - Serial.println("Server's using http version 1.1"); - } - - // you can also look for startsWith() at an offset position in the string: - stringOne = "HTTP/1.1 200 OK"; - if (stringOne.startsWith("200 OK", 9)) { - Serial.println("Got an OK from the server"); - } - - // endsWith() checks to see if a String ends with a particular character: - String sensorReading = "sensor = "; - sensorReading += analogRead(A0); - Serial.print (sensorReading); - if (sensorReading.endsWith(0)) { - Serial.println(". This reading is divisible by ten"); - } - else { - Serial.println(". This reading is not divisible by ten"); - - } - -// do nothing while true: - while(true); -} \ No newline at end of file From 15b28b415d795d42ec2bbd32bed3b32fc216528f Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 30 Aug 2011 23:22:59 +0200 Subject: [PATCH 21/29] Mouse change cursor shape when is moved over a URL. --- app/src/processing/app/syntax/JEditTextArea.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/app/src/processing/app/syntax/JEditTextArea.java b/app/src/processing/app/syntax/JEditTextArea.java index 3c1548fbd..72fb7bafd 100644 --- a/app/src/processing/app/syntax/JEditTextArea.java +++ b/app/src/processing/app/syntax/JEditTextArea.java @@ -17,6 +17,7 @@ import javax.swing.event.*; import javax.swing.text.*; import javax.swing.undo.*; import javax.swing.*; + import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.*; @@ -2025,7 +2026,19 @@ public class JEditTextArea extends JComponent select(getMarkPosition(),xyToOffset(evt.getX(),evt.getY())); } - public void mouseMoved(MouseEvent evt) {} + final Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR); + final Cursor handCursor = new Cursor(Cursor.HAND_CURSOR); + + public void mouseMoved(MouseEvent evt) { + int line = yToLine(evt.getY()); + int offset = xToOffset(line, evt.getX()); + boolean wantHandCursor = checkClickedURL(getLineText(line), offset) != null; + JComponent src = (JComponent) evt.getSource(); + if (wantHandCursor) + src.setCursor(handCursor); + else + src.setCursor(normalCursor); + } } class FocusHandler implements FocusListener From 551b8e85ac17816e979834ea63b714876398162b Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Wed, 31 Aug 2011 15:29:54 -0400 Subject: [PATCH 22/29] Don't use the low-res icon on Mac OS X. http://code.google.com/p/arduino/issues/detail?id=612 --- app/src/processing/app/Base.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java index 2e3d7b346..2326dbc80 100644 --- a/app/src/processing/app/Base.java +++ b/app/src/processing/app/Base.java @@ -1722,6 +1722,10 @@ public class Base { * Give this Frame a Processing icon. */ static public void setIcon(Frame frame) { + // don't use the low-res icon on Mac OS X; the window should + // already have the right icon from the .app file. + if (Base.isMacOS()) return; + Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE); frame.setIconImage(image); } From 61b33f11ce01953d4bbe7a49aa6bcffef8dc01eb Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Wed, 31 Aug 2011 15:39:20 -0400 Subject: [PATCH 23/29] Renaming writeError() to getWriteError() in Print (and Stream and friends). http://code.google.com/p/arduino/issues/detail?id=608 --- hardware/arduino/cores/arduino/Print.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hardware/arduino/cores/arduino/Print.h b/hardware/arduino/cores/arduino/Print.h index fce302e72..8530b0358 100755 --- a/hardware/arduino/cores/arduino/Print.h +++ b/hardware/arduino/cores/arduino/Print.h @@ -42,7 +42,7 @@ class Print public: Print() : write_error(0) {} - int writeError() { return write_error; } + int getWriteError() { return write_error; } void clearWriteError() { setWriteError(0); } virtual size_t write(uint8_t) = 0; From 1278144d5039be02e3ab78264c8c8da2df5532c0 Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Wed, 31 Aug 2011 15:52:56 -0400 Subject: [PATCH 24/29] Moving serialEvent() calls from RX interrupts to main for() loop (after loop()). http://code.google.com/p/arduino/issues/detail?id=584 --- .../SerialEvent/SerialEvent.ino | 27 +++++----- .../arduino/cores/arduino/HardwareSerial.cpp | 53 +++++++++++++++++-- .../arduino/cores/arduino/HardwareSerial.h | 2 + hardware/arduino/cores/arduino/main.cpp | 4 +- 4 files changed, 69 insertions(+), 17 deletions(-) diff --git a/build/shared/examples/4.Communication/SerialEvent/SerialEvent.ino b/build/shared/examples/4.Communication/SerialEvent/SerialEvent.ino index 458c43dad..11de7adfb 100644 --- a/build/shared/examples/4.Communication/SerialEvent/SerialEvent.ino +++ b/build/shared/examples/4.Communication/SerialEvent/SerialEvent.ino @@ -38,20 +38,23 @@ void loop() { } /* - SerialEvent occurs whenever a new byte comes in the - hardware serial RX. Don't do complex things here, as the - processor halts the regular program to run this routine: + SerialEvent occurs whenever a new data comes in the + hardware serial RX. This routine is run between each + time loop() runs, so using delay inside loop can delay + response. Multiple bytes of data may be available. */ void serialEvent() { - // get the new byte: - char inChar = (char)Serial.read(); - // add it to the inputString: - inputString += inChar; - // if the incoming character is a newline, set a flag - // so the main loop can do something about it: - if (inChar == '\n') { - stringComplete = true; - } + while (Serial.available()) { + // get the new byte: + char inChar = (char)Serial.read(); + // add it to the inputString: + inputString += inChar; + // if the incoming character is a newline, set a flag + // so the main loop can do something about it: + if (inChar == '\n') { + stringComplete = true; + } + } } diff --git a/hardware/arduino/cores/arduino/HardwareSerial.cpp b/hardware/arduino/cores/arduino/HardwareSerial.cpp index d6be2181c..3ed8d07b5 100644 --- a/hardware/arduino/cores/arduino/HardwareSerial.cpp +++ b/hardware/arduino/cores/arduino/HardwareSerial.cpp @@ -88,6 +88,8 @@ inline void store_char(unsigned char c, ring_buffer *buffer) #else void serialEvent() __attribute__((weak)); void serialEvent() {} + volatile static unsigned char serialEvent_flag = 0; + #define serialEvent_implemented #if defined(USART_RX_vect) SIGNAL(USART_RX_vect) #elif defined(SIG_USART0_RECV) @@ -108,18 +110,20 @@ inline void store_char(unsigned char c, ring_buffer *buffer) #error UDR not defined #endif store_char(c, &rx_buffer); - serialEvent(); + serialEvent_flag = 1; } #endif #if defined(USART1_RX_vect) void serialEvent1() __attribute__((weak)); void serialEvent1() {} + volatile static unsigned char serialEvent1_flag = 0; + #define serialEvent1_implemented SIGNAL(USART1_RX_vect) { unsigned char c = UDR1; store_char(c, &rx_buffer1); - serialEvent1(); + serialEvent1_flag = 1; } #elif defined(SIG_USART1_RECV) #error SIG_USART1_RECV @@ -128,11 +132,13 @@ inline void store_char(unsigned char c, ring_buffer *buffer) #if defined(USART2_RX_vect) && defined(UDR2) void serialEvent2() __attribute__((weak)); void serialEvent2() {} + volatile static unsigned char serialEvent2_flag = 0; + #define serialEvent2_implemented SIGNAL(USART2_RX_vect) { unsigned char c = UDR2; store_char(c, &rx_buffer2); - serialEvent2(); + serialEvent2_flag = 1; } #elif defined(SIG_USART2_RECV) #error SIG_USART2_RECV @@ -141,16 +147,55 @@ inline void store_char(unsigned char c, ring_buffer *buffer) #if defined(USART3_RX_vect) && defined(UDR3) void serialEvent3() __attribute__((weak)); void serialEvent3() {} + volatile static unsigned char serialEvent3_flag = 0; + #define serialEvent3_implemented SIGNAL(USART3_RX_vect) { unsigned char c = UDR3; store_char(c, &rx_buffer3); - serialEvent3(); + serialEvent3_flag = 1; } #elif defined(SIG_USART3_RECV) #error SIG_USART3_RECV #endif +void serialEventRun(void) +{ + unsigned char flag, oldSREG; +#ifdef serialEvent_implemented + oldSREG = SREG; + noInterrupts(); + flag = serialEvent_flag; + serialEvent_flag = 0; + SREG = oldSREG; + if (flag) serialEvent(); +#endif +#ifdef serialEvent1_implemented + oldSREG = SREG; + noInterrupts(); + flag = serialEvent1_flag; + serialEvent1_flag = 0; + SREG = oldSREG; + if (flag) serialEvent1(); +#endif +#ifdef serialEvent2_implemented + oldSREG = SREG; + noInterrupts(); + flag = serialEvent2_flag; + serialEvent2_flag = 0; + SREG = oldSREG; + if (flag) serialEvent2(); +#endif +#ifdef serialEvent3_implemented + oldSREG = SREG; + noInterrupts(); + flag = serialEvent3_flag; + serialEvent3_flag = 0; + SREG = oldSREG; + if (flag) serialEvent3(); +#endif +} + #if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect) #error Don't know what the Data Register Empty vector is called for the first UART diff --git a/hardware/arduino/cores/arduino/HardwareSerial.h b/hardware/arduino/cores/arduino/HardwareSerial.h index 1895f08f6..cbb0e5eae 100644 --- a/hardware/arduino/cores/arduino/HardwareSerial.h +++ b/hardware/arduino/cores/arduino/HardwareSerial.h @@ -74,4 +74,6 @@ class HardwareSerial : public Stream extern HardwareSerial Serial3; #endif +extern void serialEventRun(void); + #endif diff --git a/hardware/arduino/cores/arduino/main.cpp b/hardware/arduino/cores/arduino/main.cpp index 3c46f1e7a..1c2ea9a3c 100755 --- a/hardware/arduino/cores/arduino/main.cpp +++ b/hardware/arduino/cores/arduino/main.cpp @@ -7,8 +7,10 @@ int main(void) setup(); - for (;;) + for (;;) { loop(); + serialEventRun(); + } return 0; } From bf5e928e4c610e0871bd8b57b6e57eeafb698be5 Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Wed, 31 Aug 2011 16:48:06 -0400 Subject: [PATCH 25/29] Adding Arduino Ethernet and Arduino Mega ADK (joint w/ Mega 2560) to boards menu. http://code.google.com/p/arduino/issues/detail?id=594 --- hardware/arduino/boards.txt | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/hardware/arduino/boards.txt b/hardware/arduino/boards.txt index 7adac6233..48a0cf91b 100644 --- a/hardware/arduino/boards.txt +++ b/hardware/arduino/boards.txt @@ -102,7 +102,7 @@ nano.build.variant=eightanaloginputs ############################################################## -mega2560.name=Arduino Mega 2560 +mega2560.name=Arduino Mega 2560 or Mega ADK mega2560.upload.protocol=stk500v2 mega2560.upload.maximum_size=258048 @@ -165,6 +165,27 @@ mini.build.variant=eightanaloginputs ############################################################## +ethernet.name=Arduino Ethernet + +ethernet.upload.protocol=stk500 +ethernet.upload.maximum_size=32256 +ethernet.upload.speed=115200 + +ethernet.bootloader.low_fuses=0xff +ethernet.bootloader.high_fuses=0xde +ethernet.bootloader.extended_fuses=0x05 +ethernet.bootloader.path=optiboot +ethernet.bootloader.file=optiboot_atmega328.hex +ethernet.bootloader.unlock_bits=0x3F +ethernet.bootloader.lock_bits=0x0F + +ethernet.build.variant=standard +ethernet.build.mcu=atmega328p +ethernet.build.f_cpu=16000000L +ethernet.build.core=arduino + +############################################################## + fio.name=Arduino Fio fio.upload.protocol=stk500 From 25770f69a8829de2fe906ceabb994d81a7e3ca0c Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Thu, 1 Sep 2011 11:28:37 -0400 Subject: [PATCH 26/29] Adding missing file from ATS_String_Addition test. --- .../examples/ATS_String_Addition/Test_Equal.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h diff --git a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h b/libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h new file mode 100644 index 000000000..80dbc848b --- /dev/null +++ b/libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h @@ -0,0 +1,13 @@ +void Test_Equal(char *testString, char *expected, const String &actual) +{ + char buf[100]; actual.toCharArray(buf, 100); + boolean b = (strcmp(buf, expected) == 0); + ATS_PrintTestStatus(testString, b); + if (!b) { + Serial.print("expected '"); + Serial.print(expected); + Serial.print("', actual '"); + Serial.print(actual); + Serial.println("'"); + } +} From 94c371bed207c82782583081a9ded10d26be80e8 Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Fri, 2 Sep 2011 10:00:21 -0400 Subject: [PATCH 27/29] Moving tests into their own repository: https://github.com/arduino/Tests --- .../ArduinoTestSuite/ArduinoTestSuite.cpp | 769 ------------------ libraries/ArduinoTestSuite/ArduinoTestSuite.h | 74 -- libraries/ArduinoTestSuite/avr_cpunames.h | 186 ----- .../examples/ATS_Constants/ATS_Constants.ino | 74 -- .../examples/ATS_Delay/ATS_Delay.ino | 101 --- .../examples/ATS_General/ATS_General.ino | 95 --- .../examples/ATS_SD_File/ATS_SD_File.ino | 106 --- .../examples/ATS_SD_Files/ATS_SD_Files.ino | 78 -- .../examples/ATS_SD_Seek/ATS_SD_Seek.ino | 109 --- .../examples/ATS_Skeleton/ATS_Skeleton.ino | 50 -- .../ATS_StringIndexOfMemory.ino | 104 --- .../ATS_StringTest/ATS_StringTest.ino | 186 ----- .../ATS_String_Addition.ino | 48 -- .../examples/ATS_String_Addition/Test_Equal.h | 13 - .../examples/ATS_ToneTest/ATS_ToneTest.ino | 248 ------ .../ATS_Write_Print/ATS_Write_Print.ino | 61 -- 16 files changed, 2302 deletions(-) delete mode 100644 libraries/ArduinoTestSuite/ArduinoTestSuite.cpp delete mode 100644 libraries/ArduinoTestSuite/ArduinoTestSuite.h delete mode 100644 libraries/ArduinoTestSuite/avr_cpunames.h delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_StringTest/ATS_StringTest.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.ino delete mode 100644 libraries/ArduinoTestSuite/examples/ATS_Write_Print/ATS_Write_Print.ino diff --git a/libraries/ArduinoTestSuite/ArduinoTestSuite.cpp b/libraries/ArduinoTestSuite/ArduinoTestSuite.cpp deleted file mode 100644 index 44e75da4f..000000000 --- a/libraries/ArduinoTestSuite/ArduinoTestSuite.cpp +++ /dev/null @@ -1,769 +0,0 @@ -//************************************************************************ -//* Arduino Test Suite -//* (C) 2010 by Mark Sproul -//* (C) 2011 by Matthew Murdoch -//* Open source as per standard Arduino code -//* -//* 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. -//************************************************************************ -//* Aug 31, 2010 Started on TestArduino -//* Oct 18, 2010 Added memory testing -//* Jun 10, 2011 Added free list to memory usage calculation -//************************************************************************ - -#include -#include -#include - - - -#include "ArduinoTestSuite.h" - - -#include "avr_cpunames.h" - -#if defined(USART3_RX_vect) - #define SERIAL_PORT_COUNT 4 -#elif defined(USART1_RX_vect) - #define SERIAL_PORT_COUNT 2 -#else - #define SERIAL_PORT_COUNT 1 -#endif - - - - -//************************************************************************ -enum -{ - ATS_Manufacturer = 1, - ATS_CPU, - ATS_GCC_version, - ATS_LIBC_version, - ATS_CompiledDate, - ATS_TestSuiteName, - ATS_FreeMemory, - - -}; -unsigned long gTestStartTime; -unsigned long gTestTotalElapsedTime; -short gTagIndent; -int gYotalErrors; -int gTestCount; - - - -prog_char gTextMsg_Manufacturer[] PROGMEM = "MANUFACTURER"; -prog_char gTextMsg_CPUname[] PROGMEM = "CPU-NAME"; -prog_char gTextMsg_GCC_VERSION[] PROGMEM = "GCC-Version"; -prog_char gTextMsg_AVR_LIBC[] PROGMEM = "AVR-LibC-Ver"; -prog_char gTextMsg_COMPILED_DATE[] PROGMEM = "Compiled-date"; -prog_char gTextMsg_TEST_SUITE_NAME[] PROGMEM = "Test-Suite-Name"; -prog_char gTextMsg_memoryUsage[] PROGMEM = "Free-memory"; -prog_char gTextMsg_dotdotdot[] PROGMEM = "... "; -prog_char gTextMsg_ok[] PROGMEM = "ok"; -prog_char gTextMsg_FAIL[] PROGMEM = "FAIL"; -prog_char gTextMsg_spaceEqual[] PROGMEM = " = "; -prog_char gTextMsg_info[] PROGMEM = "info."; -prog_char gTextMsg_dashLine[] PROGMEM = "--------------------------"; -prog_char gTextMsg_DigitalRW[] PROGMEM = "DigitalReadWrite_"; -prog_char gTextMsg_PWMoutput[] PROGMEM = "PWMoutput_"; -prog_char gTextMsg_AnalogInput[] PROGMEM = "AnalogInput_"; - -//************************************************************************ -void Serial_print_P(prog_char *flashMemStr) -{ -char theChar; -int ii; - - ii = 0; -#if (FLASHEND > 0x10000) - while (theChar = pgm_read_byte_far(flashMemStr + ii++)) -#else - while (theChar = pgm_read_byte_near(flashMemStr + ii++)) -#endif - { - Serial.print(theChar); - } -} - -//************************************************************************ -void Serial_println_P(prog_char *flashMemStr) -{ - Serial_print_P(flashMemStr); - Serial.println(); -} - -//************************************************************************ -//* this is for internal use only, not made pubic to the API -static void ATS_PrintProperty( int propertyTagNum, - char *propertyName, - char *propertyValue) -{ -char lineBuffer[64]; - - strcpy_P(lineBuffer, gTextMsg_info); - switch(propertyTagNum) - { - case 0: - strcat(lineBuffer, propertyName); - break; - - case ATS_Manufacturer: - strcat_P(lineBuffer, gTextMsg_Manufacturer); - break; - - case ATS_CPU: - strcat_P(lineBuffer, gTextMsg_CPUname); - break; - - case ATS_GCC_version: - strcat_P(lineBuffer, gTextMsg_GCC_VERSION); - break; - - case ATS_LIBC_version: - strcat_P(lineBuffer, gTextMsg_AVR_LIBC); - break; - - case ATS_CompiledDate: - strcat_P(lineBuffer, gTextMsg_COMPILED_DATE); - break; - - case ATS_TestSuiteName: - strcat_P(lineBuffer, gTextMsg_TEST_SUITE_NAME); - break; - - case ATS_FreeMemory: - strcat_P(lineBuffer, gTextMsg_memoryUsage); - break; - } - - while (strlen(lineBuffer) < 20) - { - strcat(lineBuffer, " "); - } - - strcat_P(lineBuffer, gTextMsg_spaceEqual); - if (propertyValue != 0) - { - strcat(lineBuffer, propertyValue); - } - Serial.println(lineBuffer); - -} - - - - -//************************************************************************ -void ATS_begin(char *manufName, char *testSuiteName) -{ -int freeMemory; -char memoryMsg[48]; - - gYotalErrors = 0; - gTestCount = 0; - - Serial.begin(9600); - delay(100); - - gTestTotalElapsedTime = 0; - - Serial.println(); - Serial.println(); - Serial.println(); - - ATS_PrintProperty(ATS_Manufacturer, 0, manufName); - ATS_PrintProperty(ATS_CPU, 0, _AVR_CPU_NAME_); - ATS_PrintProperty(ATS_GCC_version, 0, __VERSION__); - ATS_PrintProperty(ATS_LIBC_version, 0, __AVR_LIBC_VERSION_STRING__); - ATS_PrintProperty(ATS_CompiledDate, 0, __DATE__); - ATS_PrintProperty(ATS_TestSuiteName, 0, testSuiteName); - - freeMemory = ATS_GetFreeMemory(); - sprintf(memoryMsg, "%d bytes", freeMemory); - ATS_PrintProperty(ATS_FreeMemory, 0, memoryMsg); - - randomSeed(analogRead(0)); - - gTestStartTime = micros(); -} - -//************************************************************************ -void ATS_end() -{ -unsigned long seconds; -unsigned long microSecs; -char buf[8]; - - gTestTotalElapsedTime += (micros() - gTestStartTime); - - Serial_println_P(gTextMsg_dashLine); - - // Ran 4 tests in 0.000s - Serial.print("Ran "); - Serial.print(gTestCount); - Serial.print(" tests in "); - - seconds = gTestTotalElapsedTime / 1000000; - microSecs = gTestTotalElapsedTime % 1000000; - - Serial.print(seconds); - ultoa(microSecs + 1000000, buf, 10); // add forces leading zeros - buf[0] = '.'; // replace leading '1' with decimal point - Serial.print(buf); - Serial.print('s'); - Serial.println(); - - int used = ATS_GetMaximumMemoryAllocated(); - if (used >= 0) { - Serial.print("Maximum heap memory: "); - Serial.println(used); - } - Serial.println(); - - if (gYotalErrors == 0) - { - Serial.print("OK"); - } - else - { - Serial.print("FAILED (failures="); - Serial.print(gYotalErrors); - Serial.print(")"); - } - Serial.println(); - - //* send control D to terminate (End Of File) - Serial.write(0x04); -} - - - -//************************************************************************ -void ATS_PrintTestStatus(char *testString, boolean passed) -{ -int sLen; - - // do not include time printing status in total test time - gTestTotalElapsedTime += (micros() - gTestStartTime); - - Serial.print(testString); - sLen = strlen(testString); - while (sLen < 60) - { - Serial.print(' '); - sLen++; - } - Serial_print_P(gTextMsg_dotdotdot); - if (passed) - { - Serial_print_P(gTextMsg_ok); - } - else - { - Serial_print_P(gTextMsg_FAIL); - gYotalErrors++; - } - Serial.println(); - - gTestCount++; - - // begin counting total test time again - gTestStartTime = micros(); -} - - - -//************************************************************************ -//* returns true if no errors, false if there is an error -int ATS_Test_DigitalPinWithHelper(uint8_t digitalPinToTest, uint8_t helperpin) -{ -boolean passedOK; -int pinValue; -char testName[64]; -char numString[32]; - - strcpy_P(testName, gTextMsg_DigitalRW); - sprintf(numString, "%02d", digitalPinToTest); - strcat(testName, numString); - - passedOK = true; - - //* test senario 1 - pinMode(digitalPinToTest, OUTPUT); - pinMode(helperpin, INPUT); - - digitalWrite(digitalPinToTest, HIGH); - pinValue = digitalRead(helperpin); - if (pinValue != HIGH) - { - passedOK = false; - } - - digitalWrite(digitalPinToTest, LOW); - pinValue = digitalRead(helperpin); - if (pinValue != LOW) - { - passedOK = false; - } - - - //* now reverse the input/output - pinMode(digitalPinToTest, INPUT); - pinMode(helperpin, OUTPUT); - - digitalWrite(helperpin, HIGH); - pinValue = digitalRead(digitalPinToTest); - if (pinValue != HIGH) - { - passedOK = false; - } - - digitalWrite(helperpin, LOW); - pinValue = digitalRead(digitalPinToTest); - if (pinValue != LOW) - { - passedOK = false; - } - - - if (! passedOK) - { - sprintf(numString, " (helper pin=%02d)", helperpin); - strcat(testName, numString); - } - ATS_PrintTestStatus(testName, passedOK); - return(passedOK); -} - -//************************************************************************ -boolean ATS_Test_DigitalPin(uint8_t digitalPinToTest) -{ -boolean passedOK; -uint8_t helperpin; - - if ((digitalPinToTest % 2) == 0) - { - //* if its EVEN, add 1 - helperpin = digitalPinToTest + 1; - } - else - { - //* if its ODD - helperpin = digitalPinToTest - 1; - } - passedOK = ATS_Test_DigitalPinWithHelper(digitalPinToTest, helperpin); - return(passedOK); -} - - - -//************************************************************************ -//* returns true if no errors, false if there is an error -int ATS_TestTimer( uint8_t timerPinNumber, - uint8_t inputPin, - char *statusString, - char *errorString) -{ -boolean passedOK; -unsigned long loopCounter; -unsigned long lowCount; -unsigned long highCount; -unsigned long startTime; -int percentLow; -int percentHigh; -int pinValue; -char numString[48]; -int pwmValue; - - pwmValue = 128; - loopCounter = 0; - lowCount = 0; - highCount = 0; - passedOK = true; - - startTime = millis(); - pinMode(inputPin, INPUT); - analogWrite(timerPinNumber, pwmValue); - while ((millis() - startTime) < 500) - { - pinValue = digitalRead(inputPin); - if (pinValue == HIGH) - { - highCount++; - } - else - { - lowCount++; - } - } - analogWrite(timerPinNumber, 0); - - //* the difference should be about 50% - percentLow = lowCount / ((lowCount + highCount) / 100); - percentHigh = highCount / ((lowCount + highCount) / 100); - if ((percentLow > 45) && (percentLow < 55)) - { - passedOK = true; - } - else - { - passedOK = false; - strcat(errorString, " PWM ERROR"); - } - sprintf(numString, " (PWM=%02d %d%% LOW %d%% HIGH)", pwmValue, percentLow, percentHigh); - strcat(statusString, numString); - - return(passedOK); -} - - -//************************************************************************ -//* returns true if no errors, false if there is an error -boolean ATS_Test_PWMPinWithHelper(uint8_t pwmPinToTest, uint8_t helperpin) -{ -boolean passedOK; -char testName[64]; -char errorString[48]; -char numString[8]; -uint8_t timerNumber; - - - - strcpy_P(testName, gTextMsg_PWMoutput); - sprintf(numString, "%02d", pwmPinToTest); - strcat(testName, numString); - - passedOK = true; - errorString[0] = 0; - - - //* is pin1 a timer? - timerNumber = digitalPinToTimer(pwmPinToTest); - if (timerNumber != NOT_ON_TIMER) - { - passedOK = ATS_TestTimer(pwmPinToTest, helperpin, testName, errorString); - } - else - { - //* we should not get here - passedOK = false; - } - - ATS_PrintTestStatus(testName, passedOK); - - - return(passedOK); -} - -//************************************************************************ -boolean ATS_Test_PWM_Pin(uint8_t pwmPinToTest) -{ -boolean passedOK; -uint8_t helperpin; - - if ((pwmPinToTest % 2) == 0) - { - //* if its EVEN, add 1 - helperpin = pwmPinToTest + 1; - } - else - { - //* if its ODD - helperpin = pwmPinToTest - 1; - } - passedOK = ATS_Test_PWMPinWithHelper(pwmPinToTest, helperpin); - return(passedOK); -} - - -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - #define kAnalogPinOffset 54 - #define DIGITAL_ANAPIN(a) ((a) + kAnalogPinOffset) -#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) - #define kAnalogPinOffset 38 - #define DIGITAL_ANAPIN(a) ((a) + kAnalogPinOffset) -#elif defined(__AVR_ATmega32U4__) - #define DIGITAL_ANAPIN(a) ((a) < 11 ? 21 - (a) : 22) -#else - #define kAnalogPinOffset 14 - #define DIGITAL_ANAPIN(a) ((a) + kAnalogPinOffset) -#endif - - -//************************************************************************ -boolean ATS_Test_AnalogInputWithHelper(uint8_t analogPintoTest, uint8_t helperPin) -{ -boolean passedOK; -char testName[64]; -char infoString[48]; -int analogValueHigh; -int analogValueLow; - - - //* first we have to set the ANALOG pin to INPUT - pinMode(DIGITAL_ANAPIN(analogPintoTest), INPUT); - - passedOK = true; - - strcpy_P(testName, gTextMsg_AnalogInput); - sprintf(infoString, "%02d", analogPintoTest); - strcat(testName, infoString); - - - pinMode(helperPin, OUTPUT); - - digitalWrite(helperPin, LOW); - analogValueLow = analogRead(analogPintoTest); - if (analogValueLow > 100) - { - passedOK = false; - } - - - digitalWrite(helperPin, HIGH); - analogValueHigh = analogRead(analogPintoTest); - if (analogValueHigh < 1000) - { - passedOK = false; - } - - - sprintf(infoString, " (Low=%4d High=%4d helper pin=%d)", analogValueLow, analogValueHigh, helperPin); - strcat(testName, infoString); - - ATS_PrintTestStatus(testName, passedOK); - - return(passedOK); -} - - -//************************************************************************ -boolean ATS_Test_AnalogInput(uint8_t analogPinToTest) -{ -boolean passedOK; -uint8_t helperpin; - - if ((DIGITAL_ANAPIN(analogPinToTest) % 2) == 0) - { - //* if its EVEN, add 1 - helperpin = DIGITAL_ANAPIN(analogPinToTest) + 1; - } - else - { - //* if its ODD - helperpin = DIGITAL_ANAPIN(analogPinToTest) - 1; - } - passedOK = ATS_Test_AnalogInputWithHelper(analogPinToTest, helperpin); - return(passedOK); -} - - -#define kSerialTestBaudRate 9600 -#define kSerialTestDelay 3 - - -#if (SERIAL_PORT_COUNT > 1) -//************************************************************************ -//* retunrs 0 if no errors, 1 if an error occured -short ATS_TestSerialLoopback(HardwareSerial *theSerialPort, char *serialPortName) -{ -char xmitChar; -char rcvChar; -short ii; -short serialErrCt; -short timeOutLoopCtr; - - - serialErrCt = 1; - if (theSerialPort != 0) - { - serialErrCt = 0; - theSerialPort->begin(kSerialTestBaudRate); - - for (ii=0; ii<150; ii++) - { - xmitChar = ii; - theSerialPort->print(xmitChar); - - timeOutLoopCtr = 0; - //* wait for data to come back or timeout - while (!theSerialPort->available() && (timeOutLoopCtr < kSerialTestDelay)) - { - delay(1); - timeOutLoopCtr++; - } - - if (theSerialPort->available()) - { - //* get the char - rcvChar = theSerialPort->read(); - if (rcvChar != xmitChar) - { - serialErrCt = 1; - } - } - else - { - serialErrCt = 1; - } - } - theSerialPort->end(); - - if (serialErrCt == 0) - { - ATS_PrintTestStatus(serialPortName, PASSED); - } - else - { - ATS_PrintTestStatus(serialPortName, FAILED); - } - } - - return(serialErrCt); -} -#endif - - -//************************************************************************ -boolean ATS_Test_EEPROM(void) -{ -boolean passedOK; -uint8_t dataByte; -uint8_t dataByteRead; -uint16_t dataWord; -uint16_t dataWordRead; -uint32_t dataLongWord; -uint32_t dataLongWordRead; -int addressPtr; -char reportString[48]; - - passedOK = true; - //* test BYTE read/write - addressPtr = random(E2END); - dataByte = 0x5A; - eeprom_write_byte((uint8_t *)addressPtr, dataByte); - dataByteRead = eeprom_read_byte((uint8_t *)addressPtr); - - sprintf(reportString, "EEPROM_byte_rw (addr= 0x%04X)", addressPtr); - if (dataByteRead == dataByte) - { - ATS_PrintTestStatus(reportString, PASSED); - } - else - { - ATS_PrintTestStatus(reportString, FAILED); - passedOK = false; - } - - - //* test WORD read/write - addressPtr = random(E2END); - dataWord = 0xA55A; - eeprom_write_word((uint16_t *)addressPtr, dataWord); - dataWordRead = eeprom_read_word((uint16_t *)addressPtr); - - sprintf(reportString, "EEPROM_word_rw (addr= 0x%04X)", addressPtr); - if (dataWordRead == dataWord) - { - ATS_PrintTestStatus(reportString, PASSED); - } - else - { - ATS_PrintTestStatus(reportString, FAILED); - passedOK = false; - } - - - //* test Long WORD read/write - addressPtr = random(E2END); - dataLongWord = 0x5AA5A55A; - eeprom_write_dword((uint32_t *)addressPtr, dataLongWord); - dataLongWordRead = eeprom_read_dword((uint32_t *)addressPtr); - - sprintf(reportString, "EEPROM_dword_rw (addr= 0x%04X)", addressPtr); - if (dataLongWordRead == dataLongWord) - { - ATS_PrintTestStatus(reportString, PASSED); - } - else - { - ATS_PrintTestStatus(reportString, FAILED); - passedOK = false; - } - - - return(passedOK); -} - - - -//************************************************************************ -extern unsigned int __data_start; -extern unsigned int __data_end; -extern unsigned int __bss_start; -extern unsigned int __bss_end; -extern unsigned int __heap_start; -extern void *__brkval; -char *__brkval_maximum __attribute__((weak)); - -/* - * The free list structure as maintained by the avr-libc memory allocation routines. - */ -struct __freelist { - size_t sz; - struct __freelist *nx; -}; - -/* The head of the free list structure */ -extern struct __freelist *__flp; - -/* Calculates the size of the free list */ -int ATS_FreeListSize() -{ -struct __freelist* current; -int total = 0; - - for (current = __flp; current; current = current->nx) { - total += 2; /* Add two bytes for the memory block's header */ - total += (int) current->sz; - } - - return total; -} - -//************************************************************************ -int ATS_GetFreeMemory() -{ -int free_memory; - - if((int)__brkval == 0) - { - free_memory = ((int)&free_memory) - ((int)&__heap_start); - } - else - { - free_memory = ((int)&free_memory) - ((int)__brkval); - free_memory += ATS_FreeListSize(); - } - return free_memory; -} - -int ATS_GetMaximumMemoryAllocated() -{ - if (__brkval_maximum) { - return (int)__brkval_maximum - (int)&__heap_start; - } - return -1; -} - diff --git a/libraries/ArduinoTestSuite/ArduinoTestSuite.h b/libraries/ArduinoTestSuite/ArduinoTestSuite.h deleted file mode 100644 index f2f00ca89..000000000 --- a/libraries/ArduinoTestSuite/ArduinoTestSuite.h +++ /dev/null @@ -1,74 +0,0 @@ -//************************************************************************ -//************************************************************************ -//* Aug 31, 2010 Started on TestArduino -//************************************************************************ - -#if defined(ARDUINO) && ARDUINO >= 100 -#include "Arduino.h" -#include "pins_arduino.h" -#else -#include "WProgram.h" -#include "pins_arduino.h" -#endif - - -#if defined(USART3_RX_vect) - #define SERIAL_PORT_COUNT 4 -#elif defined(USART1_RX_vect) - #define SERIAL_PORT_COUNT 2 -#else - #define SERIAL_PORT_COUNT 1 -#endif - - -void ATS_begin(char *manufName, char *testSuiteName); -void ATS_end(); - -void ATS_PrintTestStatus(char *testString, boolean passed); -boolean ATS_Test_DigitalPin(uint8_t digitalPinToTest); -boolean ATS_Test_PWM_Pin(uint8_t digitalPinToTest); -boolean ATS_Test_AnalogInput(uint8_t analogPintoTest); -boolean ATS_Test_EEPROM(void); - -short ATS_TestSerialLoopback(HardwareSerial *theSerialPort, char *serialPortName); - - -int ATS_GetFreeMemory(); -int ATS_GetMaximumMemoryAllocated(); - - -//************************************************************************ -//* this has to be an inline function because calling subroutines affects free memory -inline void ATS_ReportMemoryUsage(int _memoryUsageAtStart) __attribute__((always_inline, unused)); -inline void ATS_ReportMemoryUsage(int _memoryUsageAtStart) -{ -int freeMemoryAtEnd; -int lostMemory; -boolean memoryOK; -char memoryUsage[48]; - - freeMemoryAtEnd = ATS_GetFreeMemory(); - lostMemory = _memoryUsageAtStart - freeMemoryAtEnd; - if (lostMemory == 0) - { - strcpy(memoryUsage, "Memory Usage"); - memoryOK = true; - } - else - { - sprintf(memoryUsage, "Memory Usage (lost %d bytes)", lostMemory); - memoryOK = false; - } - ATS_PrintTestStatus(memoryUsage, memoryOK); -} - - - -extern unsigned long gTestStartTime; -extern int gYotalErrors; -extern int gTestCount; - - -#define PASSED true -#define FAILED false - diff --git a/libraries/ArduinoTestSuite/avr_cpunames.h b/libraries/ArduinoTestSuite/avr_cpunames.h deleted file mode 100644 index 80832164c..000000000 --- a/libraries/ArduinoTestSuite/avr_cpunames.h +++ /dev/null @@ -1,186 +0,0 @@ -//************************************************************************************************** -//* -//* Atmel AVR CPU name strings -//* -//************************************************************************************************** -//* Sep 19, 2010 Started on avr_cpunames.h -//************************************************************************************************** - -//#include "avr_cpunames.h" - -//************************************************************************************************** - - -#if defined (__AVR_AT94K__) - #define _AVR_CPU_NAME_ "AT94k" -#elif defined (__AVR_AT43USB320__) -#elif defined (__AVR_AT43USB355__) -#elif defined (__AVR_AT76C711__) -#elif defined (__AVR_AT86RF401__) -#elif defined (__AVR_AT90PWM1__) -#elif defined (__AVR_AT90PWM2__) -#elif defined (__AVR_AT90PWM2B__) -#elif defined (__AVR_AT90PWM3__) -#elif defined (__AVR_AT90PWM3B__) -#elif defined (__AVR_AT90PWM216__) -#elif defined (__AVR_AT90PWM316__) -#elif defined (__AVR_ATmega32C1__) -#elif defined (__AVR_ATmega32M1__) -#elif defined (__AVR_ATmega32U4__) - #define _AVR_CPU_NAME_ "ATmega32U4" -#elif defined (__AVR_ATmega32U6__) - #define _AVR_CPU_NAME_ "ATmega32U6" -#elif defined (__AVR_ATmega128__) - #define _AVR_CPU_NAME_ "Atmega128" -#elif defined (__AVR_ATmega1280__) - #define _AVR_CPU_NAME_ "ATmega1280" -#elif defined (__AVR_ATmega1281__) - #define _AVR_CPU_NAME_ "ATmega1281" -#elif defined (__AVR_ATmega1284P__) - #define _AVR_CPU_NAME_ "ATmega1284" -#elif defined (__AVR_ATmega2560__) - #define _AVR_CPU_NAME_ "ATmega2560" -#elif defined (__AVR_ATmega2561__) - #define _AVR_CPU_NAME_ "ATmega2561" -#elif defined (__AVR_AT90CAN32__) - #define _AVR_CPU_NAME_ "AT90CAN32" -#elif defined (__AVR_AT90CAN64__) - #define _AVR_CPU_NAME_ "AT90CAN64" -#elif defined (__AVR_AT90CAN128__) - #define _AVR_CPU_NAME_ "AT90CAN128" -#elif defined (__AVR_AT90USB82__) - #define _AVR_CPU_NAME_ "AT90USB82" -#elif defined (__AVR_AT90USB162__) - #define _AVR_CPU_NAME_ "AT90USB162" -#elif defined (__AVR_AT90USB646__) - #define _AVR_CPU_NAME_ "AT90USB646" -#elif defined (__AVR_AT90USB647__) - #define _AVR_CPU_NAME_ "AT90USB647" -#elif defined (__AVR_AT90USB1286__) - #define _AVR_CPU_NAME_ "AT90USB1286" -#elif defined (__AVR_AT90USB1287__) - #define _AVR_CPU_NAME_ "AT90USB1287" -#elif defined (__AVR_ATmega64__) - #define _AVR_CPU_NAME_ "ATmega64" -#elif defined (__AVR_ATmega640__) - #define _AVR_CPU_NAME_ "ATmega640" -#elif defined (__AVR_ATmega644__) - #define _AVR_CPU_NAME_ "ATmega644" -#elif defined (__AVR_ATmega644P__) - #define _AVR_CPU_NAME_ "ATmega644P" -#elif defined (__AVR_ATmega645__) - #define _AVR_CPU_NAME_ "ATmega645" -#elif defined (__AVR_ATmega6450__) - #define _AVR_CPU_NAME_ "ATmega6450" -#elif defined (__AVR_ATmega649__) - #define _AVR_CPU_NAME_ "ATmega649" -#elif defined (__AVR_ATmega6490__) - #define _AVR_CPU_NAME_ "ATmega6490" -#elif defined (__AVR_ATmega103__) - #define _AVR_CPU_NAME_ "ATmega103" -#elif defined (__AVR_ATmega32__) - #define _AVR_CPU_NAME_ "Atmega32" -#elif defined (__AVR_ATmega323__) - #define _AVR_CPU_NAME_ "ATmega323" -#elif defined (__AVR_ATmega324P__) - #define _AVR_CPU_NAME_ "ATmega324P" -#elif defined (__AVR_ATmega325__) - #define _AVR_CPU_NAME_ "ATmega325" -#elif defined (__AVR_ATmega325P__) - #define _AVR_CPU_NAME_ "ATmega325P" -#elif defined (__AVR_ATmega3250__) - #define _AVR_CPU_NAME_ "ATmega3250" -#elif defined (__AVR_ATmega3250P__) - #define _AVR_CPU_NAME_ "ATmega3250P" -#elif defined (__AVR_ATmega328P__) - #define _AVR_CPU_NAME_ "ATmega328P" -#elif defined (__AVR_ATmega329__) - #define _AVR_CPU_NAME_ "ATmega329" -#elif defined (__AVR_ATmega329P__) - #define _AVR_CPU_NAME_ "ATmega329P" -#elif defined (__AVR_ATmega3290__) - #define _AVR_CPU_NAME_ "ATmega3290" -#elif defined (__AVR_ATmega3290P__) - #define _AVR_CPU_NAME_ "ATmega3290P" -#elif defined (__AVR_ATmega32HVB__) - #define _AVR_CPU_NAME_ "ATmega32HVB" -#elif defined (__AVR_ATmega406__) - #define _AVR_CPU_NAME_ "ATmega406" -#elif defined (__AVR_ATmega16__) - #define _AVR_CPU_NAME_ "Atmega16" -#elif defined (__AVR_ATmega161__) - #define _AVR_CPU_NAME_ "ATmega161" -#elif defined (__AVR_ATmega162__) - #define _AVR_CPU_NAME_ "ATmega162" -#elif defined (__AVR_ATmega163__) - #define _AVR_CPU_NAME_ "ATmega163" -#elif defined (__AVR_ATmega164P__) - #define _AVR_CPU_NAME_ "ATmega164P" -#elif defined (__AVR_ATmega165__) - #define _AVR_CPU_NAME_ "ATmega165" -#elif defined (__AVR_ATmega165P__) - #define _AVR_CPU_NAME_ "ATmega165P" -#elif defined (__AVR_ATmega168__) - #define _AVR_CPU_NAME_ "ATmega168" -#elif defined (__AVR_ATmega168P__) - #define _AVR_CPU_NAME_ "ATmega168P" -#elif defined (__AVR_ATmega169__) - #define _AVR_CPU_NAME_ "Atmega169" -#elif defined (__AVR_ATmega169P__) - #define _AVR_CPU_NAME_ "ATmega169P" -#elif defined (__AVR_ATmega8HVA__) - #define _AVR_CPU_NAME_ "ATmega8HVA" -#elif defined (__AVR_ATmega16HVA__) - #define _AVR_CPU_NAME_ "ATmega16HVA" -#elif defined (__AVR_ATmega8__) - #define _AVR_CPU_NAME_ "ATmega8" -#elif defined (__AVR_ATmega48__) - #define _AVR_CPU_NAME_ "ATmega48" -#elif defined (__AVR_ATmega48P__) - #define _AVR_CPU_NAME_ "ATmega48P" -#elif defined (__AVR_ATmega88__) - #define _AVR_CPU_NAME_ "ATmega88" -#elif defined (__AVR_ATmega88P__) - #define _AVR_CPU_NAME_ "ATmega88P" -#elif defined (__AVR_ATmega8515__) - #define _AVR_CPU_NAME_ "ATmega8515" -#elif defined (__AVR_ATmega8535__) - #define _AVR_CPU_NAME_ "ATmega8535" -#elif defined (__AVR_AT90S8535__) -#elif defined (__AVR_AT90C8534__) -#elif defined (__AVR_AT90S8515__) -#elif defined (__AVR_AT90S4434__) -#elif defined (__AVR_AT90S4433__) -#elif defined (__AVR_AT90S4414__) -#elif defined (__AVR_ATtiny22__) -#elif defined (__AVR_ATtiny26__) -#elif defined (__AVR_AT90S2343__) -#elif defined (__AVR_AT90S2333__) -#elif defined (__AVR_AT90S2323__) -#elif defined (__AVR_AT90S2313__) -#elif defined (__AVR_ATtiny2313__) - #define _AVR_CPU_NAME_ "ATtiny2313" -#elif defined (__AVR_ATtiny13__) -#elif defined (__AVR_ATtiny13A__) -#elif defined (__AVR_ATtiny25__) -#elif defined (__AVR_ATtiny45__) -#elif defined (__AVR_ATtiny85__) -#elif defined (__AVR_ATtiny24__) -#elif defined (__AVR_ATtiny44__) -#elif defined (__AVR_ATtiny84__) -#elif defined (__AVR_ATtiny261__) -#elif defined (__AVR_ATtiny461__) -#elif defined (__AVR_ATtiny861__) -#elif defined (__AVR_ATtiny43U__) -#elif defined (__AVR_ATtiny48__) -#elif defined (__AVR_ATtiny88__) -#elif defined (__AVR_ATtiny167__) - -#else - #error cpu not defined -#endif - - -#if !defined (_AVR_CPU_NAME_) -// #define _AVR_CPU_NAME_ "UNKNOWN" -#endif diff --git a/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.ino b/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.ino deleted file mode 100644 index fc3aab765..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_Constants/ATS_Constants.ino +++ /dev/null @@ -1,74 +0,0 @@ -//************************************************************************ -//* Arduino Test of Arduino Constants -//* (C) 2010 by Rick Anderson -//* Open source as per standard Arduino code -//* -//************************************************************************ -//* Oct 16, 2010 Test of Arduino Constants -//************************************************************************ - -#include - -//************************************************************************ -void setup() -{ - int startMemoryUsage; - - //Start memory usage must be site prior to ATS_begin - startMemoryUsage = ATS_GetFreeMemory(); - ATS_begin("Arduino", "Test of Arduino Constants"); - /* - * Test Run Start - */ - - - //test true constant - ATS_PrintTestStatus("1. Test of true constant", true == 1); - - //test false consts - ATS_PrintTestStatus( "2. Test of false constant", false == 0); - - //Test of HIGH == 1 - ATS_PrintTestStatus( "3. Test of HIGH == 1", HIGH == 1); - - //Test of LOW == 0 - ATS_PrintTestStatus( "4. Test of LOW == 0", LOW == 0); - - //Test of INPUT == 1 - ATS_PrintTestStatus( "5. Test of INPUT == 1", HIGH == 1); - - //Test of OUTPUT == 0 - ATS_PrintTestStatus( "6. Test of OUTPUT == 0", LOW == 0); - - //test decimal - ATS_PrintTestStatus( "7. Test of decimal constant", 101 == ((1 * pow(10,2)) + (0 * pow(10,1)) + 1)); - - //test binary - ATS_PrintTestStatus( "8. Test of binary constant", B101 == 5); - - //test octal - ATS_PrintTestStatus( "9. Test of octal constant", 0101 == 65); - - //test hexadecimal - ATS_PrintTestStatus( "7. Test of hexadecimal constant", (0x101 == 257)); - - /* - * Test Run End - */ - ATS_ReportMemoryUsage(startMemoryUsage); - ATS_end(); - -} - - -//************************************************************************ -void loop() -{ - - -} - - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.ino b/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.ino deleted file mode 100644 index 111302e38..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_Delay/ATS_Delay.ino +++ /dev/null @@ -1,101 +0,0 @@ -//************************************************************************ -//* Arduino Test Suite -//* ATS_ToneTest -//* -//* Copyright (c) 2010 Mark Sproul 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 -//************************************************************************ -//* Aug 31, 2010 Started on TestArduino -//* Oct 28, 2010 Started on Delay -//************************************************************************ - -#include - -//************************************************************************ -void setup() -{ -short ii; -short testNum; -int startMemoryUsage; -unsigned long startMillis; -unsigned long endMillis; -unsigned long deltaMillis; -unsigned long errMillis; -boolean passed; -char testNameString[80]; - - - startMemoryUsage = ATS_GetFreeMemory(); - - ATS_begin("Arduino", "DelayTest"); - - testNum = 1; - //* we start at 2 because 0/1 are RXD/TXD - for (ii=0; ii<1000; ii+= 15) - { - startMillis = millis(); - - delay(ii); - - endMillis = millis(); - - deltaMillis = endMillis - startMillis; - - if (deltaMillis >= ii) - { - errMillis = deltaMillis - ii; - } - else - { - errMillis = ii - deltaMillis; - } - - if (errMillis <= 1) - { - passed = true; - } - else - { - passed = false; - } - sprintf(testNameString, "DelayTest.%02d (delay= %4d actual delay=%ld err=%ld)", testNum, ii, deltaMillis, errMillis); - - ATS_PrintTestStatus(testNameString, passed); - - - testNum++; - } - - - - - ATS_ReportMemoryUsage(startMemoryUsage); - - ATS_end(); - -} - - -//************************************************************************ -void loop() -{ - - -} - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.ino b/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.ino deleted file mode 100644 index 588342dca..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_General/ATS_General.ino +++ /dev/null @@ -1,95 +0,0 @@ -//************************************************************************ -//* Arduino Test Suite -//* (C) 2010 by Mark Sproul -//* Open source as per standard Arduino code -//* -//************************************************************************ -//* Aug 31, 2010 Started on TestArduino -//* Oct 18, 2010 Added memory testing -//************************************************************************ - -#include - -#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) -#define kBoard_PinCount 20 -#define kBoard_AnalogCount 6 -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define kBoard_PinCount 70 -#define kBoard_AnalogCount 16 - -#elif defined(CORE_TEENSY) -#define kBoard_PinCount CORE_NUM_TOTAL_PINS -#define kBoard_AnalogCount CORE_NUM_ANALOG -#define SERIAL_PORT_COUNT 2 -HardwareSerial Serial1 = HardwareSerial(); -#endif - - - - -//************************************************************************ -void setup() -{ - short ii; - uint8_t timerNumber; - int startMemoryUsage; - - startMemoryUsage = ATS_GetFreeMemory(); - - ATS_begin("Arduino", "general"); - - //* test digital pins - //* we start at 2 because 0/1 are RXD/TXD - for (ii=2; ii 1) - ATS_TestSerialLoopback(&Serial1, "Serial1"); -#endif -#if (SERIAL_PORT_COUNT > 2) - ATS_TestSerialLoopback(&Serial2, "Serial2"); -#endif -#if (SERIAL_PORT_COUNT > 3) - ATS_TestSerialLoopback(&Serial3, "Serial3"); -#endif - - ATS_Test_EEPROM(); - - - ATS_ReportMemoryUsage(startMemoryUsage); - - ATS_end(); - -} - - -//************************************************************************ -void loop() -{ - - -} - - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.ino b/libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.ino deleted file mode 100644 index fefd6b07d..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_SD_File/ATS_SD_File.ino +++ /dev/null @@ -1,106 +0,0 @@ -// Tests writing to and reading from a file, in particular the -// the Stream implementation (e.g. read() and peek()). - -#include -#include - -void setup() -{ - int startMemoryUsage = ATS_GetFreeMemory(); - boolean b; - File f; - - ATS_begin("Arduino", "SD Test"); - - ATS_PrintTestStatus("SD.begin()", b = SD.begin(4)); - if (!b) goto done; - - SD.remove("test.txt"); - - f = SD.open("test.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - f.print("abc"); - f.print("de"); - f.close(); - - f = SD.open("test.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - f.print("fgh"); - f.close(); - - f = SD.open("test.txt"); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - ATS_PrintTestStatus("read()", f.read() == 'a'); - ATS_PrintTestStatus("peek()", f.peek() == 'b'); - ATS_PrintTestStatus("read()", f.read() == 'b'); - ATS_PrintTestStatus("read()", f.read() == 'c'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("read()", f.read() == 'd'); - ATS_PrintTestStatus("available()", f.available() != 0); - ATS_PrintTestStatus("read()", f.read() == 'e'); - ATS_PrintTestStatus("available()", f.available() != 0); - ATS_PrintTestStatus("peek()", f.peek() == 'f'); - ATS_PrintTestStatus("read()", f.read() == 'f'); - ATS_PrintTestStatus("peek()", f.peek() == 'g'); - ATS_PrintTestStatus("available()", f.available() != 0); - ATS_PrintTestStatus("peek()", f.peek() == 'g'); - ATS_PrintTestStatus("read()", f.read() == 'g'); - ATS_PrintTestStatus("available()", f.available() != 0); - ATS_PrintTestStatus("available()", f.available() != 0); - ATS_PrintTestStatus("available()", f.available() != 0); - ATS_PrintTestStatus("peek()", f.peek() == 'h'); - ATS_PrintTestStatus("read()", f.read() == 'h'); - ATS_PrintTestStatus("available()", f.available() == 0); - ATS_PrintTestStatus("peek()", f.peek() == -1); - ATS_PrintTestStatus("read()", f.read() == -1); - ATS_PrintTestStatus("peek()", f.peek() == -1); - ATS_PrintTestStatus("read()", f.read() == -1); - - f.close(); - - SD.remove("test2.txt"); - - f = SD.open("test2.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - f.print("ABC"); - f.close(); - - f = SD.open("test.txt"); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - ATS_PrintTestStatus("peek()", f.peek() == 'a'); - - f.close(); - - f = SD.open("test2.txt"); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - ATS_PrintTestStatus("peek()", f.peek() == 'A'); - ATS_PrintTestStatus("read()", f.read() == 'A'); - - f.close(); - -done: - ATS_ReportMemoryUsage(startMemoryUsage); - ATS_end(); - -} - -void loop() {} - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino b/libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino deleted file mode 100644 index c3804f4de..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino +++ /dev/null @@ -1,78 +0,0 @@ -#include -#include - -void setup() -{ - int startMemoryUsage = ATS_GetFreeMemory(); - boolean b; - File f; - - ATS_begin("Arduino", "SD Files Test"); - - ATS_PrintTestStatus("SD.begin()", b = SD.begin(4)); - if (!b) goto done; - - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); - ATS_PrintTestStatus("SD.open()", f = SD.open("asdf.txt", FILE_WRITE)); f.close(); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf.txt")); - ATS_PrintTestStatus("SD.exists()", SD.exists("/asdf.txt")); - ATS_PrintTestStatus("SD.remove()", SD.remove("asdf.txt")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); - - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("/asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("asdf")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - - ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("x/y/z")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/z")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/z/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("/x/y/z/")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("x/y/z")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("x/y/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("/x")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); - - ATS_PrintTestStatus("!SD.open()", !(f = SD.open("asdf/asdf.txt", FILE_WRITE))); f.close(); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.open()", f = SD.open("asdf/asdf.txt", FILE_WRITE)); f.close(); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("!SD.rmdir()", !SD.rmdir("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("SD.remove()", SD.remove("asdf/asdf.txt")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("asdf")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - -done: - ATS_ReportMemoryUsage(startMemoryUsage); - ATS_end(); - -} - -void loop() {} - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino b/libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino deleted file mode 100644 index 5b0916ca7..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino +++ /dev/null @@ -1,109 +0,0 @@ -// Tests writing to and reading from a file, in particular the -// the Stream implementation (e.g. read() and peek()). - -#include -#include - -void setup() -{ - int startMemoryUsage = ATS_GetFreeMemory(); - boolean b; - File f; - - ATS_begin("Arduino", "SD Test"); - - ATS_PrintTestStatus("SD.begin()", b = SD.begin(4)); - if (!b) goto done; - - SD.remove("test.txt"); - - f = SD.open("test.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - ATS_PrintTestStatus("initial position", f.position() == 0); - ATS_PrintTestStatus("initial size", f.size() == 0); - - f.print("0123456789"); - - ATS_PrintTestStatus("position after writing", f.position() == 10); - ATS_PrintTestStatus("size after writing", f.size() == 10); - - f.seek(0); - - ATS_PrintTestStatus("size after seek", f.size() == 10); - ATS_PrintTestStatus("position after seek", f.position() == 0); - - f.seek(7); - - ATS_PrintTestStatus("position after seek", f.position() == 7); - ATS_PrintTestStatus("reading after seek", f.read() == '7'); - ATS_PrintTestStatus("position after reading after seeking", f.position() == 8); - ATS_PrintTestStatus("reading after reading after seeking", f.read() == '8'); - - f.seek(3); - - ATS_PrintTestStatus("position after seeking", f.position() == 3); - ATS_PrintTestStatus("peeking after seeking", f.peek() == '3'); - ATS_PrintTestStatus("position after peeking after seeking", f.position() == 3); - ATS_PrintTestStatus("peeking after peeking after seeking", f.peek() == '3'); - ATS_PrintTestStatus("position after peeking after seeking", f.position() == 3); - ATS_PrintTestStatus("peeking after peeking after seeking", f.read() == '3'); - ATS_PrintTestStatus("position after peeking after seeking", f.position() == 4); - - f.seek(1); - - ATS_PrintTestStatus("position after seeking", f.position() == 1); - ATS_PrintTestStatus("peeking after seeking", f.peek() == '1'); - - f.seek(4); - - ATS_PrintTestStatus("position after seeking", f.position() == 4); - ATS_PrintTestStatus("peeking after seeking", f.peek() == '4'); - - f.seek(7); - - ATS_PrintTestStatus("position()", f.position() == 7); - ATS_PrintTestStatus("read()", f.read() == '7'); - - f.seek(0); - f.peek(); - f.print("AB"); - - ATS_PrintTestStatus("position()", f.position() == 2); - ATS_PrintTestStatus("size()", f.size() == 10); - ATS_PrintTestStatus("read()", f.read() == '2'); - - f.seek(0); - - ATS_PrintTestStatus("read()", f.read() == 'A'); - ATS_PrintTestStatus("read()", f.read() == 'B'); - ATS_PrintTestStatus("read()", f.read() == '2'); - - f.close(); - - f = SD.open("test.txt"); - ATS_PrintTestStatus("SD.open()", f); - if (!f) goto done; - - ATS_PrintTestStatus("position()", f.position() == 0); - ATS_PrintTestStatus("size()", f.size() == 10); - ATS_PrintTestStatus("peek()", f.peek() == 'A'); - ATS_PrintTestStatus("read()", f.read() == 'A'); - - f.seek(4); - - ATS_PrintTestStatus("position()", f.position() == 4); - ATS_PrintTestStatus("size()", f.size() == 10); - ATS_PrintTestStatus("peek()", f.peek() == '4'); - ATS_PrintTestStatus("read()", f.read() == '4'); - - f.close(); - -done: - ATS_ReportMemoryUsage(startMemoryUsage); - ATS_end(); - -} - -void loop() {} diff --git a/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.ino b/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.ino deleted file mode 100644 index 58ecaff6c..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_Skeleton/ATS_Skeleton.ino +++ /dev/null @@ -1,50 +0,0 @@ -//************************************************************************ -//* Arduino Test Example Skeleton -//* (C) 2010 by Rick Anderson -//* Open source as per standard Arduino code -//* -//************************************************************************ -//* Oct 16, 2010 Started on String Test -//************************************************************************ - -#include - -//************************************************************************ -void setup() -{ - int startMemoryUsage; - - //startMemoryUsage must be set directly before ATS_begin - startMemoryUsage = ATS_GetFreeMemory(); - ATS_begin("Arduino", "Skeleton Test"); - /* - * Test Run Start - * Test one passes because result is set to true - * Test two fails becuase result is set to false - * You can test memory for any set of tests by using the ATS_ReportMemoryUsage test - * There is also a way to print current memeory for debugging - */ - ATS_PrintTestStatus("1. Test of true test status", true); - - ATS_PrintTestStatus("2. Test of false test status, this will fail.", false); - - ATS_ReportMemoryUsage(startMemoryUsage); - /* - * Test Run End - */ - - ATS_end(); - -} - - -//************************************************************************ -void loop() -{ - - -} - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.ino b/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.ino deleted file mode 100644 index 2de273ece..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_StringIndexOfMemory/ATS_StringIndexOfMemory.ino +++ /dev/null @@ -1,104 +0,0 @@ -//************************************************************************ -//* Arduino Test Example Skeleton -//* (C) 2010 by Rick Anderson -//* Open source as per standard Arduino code -//* -//************************************************************************ -//* Oct 16, 2010 Started on String Test -//************************************************************************ - -#include - -//************************************************************************ - -void do_string_operations(int startMemoryUsage) -{ - String stringOne; - int firstClosingBracket; - int firstOpeningBracket; - int secondOpeningBracket; - int secondClosingBracket; - int bodyTag; - int firstListItem; - int secondListItem; - int lastOpeningBracket; - int lastListItem; - int lastParagraph; - int secondLastParagraph; - int thirdLastParagraph; - - // 1111111111 - // 01234567890123456789 - stringOne = ""; - firstClosingBracket = stringOne.indexOf('>'); - ATS_PrintTestStatus("firstClosingBracket", firstClosingBracket == 5); - - // 1111111111 - // 01234567890123456789 - stringOne = ""; - secondOpeningBracket = firstClosingBracket + 1; - secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket ); - ATS_PrintTestStatus("secondClosingBracket", secondClosingBracket == 11); - - // you can also use indexOf() to search for Strings: - // 1111111111 - // 01234567890123456789 - stringOne = ""; - bodyTag = stringOne.indexOf(""); - ATS_PrintTestStatus("bodyTag", bodyTag == 12); - - // 111111111122222222223333333333 - // 0123456789012345678901234567890123456789 - stringOne = "
    • item
    • item
    • item
    "; - firstListItem = stringOne.indexOf("
  • "); - secondListItem = stringOne.indexOf("
  • ", firstListItem + 1 ); - - ATS_PrintTestStatus("firstListItem", firstListItem == 4); - ATS_PrintTestStatus("secondListItem", secondListItem == 12); - - // lastIndexOf() gives you the last occurrence of a character or string: - lastOpeningBracket = stringOne.lastIndexOf('<'); - ATS_PrintTestStatus("lastOpeningBracket", lastOpeningBracket == 28); - - lastListItem = stringOne.lastIndexOf("
  • "); - ATS_PrintTestStatus("lastListItem", lastListItem == 20); - - // lastIndexOf() can also search for a string: - // 11111111112222222222333333333344444444445555555555 - // 012345678901234567890123456789012345678901234567890123456789 - stringOne = "

    Lorem ipsum dolor sit amet

    Ipsem

    Quod

    "; - lastParagraph = stringOne.lastIndexOf(" Started on String Test -//************************************************************************ - -#include - -//************************************************************************ -void setup() -{ - - int startMemoryUsage; - - ATS_begin("Arduino", "Test of String Library"); - - /* - * Test Variable Setup - * Best practive set all your test variables prior to teseting. - * This is required for Memory tests. - */ - - String stringOne = String("stringThree = "); - String stringTwo = String("this string"); - String stringThree = String (); - char charResult[100]; - - - - /* - * Run the tests - */ - - // adding a constant integer to a string: - stringThree = stringOne + 123; - //strcpy(charResult, "\0"); - stringThree.toCharArray(charResult, sizeof(charResult)); - - ATS_PrintTestStatus("1. Adding a constant integer to a string:", strcmp(charResult,"stringThree = 123" ) == 0); - - // adding a constant long interger to a string: - stringThree = stringOne + 123456789; - stringThree.toCharArray(charResult, sizeof(charResult)); - - ATS_PrintTestStatus("2. Adding a constant long interger to a string", strcmp(charResult,"stringThree = 123456789" ) == 0); - - - // adding a constant character to a string: - stringThree = stringOne + 'A'; - stringThree.toCharArray(charResult, sizeof(charResult)); - - ATS_PrintTestStatus("3. Adding a constant character to a string", strcmp(charResult,"stringThree = A" ) == 0); - - - // adding a constant string to a string: - stringThree = stringOne + "abc"; - stringThree.toCharArray(charResult, sizeof(charResult)); - - ATS_PrintTestStatus("4. Adding a constant string variable to a string", strcmp(charResult,"stringThree = abc" ) == 0); - - //"5. Adding a constant long interger to a string" - stringThree = stringOne + stringTwo; - stringThree.toCharArray(charResult, sizeof(charResult)); - - ATS_PrintTestStatus("5. Adding a constant long interger to a string", strcmp(charResult,"stringThree = this string" ) == 0); - - - /* - * setup up String Comparison Operater Tests - */ - - stringOne = String("this"); - stringTwo = String("that"); - - // two strings equal: - ATS_PrintTestStatus("6. Two strings equal",stringOne == "this"); - - // two strings not equal: - ATS_PrintTestStatus("7. Two strings not equal",stringOne != stringTwo); - - // two strings not equal (case sensitivity matters): - stringOne = "This"; - stringTwo = "this"; - ATS_PrintTestStatus("8. Two strings not equal [case sensitivity matters]", stringOne != stringTwo); - - // you can also use equals() to see if two strings are the same: - stringOne = "this"; - stringTwo = "this"; - ATS_PrintTestStatus("9. Equals() method equals", stringOne.equals(stringTwo)); - - - // you can also use not equals() to see if two strings are not the same: - stringOne = String("This"); - stringTwo = String("this"); - ATS_PrintTestStatus("10. Not equals() method equals", !stringOne.equals(stringTwo)); - - // or perhaps you want to ignore case: - ATS_PrintTestStatus("11. EqualsIgnoreCase() method equals", stringOne.equalsIgnoreCase(stringTwo)); - -#if ARDUINO < 100 || defined(CORE_TEENSY) -// David Mellis decided not to keep implicit string to number comparison operators -// in Arduino 1.0. Only run this test on older version, or if using Teensy - // a numeric string compared to the number it represents: - stringOne = "1"; - int numberOne = 1; - ATS_PrintTestStatus("12. A numeric string compared to the number it represents", stringOne == numberOne); -#endif - - // two numeric strings compared: - stringOne = "2"; - stringTwo = "1"; - ATS_PrintTestStatus("13. Two numeric strings compared",stringOne >= stringTwo); - - - // comparison operators can be used to compare strings for alphabetic sorting too: - -/* - stringOne = String("Brown"); - ATS_PrintTestStatus("14. comparison operator < can be used to compare strings for alphabetic sorting ",stringOne < "Charles"); - ATS_PrintTestStatus("15. comparison operator > can be used to compare strings for alphabetic sorting ",stringOne > "Adams"); - ATS_PrintTestStatus("16. comparison operator <= can be used to compare strings for alphabetic sorting ",stringOne <= "Browne"); - ATS_PrintTestStatus("17. comparison operator >= can be used to compare strings for alphabetic sorting ",stringOne >= "Brow"); - */ - - - // the compareTo() operator also allows you to compare strings - stringOne = "Cucumber"; - stringTwo = "Cucuracha"; - - ATS_PrintTestStatus("18. The compareTo() operator also allows you to compare strings", stringOne.compareTo(stringTwo) < 0); - - // These two tests assume the string compare parses numbers - // within strings, but it does not actually do any such thing - // compareTo() String with numnber > String with number: - //stringOne = "Sensor: 50"; - //stringTwo= "Sensor: 150"; - //ATS_PrintTestStatus("19. The compareTo() String with integers", stringOne.compareTo(stringTwo) < 0); -// compareTo() String with numnber > String with number append integer, matches example code: - //stringOne = "Sensor: "; - //stringTwo= "Sensor: "; - //stringOne += 50; - //stringTwo += 150; - //ATS_PrintTestStatus("20. The compareTo() compare strings with appended integers", stringOne.compareTo(stringTwo) < 0); - - - /* - * setup up String Append Operation Tests - */ - // Serious awful problem here - stringOne = String("Sensor "); - stringTwo = String("value"); - - stringOne += stringTwo; - ATS_PrintTestStatus("21. Adding string to string += ", stringOne.equals("Sensor value")); - - ATS_PrintTestStatus("22. The compareTo() compare strings with appended integers", stringOne.compareTo(stringTwo) < 0); - /* - * Test complete - */ - - ATS_end(); - -} - - -//************************************************************************ -void loop() -{ - - -} - - - - - - - - - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.ino b/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.ino deleted file mode 100644 index fc611bb67..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/ATS_String_Addition.ino +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include "Test_Equal.h" - -void setup() -{ - ATS_begin("Arduino", "String Addition Test"); - - String stringOne = String("string"); - String stringTwo = String("other"); - String stringThree = stringOne + stringTwo; - - Test_Equal("Add strings", "stringother", stringThree); - Test_Equal("Adding strings doesn't change them", "string", stringOne); - Test_Equal("Adding strings doesn't change them", "other", stringTwo); - Test_Equal("Add strings", "stringotherstringstringstringother", stringOne + stringTwo + stringOne + stringOne + stringOne + stringTwo); - Test_Equal("Add string to integer", "string12345", stringOne + 12345); - Test_Equal("Add string to negative integer", "string-12345", stringOne + -12345); - Test_Equal("Add integer to string", "123string", 123 + stringOne); - Test_Equal("Add string to integers", "string123456789", stringOne + 123 + 456 + 789); - Test_Equal("Add integer to string", "123string456789", 123 + stringOne + 456 + 789); - Test_Equal("Add string to long", "string123456789", stringOne + 123456789L); - Test_Equal("Add string to negative long", "string-123456789", stringOne + -123456789L); - Test_Equal("Add string to unsigned long", "string123456789", stringOne + 123456789UL); - Test_Equal("Add string to byte", "string123", stringOne + byte(123)); - Test_Equal("Add char", "stringA", stringOne + 'A'); - Test_Equal("Add char", "Astring", 'A' + stringOne); - Test_Equal("Add \"string\"", "stringabc", stringOne + "abc"); - Test_Equal("Add \"string\"", "abcstring", "abc" + stringOne); - Test_Equal("Add multiple \"string\"", "stringabcdef", stringOne + "abc" + "def"); - Test_Equal("Add multiple \"string\"", "abcstringdef", "abc" + stringOne + "def"); - Test_Equal("Add \"string\" and int", "bc", "abc" + 1); - - ATS_end(); -} - -void loop() {} - - - - - - - - - - - - diff --git a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h b/libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h deleted file mode 100644 index 80dbc848b..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_String_Addition/Test_Equal.h +++ /dev/null @@ -1,13 +0,0 @@ -void Test_Equal(char *testString, char *expected, const String &actual) -{ - char buf[100]; actual.toCharArray(buf, 100); - boolean b = (strcmp(buf, expected) == 0); - ATS_PrintTestStatus(testString, b); - if (!b) { - Serial.print("expected '"); - Serial.print(expected); - Serial.print("', actual '"); - Serial.print(actual); - Serial.println("'"); - } -} diff --git a/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.ino b/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.ino deleted file mode 100644 index 195a3ca18..000000000 --- a/libraries/ArduinoTestSuite/examples/ATS_ToneTest/ATS_ToneTest.ino +++ /dev/null @@ -1,248 +0,0 @@ -//************************************************************************ -//* Arduino Test Suite -//* ATS_ToneTest -//* -//* Copyright (c) 2010 Mark Sproul 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 -//************************************************************************ -//* Aug 31, 2010 Started on TestArduino -//* Oct 23, 2010 Started on ToneTest -//************************************************************************ - -#include - -#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) - #define kBoard_PinCount 20 - #define kBoard_AnalogCount 6 -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - #define kBoard_PinCount 70 - #define kBoard_AnalogCount 16 -#elif defined(CORE_TEENSY) - #define kBoard_PinCount CORE_NUM_TOTAL_PINS - #define kBoard_AnalogCount CORE_NUM_ANALOG -#endif - -//************************************************************************ -void TestTonePin(uint8_t toneOutputPinNumber) -{ -uint8_t helperpin; -unsigned long startMilliSecs; -unsigned long highCount, lowCount; -int previousState; -int currentState; -char testNameString[80]; -long outputFreq; -long measuredFreq; -boolean passed; -long percentError; -long deltaFreq; - - if ((toneOutputPinNumber % 2) == 0) - { - //* if its EVEN, add 1 - helperpin = toneOutputPinNumber + 1; - } - else - { - //* if its ODD - helperpin = toneOutputPinNumber - 1; - } - if (helperpin >= kBoard_PinCount) return; - - //* dont set the mode of the OUTPUT pin, the tone command does that - - pinMode(helperpin, INPUT); - - previousState = digitalRead(helperpin); - startMilliSecs = millis(); - highCount = 0; - lowCount = 0; - measuredFreq = 0; - //* we are going to watch for one second - outputFreq = random(200, 2000); - - tone(toneOutputPinNumber, outputFreq); - while ((millis() - startMilliSecs) < 1000) - { - currentState = digitalRead(helperpin); - if (currentState == HIGH) - { - highCount++; - } - else - { - lowCount++; - } - //* check to see if it changed state - if ((currentState == HIGH) && (previousState == LOW)) - { - measuredFreq++; - } - - previousState = currentState; - } - noTone(toneOutputPinNumber); - - deltaFreq = abs(measuredFreq - outputFreq); - - percentError = 100 - abs(((outputFreq - deltaFreq) * 100) / outputFreq); - - sprintf(testNameString, "ToneTest.%02d (out freq= %4ld measured freq= %4ld err= %ld%%)", toneOutputPinNumber, outputFreq, measuredFreq, percentError); - if (percentError < 5) - { - passed = true; - } - else - { - passed = false; - } - - ATS_PrintTestStatus(testNameString, passed); -} - - -//************************************************************************ -//* this test to make sure the duration option works -void TestToneDuration(uint8_t toneOutputPinNumber) -{ -uint8_t helperpin; -unsigned long startMilliSecs; -unsigned long highCount, lowCount; -int previousState; -int currentState; -char testNameString[80]; -long outputFreq; -long measuredFreq; -boolean passed; -long percentError; -long deltaFreq; -long durationTime; - - if ((toneOutputPinNumber % 2) == 0) - { - //* if its EVEN, add 1 - helperpin = toneOutputPinNumber + 1; - } - else - { - //* if its ODD - helperpin = toneOutputPinNumber - 1; - } - if (helperpin >= kBoard_PinCount) return; - - //* dont set the mode of the OUTPUT pin, the tone command does that - - pinMode(helperpin, INPUT); - - previousState = digitalRead(helperpin); - startMilliSecs = millis(); - highCount = 0; - lowCount = 0; - measuredFreq = 0; - durationTime = 0; - //* we are going to watch for one second - outputFreq = random(500, 2000); - - tone(toneOutputPinNumber, outputFreq, 1000); - while ((millis() - startMilliSecs) < 2000) - { - currentState = digitalRead(helperpin); - if (currentState == HIGH) - { - highCount++; - } - else - { - lowCount++; - } - //* count the freq - if ((currentState == HIGH) && (previousState == LOW)) - { - measuredFreq++; - } - - //* check to see if it changed state - if (currentState != previousState) - { - durationTime = millis() - startMilliSecs; - } - - previousState = currentState; - } - - deltaFreq = abs(measuredFreq - outputFreq); - - percentError = 100 - abs(((outputFreq - deltaFreq) * 100) / outputFreq); - - sprintf(testNameString, "ToneTesDurationt.%02d (durationTime =%4ld/1000 freq err= %ld%%)", toneOutputPinNumber, durationTime, percentError); - if ((durationTime > 990) && (durationTime < 1010) && (percentError < 5)) - { - passed = true; - } - else - { - passed = false; - } - noTone(toneOutputPinNumber); - - ATS_PrintTestStatus(testNameString, passed); -} - - - -//************************************************************************ -void setup() -{ -short ii; -uint8_t timerNumber; -int startMemoryUsage; - - startMemoryUsage = ATS_GetFreeMemory(); - - ATS_begin("Arduino", "ToneTest"); - - - //* we start at 2 because 0/1 are RXD/TXD - for (ii=2; ii - -void Test_Equal(long actual, long expected) -{ - char buf[100]; - boolean b = expected == actual; - ATS_PrintTestStatus("", b); - if (!b) { - Serial.print("expected '"); - Serial.print(expected); - Serial.print("', actual '"); - Serial.print(actual); - Serial.println("'"); - } -} - -void setup() -{ - byte buf[5] = { 65, 66, 67, 0, 69 }; - ATS_begin("Arduino", "Write & Print Return Values Test"); - - Test_Equal(Serial.write('a'), 1); - Test_Equal(Serial.write(byte(0)), 1); - Test_Equal(Serial.write("abc"), 3); - Test_Equal(Serial.write(""), 0); - Test_Equal(Serial.write(buf, 5), 5); - Test_Equal(Serial.print(0), 1); - Test_Equal(Serial.print(""), 0); - Test_Equal(Serial.print("abc"), 3); - Test_Equal(Serial.print(0), 1); - Test_Equal(Serial.print(1), 1); - Test_Equal(Serial.print(11), 2); - Test_Equal(Serial.print(12345), 5); - Test_Equal(Serial.print(-1), 2); - Test_Equal(Serial.print(-123), 4); - Test_Equal(Serial.println(), 2); - Test_Equal(Serial.println(""), 2); - Test_Equal(Serial.println("abc"), 5); - Test_Equal(Serial.println(0), 3); - Test_Equal(Serial.println(1), 3); - Test_Equal(Serial.println(11), 4); - Test_Equal(Serial.println(12345), 7); - Test_Equal(Serial.println(-1), 4); - Test_Equal(Serial.println(-123), 6); - - ATS_end(); -} - -void loop() {} - - - - - - - - - - - - From be786b70deefff4a58d9f0f9ae5765bc7baa8f71 Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Fri, 2 Sep 2011 10:02:55 -0400 Subject: [PATCH 28/29] Revert "Don't include ArduinoTestSuite in Mac OS X distribution." This reverts commit a18eb93d817b11c5b8659d55376856c9c06ca743. --- build/build.xml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/build/build.xml b/build/build.xml index d6e00e2bd..c87c96179 100644 --- a/build/build.xml +++ b/build/build.xml @@ -228,9 +228,7 @@ - - - + From 108df37445a4254fbe008471d9747e6a9d755c1a Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Fri, 2 Sep 2011 14:43:44 -0400 Subject: [PATCH 29/29] Updating Firmata to r71. Note that I also changed the extensions of the examples (firmwares) from .pde to .ino and removed the Makefiles (since they assume the pde extension). http://code.google.com/p/arduino/issues/detail?id=447 --- libraries/Firmata/Boards.h | 99 ++-- libraries/Firmata/Firmata.cpp | 60 +-- libraries/Firmata/Firmata.h | 21 +- .../AllInputsFirmata/AllInputsFirmata.ino | 2 +- .../Firmata/examples/AnalogFirmata/Makefile | 263 ----------- .../examples/EchoString/EchoString.ino | 7 +- .../Firmata/examples/EchoString/Makefile | 263 ----------- .../examples/I2CFirmata/I2CFirmata.ino | 6 +- .../Firmata/examples/ServoFirmata/Makefile | 263 ----------- .../examples/SimpleAnalogFirmata/Makefile | 263 ----------- .../examples/SimpleDigitalFirmata/Makefile | 263 ----------- .../SimpleDigitalFirmata.ino | 2 +- .../Firmata/examples/StandardFirmata/Makefile | 273 ----------- .../StandardFirmata/StandardFirmata.ino | 2 +- .../StandardFirmata_2_2_forUNO_0_3.ino | 436 ------------------ 15 files changed, 113 insertions(+), 2110 deletions(-) delete mode 100644 libraries/Firmata/examples/AnalogFirmata/Makefile delete mode 100644 libraries/Firmata/examples/EchoString/Makefile delete mode 100644 libraries/Firmata/examples/ServoFirmata/Makefile delete mode 100644 libraries/Firmata/examples/SimpleAnalogFirmata/Makefile delete mode 100644 libraries/Firmata/examples/SimpleDigitalFirmata/Makefile delete mode 100644 libraries/Firmata/examples/StandardFirmata/Makefile delete mode 100644 libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.ino diff --git a/libraries/Firmata/Boards.h b/libraries/Firmata/Boards.h index f71632095..52f61873f 100644 --- a/libraries/Firmata/Boards.h +++ b/libraries/Firmata/Boards.h @@ -3,7 +3,13 @@ #ifndef Firmata_Boards_h #define Firmata_Boards_h -#include // for digitalRead, digitalWrite, etc +#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 @@ -120,40 +126,59 @@ writePort(port, value, bitmask): Write an 8 bit port. // 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 24 // 14 digital + 2 unused + 8 analog +#define TOTAL_PINS 22 // 14 digital + 8 analog +#endif #define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) (((p) >= 2 && (p) <= 13) || ((p) >= 16 && (p) <= 21)) -#define IS_PIN_ANALOG(p) ((p) >= 16 && (p) <= 23) +#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) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) ((p) >= 2 && (p) <= 13 && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) -#define PIN_TO_DIGITAL(p) (((p) < 16) ? (p) : (p) - 2) -#define PIN_TO_ANALOG(p) ((p) - 16) +#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) IS_PIN_DIGITAL(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 22 // 14 digital + 2 unused + 6 analog +#define TOTAL_PINS 20 // 14 digital + 6 analog #define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) (((p) >= 2 && (p) <= 13) || ((p) >= 16 && (p) <= 21)) -#define IS_PIN_ANALOG(p) ((p) >= 16 && (p) <= 21) +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) #define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) ((p) >= 2 && (p) <= 13 && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) -#define PIN_TO_DIGITAL(p) (((p) < 16) ? (p) : (p) - 2) -#define PIN_TO_ANALOG(p) ((p) - 16) +#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__) +#elif defined(__AVR_ATmega1280__) #define TOTAL_ANALOG_PINS 16 #define TOTAL_PINS 70 // 54 digital + 16 analog #define VERSION_BLINK_PIN 13 @@ -161,21 +186,13 @@ writePort(port, value, bitmask): Write an 8 bit port. #define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) #define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) #define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) +#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) -// Wiring -#elif defined(__AVR_ATmega128__) -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS 51 -#define VERSION_BLINK_PIN 48 -// TODO: hardware abstraction for wiring board - - // Teensy 1.0 #elif defined(__AVR_AT90USB162__) #define TOTAL_ANALOG_PINS 0 @@ -201,7 +218,7 @@ writePort(port, value, bitmask): Write an 8 bit port. #define IS_PIN_ANALOG(p) ((p) >= 11 && (p) <= 22) #define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) #define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) +#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) @@ -217,7 +234,7 @@ writePort(port, value, bitmask): Write an 8 bit port. #define IS_PIN_ANALOG(p) ((p) >= 38 && (p) < TOTAL_PINS) #define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) #define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) +#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) @@ -233,7 +250,7 @@ writePort(port, value, bitmask): Write an 8 bit port. #define IS_PIN_ANALOG(p) ((p) >= 24 && (p) < TOTAL_PINS) #define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) #define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) +#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) @@ -249,7 +266,7 @@ writePort(port, value, bitmask): Write an 8 bit port. #define IS_PIN_ANALOG(p) ((p) >= 36 && (p) < TOTAL_PINS) #define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) #define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) +#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) @@ -270,9 +287,9 @@ static inline unsigned char readPort(byte, byte) __attribute__((always_inline, u static inline unsigned char readPort(byte port, byte bitmask) { #if defined(ARDUINO_PINOUT_OPTIMIZE) - if (port == 0) return PIND & B11111100 & bitmask; // ignore Rx/Tx 0/1 - if (port == 1) return PINB & B00111111 & bitmask; // pins 8-13 (14,15 are disabled for the crystal) - if (port == 2) return PINC & bitmask; + 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; @@ -297,17 +314,27 @@ static inline unsigned char writePort(byte port, byte value, byte bitmask) { #if defined(ARDUINO_PINOUT_OPTIMIZE) if (port == 0) { - bitmask = bitmask & 0xFC; // Tx & Rx pins + bitmask = bitmask & 0xFC; // do not touch Tx & Rx pins + byte valD = value & bitmask; + byte maskD = ~bitmask; cli(); - PORTD = (PORTD & ~bitmask) | (bitmask & value); + 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 & ~bitmask) | (bitmask & value); + 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 & ~bitmask) | (bitmask & value); + PORTC = (PORTC & maskC) | valC; sei(); } #else diff --git a/libraries/Firmata/Firmata.cpp b/libraries/Firmata/Firmata.cpp index e30deae6c..0d68a5744 100644 --- a/libraries/Firmata/Firmata.cpp +++ b/libraries/Firmata/Firmata.cpp @@ -14,9 +14,8 @@ //* Includes //****************************************************************************** -#include "Arduino.h" -#include "HardwareSerial.h" #include "Firmata.h" +#include "HardwareSerial.h" extern "C" { #include @@ -27,27 +26,27 @@ extern "C" { //* Support Functions //****************************************************************************** -void sendValueAsTwo7bitBytes(int value) +void FirmataClass::sendValueAsTwo7bitBytes(int value) { - Serial.print(value & B01111111, BYTE); // LSB - Serial.print(value >> 7 & B01111111, BYTE); // MSB + FirmataSerial.write(value & B01111111); // LSB + FirmataSerial.write(value >> 7 & B01111111); // MSB } -void startSysex(void) +void FirmataClass::startSysex(void) { - Serial.print(START_SYSEX, BYTE); + FirmataSerial.write(START_SYSEX); } -void endSysex(void) +void FirmataClass::endSysex(void) { - Serial.print(END_SYSEX, BYTE); + FirmataSerial.write(END_SYSEX); } //****************************************************************************** //* Constructors //****************************************************************************** -FirmataClass::FirmataClass(void) +FirmataClass::FirmataClass(Stream &s) : FirmataSerial(s) { firmwareVersionCount = 0; systemReset(); @@ -66,22 +65,27 @@ void FirmataClass::begin(void) /* begin method for overriding default serial bitrate */ void FirmataClass::begin(long speed) { -#if defined(__AVR_ATmega128__) // Wiring - Serial.begin((uint32_t)speed); -#else Serial.begin(speed); -#endif + FirmataSerial = Serial; blinkVersion(); delay(300); 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) { - Serial.print(REPORT_VERSION, BYTE); - Serial.print(FIRMATA_MAJOR_VERSION, BYTE); - Serial.print(FIRMATA_MINOR_VERSION, BYTE); + FirmataSerial.write(REPORT_VERSION); + FirmataSerial.write(FIRMATA_MAJOR_VERSION); + FirmataSerial.write(FIRMATA_MINOR_VERSION); } void FirmataClass::blinkVersion(void) @@ -101,9 +105,9 @@ void FirmataClass::printFirmwareVersion(void) if(firmwareVersionCount) { // make sure that the name has been set before reporting startSysex(); - Serial.print(REPORT_FIRMWARE, BYTE); - Serial.print(firmwareVersionVector[0]); // major version number - Serial.print(firmwareVersionVector[1]); // minor version number + FirmataSerial.write(REPORT_FIRMWARE); + FirmataSerial.write(firmwareVersionVector[0]); // major version number + FirmataSerial.write(firmwareVersionVector[1]); // minor version number for(i=2; i> 7, BYTE); // Tx bits 7-13 + FirmataSerial.write(DIGITAL_MESSAGE | (portNumber & 0xF)); + FirmataSerial.write((byte)portData % 128); // Tx bits 0-6 + FirmataSerial.write(portData >> 7); // Tx bits 7-13 } @@ -308,7 +312,7 @@ void FirmataClass::sendSysex(byte command, byte bytec, byte* bytev) { byte i; startSysex(); - Serial.print(command, BYTE); + FirmataSerial.write(command); for(i=0; i -#include - +#include "Boards.h" /* Hardware Abstraction Layer + Wiring/Arduino */ /* Version numbers for the protocol. The protocol is still changing, so these * version numbers are important. This number can be queried so that host * software can test whether it will be compatible with the currently * installed firmware. */ #define FIRMATA_MAJOR_VERSION 2 // for non-compatible changes -#define FIRMATA_MINOR_VERSION 2 // for backwards compatible changes +#define FIRMATA_MINOR_VERSION 3 // for backwards compatible changes +#define FIRMATA_BUGFIX_VERSION 1 // for bugfix releases #define MAX_DATA_BYTES 32 // max number of data bytes in non-Sysex messages @@ -66,8 +65,8 @@ #define SYSEX_SAMPLING_INTERVAL 0x7A // same as SAMPLING_INTERVAL // pin modes -//#define INPUT 0x00 // defined in Arduino.h -//#define OUTPUT 0x01 // defined in Arduino.h +//#define INPUT 0x00 // defined in wiring.h +//#define OUTPUT 0x01 // defined in wiring.h #define ANALOG 0x02 // analog pin in analogInput mode #define PWM 0x03 // digital pin in PWM output mode #define SERVO 0x04 // digital pin in Servo output mode @@ -88,10 +87,11 @@ extern "C" { class FirmataClass { public: - FirmataClass(); + FirmataClass(Stream &s); /* Arduino constructors */ void begin(); void begin(long); + void begin(Stream &s); /* querying functions */ void printVersion(void); void blinkVersion(void); @@ -116,6 +116,7 @@ public: void detach(byte command); private: + Stream &FirmataSerial; /* firmware name and version */ byte firmwareVersionCount; byte *firmwareVersionVector; @@ -141,6 +142,9 @@ private: void processSysexMessage(void); void systemReset(void); void pin13strobe(int count, int onInterval, int offInterval); + void sendValueAsTwo7bitBytes(int value); + void startSysex(void); + void endSysex(void); }; extern FirmataClass Firmata; @@ -155,8 +159,5 @@ extern FirmataClass Firmata; */ #define setFirmwareVersion(x, y) setFirmwareNameAndVersion(__FILE__, x, y) -/* Hardware Abstraction Layer */ -#include "Boards.h" - #endif /* Firmata_h */ diff --git a/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino b/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino index 5bca72a83..775594938 100644 --- a/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino +++ b/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino @@ -56,7 +56,7 @@ void loop() byte i; for (i=0; i -# -# - Write prototypes for all your functions (or define them before you -# call them). A prototype declares the types of parameters a -# function will take and what type of value it will return. This -# means that you can have a call to a function before the definition -# of the function. A function prototype looks like the first line of -# the function, with a semi-colon at the end. For example: -# int digitalRead(int pin); -# -# Instructions for using the makefile: -# -# 1. Copy this file into the folder with your sketch. -# -# 2. Below, modify the line containing "TARGET" to refer to the name of -# of your program's file without an extension (e.g. TARGET = foo). -# -# 3. Modify the line containg "ARDUINO" to point the directory that -# contains the Arduino core (for normal Arduino installations, this -# is the hardware/cores/arduino sub-directory). -# -# 4. Modify the line containing "PORT" to refer to the filename -# representing the USB or serial connection to your Arduino board -# (e.g. PORT = /dev/tty.USB0). If the exact name of this file -# changes, you can use * as a wildcard (e.g. PORT = /dev/tty.USB*). -# -# 5. At the command line, change to the directory containing your -# program's file and the makefile. -# -# 6. Type "make" and press enter to compile/verify your program. -# -# 7. Type "make upload", reset your Arduino board, and press enter to -# upload your program to the Arduino board. -# -# $Id: Makefile,v 1.7 2007/04/13 05:28:23 eighthave Exp $ - -PORT = /dev/tty.usbserial-* -TARGET := $(shell pwd | sed 's|.*/\(.*\)|\1|') -ARDUINO = /Applications/arduino -ARDUINO_SRC = $(ARDUINO)/hardware/cores/arduino -ARDUINO_LIB_SRC = $(ARDUINO)/hardware/libraries -INCLUDE = -I$(ARDUINO_SRC) -I$(ARDUINO)/hardware/tools/avr/avr/include \ - -I$(ARDUINO_LIB_SRC)/EEPROM \ - -I$(ARDUINO_LIB_SRC)/Firmata \ - -I$(ARDUINO_LIB_SRC)/Servo \ - -I$(ARDUINO_LIB_SRC) -SRC = $(wildcard $(ARDUINO_SRC)/*.c) -CXXSRC = applet/$(TARGET).cpp $(ARDUINO_SRC)/HardwareSerial.cpp \ - $(ARDUINO_LIB_SRC)/EEPROM/EEPROM.cpp \ - $(ARDUINO_LIB_SRC)/Firmata/Firmata.cpp \ - $(ARDUINO_LIB_SRC)/Servo/Servo.cpp \ - $(ARDUINO_SRC)/WMath.cpp -HEADERS = $(wildcard $(ARDUINO_SRC)/*.h) $(wildcard $(ARDUINO_LIB_SRC)/*/*.h) - -MCU = atmega168 -#MCU = atmega8 -F_CPU = 16000000 -FORMAT = ihex -UPLOAD_RATE = 19200 - -# Name of this Makefile (used for "make depend"). -MAKEFILE = Makefile - -# Debugging format. -# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. -# AVR (extended) COFF requires stabs, plus an avr-objcopy run. -DEBUG = stabs - -OPT = s - -# Place -D or -U options here -CDEFS = -DF_CPU=$(F_CPU) -CXXDEFS = -DF_CPU=$(F_CPU) - -# Compiler flag to set the C Standard level. -# c89 - "ANSI" C -# gnu89 - c89 plus GCC extensions -# c99 - ISO C99 standard (not yet fully implemented) -# gnu99 - c99 plus GCC extensions -CSTANDARD = -std=gnu99 -CDEBUG = -g$(DEBUG) -CWARN = -Wall -Wstrict-prototypes -CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -#CEXTRA = -Wa,-adhlns=$(<:.c=.lst) - -CFLAGS = $(CDEBUG) $(CDEFS) $(INCLUDE) -O$(OPT) $(CWARN) $(CSTANDARD) $(CEXTRA) -CXXFLAGS = $(CDEFS) $(INCLUDE) -O$(OPT) -#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs -LDFLAGS = - - -# Programming support using avrdude. Settings and variables. -AVRDUDE_PROGRAMMER = stk500 -AVRDUDE_PORT = $(PORT) -AVRDUDE_WRITE_FLASH = -U flash:w:applet/$(TARGET).hex -AVRDUDE_FLAGS = -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) \ - -b $(UPLOAD_RATE) -q -V - -# Program settings -CC = avr-gcc -CXX = avr-g++ -OBJCOPY = avr-objcopy -OBJDUMP = avr-objdump -SIZE = avr-size -NM = avr-nm -AVRDUDE = avrdude -REMOVE = rm -f -MV = mv -f - -# Define all object files. -OBJ = $(SRC:.c=.o) $(CXXSRC:.cpp=.o) $(ASRC:.S=.o) - -# Define all listing files. -LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) - -# Combine all necessary flags and optional flags. -# Add target processor to flags. -ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) -ALL_CXXFLAGS = -mmcu=$(MCU) -I. $(CXXFLAGS) -ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) - - -# Default target. -all: build - -build: applet/$(TARGET).hex - -eep: applet/$(TARGET).eep -lss: applet/$(TARGET).lss -sym: applet/$(TARGET).sym - - -# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. -COFFCONVERT=$(OBJCOPY) --debugging \ ---change-section-address .data-0x800000 \ ---change-section-address .bss-0x800000 \ ---change-section-address .noinit-0x800000 \ ---change-section-address .eeprom-0x810000 - - -coff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -extcoff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-ext-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -.SUFFIXES: .elf .hex .eep .lss .sym .pde - -.elf.hex: - $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ - -.elf.eep: - -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ - --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ - -# Create extended listing file from ELF output file. -.elf.lss: - $(OBJDUMP) -h -S $< > $@ - -# Create a symbol table from ELF output file. -.elf.sym: - $(NM) -n $< > $@ - - -# Compile: create object files from C++ source files. -.cpp.o: $(HEADERS) - $(CXX) -c $(ALL_CXXFLAGS) $< -o $@ - -# Compile: create object files from C source files. -.c.o: $(HEADERS) - $(CC) -c $(ALL_CFLAGS) $< -o $@ - - -# Compile: create assembler files from C source files. -.c.s: - $(CC) -S $(ALL_CFLAGS) $< -o $@ - - -# Assemble: create object files from assembler source files. -.S.o: - $(CC) -c $(ALL_ASFLAGS) $< -o $@ - - - -applet/$(TARGET).cpp: $(TARGET).pde - test -d applet || mkdir applet - echo '#include "WProgram.h"' > applet/$(TARGET).cpp - echo '#include "avr/interrupt.h"' >> applet/$(TARGET).cpp - sed -n 's|^\(void .*)\).*|\1;|p' $(TARGET).pde | grep -v 'setup()' | \ - grep -v 'loop()' >> applet/$(TARGET).cpp - cat $(TARGET).pde >> applet/$(TARGET).cpp - cat $(ARDUINO_SRC)/main.cxx >> applet/$(TARGET).cpp - -# Link: create ELF output file from object files. -applet/$(TARGET).elf: applet/$(TARGET).cpp $(OBJ) - $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) - -pd_close_serial: - echo 'close;' | /Applications/Pd-extended.app/Contents/Resources/bin/pdsend 34567 || true - -# Program the device. -upload: applet/$(TARGET).hex - $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) - - -pd_test: build pd_close_serial upload - -# Target: clean project. -clean: - $(REMOVE) -- applet/$(TARGET).hex applet/$(TARGET).eep \ - applet/$(TARGET).cof applet/$(TARGET).elf $(TARGET).map \ - applet/$(TARGET).sym applet/$(TARGET).lss applet/$(TARGET).cpp \ - $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) - rmdir -- applet - -depend: - if grep '^# DO NOT DELETE' $(MAKEFILE) >/dev/null; \ - then \ - sed -e '/^# DO NOT DELETE/,$$d' $(MAKEFILE) > \ - $(MAKEFILE).$$$$ && \ - $(MV) $(MAKEFILE).$$$$ $(MAKEFILE); \ - fi - echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' \ - >> $(MAKEFILE); \ - $(CC) -M -mmcu=$(MCU) $(CDEFS) $(INCLUDE) $(SRC) $(ASRC) >> $(MAKEFILE) - -.PHONY: all build eep lss sym coff extcoff clean depend pd_close_serial pd_test - -# for emacs -etags: - make etags_`uname -s` - etags *.pde \ - $(ARDUINO_SRC)/*.[ch] \ - $(ARDUINO_SRC)/*.cpp \ - $(ARDUINO_LIB_SRC)/*/*.[ch] \ - $(ARDUINO_LIB_SRC)/*/*.cpp \ - $(ARDUINO)/hardware/tools/avr/avr/include/avr/*.[ch] \ - $(ARDUINO)/hardware/tools/avr/avr/include/*.[ch] - -etags_Darwin: -# etags -a - -etags_Linux: -# etags -a /usr/include/*.h linux/input.h /usr/include/sys/*.h - -etags_MINGW: -# etags -a /usr/include/*.h /usr/include/sys/*.h - - - diff --git a/libraries/Firmata/examples/EchoString/EchoString.ino b/libraries/Firmata/examples/EchoString/EchoString.ino index e5c4e6fe5..e708ec210 100644 --- a/libraries/Firmata/examples/EchoString/EchoString.ino +++ b/libraries/Firmata/examples/EchoString/EchoString.ino @@ -14,12 +14,7 @@ void stringCallback(char *myString) void sysexCallback(byte command, byte argc, byte*argv) { - Serial.write(START_SYSEX); - Serial.write(command); - for(byte i=0; i -# -# - Write prototypes for all your functions (or define them before you -# call them). A prototype declares the types of parameters a -# function will take and what type of value it will return. This -# means that you can have a call to a function before the definition -# of the function. A function prototype looks like the first line of -# the function, with a semi-colon at the end. For example: -# int digitalRead(int pin); -# -# Instructions for using the makefile: -# -# 1. Copy this file into the folder with your sketch. -# -# 2. Below, modify the line containing "TARGET" to refer to the name of -# of your program's file without an extension (e.g. TARGET = foo). -# -# 3. Modify the line containg "ARDUINO" to point the directory that -# contains the Arduino core (for normal Arduino installations, this -# is the hardware/cores/arduino sub-directory). -# -# 4. Modify the line containing "PORT" to refer to the filename -# representing the USB or serial connection to your Arduino board -# (e.g. PORT = /dev/tty.USB0). If the exact name of this file -# changes, you can use * as a wildcard (e.g. PORT = /dev/tty.USB*). -# -# 5. At the command line, change to the directory containing your -# program's file and the makefile. -# -# 6. Type "make" and press enter to compile/verify your program. -# -# 7. Type "make upload", reset your Arduino board, and press enter to -# upload your program to the Arduino board. -# -# $Id: Makefile,v 1.7 2007/04/13 05:28:23 eighthave Exp $ - -PORT = /dev/tty.usbserial-* -TARGET := $(shell pwd | sed 's|.*/\(.*\)|\1|') -ARDUINO = /Applications/arduino -ARDUINO_SRC = $(ARDUINO)/hardware/cores/arduino -ARDUINO_LIB_SRC = $(ARDUINO)/hardware/libraries -INCLUDE = -I$(ARDUINO_SRC) -I$(ARDUINO)/hardware/tools/avr/avr/include \ - -I$(ARDUINO_LIB_SRC)/EEPROM \ - -I$(ARDUINO_LIB_SRC)/Firmata \ - -I$(ARDUINO_LIB_SRC)/Servo \ - -I$(ARDUINO_LIB_SRC) -SRC = $(wildcard $(ARDUINO_SRC)/*.c) -CXXSRC = applet/$(TARGET).cpp $(ARDUINO_SRC)/HardwareSerial.cpp \ - $(ARDUINO_LIB_SRC)/EEPROM/EEPROM.cpp \ - $(ARDUINO_LIB_SRC)/Firmata/Firmata.cpp \ - $(ARDUINO_LIB_SRC)/Servo/Servo.cpp \ - $(ARDUINO_SRC)/WMath.cpp -HEADERS = $(wildcard $(ARDUINO_SRC)/*.h) $(wildcard $(ARDUINO_LIB_SRC)/*/*.h) - -MCU = atmega168 -#MCU = atmega8 -F_CPU = 16000000 -FORMAT = ihex -UPLOAD_RATE = 19200 - -# Name of this Makefile (used for "make depend"). -MAKEFILE = Makefile - -# Debugging format. -# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. -# AVR (extended) COFF requires stabs, plus an avr-objcopy run. -DEBUG = stabs - -OPT = s - -# Place -D or -U options here -CDEFS = -DF_CPU=$(F_CPU) -CXXDEFS = -DF_CPU=$(F_CPU) - -# Compiler flag to set the C Standard level. -# c89 - "ANSI" C -# gnu89 - c89 plus GCC extensions -# c99 - ISO C99 standard (not yet fully implemented) -# gnu99 - c99 plus GCC extensions -CSTANDARD = -std=gnu99 -CDEBUG = -g$(DEBUG) -CWARN = -Wall -Wstrict-prototypes -CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -#CEXTRA = -Wa,-adhlns=$(<:.c=.lst) - -CFLAGS = $(CDEBUG) $(CDEFS) $(INCLUDE) -O$(OPT) $(CWARN) $(CSTANDARD) $(CEXTRA) -CXXFLAGS = $(CDEFS) $(INCLUDE) -O$(OPT) -#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs -LDFLAGS = - - -# Programming support using avrdude. Settings and variables. -AVRDUDE_PROGRAMMER = stk500 -AVRDUDE_PORT = $(PORT) -AVRDUDE_WRITE_FLASH = -U flash:w:applet/$(TARGET).hex -AVRDUDE_FLAGS = -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) \ - -b $(UPLOAD_RATE) -q -V - -# Program settings -CC = avr-gcc -CXX = avr-g++ -OBJCOPY = avr-objcopy -OBJDUMP = avr-objdump -SIZE = avr-size -NM = avr-nm -AVRDUDE = avrdude -REMOVE = rm -f -MV = mv -f - -# Define all object files. -OBJ = $(SRC:.c=.o) $(CXXSRC:.cpp=.o) $(ASRC:.S=.o) - -# Define all listing files. -LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) - -# Combine all necessary flags and optional flags. -# Add target processor to flags. -ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) -ALL_CXXFLAGS = -mmcu=$(MCU) -I. $(CXXFLAGS) -ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) - - -# Default target. -all: build - -build: applet/$(TARGET).hex - -eep: applet/$(TARGET).eep -lss: applet/$(TARGET).lss -sym: applet/$(TARGET).sym - - -# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. -COFFCONVERT=$(OBJCOPY) --debugging \ ---change-section-address .data-0x800000 \ ---change-section-address .bss-0x800000 \ ---change-section-address .noinit-0x800000 \ ---change-section-address .eeprom-0x810000 - - -coff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -extcoff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-ext-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -.SUFFIXES: .elf .hex .eep .lss .sym .pde - -.elf.hex: - $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ - -.elf.eep: - -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ - --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ - -# Create extended listing file from ELF output file. -.elf.lss: - $(OBJDUMP) -h -S $< > $@ - -# Create a symbol table from ELF output file. -.elf.sym: - $(NM) -n $< > $@ - - -# Compile: create object files from C++ source files. -.cpp.o: $(HEADERS) - $(CXX) -c $(ALL_CXXFLAGS) $< -o $@ - -# Compile: create object files from C source files. -.c.o: $(HEADERS) - $(CC) -c $(ALL_CFLAGS) $< -o $@ - - -# Compile: create assembler files from C source files. -.c.s: - $(CC) -S $(ALL_CFLAGS) $< -o $@ - - -# Assemble: create object files from assembler source files. -.S.o: - $(CC) -c $(ALL_ASFLAGS) $< -o $@ - - - -applet/$(TARGET).cpp: $(TARGET).pde - test -d applet || mkdir applet - echo '#include "WProgram.h"' > applet/$(TARGET).cpp - echo '#include "avr/interrupt.h"' >> applet/$(TARGET).cpp - sed -n 's|^\(void .*)\).*|\1;|p' $(TARGET).pde | grep -v 'setup()' | \ - grep -v 'loop()' >> applet/$(TARGET).cpp - cat $(TARGET).pde >> applet/$(TARGET).cpp - cat $(ARDUINO_SRC)/main.cxx >> applet/$(TARGET).cpp - -# Link: create ELF output file from object files. -applet/$(TARGET).elf: applet/$(TARGET).cpp $(OBJ) - $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) - -pd_close_serial: - echo 'close;' | /Applications/Pd-extended.app/Contents/Resources/bin/pdsend 34567 || true - -# Program the device. -upload: applet/$(TARGET).hex - $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) - - -pd_test: build pd_close_serial upload - -# Target: clean project. -clean: - $(REMOVE) -- applet/$(TARGET).hex applet/$(TARGET).eep \ - applet/$(TARGET).cof applet/$(TARGET).elf $(TARGET).map \ - applet/$(TARGET).sym applet/$(TARGET).lss applet/$(TARGET).cpp \ - $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) - rmdir -- applet - -depend: - if grep '^# DO NOT DELETE' $(MAKEFILE) >/dev/null; \ - then \ - sed -e '/^# DO NOT DELETE/,$$d' $(MAKEFILE) > \ - $(MAKEFILE).$$$$ && \ - $(MV) $(MAKEFILE).$$$$ $(MAKEFILE); \ - fi - echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' \ - >> $(MAKEFILE); \ - $(CC) -M -mmcu=$(MCU) $(CDEFS) $(INCLUDE) $(SRC) $(ASRC) >> $(MAKEFILE) - -.PHONY: all build eep lss sym coff extcoff clean depend pd_close_serial pd_test - -# for emacs -etags: - make etags_`uname -s` - etags *.pde \ - $(ARDUINO_SRC)/*.[ch] \ - $(ARDUINO_SRC)/*.cpp \ - $(ARDUINO_LIB_SRC)/*/*.[ch] \ - $(ARDUINO_LIB_SRC)/*/*.cpp \ - $(ARDUINO)/hardware/tools/avr/avr/include/avr/*.[ch] \ - $(ARDUINO)/hardware/tools/avr/avr/include/*.[ch] - -etags_Darwin: -# etags -a - -etags_Linux: -# etags -a /usr/include/*.h linux/input.h /usr/include/sys/*.h - -etags_MINGW: -# etags -a /usr/include/*.h /usr/include/sys/*.h - - - diff --git a/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino b/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino index 11202e9b2..f2c931b95 100644 --- a/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino +++ b/libraries/Firmata/examples/I2CFirmata/I2CFirmata.ino @@ -48,7 +48,7 @@ void readAndReportData(byte address, int theRegister, byte numBytes) { if (theRegister != REGISTER_NOT_SPECIFIED) { Wire.beginTransmission(address); - Wire.send((byte)theRegister); + Wire.write((byte)theRegister); Wire.endTransmission(); delayMicroseconds(i2cReadDelayTime); // delay is necessary for some devices such as WiiNunchuck } @@ -63,7 +63,7 @@ void readAndReportData(byte address, int theRegister, byte numBytes) i2cRxData[0] = address; i2cRxData[1] = theRegister; for (int i = 0; i < numBytes; i++) { - i2cRxData[2 + i] = Wire.receive(); + i2cRxData[2 + i] = Wire.read(); } // send slave address, register and received bytes Firmata.sendSysex(I2C_REPLY, numBytes + 2, i2cRxData); @@ -95,7 +95,7 @@ void sysexCallback(byte command, byte argc, byte *argv) Wire.beginTransmission(slaveAddress); for (byte i = 2; i < argc; i += 2) { data = argv[i] + (argv[i + 1] << 7); - Wire.send(data); + Wire.write(data); } Wire.endTransmission(); delayMicroseconds(70); // TODO is this needed? diff --git a/libraries/Firmata/examples/ServoFirmata/Makefile b/libraries/Firmata/examples/ServoFirmata/Makefile deleted file mode 100644 index e968c0a3d..000000000 --- a/libraries/Firmata/examples/ServoFirmata/Makefile +++ /dev/null @@ -1,263 +0,0 @@ -# Arduino makefile -# -# This makefile allows you to build sketches from the command line -# without the Arduino environment (or Java). -# -# The Arduino environment does preliminary processing on a sketch before -# compiling it. If you're using this makefile instead, you'll need to do -# a few things differently: -# -# - Give your program's file a .cpp extension (e.g. foo.cpp). -# -# - Put this line at top of your code: #include -# -# - Write prototypes for all your functions (or define them before you -# call them). A prototype declares the types of parameters a -# function will take and what type of value it will return. This -# means that you can have a call to a function before the definition -# of the function. A function prototype looks like the first line of -# the function, with a semi-colon at the end. For example: -# int digitalRead(int pin); -# -# Instructions for using the makefile: -# -# 1. Copy this file into the folder with your sketch. -# -# 2. Below, modify the line containing "TARGET" to refer to the name of -# of your program's file without an extension (e.g. TARGET = foo). -# -# 3. Modify the line containg "ARDUINO" to point the directory that -# contains the Arduino core (for normal Arduino installations, this -# is the hardware/cores/arduino sub-directory). -# -# 4. Modify the line containing "PORT" to refer to the filename -# representing the USB or serial connection to your Arduino board -# (e.g. PORT = /dev/tty.USB0). If the exact name of this file -# changes, you can use * as a wildcard (e.g. PORT = /dev/tty.USB*). -# -# 5. At the command line, change to the directory containing your -# program's file and the makefile. -# -# 6. Type "make" and press enter to compile/verify your program. -# -# 7. Type "make upload", reset your Arduino board, and press enter to -# upload your program to the Arduino board. -# -# $Id: Makefile,v 1.7 2007/04/13 05:28:23 eighthave Exp $ - -PORT = /dev/tty.usbserial-* -TARGET := $(shell pwd | sed 's|.*/\(.*\)|\1|') -ARDUINO = /Applications/arduino -ARDUINO_SRC = $(ARDUINO)/hardware/cores/arduino -ARDUINO_LIB_SRC = $(ARDUINO)/hardware/libraries -INCLUDE = -I$(ARDUINO_SRC) -I$(ARDUINO)/hardware/tools/avr/avr/include \ - -I$(ARDUINO_LIB_SRC)/EEPROM \ - -I$(ARDUINO_LIB_SRC)/Firmata \ - -I$(ARDUINO_LIB_SRC)/Servo \ - -I$(ARDUINO_LIB_SRC) -SRC = $(wildcard $(ARDUINO_SRC)/*.c) -CXXSRC = applet/$(TARGET).cpp $(ARDUINO_SRC)/HardwareSerial.cpp \ - $(ARDUINO_LIB_SRC)/EEPROM/EEPROM.cpp \ - $(ARDUINO_LIB_SRC)/Firmata/Firmata.cpp \ - $(ARDUINO_LIB_SRC)/Servo/Servo.cpp \ - $(ARDUINO_SRC)/WMath.cpp -HEADERS = $(wildcard $(ARDUINO_SRC)/*.h) $(wildcard $(ARDUINO_LIB_SRC)/*/*.h) - -MCU = atmega168 -#MCU = atmega8 -F_CPU = 16000000 -FORMAT = ihex -UPLOAD_RATE = 19200 - -# Name of this Makefile (used for "make depend"). -MAKEFILE = Makefile - -# Debugging format. -# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. -# AVR (extended) COFF requires stabs, plus an avr-objcopy run. -DEBUG = stabs - -OPT = s - -# Place -D or -U options here -CDEFS = -DF_CPU=$(F_CPU) -CXXDEFS = -DF_CPU=$(F_CPU) - -# Compiler flag to set the C Standard level. -# c89 - "ANSI" C -# gnu89 - c89 plus GCC extensions -# c99 - ISO C99 standard (not yet fully implemented) -# gnu99 - c99 plus GCC extensions -CSTANDARD = -std=gnu99 -CDEBUG = -g$(DEBUG) -CWARN = -Wall -Wstrict-prototypes -CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -#CEXTRA = -Wa,-adhlns=$(<:.c=.lst) - -CFLAGS = $(CDEBUG) $(CDEFS) $(INCLUDE) -O$(OPT) $(CWARN) $(CSTANDARD) $(CEXTRA) -CXXFLAGS = $(CDEFS) $(INCLUDE) -O$(OPT) -#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs -LDFLAGS = - - -# Programming support using avrdude. Settings and variables. -AVRDUDE_PROGRAMMER = stk500 -AVRDUDE_PORT = $(PORT) -AVRDUDE_WRITE_FLASH = -U flash:w:applet/$(TARGET).hex -AVRDUDE_FLAGS = -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) \ - -b $(UPLOAD_RATE) -q -V - -# Program settings -CC = avr-gcc -CXX = avr-g++ -OBJCOPY = avr-objcopy -OBJDUMP = avr-objdump -SIZE = avr-size -NM = avr-nm -AVRDUDE = avrdude -REMOVE = rm -f -MV = mv -f - -# Define all object files. -OBJ = $(SRC:.c=.o) $(CXXSRC:.cpp=.o) $(ASRC:.S=.o) - -# Define all listing files. -LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) - -# Combine all necessary flags and optional flags. -# Add target processor to flags. -ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) -ALL_CXXFLAGS = -mmcu=$(MCU) -I. $(CXXFLAGS) -ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) - - -# Default target. -all: build - -build: applet/$(TARGET).hex - -eep: applet/$(TARGET).eep -lss: applet/$(TARGET).lss -sym: applet/$(TARGET).sym - - -# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. -COFFCONVERT=$(OBJCOPY) --debugging \ ---change-section-address .data-0x800000 \ ---change-section-address .bss-0x800000 \ ---change-section-address .noinit-0x800000 \ ---change-section-address .eeprom-0x810000 - - -coff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -extcoff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-ext-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -.SUFFIXES: .elf .hex .eep .lss .sym .pde - -.elf.hex: - $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ - -.elf.eep: - -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ - --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ - -# Create extended listing file from ELF output file. -.elf.lss: - $(OBJDUMP) -h -S $< > $@ - -# Create a symbol table from ELF output file. -.elf.sym: - $(NM) -n $< > $@ - - -# Compile: create object files from C++ source files. -.cpp.o: $(HEADERS) - $(CXX) -c $(ALL_CXXFLAGS) $< -o $@ - -# Compile: create object files from C source files. -.c.o: $(HEADERS) - $(CC) -c $(ALL_CFLAGS) $< -o $@ - - -# Compile: create assembler files from C source files. -.c.s: - $(CC) -S $(ALL_CFLAGS) $< -o $@ - - -# Assemble: create object files from assembler source files. -.S.o: - $(CC) -c $(ALL_ASFLAGS) $< -o $@ - - - -applet/$(TARGET).cpp: $(TARGET).pde - test -d applet || mkdir applet - echo '#include "WProgram.h"' > applet/$(TARGET).cpp - echo '#include "avr/interrupt.h"' >> applet/$(TARGET).cpp - sed -n 's|^\(void .*)\).*|\1;|p' $(TARGET).pde | grep -v 'setup()' | \ - grep -v 'loop()' >> applet/$(TARGET).cpp - cat $(TARGET).pde >> applet/$(TARGET).cpp - cat $(ARDUINO_SRC)/main.cxx >> applet/$(TARGET).cpp - -# Link: create ELF output file from object files. -applet/$(TARGET).elf: applet/$(TARGET).cpp $(OBJ) - $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) - -pd_close_serial: - echo 'close;' | /Applications/Pd-extended.app/Contents/Resources/bin/pdsend 34567 || true - -# Program the device. -upload: applet/$(TARGET).hex - $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) - - -pd_test: build pd_close_serial upload - -# Target: clean project. -clean: - $(REMOVE) -- applet/$(TARGET).hex applet/$(TARGET).eep \ - applet/$(TARGET).cof applet/$(TARGET).elf $(TARGET).map \ - applet/$(TARGET).sym applet/$(TARGET).lss applet/$(TARGET).cpp \ - $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) - rmdir -- applet - -depend: - if grep '^# DO NOT DELETE' $(MAKEFILE) >/dev/null; \ - then \ - sed -e '/^# DO NOT DELETE/,$$d' $(MAKEFILE) > \ - $(MAKEFILE).$$$$ && \ - $(MV) $(MAKEFILE).$$$$ $(MAKEFILE); \ - fi - echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' \ - >> $(MAKEFILE); \ - $(CC) -M -mmcu=$(MCU) $(CDEFS) $(INCLUDE) $(SRC) $(ASRC) >> $(MAKEFILE) - -.PHONY: all build eep lss sym coff extcoff clean depend pd_close_serial pd_test - -# for emacs -etags: - make etags_`uname -s` - etags *.pde \ - $(ARDUINO_SRC)/*.[ch] \ - $(ARDUINO_SRC)/*.cpp \ - $(ARDUINO_LIB_SRC)/*/*.[ch] \ - $(ARDUINO_LIB_SRC)/*/*.cpp \ - $(ARDUINO)/hardware/tools/avr/avr/include/avr/*.[ch] \ - $(ARDUINO)/hardware/tools/avr/avr/include/*.[ch] - -etags_Darwin: -# etags -a - -etags_Linux: -# etags -a /usr/include/*.h linux/input.h /usr/include/sys/*.h - -etags_MINGW: -# etags -a /usr/include/*.h /usr/include/sys/*.h - - - diff --git a/libraries/Firmata/examples/SimpleAnalogFirmata/Makefile b/libraries/Firmata/examples/SimpleAnalogFirmata/Makefile deleted file mode 100644 index e968c0a3d..000000000 --- a/libraries/Firmata/examples/SimpleAnalogFirmata/Makefile +++ /dev/null @@ -1,263 +0,0 @@ -# Arduino makefile -# -# This makefile allows you to build sketches from the command line -# without the Arduino environment (or Java). -# -# The Arduino environment does preliminary processing on a sketch before -# compiling it. If you're using this makefile instead, you'll need to do -# a few things differently: -# -# - Give your program's file a .cpp extension (e.g. foo.cpp). -# -# - Put this line at top of your code: #include -# -# - Write prototypes for all your functions (or define them before you -# call them). A prototype declares the types of parameters a -# function will take and what type of value it will return. This -# means that you can have a call to a function before the definition -# of the function. A function prototype looks like the first line of -# the function, with a semi-colon at the end. For example: -# int digitalRead(int pin); -# -# Instructions for using the makefile: -# -# 1. Copy this file into the folder with your sketch. -# -# 2. Below, modify the line containing "TARGET" to refer to the name of -# of your program's file without an extension (e.g. TARGET = foo). -# -# 3. Modify the line containg "ARDUINO" to point the directory that -# contains the Arduino core (for normal Arduino installations, this -# is the hardware/cores/arduino sub-directory). -# -# 4. Modify the line containing "PORT" to refer to the filename -# representing the USB or serial connection to your Arduino board -# (e.g. PORT = /dev/tty.USB0). If the exact name of this file -# changes, you can use * as a wildcard (e.g. PORT = /dev/tty.USB*). -# -# 5. At the command line, change to the directory containing your -# program's file and the makefile. -# -# 6. Type "make" and press enter to compile/verify your program. -# -# 7. Type "make upload", reset your Arduino board, and press enter to -# upload your program to the Arduino board. -# -# $Id: Makefile,v 1.7 2007/04/13 05:28:23 eighthave Exp $ - -PORT = /dev/tty.usbserial-* -TARGET := $(shell pwd | sed 's|.*/\(.*\)|\1|') -ARDUINO = /Applications/arduino -ARDUINO_SRC = $(ARDUINO)/hardware/cores/arduino -ARDUINO_LIB_SRC = $(ARDUINO)/hardware/libraries -INCLUDE = -I$(ARDUINO_SRC) -I$(ARDUINO)/hardware/tools/avr/avr/include \ - -I$(ARDUINO_LIB_SRC)/EEPROM \ - -I$(ARDUINO_LIB_SRC)/Firmata \ - -I$(ARDUINO_LIB_SRC)/Servo \ - -I$(ARDUINO_LIB_SRC) -SRC = $(wildcard $(ARDUINO_SRC)/*.c) -CXXSRC = applet/$(TARGET).cpp $(ARDUINO_SRC)/HardwareSerial.cpp \ - $(ARDUINO_LIB_SRC)/EEPROM/EEPROM.cpp \ - $(ARDUINO_LIB_SRC)/Firmata/Firmata.cpp \ - $(ARDUINO_LIB_SRC)/Servo/Servo.cpp \ - $(ARDUINO_SRC)/WMath.cpp -HEADERS = $(wildcard $(ARDUINO_SRC)/*.h) $(wildcard $(ARDUINO_LIB_SRC)/*/*.h) - -MCU = atmega168 -#MCU = atmega8 -F_CPU = 16000000 -FORMAT = ihex -UPLOAD_RATE = 19200 - -# Name of this Makefile (used for "make depend"). -MAKEFILE = Makefile - -# Debugging format. -# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. -# AVR (extended) COFF requires stabs, plus an avr-objcopy run. -DEBUG = stabs - -OPT = s - -# Place -D or -U options here -CDEFS = -DF_CPU=$(F_CPU) -CXXDEFS = -DF_CPU=$(F_CPU) - -# Compiler flag to set the C Standard level. -# c89 - "ANSI" C -# gnu89 - c89 plus GCC extensions -# c99 - ISO C99 standard (not yet fully implemented) -# gnu99 - c99 plus GCC extensions -CSTANDARD = -std=gnu99 -CDEBUG = -g$(DEBUG) -CWARN = -Wall -Wstrict-prototypes -CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -#CEXTRA = -Wa,-adhlns=$(<:.c=.lst) - -CFLAGS = $(CDEBUG) $(CDEFS) $(INCLUDE) -O$(OPT) $(CWARN) $(CSTANDARD) $(CEXTRA) -CXXFLAGS = $(CDEFS) $(INCLUDE) -O$(OPT) -#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs -LDFLAGS = - - -# Programming support using avrdude. Settings and variables. -AVRDUDE_PROGRAMMER = stk500 -AVRDUDE_PORT = $(PORT) -AVRDUDE_WRITE_FLASH = -U flash:w:applet/$(TARGET).hex -AVRDUDE_FLAGS = -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) \ - -b $(UPLOAD_RATE) -q -V - -# Program settings -CC = avr-gcc -CXX = avr-g++ -OBJCOPY = avr-objcopy -OBJDUMP = avr-objdump -SIZE = avr-size -NM = avr-nm -AVRDUDE = avrdude -REMOVE = rm -f -MV = mv -f - -# Define all object files. -OBJ = $(SRC:.c=.o) $(CXXSRC:.cpp=.o) $(ASRC:.S=.o) - -# Define all listing files. -LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) - -# Combine all necessary flags and optional flags. -# Add target processor to flags. -ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) -ALL_CXXFLAGS = -mmcu=$(MCU) -I. $(CXXFLAGS) -ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) - - -# Default target. -all: build - -build: applet/$(TARGET).hex - -eep: applet/$(TARGET).eep -lss: applet/$(TARGET).lss -sym: applet/$(TARGET).sym - - -# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. -COFFCONVERT=$(OBJCOPY) --debugging \ ---change-section-address .data-0x800000 \ ---change-section-address .bss-0x800000 \ ---change-section-address .noinit-0x800000 \ ---change-section-address .eeprom-0x810000 - - -coff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -extcoff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-ext-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -.SUFFIXES: .elf .hex .eep .lss .sym .pde - -.elf.hex: - $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ - -.elf.eep: - -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ - --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ - -# Create extended listing file from ELF output file. -.elf.lss: - $(OBJDUMP) -h -S $< > $@ - -# Create a symbol table from ELF output file. -.elf.sym: - $(NM) -n $< > $@ - - -# Compile: create object files from C++ source files. -.cpp.o: $(HEADERS) - $(CXX) -c $(ALL_CXXFLAGS) $< -o $@ - -# Compile: create object files from C source files. -.c.o: $(HEADERS) - $(CC) -c $(ALL_CFLAGS) $< -o $@ - - -# Compile: create assembler files from C source files. -.c.s: - $(CC) -S $(ALL_CFLAGS) $< -o $@ - - -# Assemble: create object files from assembler source files. -.S.o: - $(CC) -c $(ALL_ASFLAGS) $< -o $@ - - - -applet/$(TARGET).cpp: $(TARGET).pde - test -d applet || mkdir applet - echo '#include "WProgram.h"' > applet/$(TARGET).cpp - echo '#include "avr/interrupt.h"' >> applet/$(TARGET).cpp - sed -n 's|^\(void .*)\).*|\1;|p' $(TARGET).pde | grep -v 'setup()' | \ - grep -v 'loop()' >> applet/$(TARGET).cpp - cat $(TARGET).pde >> applet/$(TARGET).cpp - cat $(ARDUINO_SRC)/main.cxx >> applet/$(TARGET).cpp - -# Link: create ELF output file from object files. -applet/$(TARGET).elf: applet/$(TARGET).cpp $(OBJ) - $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) - -pd_close_serial: - echo 'close;' | /Applications/Pd-extended.app/Contents/Resources/bin/pdsend 34567 || true - -# Program the device. -upload: applet/$(TARGET).hex - $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) - - -pd_test: build pd_close_serial upload - -# Target: clean project. -clean: - $(REMOVE) -- applet/$(TARGET).hex applet/$(TARGET).eep \ - applet/$(TARGET).cof applet/$(TARGET).elf $(TARGET).map \ - applet/$(TARGET).sym applet/$(TARGET).lss applet/$(TARGET).cpp \ - $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) - rmdir -- applet - -depend: - if grep '^# DO NOT DELETE' $(MAKEFILE) >/dev/null; \ - then \ - sed -e '/^# DO NOT DELETE/,$$d' $(MAKEFILE) > \ - $(MAKEFILE).$$$$ && \ - $(MV) $(MAKEFILE).$$$$ $(MAKEFILE); \ - fi - echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' \ - >> $(MAKEFILE); \ - $(CC) -M -mmcu=$(MCU) $(CDEFS) $(INCLUDE) $(SRC) $(ASRC) >> $(MAKEFILE) - -.PHONY: all build eep lss sym coff extcoff clean depend pd_close_serial pd_test - -# for emacs -etags: - make etags_`uname -s` - etags *.pde \ - $(ARDUINO_SRC)/*.[ch] \ - $(ARDUINO_SRC)/*.cpp \ - $(ARDUINO_LIB_SRC)/*/*.[ch] \ - $(ARDUINO_LIB_SRC)/*/*.cpp \ - $(ARDUINO)/hardware/tools/avr/avr/include/avr/*.[ch] \ - $(ARDUINO)/hardware/tools/avr/avr/include/*.[ch] - -etags_Darwin: -# etags -a - -etags_Linux: -# etags -a /usr/include/*.h linux/input.h /usr/include/sys/*.h - -etags_MINGW: -# etags -a /usr/include/*.h /usr/include/sys/*.h - - - diff --git a/libraries/Firmata/examples/SimpleDigitalFirmata/Makefile b/libraries/Firmata/examples/SimpleDigitalFirmata/Makefile deleted file mode 100644 index e968c0a3d..000000000 --- a/libraries/Firmata/examples/SimpleDigitalFirmata/Makefile +++ /dev/null @@ -1,263 +0,0 @@ -# Arduino makefile -# -# This makefile allows you to build sketches from the command line -# without the Arduino environment (or Java). -# -# The Arduino environment does preliminary processing on a sketch before -# compiling it. If you're using this makefile instead, you'll need to do -# a few things differently: -# -# - Give your program's file a .cpp extension (e.g. foo.cpp). -# -# - Put this line at top of your code: #include -# -# - Write prototypes for all your functions (or define them before you -# call them). A prototype declares the types of parameters a -# function will take and what type of value it will return. This -# means that you can have a call to a function before the definition -# of the function. A function prototype looks like the first line of -# the function, with a semi-colon at the end. For example: -# int digitalRead(int pin); -# -# Instructions for using the makefile: -# -# 1. Copy this file into the folder with your sketch. -# -# 2. Below, modify the line containing "TARGET" to refer to the name of -# of your program's file without an extension (e.g. TARGET = foo). -# -# 3. Modify the line containg "ARDUINO" to point the directory that -# contains the Arduino core (for normal Arduino installations, this -# is the hardware/cores/arduino sub-directory). -# -# 4. Modify the line containing "PORT" to refer to the filename -# representing the USB or serial connection to your Arduino board -# (e.g. PORT = /dev/tty.USB0). If the exact name of this file -# changes, you can use * as a wildcard (e.g. PORT = /dev/tty.USB*). -# -# 5. At the command line, change to the directory containing your -# program's file and the makefile. -# -# 6. Type "make" and press enter to compile/verify your program. -# -# 7. Type "make upload", reset your Arduino board, and press enter to -# upload your program to the Arduino board. -# -# $Id: Makefile,v 1.7 2007/04/13 05:28:23 eighthave Exp $ - -PORT = /dev/tty.usbserial-* -TARGET := $(shell pwd | sed 's|.*/\(.*\)|\1|') -ARDUINO = /Applications/arduino -ARDUINO_SRC = $(ARDUINO)/hardware/cores/arduino -ARDUINO_LIB_SRC = $(ARDUINO)/hardware/libraries -INCLUDE = -I$(ARDUINO_SRC) -I$(ARDUINO)/hardware/tools/avr/avr/include \ - -I$(ARDUINO_LIB_SRC)/EEPROM \ - -I$(ARDUINO_LIB_SRC)/Firmata \ - -I$(ARDUINO_LIB_SRC)/Servo \ - -I$(ARDUINO_LIB_SRC) -SRC = $(wildcard $(ARDUINO_SRC)/*.c) -CXXSRC = applet/$(TARGET).cpp $(ARDUINO_SRC)/HardwareSerial.cpp \ - $(ARDUINO_LIB_SRC)/EEPROM/EEPROM.cpp \ - $(ARDUINO_LIB_SRC)/Firmata/Firmata.cpp \ - $(ARDUINO_LIB_SRC)/Servo/Servo.cpp \ - $(ARDUINO_SRC)/WMath.cpp -HEADERS = $(wildcard $(ARDUINO_SRC)/*.h) $(wildcard $(ARDUINO_LIB_SRC)/*/*.h) - -MCU = atmega168 -#MCU = atmega8 -F_CPU = 16000000 -FORMAT = ihex -UPLOAD_RATE = 19200 - -# Name of this Makefile (used for "make depend"). -MAKEFILE = Makefile - -# Debugging format. -# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. -# AVR (extended) COFF requires stabs, plus an avr-objcopy run. -DEBUG = stabs - -OPT = s - -# Place -D or -U options here -CDEFS = -DF_CPU=$(F_CPU) -CXXDEFS = -DF_CPU=$(F_CPU) - -# Compiler flag to set the C Standard level. -# c89 - "ANSI" C -# gnu89 - c89 plus GCC extensions -# c99 - ISO C99 standard (not yet fully implemented) -# gnu99 - c99 plus GCC extensions -CSTANDARD = -std=gnu99 -CDEBUG = -g$(DEBUG) -CWARN = -Wall -Wstrict-prototypes -CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -#CEXTRA = -Wa,-adhlns=$(<:.c=.lst) - -CFLAGS = $(CDEBUG) $(CDEFS) $(INCLUDE) -O$(OPT) $(CWARN) $(CSTANDARD) $(CEXTRA) -CXXFLAGS = $(CDEFS) $(INCLUDE) -O$(OPT) -#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs -LDFLAGS = - - -# Programming support using avrdude. Settings and variables. -AVRDUDE_PROGRAMMER = stk500 -AVRDUDE_PORT = $(PORT) -AVRDUDE_WRITE_FLASH = -U flash:w:applet/$(TARGET).hex -AVRDUDE_FLAGS = -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) \ - -b $(UPLOAD_RATE) -q -V - -# Program settings -CC = avr-gcc -CXX = avr-g++ -OBJCOPY = avr-objcopy -OBJDUMP = avr-objdump -SIZE = avr-size -NM = avr-nm -AVRDUDE = avrdude -REMOVE = rm -f -MV = mv -f - -# Define all object files. -OBJ = $(SRC:.c=.o) $(CXXSRC:.cpp=.o) $(ASRC:.S=.o) - -# Define all listing files. -LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) - -# Combine all necessary flags and optional flags. -# Add target processor to flags. -ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) -ALL_CXXFLAGS = -mmcu=$(MCU) -I. $(CXXFLAGS) -ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) - - -# Default target. -all: build - -build: applet/$(TARGET).hex - -eep: applet/$(TARGET).eep -lss: applet/$(TARGET).lss -sym: applet/$(TARGET).sym - - -# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. -COFFCONVERT=$(OBJCOPY) --debugging \ ---change-section-address .data-0x800000 \ ---change-section-address .bss-0x800000 \ ---change-section-address .noinit-0x800000 \ ---change-section-address .eeprom-0x810000 - - -coff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -extcoff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-ext-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -.SUFFIXES: .elf .hex .eep .lss .sym .pde - -.elf.hex: - $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ - -.elf.eep: - -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ - --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ - -# Create extended listing file from ELF output file. -.elf.lss: - $(OBJDUMP) -h -S $< > $@ - -# Create a symbol table from ELF output file. -.elf.sym: - $(NM) -n $< > $@ - - -# Compile: create object files from C++ source files. -.cpp.o: $(HEADERS) - $(CXX) -c $(ALL_CXXFLAGS) $< -o $@ - -# Compile: create object files from C source files. -.c.o: $(HEADERS) - $(CC) -c $(ALL_CFLAGS) $< -o $@ - - -# Compile: create assembler files from C source files. -.c.s: - $(CC) -S $(ALL_CFLAGS) $< -o $@ - - -# Assemble: create object files from assembler source files. -.S.o: - $(CC) -c $(ALL_ASFLAGS) $< -o $@ - - - -applet/$(TARGET).cpp: $(TARGET).pde - test -d applet || mkdir applet - echo '#include "WProgram.h"' > applet/$(TARGET).cpp - echo '#include "avr/interrupt.h"' >> applet/$(TARGET).cpp - sed -n 's|^\(void .*)\).*|\1;|p' $(TARGET).pde | grep -v 'setup()' | \ - grep -v 'loop()' >> applet/$(TARGET).cpp - cat $(TARGET).pde >> applet/$(TARGET).cpp - cat $(ARDUINO_SRC)/main.cxx >> applet/$(TARGET).cpp - -# Link: create ELF output file from object files. -applet/$(TARGET).elf: applet/$(TARGET).cpp $(OBJ) - $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) - -pd_close_serial: - echo 'close;' | /Applications/Pd-extended.app/Contents/Resources/bin/pdsend 34567 || true - -# Program the device. -upload: applet/$(TARGET).hex - $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) - - -pd_test: build pd_close_serial upload - -# Target: clean project. -clean: - $(REMOVE) -- applet/$(TARGET).hex applet/$(TARGET).eep \ - applet/$(TARGET).cof applet/$(TARGET).elf $(TARGET).map \ - applet/$(TARGET).sym applet/$(TARGET).lss applet/$(TARGET).cpp \ - $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) - rmdir -- applet - -depend: - if grep '^# DO NOT DELETE' $(MAKEFILE) >/dev/null; \ - then \ - sed -e '/^# DO NOT DELETE/,$$d' $(MAKEFILE) > \ - $(MAKEFILE).$$$$ && \ - $(MV) $(MAKEFILE).$$$$ $(MAKEFILE); \ - fi - echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' \ - >> $(MAKEFILE); \ - $(CC) -M -mmcu=$(MCU) $(CDEFS) $(INCLUDE) $(SRC) $(ASRC) >> $(MAKEFILE) - -.PHONY: all build eep lss sym coff extcoff clean depend pd_close_serial pd_test - -# for emacs -etags: - make etags_`uname -s` - etags *.pde \ - $(ARDUINO_SRC)/*.[ch] \ - $(ARDUINO_SRC)/*.cpp \ - $(ARDUINO_LIB_SRC)/*/*.[ch] \ - $(ARDUINO_LIB_SRC)/*/*.cpp \ - $(ARDUINO)/hardware/tools/avr/avr/include/avr/*.[ch] \ - $(ARDUINO)/hardware/tools/avr/avr/include/*.[ch] - -etags_Darwin: -# etags -a - -etags_Linux: -# etags -a /usr/include/*.h linux/input.h /usr/include/sys/*.h - -etags_MINGW: -# etags -a /usr/include/*.h /usr/include/sys/*.h - - - diff --git a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino index 64b566ee3..bbe42ed8d 100644 --- a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino +++ b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino @@ -52,7 +52,7 @@ void loop() byte i; for (i=0; i -# -# - Write prototypes for all your functions (or define them before you -# call them). A prototype declares the types of parameters a -# function will take and what type of value it will return. This -# means that you can have a call to a function before the definition -# of the function. A function prototype looks like the first line of -# the function, with a semi-colon at the end. For example: -# int digitalRead(int pin); -# -# Instructions for using the makefile: -# -# 1. Copy this file into the folder with your sketch. -# -# 2. Below, modify the line containing "TARGET" to refer to the name of -# of your program's file without an extension (e.g. TARGET = foo). -# -# 3. Modify the line containg "ARDUINO" to point the directory that -# contains the Arduino core (for normal Arduino installations, this -# is the hardware/cores/arduino sub-directory). -# -# 4. Modify the line containing "PORT" to refer to the filename -# representing the USB or serial connection to your Arduino board -# (e.g. PORT = /dev/tty.USB0). If the exact name of this file -# changes, you can use * as a wildcard (e.g. PORT = /dev/tty.USB*). -# -# 5. At the command line, change to the directory containing your -# program's file and the makefile. -# -# 6. Type "make" and press enter to compile/verify your program. -# -# 7. Type "make upload", reset your Arduino board, and press enter to -# upload your program to the Arduino board. -# -# $Id: Makefile,v 1.7 2007/04/13 05:28:23 eighthave Exp $ - -PORT = /dev/tty.usbserial-* -TARGET := $(shell pwd | sed 's|.*/\(.*\)|\1|') -ARDUINO = /Applications/arduino -ARDUINO_SRC = $(ARDUINO)/hardware/cores/arduino -ARDUINO_LIB_SRC = $(ARDUINO)/hardware/libraries -ARDUINO_TOOLS = $(ARDUINO)/hardware/tools -INCLUDE = -I$(ARDUINO_SRC) -I$(ARDUINO)/hardware/tools/avr/avr/include \ - -I$(ARDUINO_LIB_SRC)/EEPROM \ - -I$(ARDUINO_LIB_SRC)/Firmata \ - -I$(ARDUINO_LIB_SRC)/Matrix \ - -I$(ARDUINO_LIB_SRC)/Servo \ - -I$(ARDUINO_LIB_SRC)/Wire \ - -I$(ARDUINO_LIB_SRC) -SRC = $(wildcard $(ARDUINO_SRC)/*.c) -CXXSRC = applet/$(TARGET).cpp $(ARDUINO_SRC)/HardwareSerial.cpp \ - $(ARDUINO_LIB_SRC)/EEPROM/EEPROM.cpp \ - $(ARDUINO_LIB_SRC)/Firmata/Firmata.cpp \ - $(ARDUINO_LIB_SRC)/Servo/Servo.cpp \ - $(ARDUINO_SRC)/Print.cpp \ - $(ARDUINO_SRC)/WMath.cpp -HEADERS = $(wildcard $(ARDUINO_SRC)/*.h) $(wildcard $(ARDUINO_LIB_SRC)/*/*.h) - -MCU = atmega168 -#MCU = atmega8 -F_CPU = 16000000 -FORMAT = ihex -UPLOAD_RATE = 19200 - -# Name of this Makefile (used for "make depend"). -MAKEFILE = Makefile - -# Debugging format. -# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. -# AVR (extended) COFF requires stabs, plus an avr-objcopy run. -DEBUG = stabs - -OPT = s - -# Place -D or -U options here -CDEFS = -DF_CPU=$(F_CPU) -CXXDEFS = -DF_CPU=$(F_CPU) - -# Compiler flag to set the C Standard level. -# c89 - "ANSI" C -# gnu89 - c89 plus GCC extensions -# c99 - ISO C99 standard (not yet fully implemented) -# gnu99 - c99 plus GCC extensions -CSTANDARD = -std=gnu99 -CDEBUG = -g$(DEBUG) -CWARN = -Wall -Wstrict-prototypes -CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -#CEXTRA = -Wa,-adhlns=$(<:.c=.lst) - -CFLAGS = $(CDEBUG) $(CDEFS) $(INCLUDE) -O$(OPT) $(CWARN) $(CSTANDARD) $(CEXTRA) -CXXFLAGS = $(CDEFS) $(INCLUDE) -O$(OPT) -#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs -LDFLAGS = - - -# Programming support using avrdude. Settings and variables. -AVRDUDE_PROGRAMMER = stk500 -AVRDUDE_PORT = $(PORT) -AVRDUDE_WRITE_FLASH = -U flash:w:applet/$(TARGET).hex -AVRDUDE_FLAGS = -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) \ - -b $(UPLOAD_RATE) -q -V - -# Program settings -ARDUINO_AVR_BIN = $(ARDUINO_TOOLS)/avr/bin -CC = $(ARDUINO_AVR_BIN)/avr-gcc -CXX = $(ARDUINO_AVR_BIN)/avr-g++ -OBJCOPY = $(ARDUINO_AVR_BIN)/avr-objcopy -OBJDUMP = $(ARDUINO_AVR_BIN)/avr-objdump -SIZE = $(ARDUINO_AVR_BIN)/avr-size -NM = $(ARDUINO_AVR_BIN)/avr-nm -#AVRDUDE = $(ARDUINO_AVR_BIN)/avrdude -AVRDUDE = avrdude -REMOVE = rm -f -MV = mv -f - -# Define all object files. -OBJ = $(SRC:.c=.o) $(CXXSRC:.cpp=.o) $(ASRC:.S=.o) - -# Define all listing files. -LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) - -# Combine all necessary flags and optional flags. -# Add target processor to flags. -ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) -ALL_CXXFLAGS = -mmcu=$(MCU) -I. $(CXXFLAGS) -ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) - - -# Default target. -all: build - -build: applet/$(TARGET).hex - -eep: applet/$(TARGET).eep -lss: applet/$(TARGET).lss -sym: applet/$(TARGET).sym - - -# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. -COFFCONVERT=$(OBJCOPY) --debugging \ ---change-section-address .data-0x800000 \ ---change-section-address .bss-0x800000 \ ---change-section-address .noinit-0x800000 \ ---change-section-address .eeprom-0x810000 - - -coff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -extcoff: applet/$(TARGET).elf - $(COFFCONVERT) -O coff-ext-avr applet/$(TARGET).elf applet/$(TARGET).cof - - -.SUFFIXES: .elf .hex .eep .lss .sym .pde - -.elf.hex: - $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ - -.elf.eep: - -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ - --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ - -# Create extended listing file from ELF output file. -.elf.lss: - $(OBJDUMP) -h -S $< > $@ - -# Create a symbol table from ELF output file. -.elf.sym: - $(NM) -n $< > $@ - - -# Compile: create object files from C++ source files. -.cpp.o: $(HEADERS) - $(CXX) -c $(ALL_CXXFLAGS) $< -o $@ - -# Compile: create object files from C source files. -.c.o: $(HEADERS) - $(CC) -c $(ALL_CFLAGS) $< -o $@ - - -# Compile: create assembler files from C source files. -.c.s: - $(CC) -S $(ALL_CFLAGS) $< -o $@ - - -# Assemble: create object files from assembler source files. -.S.o: - $(CC) -c $(ALL_ASFLAGS) $< -o $@ - - - -applet/$(TARGET).cpp: $(TARGET).pde - test -d applet || mkdir applet - echo '#include "WProgram.h"' > applet/$(TARGET).cpp - echo '#include "avr/interrupt.h"' >> applet/$(TARGET).cpp - sed -n 's|^\(void .*)\).*|\1;|p' $(TARGET).pde | grep -v 'setup()' | \ - grep -v 'loop()' >> applet/$(TARGET).cpp - cat $(TARGET).pde >> applet/$(TARGET).cpp - cat $(ARDUINO_SRC)/main.cxx >> applet/$(TARGET).cpp - -# Link: create ELF output file from object files. -applet/$(TARGET).elf: applet/$(TARGET).cpp $(OBJ) - $(CC) $(ALL_CFLAGS) $(OBJ) -lm --output $@ $(LDFLAGS) -# $(CC) $(ALL_CFLAGS) $(OBJ) $(ARDUINO_TOOLS)/avr/avr/lib/avr5/crtm168.o --output $@ $(LDFLAGS) - -pd_close_serial: - echo 'close;' | /Applications/Pd-extended.app/Contents/Resources/bin/pdsend 34567 || true - -# Program the device. -upload: applet/$(TARGET).hex - $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) - - -pd_test: build pd_close_serial upload - -# Target: clean project. -clean: - $(REMOVE) -- applet/$(TARGET).hex applet/$(TARGET).eep \ - applet/$(TARGET).cof applet/$(TARGET).elf $(TARGET).map \ - applet/$(TARGET).sym applet/$(TARGET).lss applet/$(TARGET).cpp \ - $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) - rmdir -- applet - -depend: - if grep '^# DO NOT DELETE' $(MAKEFILE) >/dev/null; \ - then \ - sed -e '/^# DO NOT DELETE/,$$d' $(MAKEFILE) > \ - $(MAKEFILE).$$$$ && \ - $(MV) $(MAKEFILE).$$$$ $(MAKEFILE); \ - fi - echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' \ - >> $(MAKEFILE); \ - $(CC) -M -mmcu=$(MCU) $(CDEFS) $(INCLUDE) $(SRC) $(ASRC) >> $(MAKEFILE) - -.PHONY: all build eep lss sym coff extcoff clean depend pd_close_serial pd_test - -# for emacs -etags: - make etags_`uname -s` - etags *.pde \ - $(ARDUINO_SRC)/*.[ch] \ - $(ARDUINO_SRC)/*.cpp \ - $(ARDUINO_LIB_SRC)/*/*.[ch] \ - $(ARDUINO_LIB_SRC)/*/*.cpp \ - $(ARDUINO)/hardware/tools/avr/avr/include/avr/*.[ch] \ - $(ARDUINO)/hardware/tools/avr/avr/include/*.[ch] - -etags_Darwin: -# etags -a - -etags_Linux: -# etags -a /usr/include/*.h linux/input.h /usr/include/sys/*.h - -etags_MINGW: -# etags -a /usr/include/*.h /usr/include/sys/*.h - - -path: - echo $(PATH) - echo $$PATH - diff --git a/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino b/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino index cd433663f..51f090c31 100644 --- a/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino +++ b/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino @@ -323,7 +323,7 @@ void setup() { byte i; - Firmata.setFirmwareVersion(2, 2); + Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION); Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); diff --git a/libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.ino b/libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.ino deleted file mode 100644 index 4cfa6581b..000000000 --- a/libraries/Firmata/examples/StandardFirmata_2_2_forUNO_0_3/StandardFirmata_2_2_forUNO_0_3.ino +++ /dev/null @@ -1,436 +0,0 @@ -/* - This introduces modifications on the normal Firmata made for Arduino so that the LED - blinks until receiving the first command over serial. - - Copyright (C) 2010 David Cuartielles. All rights reserved. - - based at 99.9% on Firmata by HC Steiner according to the following license terms: - - 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. - - formatted using the GNU C formatting and indenting -*/ - -/* - * TODO: use Program Control to load stored profiles from EEPROM - */ - -#include -#include - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* has the command arrived? */ -boolean firstCommand = false; -int dataOnSerial = 0; -boolean statusLed = false; - -/* 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) -unsigned long toggleMillis; - -Servo servos[MAX_SERVOS]; - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void toggleLed() -{ - if (millis() - toggleMillis > 500) { - statusLed = !statusLed; - digitalWrite(13, statusLed); - toggleMillis = millis(); - } -} - -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 (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)); - } else { - Firmata.sendString("Servo only on pins from 2 to 13"); - } - } - break; - case I2C: - pinConfig[pin] = mode; - Firmata.sendString("I2C mode not yet supported"); - 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) -{ - switch(command) { - 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)) { - // servos are pins from 2 to 13, so offset for array - 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); - 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); - } - 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; - } -} - -/*============================================================================== - * SETUP() - *============================================================================*/ -void setup() -{ - byte i; - - Firmata.setFirmwareVersion(2, 2); - - 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); - - // TODO: load state from EEPROM here - - /* these are initialized to zero by the compiler startup code - for (i=0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; - portConfigInputs[i] = 0; - previousPINs[i] = 0; - } - */ - for (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 defult, do not report any analog inputs - analogInputsToReport = 0; - - Firmata.begin(57600); - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - for (i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - - /* init the toggleLed counter */ - toggleMillis = millis(); - pinMode(13, OUTPUT); -} - -/*============================================================================== - * 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(); - - //XXX: hack Firmata to blink until serial command arrives - dataOnSerial = Firmata.available(); - if (dataOnSerial > 0 && !firstCommand) { - firstCommand = true; - } - //XXX: do the blink if the first command hasn't arrived yet - // configures pin 13 as output and then back as input - if (!firstCommand) { - toggleLed(); - } - - /* SERIALREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while(dataOnSerial) { - Firmata.processInput(); - dataOnSerial = Firmata.available(); - } - - /* 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