Sei sulla pagina 1di 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.flush(); Serial.println("We have a new client"); client.println("Hello, client!"); alreadyConnected = true; } if (client.available() > 0) { // read the bytes incoming from the client: char thisChar = client.read(); // echo the bytes back to the client: server.write(thisChar); // echo the bytes to the server as well: Serial.write(thisChar); } } }

/* Web client This sketch connects to a website (http://www.google.com) using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 18 Dec 2009 modified 9 Apr 2012 by David A. Mellis */ #include <SPI.h> #include <Ethernet.h> // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 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): EthernetClient client; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore:

for(;;) ; } // give the Ethernet shield a second to initialize: delay(1000); Serial.println("connecting..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { // kf you didn't get a connection to the server: Serial.println("connection failed"); } } void { // // if } // if the server's disconnected, stop the client: if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); // do nothing forevermore: for(;;) ; } } loop() if there are incoming bytes available from the server, read them and print them: (client.available()) { char c = client.read(); Serial.print(c);

/* Repeating Web client This sketch connects to a a web server and makes a request using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or the Adafruit Ethernet shield, either one will work, as long as it's got a Wiznet Ethernet module on board. This example uses DNS, by assigning the Ethernet client with a MAC address, IP address, and DNS address. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 19 Apr 2012 by Tom Igoe

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

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

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

currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } }

// NEW IN VERSION 1.4: // Changed Serial.print() for Serial.write() in ScratchBoardSensorReport functio n to make it compatible with latest Arduino IDE (1.0) // NEW IN VERSION 1.3: // Now it works on GNU/Linux. Also tested with MacOS and Windows 7. // timer2 set to 20ms, fixing a glitch that made this period unstable in previou s versions. // readSerialport() function optimized. // pulse() modified so that it receives pulse width as a parameter instead using a global variable. // updateServoMotors changes its name as a global variable had the same name. // Some minor fixes. // Thanks to Jorge Gomez for all these new fixes! #define TIMER2_PRELOAD 100 char outputs[10]; int states[10]; unsigned long initialPulseTime; unsigned long lastDataReceivedTime; volatile boolean updateServoMotors; volatile boolean newInterruption; void setup() { Serial.begin(38400); Serial.flush(); configurePins(); configureServomotors(); lastDataReceivedTime = millis(); } void loop() { if (updateServoMotors) { sendUpdateServomotors(); sendSensorValues();

updateServoMotors = false; } else { readSerialPort(); } } void configurePins() { for (int index = 0; index < 10; index++) { states[index] = 0; pinMode(index+4, OUTPUT); digitalWrite(index+4, LOW); //reset pins } outputs[1] outputs[2] outputs[5] outputs[6] outputs[7] outputs[9] = = = = = = 'a';//pin 'a';//pin 'a';//pin 'd';//pin 'd';//pin 'd';//pin 5 6 9 10 11 13

pinMode(2,INPUT); pinMode(3,INPUT); outputs[0] = 'c'; outputs[3] = 'c'; outputs[4] = 's'; outputs[8] = 's'; }

//pin //pin //pin //pin

4 7 8 12

void configureServomotors() //servomotors interruption configuration (interrupti on each 10 ms on timer2) { newInterruption = false; updateServoMotors = false; TCCR2A = 0; TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20; TIMSK2 = 1<<TOIE2; //timer2 Overflow Interrupt TCNT2 = TIMER2_PRELOAD; //start timer } void sendSensorValues() { int sensorValues[6], readings[5], sensorIndex; for (sensorIndex = 0; sensorIndex < 6; sensorIndex++) //for analog sensors, calculate the median of 5 sensor readings in order to avoid variability and powe r surges { for (int p = 0; p < 5; p++) readings[p] = analogRead(sensorIndex); InsertionSort(readings, 5); //sort readings sensorValues[sensorIndex] = readings[2]; //select median reading } //send analog sensor values for (sensorIndex = 0; sensorIndex < 6; sensorIndex++) ScratchBoardSensorReport(sensorIndex, sensorValues[sensorIndex]);

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

digitalWrite(pos + 2, LOW); } //reset servomotors newInterruption = false; updateServoMotors = false; TCNT2 = TIMER2_PRELOAD; //protocol handshaking sendSensorValues(); lastDataReceivedTime = millis(); } void updateActuator(int pinNumber) { if (outputs[pinNumber] == 'd') digitalWrite(pinNumber + 4, states[pinNumber]) ; else if (outputs[pinNumber] == 'a') analogWrite(pinNumber + 4, states[pinNumb er]); } void sendUpdateServomotors() { for (int p = 0; p < 10; p++) { if (outputs[p] == 'c') servomotorC(p + 4, states[p]); if (outputs[p] == 's') servomotorS(p + 4, states[p]); } } void servomotorC (int pinNumber, int dir) { if (dir == 1) pulse(pinNumber, 1300); //clockwise rotation else if (dir == 2) pulse(pinNumber, 1700); //anticlockwise rotation } void servomotorS (int pinNumber, int angle) { if (angle < 0) pulse(pinNumber, 0); else if (angle > 180) pulse(pinNumber, 2400); else pulse(pinNumber, (angle * 10) + 600); } void pulse (int pinNumber, int pulseWidth) { initialPulseTime = micros(); digitalWrite(pinNumber, HIGH); while (micros() < pulseWidth + initialPulseTime){} digitalWrite(pinNumber, LOW); } 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() - lastDataReceivedTime > 1000) reset(); //reset state if actuator s reception timeout = one second }

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

Ethernet.begin(mac); //Ethernet.begin(mac, ip, gateway, subnet); //for manual setup server.begin();

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

break; case '7': //add code here triggerPin(7, break; case '8': //add code here triggerPin(8, break; case '9': //add code here triggerPin(9, break; } }

to trigger on 7 client); to trigger on 8 client); to trigger on 9 client);

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

Potrebbero piacerti anche