You are on page 1of 13

/* Chat Server A simple server that distributes any incoming messages to all connected clients.

To use telnet to your device's IP address and type. You can see the client's input in the serial monitor as well. Using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 * Analog inputs attached to pins A0 through A5 (optional) created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe */ #include <SPI.h> #include <Ethernet.h> // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network. // gateway and subnet are optional: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,1, 177); IPAddress gateway(192,168,1, 1); IPAddress subnet(255, 255, 0, 0); // telnet defaults to port 23 EthernetServer server(23); boolean alreadyConnected = false; // whether or not the client was connected pre viously void setup() { // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet); // start listening for clients server.begin(); // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } Serial.print("Chat server address:"); Serial.println(Ethernet.localIP()); } void loop() { // wait for a new client: EthernetClient client = server.available(); // when the client sends the first byte, say hello: if (client) { if (!alreadyConnected) {

// clead out the input buffer: client. 12.h> #include <Ethernet. 0xED }. alreadyConnected = true.write(thisChar).google.104). client. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE.println("Hello. 0xEF. } } } /* Web client This sketch connects to a website (http://www. 13 created 18 Dec 2009 modified 9 Apr 2012 by David A.flush(). void setup() { // Open serial communications and wait for port to open: Serial. Needed for Leonardo only } // start the Ethernet connection: if (Ethernet.33. } if (client. 0xFE. // echo the bytes back to the client: server. // echo the bytes to the server as well: Serial. client!"). // wait for serial port to connect. while (!Serial) { .println("Failed to configure Ethernet using DHCP"). 0xBE.194.begin(9600). // no point in carrying on.write(thisChar). Serial.com) using an Arduino Wiznet Ethernet shield. so do nothing forevermore: . Circuit: * Ethernet shield attached to pins 10. 0xAD. IPAddress server(173. // Google // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client.begin(mac) == 0) { Serial.available() > 0) { // read the bytes incoming from the client: char thisChar = client.println("We have a new client"). 11. Mellis */ #include <SPI.read().h> // Enter a MAC address for your controller below.

