Go Down

Topic: Ethernet Shield Hangs When Combining Sketches (Read 861 times) previous topic - next topic

Freumar

I am trying to add a clock to my current project using UDP NTP. I am using an example Time NTP sketch that I have working as a stand-alone clock. When I try to add it to my current project, however, the Arduino hangs and displays nothing on the Serial monitor, not even the "Server is at: " message it should show when performing setup. To combine them, I just copy and past the loop with the variable declarations above it into my current program, change the name of the function from loop() to timeCheck() and call it at the end of my setup().

I am posting my codes below since I can't exceed a certain amount of characters in one post.

Clock:
Code: [Select]
/*

Udp NTP Client

Get the time from a Network Time Protocol (NTP) time server
Demonstrates use of UDP sendPacket and ReceivePacket
For more on NTP time servers and the messages needed to communicate with them,
see http://en.wikipedia.org/wiki/Network_Time_Protocol

Warning: NTP Servers are subject to temporary failure or IP address change.
Plese check

   http://tf.nist.gov/tf-cgi/servers.cgi

if the time server used in the example didn't work.

created 4 Sep 2010
by Michael Margolis
modified 9 Apr 2012
by Tom Igoe

This code is in the public domain.

*/

#include <SPI.h>        
#include <Ethernet.h>
#include <EthernetUdp.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 };



void setup()
{
// Open serial communications and wait for port to open:
 Serial.begin(9600);
  while (!Serial) {
   ; // wait for serial port to connect. Needed for Leonardo only
 }


 // start Ethernet and UDP
 if (Ethernet.begin(mac) == 0) {
   Serial.println("Failed to configure Ethernet using DHCP");
   // no point in carrying on, so do nothing forevermore:
   for(;;)
     ;
 }
}

unsigned int localPort = 8888;      // local port to listen for UDP packets

IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov NTP server

const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void loop()
{
 Udp.begin(localPort);
 // set all bytes in the buffer to 0
 memset(packetBuffer, 0, NTP_PACKET_SIZE);
 // Initialize values needed to form NTP request
 // (see URL above for details on the packets)
 packetBuffer[0] = 0b11100011;   // LI, Version, Mode
 packetBuffer[1] = 0;     // Stratum, or type of clock
 packetBuffer[2] = 6;     // Polling Interval
 packetBuffer[3] = 0xEC;  // Peer Clock Precision
 // 8 bytes of zero for Root Delay & Root Dispersion
 packetBuffer[12]  = 49;
 packetBuffer[13]  = 0x4E;
 packetBuffer[14]  = 49;
 packetBuffer[15]  = 52;

 // all NTP fields have been given values, now
 // you can send a packet requesting a timestamp:  
 Udp.beginPacket(timeServer, 123); //NTP requests are to port 123
 Udp.write(packetBuffer,NTP_PACKET_SIZE);
 Udp.endPacket();

   // wait to see if a reply is available
 delay(1000);  
 if ( Udp.parsePacket() ) {  
   // We've received a packet, read the data from it
   Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer

   //the timestamp starts at byte 40 of the received packet and is four bytes,
   // or two words, long. First, esxtract the two words:

   unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
   unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);  
   // combine the four bytes (two words) into a long integer
   // this is NTP time (seconds since Jan 1 1900):
   unsigned long secsSince1900 = highWord << 16 | lowWord;  
   Serial.print("Seconds since Jan 1 1900 = " );
   Serial.println(secsSince1900);              

   // now convert NTP time into everyday time:
   Serial.print("Unix time = ");
   // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
   const unsigned long seventyYears = 2208988800UL;    
   // subtract seventy years:
   unsigned long epoch = secsSince1900 - seventyYears;  
   // print Unix time:
   Serial.println(epoch);                              


   // print the hour, minute and second:
   Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
   Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
   Serial.print(':');  
   if ( ((epoch % 3600) / 60) < 10 ) {
     // In the first 10 minutes of each hour, we'll want a leading '0'
     Serial.print('0');
   }
   Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
   Serial.print(':');
   if ( (epoch % 60) < 10 ) {
     // In the first 10 seconds of each minute, we'll want a leading '0'
     Serial.print('0');
   }
   Serial.println(epoch %60); // print the second
   
   Serial.println("The Day of the Week is:");
   Serial.println((epoch % 604800) / 86400);
 }
 // wait ten seconds before asking for the time again
 delay(30000);
}