println("connected"). and DNS address.0"). } } loop() if there are incoming bytes available from the server. IP address.").println("connection failed").. read them and print them: (client.. Circuit: * Ethernet shield attached to pins 10. stop the client: if (!client. /* Repeating Web client This sketch connects to a a web server and makes a request using a Wiznet Ethernet shield. } } void { // // if } // if the server's disconnected. Serial.available()) { char c = client.. by assigning the Ethernet client with a MAC address. client. client. You can use the Arduino Ethernet shield.println(). 11. Serial..println("connecting. // if you get a connection. } // give the Ethernet shield a second to initialize: delay(1000).connect(server. either one will work.) . // do nothing forevermore: for(. 12.println("GET /search?q=arduino HTTP/1.read(). 13 created 19 Apr 2012 by Tom Igoe . } else { // kf you didn't get a connection to the server: Serial. This example uses DNS.print(c).stop()."). or the Adafruit Ethernet shield.println("disconnecting. report back via serial: if (client. as long as it's got a Wiznet Ethernet module on board. Serial.for(. 80)) { Serial.connected()) { Serial.) .println(). // Make a HTTP request: client.

connected() && lastConnected) { Serial. unsigned long lastConnectionTime = 0.1). // delay between updates. // give the ethernet module time to boot up: delay(1000). Serial.cc/en/Tutorial/WebClientRepeating This code is in the public domain.read(). // fill in your address here: byte mac[] = { 0xDE. client.1.0. */ #include <SPI.cc". // fill in your Domain Name Server address here: IPAddress myDns(1.stop(). in milliseconds boolean lastConnected = false. send it out the serial port. Serial. // for manual configuration: IPAddress ip(10.localIP()). This is for debugging purposes only: (client. } void // // // if } // if there's no net connection. ip. // last time you connected to the server.h> // assign a MAC address for the ethernet controller. // state of the connection last t ime through the main loop const unsigned long postingInterval = 60*1000. } loop() { if there's incoming data from the net connection.available()) { char c = client. char server[] = "www.0.println("disconnecting. but there was one last time // through the loop. Serial. myDns).begin(mac.println(Ethernet. // fill in an available IP address on your network here. 0xFE.http://arduino.1.begin(9600).print(c)."). // initialize the library instance: EthernetClient client. // print the Ethernet board/shield's IP address: Serial. . 0xBE. then stop the client: if (!client.arduino.println().print("My IP address: "). // start the Ethernet connection using a fixed IP address and DNS server: Ethernet. 0xAD. 0xED}. 0xEF.20).h> #include <Ethernet. in mil liseconds void setup() { // start serial port: Serial.

client.// if you're not connected. 80)) { Serial. 177). 11.println("Host: www.println("disconnecting.connect(server. IPAddress ip(192."). 0xEF.println("Connection: close").connected() && (millis() . 0xAD. } } /* Web Server A simple web server that shows the value of the analog input pins. } // this method makes a HTTP connection to the server: void httpRequest() { // if there's a successful connection: if (client.1"). client.println("User-Agent: arduino-ethernet").println("GET /latest.println().println("connecting. 0xED }..h> #include <Ethernet.txt HTTP/1. 0xBE.connected(). 12. client. client. // The IP address will be dependent on your local network: byte mac[] = { 0xDE. Circuit: * Ethernet shield attached to pins 10. Mellis modified 9 Apr 2012 by Tom Igoe */ #include <SPI.1. 0xFE. using an Arduino Wiznet Ethernet shield.println("connection failed"). and ten seconds have passed since // your last connection. Serial. client. } // store the state of the connection for next time through // the loop: lastConnected = client. } else { // if you couldn't make a connection: Serial. 13 * Analog inputs attached to pins A0 through A5 (optional) created 18 Dec 2009 by David A."). // note the time that the connection was made: lastConnectionTime = millis(). then connect again and send data: if(!client.168. // send the HTTP PUT request: client.stop()..arduino.cc").lastConnectionTime > postingInterval)) { httpRequest().h> // Enter a MAC address and IP address for your controller below. .

println("<meta http-equiv=\"refresh\" content=\"5\">"). break.available()) { char c = client. } client.print(sensorReading).println("</html>").print("analog input "). while (!Serial) { . client.println("HTTP/1. server. client.println("Connection: close").read(). Serial. client. the http request has ended.write(c). // output the value of each analog input pin for (int analogChannel = 0. client.// Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80). } if (c == '\n') { // you're starting a new line .println("Content-Type: text/html"). analogChannel++) { int sensorReading = analogRead(analogChannel).begin(9600). analogChannel < 6.println("new client"). client.begin(). void setup() { // Open serial communications and wait for port to open: Serial. // add a meta refresh tag. // an http request ends with a blank line boolean currentLineIsBlank = true. Needed for Leonardo only } // start the Ethernet connection and the server: Ethernet. Serial. client. client. if (client) { Serial.print(analogChannel).connected()) { if (client.begin(mac. so the browser pulls again every 5 seconds: client. client. // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client. while (client.println("<br />"). } void loop() { // listen for incoming clients EthernetClient client = server.localIP()). // if you've gotten to the end of the line (received a newline // character) and the line is blank.print("server is at ").println("<html>").println("<!DOCTYPE HTML>").available(). Serial. client.println().println(Ethernet.1 200 OK"). client.print(" is "). // wait for serial port to connect. ip).

currentLineIsBlank = true. volatile boolean newInterruption. void setup() { Serial. Serial. // close the connection: client. configureServomotors(). } } } // give the web browser time to receive the data delay(1).println("client disonnected"). // readSerialport() function optimized. // Thanks to Jorge Gomez for all these new fixes! #define TIMER2_PRELOAD 100 char outputs[10].0) // NEW IN VERSION 1. volatile boolean updateServoMotors. .stop(). int states[10]. // Some minor fixes. // updateServoMotors changes its name as a global variable had the same name. } } // NEW IN VERSION 1. } void loop() { if (updateServoMotors) { sendUpdateServomotors(). Serial.3: // Now it works on GNU/Linux. unsigned long initialPulseTime. } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false. // pulse() modified so that it receives pulse width as a parameter instead using a global variable. lastDataReceivedTime = millis(). fixing a glitch that made this period unstable in previou s versions.flush().print() for Serial. sendSensorValues(). // timer2 set to 20ms.4: // Changed Serial.write() in ScratchBoardSensorReport functio n to make it compatible with latest Arduino IDE (1.begin(38400). Also tested with MacOS and Windows 7. unsigned long lastDataReceivedTime. configurePins().

sensorValues[sensorIndex]). for (sensorIndex = 0. TIMSK2 = 1<<TOIE2.//pin 'd'.INPUT).//pin 'd'. readings[5]. index++) { states[index] = 0. } //pin //pin //pin //pin 4 7 8 12 void configureServomotors() //servomotors interruption configuration (interrupti on each 10 ms on timer2) { newInterruption = false.//pin 'a'. sensorIndex < 6. TCCR2A = 0. //timer2 Overflow Interrupt TCNT2 = TIMER2_PRELOAD. OUTPUT). digitalWrite(index+4.//pin 5 6 9 10 11 13 pinMode(2. InsertionSort(readings. sensorIndex++) ScratchBoardSensorReport(sensorIndex. 5). sensorIndex < 6. outputs[3] = 'c'. //reset pins } outputs[1] outputs[2] outputs[5] outputs[6] outputs[7] outputs[9] = = = = = = 'a'. outputs[8] = 's'. sensorIndex. pinMode(3. . calculate the median of 5 sensor readings in order to avoid variability and powe r surges { for (int p = 0.updateServoMotors = false. updateServoMotors = false. p++) readings[p] = analogRead(sensorIndex). TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20.INPUT). //select median reading } //send analog sensor values for (sensorIndex = 0. } } void configurePins() { for (int index = 0. pinMode(index+4. } else { readSerialPort(). //start timer } void sendSensorValues() { int sensorValues[6].//pin 'd'. outputs[0] = 'c'. LOW). p < 5. outputs[4] = 's'. //sort readings sensorValues[sensorIndex] = readings[2].//pin 'a'. sensorIndex++) //for analog sensors. index < 10.

we need to simulate the setup execution that oc curs when a usb connection is opened or closed without this module { for (int pos = 0. array[a] = array[b]. } void InsertionSort(int* array. int b) { int temp = array[a]. j-1 ).4] = ((sensorHighByte & 0x07) << 7) | (inByte & 0x7F). array[b] = temp. i++) for (int j = i. j. if (inByte >= 128) // Are we receiving the word's header? { sensorHighByte = inByte.write( B10000000 | ((sensor & B1111)<<3) | ((value>>7) & B111)). } } } else checkScratchDisconnection(). int value) //PicoBoard protocol. digitalRead(2)?1023:0). (j > 0) && ( array[j] < array[j-1] ). } void readSerialPort() { int pin. pin = ((inByte >> 3) & 0x0F). Serial. 2 byt es per sensor { Serial.4).available() > 1) { lastDataReceivedTime = millis(). if (inByte <= 127) // This prevents Linux ttyACM driver to fail { states[pin . .read(). } void ScratchBoardSensorReport(int sensor. pos < 10. updateActuator(pin .read(). inByte = Serial. int n) { for (int i = 1. inByte.//send digital sensor values ScratchBoardSensorReport(6.write( value & B1111111). j--) swap( array. i < n. ScratchBoardSensorReport(7. if (Serial. digitalRead(3)?1023:0). int a.available()). // Wait for the end of the word with data inByte = Serial. pos++) //stop all actuators { states[pos] = 0. } void reset() //with xbee module. while (!Serial. sensorHighByte. } void swap (int* array.

//reset state if actuator s reception timeout = one second } . LOW). //protocol handshaking sendSensorValues(). 1700). } void pulse (int pinNumber. states[p]). (angle * 10) + 600). 2400). else if (outputs[pinNumber] == 'a') analogWrite(pinNumber + 4. HIGH). LOW). 1300). states[p]). if (outputs[p] == 's') servomotorS(p + 4. } void sendUpdateServomotors() { for (int p = 0. else pulse(pinNumber. //anticlockwise rotation } void servomotorS (int pinNumber. int pulseWidth) { initialPulseTime = micros(). } void updateActuator(int pinNumber) { if (outputs[pinNumber] == 'd') digitalWrite(pinNumber + 4. 0). TCNT2 = TIMER2_PRELOAD. } void checkScratchDisconnection() //the reset is necessary when using an wireless arduino board (because we need to ensure that arduino isn't waiting the actuato rs state from Scratch) or when scratch isn't sending information (because is how serial port close is detected) { if (millis() . digitalWrite(pinNumber. int angle) { if (angle < 0) pulse(pinNumber. p++) { if (outputs[p] == 'c') servomotorC(p + 4. updateServoMotors = false.digitalWrite(pos + 2. else if (angle > 180) pulse(pinNumber. int dir) { if (dir == 1) pulse(pinNumber. } } void servomotorC (int pinNumber. p < 10. states[pinNumb er]). } //reset servomotors newInterruption = false. //clockwise rotation else if (dir == 2) pulse(pinNumber.lastDataReceivedTime > 1000) reset(). states[pinNumber]) . while (micros() < pulseWidth + initialPulseTime){} digitalWrite(pinNumber. lastDataReceivedTime = millis().

384 ms //as we need a 20 ms interruption period but timer2 doesn't have a suitable pr eescaler for this. 255. 0xEF.11. pinMode(7. Ethernet. OUTPUT). 0xED }. 255.h> boolean reading = false. TCNT2 = TIMER2_PRELOAD.12 & 13 are used by the ethernet shield pinMode(2. OUTPUT). pinMode(6. //Pins 10. //Manual setup only //byte subnet[] = { 255. pinMode(8.000/256/1024) times per second approximately => interruption period = 1 / 16. ip. //Ethernet. } newInterruption = !newInterruption.000/156/1024 = 9. //to have a 10 ms interruption period.begin(mac.begin(mac). 168. pinMode(4. 0xAD.0+ ONLY #include <Ethernet.984 ms => count er initial value (TCNT) = 100 if (newInterruption) { updateServoMotors = true.ISR(TIMER2_OVF_vect) //timer1 overflow interrupt vector handler { //timer2 => 8 bits counter => 256 clock ticks //preeescaler = 1024 => this routine is called 61 (16.000. //port 80 //////////////////////////////////////////////////////////////////////// void setup(){ Serial.0+ ONLY //ARDUINO 1. 0. OUTPUT). . EthernetServer server = EthernetServer(80). 0xBE. OUTPUT).000. OUTPUT).000/256/1024 = 16. 168. 199 }. gateway. timer2 counter must overflow after 156 clock ticks => interruption period = 1 / 16. 1 }. OUTPUT). //Manual setup only // if need to change the MAC address (Very Rare) byte mac[] = { 0xDE. //for manual setup server. pinMode(3. we program the timer with a 10 ms interruption period and we consider an interruption every 2 times this routine is called. OUTPUT). 0 }. //Manual setup only //byte gateway[] = { 192. pinMode(5. pinMode(9. OUTPUT).000. 0xFE.begin().h> #include <SPI.begin(9600). 0. //reset timer } //ARDUINO 1. subnet). //////////////////////////////////////////////////////////////////////// //CONFIGURE //////////////////////////////////////////////////////////////////////// //byte ip[] = { 192.

} void checkForClient(){ EthernetClient client = server. client. client. //found the ?. client). break. break. case '6': //add code here to trigger on 6 triggerPin(6. client).localIP()). checkForClient(). case '3': //add code here to trigger on 3 triggerPin(3. begin reading the info if(reading){ Serial. break.println().read(). if (client) { // an http request ends with a blank line boolean currentLineIsBlank = true. client). client). } char c = client.connected()) { if (client. and process qequest. sentHeader = true. if(reading && c == ' ') reading = false.println("HTTP/1.Serial.available(). } void loop(){ // listen for incoming clients. . switch (c) { case '2': //add code here to trigger on 2 triggerPin(2. case '5': //add code here to trigger on 5 triggerPin(5.println("Content-Type: text/html"). break.available()) { if(!sentHeader){ // send a standard http response header client. if(c == '?') reading = true.1 200 OK"). boolean sentHeader = false.println(Ethernet. client). case '4': //add code here to trigger on 4 triggerPin(4.print(c). while (client.

break. break. if (c == '\n') { currentLineIsBlank = true. digitalWrite(pin. HIGH). client. }else if (c != '\r') { currentLineIsBlank = false. client. to trigger on 8 client). delay(25). client. delay(25).print("<br>"). // give the web browser time to receive the data client. if (c == '\n' && currentLineIsBlank) break. case '7': //add code here triggerPin(7. case '9': //add code here triggerPin(9.stop(). } } to trigger on 7 client).println(pin).Client needed just for HTML output purposes. } } } delay(1). break. digitalWrite(pin. case '8': //add code here triggerPin(8. } . LOW). to trigger on 9 client). EthernetClient client){ //blink a pin . break.print("Turning on pin "). // close the connection: } } void triggerPin(int pin.