Freumar

Current Program:
Code: [Select]
#include <SPI.h>
#include <Ethernet.h>
#include <EEPROM.h>
#include <EthernetUdp.h>
#include <Time.h>

// Ethernet library configuration
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  //physical mac address
byte ip[] = { 192, 168, 0, 222 };                     // ip in lan
EthernetServer server(82);                            //server port

// HMTL processing variables
String readString = "";             //string to get incoming data

char c;
char buffer[10];
int dataLength =0;

// Buffer containing processed hmtl data
char data[80];
char datamotor[5];
int  index=3;

//Setting the time
int wdstarth = 0;
int wdstartm = 0;
int wdstartp = 0;
int westarth = 0;
int westartm = 0;
int westartp = 0;
int wdstoph = 0;
int wdstopm = 0;
int wdstopp = 0;
int westoph = 0;
int westopm = 0;
int westopp = 0;
int control = 2;

// Setup function
void setup()
{
   Ethernet.begin(mac, ip);   //start Ethernet
   Serial.begin(9600);
   Serial.print("The server is at: ");
   Serial.println(Ethernet.localIP());
   
   wdstarth = EEPROM.read(0);
   wdstartm = EEPROM.read(1);
   westarth = EEPROM.read(2);
   westartm = EEPROM.read(3);
   wdstoph = EEPROM.read(4);
   wdstopm = EEPROM.read(5);
   westoph = EEPROM.read(6);
   westopm = EEPROM.read(7);
   control = EEPROM.read(8);
}


// Loop function
void loop()
{
 EthernetClient client = server.available();
 if (client)
 {
    while (client.connected())
    {
       while (client.available())  // Receive client data
       {
       
         Serial.print(".");
         c = client.read();   //read char by char HTTP request
         readString +=c;
         //Serial.print(c);          //output chars to serial port
       
         // If first request upon connexion, the 3 first characters will be "GET"
         // If "GET" is caught, skip the request info
         if( readString.equals("GET"))
         {
           Serial.println("");
           Serial.println("GET caught, skipping request and printing HTML");
           break;
         }
       
         // Otherwise, if the request contains data,
         // the first characters will be "POST"
         // We then skip the request header and this "if" becomes our main function
         if( readString.equals("POST"))
         {
           Serial.println("");
           Serial.println("POST caught, skipping header and acquiring DATA");
           // 320 is arbitrary. The actual length that has to be skipped depends on
           // several user settings ( browser, language, addons...)
           // the skipped length has not to be too long to skip relevant data
           // and not to short to waste computing time
           for(int i=0; i<320; i++)
           {
             c = client.read();
             Serial.print(c); // UNCOMMENT FOR DEBUG
           }
           //Searches for "Length: "
           while(c  != 'L')
           {            
             c = client.read();
             Serial.print(c); // UNCOMMENT FOR DEBUG
           }
           // Skip "Length: "
           for (int i=0; i<7; i++)
           {
             c = client.read();
             Serial.print(c); // UNCOMMENT FOR DEBUG
           }
         
           // Read the data package length
           readString="";
           c = client.read();
         
           while(c != '\n')
           {
             readString += c;
             Serial.print(c);
             c = client.read();  
           }
         
           // convert data read from String to int
           readString.toCharArray(buffer, readString.length());
           dataLength = atoi(buffer);
           Serial.println("");
           Serial.print("dataLength: ");
           Serial.println(dataLength);
         
           // gets DATA
           client.read(); // skips additional newline
           client.read();
           for (int i=0; i<dataLength; i++)
           {
             data[i] = client.read();
           }
         
           Serial.println("");
           Serial.print("data: ");
           Serial.println(data);
           
           checkURL();
         
           readString ="";
         }      
       }
     
     
       // HTML CODE
         client.println("HTTP/1.1 200 OK");
         client.println("Content-Type: text/html");
         client.println("Connnection: close");
         client.println();
         client.println("<!DOCTYPE HTML>");
         client.println("<html>");
         client.print("<center><table border='1'><tr><td colspan='4' align='center'><b>Omni Systems Outdoor Lights Controller</b></td></tr><tr><td colspan='4' align='center'>");
         client.println("</td></tr><form method='post'><tr>");
         client.println("<td align='center' colspan='2'><b>Weekdays</b></td><td align='center' colspan='2'><b>Weekends</b></td></tr>");
         client.println("<tr><td align='center'><b>Start:</b></td><td align='center'><input type='text' name='wdstart' size='7' value='"); if (wdstarth > 9) {client.println(wdstarth);} else {client.println(0);client.println(wdstarth);}client.println(":"); if (wdstartm > 9) {client.println(wdstartm);} else {client.println(0);client.println(wdstartm);} client.println("'></td><td align='center'><b>Start:</b></td><td align='center'><input type='text' name='westart' size='7' value='"); if (westarth > 9) {client.println(westarth);} else {client.println(0);client.println(westarth);} client.println(":"); if (westartm > 9) {client.println(westartm);} else {client.println(0);client.println(westartm);} client.println("'></td>");
         client.println("<tr><td align='center'><b>Stop:</b></td><td align='center'><input type='text' name='wdstop' size='7' value='"); if (wdstoph > 9) {client.println(wdstoph);} else {client.println(0);client.println(wdstoph);}client.println(":"); if (wdstopm > 9) {client.println(wdstopm);} else {client.println(0);client.println(wdstopm);} client.println("'></td><td align='center'><b>Stop:</b></td><td align='center'><input type='text' name='westop' size='7' value='"); if (westoph > 9) {client.println(westoph);} else {client.println(0);client.println(westoph);} client.println(":"); if (westopm > 9) {client.println(westopm);} else {client.println(0);client.println(westopm);} client.println("'></td>");
         client.println("</tr><tr><td colspan='4' align='center'><b>Light Control: ");
         client.println("<input type='radio' name='on' value='0'"); if (control==0) client.print("checked"); client.println(">On");
         client.println("<input type='radio' name='on' value='1'"); if (control==1) client.print("checked"); client.println(">Off");
         client.println("<input type='radio' name='on' value='2'"); if (control==2) client.print("checked"); client.println(">Automatic");
         client.println("</td></tr><tr><td colspan='4' align='center'><input type='submit' value='Submit Changes'></td></tr></table>");
         client.println("</html>");
     
       Serial.println("__________");
       delay(100);
     
       client.stop();
     
    }
 }

 // Reinitializing variables
 readString ="";          // Reinitialize String
 for (int i=0; i<10; i++)
   {buffer[i] = '\0';}
 for (int i=0; i<50; i++)
   {data[i] = '\0';}
 for (int i=0; i<5; i++)
   {datamotor[i] = '\0';}
 dataLength =0;
 index = 3;
}

void checkURL() {
 wdstarth = atoi(&data[8]);
 wdstartm = atoi(&data[13]);
 westarth = atoi(&data[24]);
 westartm = atoi(&data[29]);
 wdstoph = atoi(&data[39]);
 wdstopm = atoi(&data[44]);
 westoph = atoi(&data[54]);
 westopm = atoi(&data[59]);
 control = atoi(&data[65]);
 EEPROM.write(0, wdstarth);
 EEPROM.write(1, wdstartm);
 EEPROM.write(2, westarth);
 EEPROM.write(3, westartm);
 EEPROM.write(4, wdstoph);
 EEPROM.write(5, wdstopm);
 EEPROM.write(6, westoph);
 EEPROM.write(7, westopm);
 EEPROM.write(8, control);
}


If anyone could look at these two pieces of code and possibly find a reason why they don't get along, I would very much appreciate it!!

tecpenguin

Hi:

Cant post new topics.

The Leonardo circuit diagram has two processors.
The documentation says it has only one.
The photograph has one processor.

I will use arduino when:

There are circuit diagrams available
I am able to create new topics in the forum.

SurferTim

You are probably running out of SRAM. Try using the F() function to reduce the SRAM use by keeping static strings in program memory.
Code: [Select]
        // HTML CODE
          client.println(F("HTTP/1.1 200 OK"));
          client.println(F("Content-Type: text/html"));
          client.println(F("Connnection: close"));
          // and the rest the same


Headroom

The circuit diagram shows two processors because the Atmega processor used on the Leonardo is available in different packages TQFP, VQFN etc. There is only one processor on the Leonardo board.
http://trippylighting.com

http://ledshield.wordpress.com/

Go Up