Advertisement
Guest User

Untitled

a guest
Jul 1st, 2015
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 17.92 KB | None | 0 0
  1. /*
  2. [] [] [] []  Mail Box You got new Mail Logging [] [] [] []
  3.  
  4.  2015-02-09 1117
  5.  - PHASE 2
  6.  - Working on getting the read/write and display of the time stamps correct.
  7.  - Learend how to find the file size.
  8.  - Learned that a myFile.position() tells you where the cursor is from the first time you read it.
  9.  - Figured out how to get it to read the following 28 bytes.
  10.  
  11.  2015-02-05 1816
  12.  - Got webpage up and running.
  13.  - When button is pushed. It writes a line to the maillog.txt file
  14.  - LED also lights up when 'door is open'
  15.  
  16.  
  17.  2015-02-05 1558 Build 1.0
  18.  - Testing out webserver.
  19.  
  20.  2015-07-07 1150
  21.  - Attached RTC chip to circuit. Will be attempting to read the RTC data and log it on button presses
  22. 1504
  23. - I have working code to read from the RTC and generate a string. Thou it has added alot of data to the code, and I am very limited on dynamic memory. Thus causing the read/write to SD to fail.
  24.  
  25.  Goals:
  26.  - [X] Get a basic web page to work. - 2015-02-05
  27.  - [X] Get Arduino to respond to a button push (Representing the Xbee's signal) - 2015-02-05
  28.  - [X] Get Arduino to read from an SD card - 2015-02-05
  29.  - [X] Get Arduino to write to the SD Card when button is pushed - 2015-02-05
  30.  - [X] Write to a TXT file.  - 2015-02-05
  31.  - [X] Get SD Card Write to write to an HTML file instead. (Insert line, not write line at end)  - 2015-02-05
  32.  - [ ] Get Arduino to read from the SD Card maillog.txt backwards. So most recent will be at the top.
  33.  - [X] Get Arduino to read RTC (Real Time Clock) 2015-07-01 1505
  34.  - [ ] Get Arduino to write to SD Card with Time code when a button is pushed.
  35.  - [ ] Confirm Arduino webpage shows the logged info
  36.  - [ ] Setup Xbee's to talk to each other.
  37.  - [ ] Make Xbee test circuit to verify the distance.
  38.  - [ ] Figure out the best way for XBee to communicate to Arduino
  39.  Either:
  40.  -- When Mailbox XBee gets power. It immedely sends command or acts as button push.
  41.  -- OR When Mailbox XBee gets power. It waits and sends a specific command/code down. (aka a specific resistance value) Perhase to prevent accidental error.
  42.  (Recieving XBee needs to read a 120ohm value to figure out it is true. If not, it will find it to be false error)
  43.  - [ ] Program Arudino to respond to XBee (XBee replaces the push button)
  44.  
  45.  
  46.  Advanced Goals:
  47.  - [ ] Have Arduino play an audio code when the mail comes.
  48.  - [ ] Have Arduino show previous 20 in backwards order
  49.  
  50.  */
  51.  
  52.  
  53.  
  54.  
  55. /*
  56.  Circuit:
  57.  * Ethernet shield attached to pins 10, 11, 12, 13
  58.  * Analog inputs attached to pins A0 through A5 (optional)
  59.  
  60.  * RTC CHIP:
  61.  ** RTC Chip Uses A4 and A5
  62.  ** RTC CHIP SDA -> A4
  63.  ** RTC CHIP SCL -> A5
  64.  
  65.  * SD card attached to SPI bus as follows:
  66.  ** MOSI - pin 11
  67.  ** MISO - pin 12
  68.  ** CLK - pin 13
  69.  ** CS - pin 4
  70.  
  71.  
  72.  */
  73. // = = = = = = = = = = Includes = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  74. #include <SPI.h>        // Needed to us the 6 special pins for the eithernet card
  75. #include <Ethernet.h>   // Needed to use the eithernet card
  76. #include <SD.h>         // Needed to read/write to the SD Card
  77. #include "Wire.h"       // Needed for RTC Chip
  78.  
  79. /*
  80.  
  81.  
  82.  */
  83.  
  84. // ============ Ethernet  ============
  85. // Enter a MAC address and IP address for your controller below.
  86. // The IP address will be dependent on your local network:
  87. byte mac[] = {
  88.   0xDE, 0xAD, 0xDA, 0x00, 0xC1, 0xDE
  89. };
  90. IPAddress ip(10, 0, 0, 88);
  91.  
  92. // Initialize the Ethernet server library
  93. // with the IP address and port you want to use
  94. // (port 80 is default for HTTP):
  95. EthernetServer server(80);
  96.  
  97. // ============ SD Card  ============
  98. File myFile;  // Name of the file we will be using
  99.  
  100.  
  101. // ============ Push Button  ============
  102. // push button and LED indicator circuit
  103. const int buttonDelete = 5;     // the number of the pushbutton pin (Delete button of the file)
  104. const int buttonPin = 6;     // the number of the pushbutton pin
  105. const int ledPin =  7;      // the number of the LED pin
  106. // variables will change:
  107. boolean buttonState = 0;         // interger for reading the pushbutton status
  108. boolean doorState = 0;           // interger to see if the door is open. (Prevents code from looping and writing tons of lines for each door open)
  109.  
  110.  
  111. // ============ RTC - Real Time Clock  ============
  112. #define DS1307_ADDRESS 0x68     // RTC Address.
  113. char timestamp[27];             // Sets up the 28 char count for the write to SD card line. EX: char timestamp[27] = ("2015-07-01 WED 12:31 </br>");
  114.  
  115.  
  116.  
  117. // = = = = = = = = = = SETUP = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  118. void setup() {
  119.  
  120.   // ============ ETHERNET  ============
  121.   // start the Ethernet connection and the server:
  122.   Ethernet.begin(mac, ip);
  123.   server.begin();
  124.  
  125.   // ============ SERIAL  ============
  126.   // Open serial communications and wait for port to open:
  127.   Serial.begin(9600);
  128.   while (!Serial) {
  129.     ; // wait for serial port to connect. Needed for Leonardo only
  130.   }
  131.   Serial.print("server is at ");
  132.   Serial.println(Ethernet.localIP());
  133.  
  134.   // ============ SD Card  ============
  135.   Serial.print("Initializing SD card...");
  136.   // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  137.   // Note that even if it's not used as the CS pin, the hardware SS pin
  138.   // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  139.   // or the SD library functions will not work.
  140.   pinMode(10, OUTPUT);
  141.  
  142.   if (!SD.begin(4)) {
  143.     Serial.println("initialization failed!");
  144.     return;
  145.   }
  146.   Serial.println("initialization done.");
  147.  
  148.  
  149.   // ============ Push Button / XBee button ===============
  150.   // initialize the LED pin as an output:
  151.   pinMode(ledPin, OUTPUT);
  152.   // initialize the pushbutton pin as an input:
  153.   pinMode(buttonPin, INPUT);
  154.   pinMode(buttonDelete, INPUT);
  155.  
  156.  
  157.   // ============ RTC - Real Time Clock  ============
  158.   Wire.begin();         // Sets up the Wire.h to be used.
  159.  
  160. }
  161.  
  162. // = = = = = = = = = = LOOP = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  163. void loop() {
  164.  
  165.  
  166.   // ============ ETHERNET  ============
  167.   // listen for incoming clients
  168.   EthernetClient client = server.available();
  169.   if (client) {
  170.     webpage();  // Directs to the VOID WEBPAGE Below. This will help keep the loop empty.
  171.   }
  172.  
  173.  
  174.  
  175.   // ================ Button Action ====================
  176.   // read the state of the pushbutton value:
  177.   buttonState = digitalRead(buttonPin);
  178.  
  179.   // check if the pushbutton is pressed.
  180.   // if it is, the buttonState is HIGH:
  181.   if (buttonState == HIGH) {
  182.     if (doorState == LOW) {                // Checks to see if the door was previously closed. If still HIGH (door still open, prevents the time log to time stamp it.)
  183.       dooropen();                        // Jumps down to the VOID DOOROPEN to do actions.
  184.     }
  185.  
  186.   }
  187.   else if (buttonState == LOW) {
  188.     // turn LED off:
  189.     digitalWrite(ledPin, LOW);             // When button is LOW. It turns off the LED
  190.     doorState = LOW;                       // Resets doorState to LOW so the above loop will be good to go next time the door is opened.
  191.   }
  192.  
  193.  
  194.   // ================ Delete File Action ====================
  195.  
  196.   if (digitalRead(buttonDelete) == HIGH) {
  197.     SD.remove("maillog.txt");
  198.     Serial.println("maillog.txt has been deleted");
  199.   }
  200.  
  201. }
  202.  
  203.  
  204. // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  205. // - - - - - - - - - - WEBPAGE  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  206. void webpage() {
  207.  
  208.   EthernetClient client = server.available();
  209.   Serial.println("new client");  // Testing - To verify in serial that there is a connection made.
  210.   // an http request ends with a blank line
  211.   boolean currentLineIsBlank = true;
  212.   while (client.connected()) {
  213.     if (client.available()) {
  214.       char c = client.read();
  215.       // Serial.write(c);      // print HTTP request character to serial monitor
  216.  
  217.       // if you've gotten to the end of the line (received a newline
  218.       // character) and the line is blank, the http request has ended,
  219.       // so you can send a reply
  220.       if (c == '\n' && currentLineIsBlank) {
  221.         // send a standard http response header
  222.         client.println("HTTP/1.1 200 OK");
  223.         client.println("Content-Type: text/html");
  224.         client.println("Connection: close");  // the connection will be closed after completion of the response
  225.         // client.println("Refresh: 5");  // refresh the page automatically every 5 sec
  226.         client.println();
  227.         client.println("<!DOCTYPE HTML>");
  228.         client.println("<html>");
  229.  
  230.  
  231.         // - - - - - - - READ SD CARD FILE - - - - - - - -
  232.  
  233.         // [X] myFileGet this section to read from each line of the SD Card. -2015-02-05
  234.         /*
  235.          - Could set it up as a loop.
  236.          - 1) Count the lines in txt file.
  237.          - 2) While the line number is less than the total lines in the txt file. Then keep client.print
  238.          - - Only spit out the last 20 days?
  239.          - 1) Count total lines. (Say 345)
  240.          - 2) Subtract 20 from Total lines (345) = 325
  241.          - 3) client.print line 325
  242.          - 4) client.println("<br />");
  243.          - 5) increase++ Total line number 325 + 1 = 326.
  244.          - 6) repeate loop now printing line 326.
  245.          */
  246.         client.println("<hr /><b>");
  247.         myFile = SD.open("day00.txt");            // Opens day 00 text file
  248.         if (myFile) {
  249.           // Serial.println("maillog.txt:");         // Testing only.
  250.           while (myFile.available()) {              // Check to see if a new character is availble
  251.             client.write(myFile.read());            // Reads a character. and repeates loop and writes it to the client.  (This MUST WRITE not READ)
  252.             // each line of the text file (maillog.txt) must have a </br> for it to properly format the lines.
  253.             // ex:  2013-01-14 WED 11:13 </br>
  254.           }              // end of while loop
  255.           // close the file:
  256.           myFile.close();
  257.         }
  258.         client.println("</b><br /><hr />");
  259.  
  260.         myFile = SD.open("maillog.txt");            // Opens maillog.txt
  261.         if (myFile) {
  262.           // Serial.println("maillog.txt:");         // Testing only.
  263.           while (myFile.available()) {              // Check to see if a new character is availble
  264.             client.write(myFile.read());            // Reads a character. and repeates loop and writes it to the client.  (This MUST WRITE not READ)
  265.             // each line of the text file (maillog.txt) must have a </br> for it to properly format the lines.
  266.             // ex:  2013-01-14 WED 11:13 </br>
  267.           }              // end of while loop
  268.           // close the file:
  269.           myFile.close();
  270.         }
  271.  
  272.         // - - END OF HTML Page- - - - - - - -
  273.         client.println("</html>");
  274.         break;
  275.       }
  276.       if (c == '\n') {
  277.         // you're starting a new line
  278.         currentLineIsBlank = true;
  279.       }
  280.       else if (c != '\r') {
  281.         // you've gotten a character on the current line
  282.         currentLineIsBlank = false;
  283.       }
  284.     }
  285.   }
  286.   // give the web browser time to receive the data
  287.   delay(1);
  288.   // close the connection:
  289.   client.stop();
  290.   Serial.println("client disonnected");
  291. }
  292.  
  293.  
  294. // - - - - - - - - - - Push Button / XBee New Mail action  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  295.  
  296. void dooropen() {
  297.   doorState = HIGH;                           // Sets the doorState to High. This stops the above loop from repeating over and over.
  298.   digitalWrite(ledPin, HIGH);                 // Makes the LED turn on to indicate the Button has been pushed.
  299.  
  300.   // RTC get it to build the data string
  301.  
  302.  
  303.   //char timestamp[27] = ("2015-07-01 WED 12:31 </br>");   // Temporary 'timestamp' This will get replaced by reading from the future RTC.
  304.  
  305.   printDate();
  306.  
  307.  
  308.   int mailFileSize = 0;            // Is the total size of maillog.txt
  309.   int cursorPosition = 0;          // value set when I go to read the previous 5
  310.   // char previous1[28] = ("2015-02-09 SAT 12:12 </br>");
  311.   // char previous2[28] = ("2015-02-09 SAT 12:12 </br>");
  312.   // char previous3[28] = ("2015-02-09 SAT 12:12 </br>");
  313.   // char previous4[28] = ("2015-02-09 SAT 12:12 </br>");
  314.   // char previous5[28] = ("2014-02-09 SAT 12:12 </br>");
  315.   char prev_index = 0;           // This is counting characters as it read the file.
  316.   // char prev_char = 0;
  317.  
  318.  
  319.   // Write this button push to file
  320.   // open the file. note that only one file can be open at a time,
  321.   // so you have to close this one before opening another.
  322.  
  323.  
  324.   // - - - - - - - - - - Write to SD card - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  325.  
  326.  
  327.   myFile = SD.open("maillog.txt", FILE_WRITE);
  328.   // if the file opened okay, write to it:
  329.   if (myFile) {
  330.     Serial.println(myFile.size());                    // Testing. File size before write
  331.     // Serial.println(myFile.position());                // Testing. Location of 'cursor' (Should be at end of file)
  332.     Serial.print("Writing to maillog.txt...");         // Testing. only.
  333.     myFile.println(timestamp);                        // Writes the current timestamp to the file
  334.     mailFileSize = myFile.size();                     // Writes interger the total file size. Aka the 'end' byte of the file.
  335.     myFile.close();                                   // close the file:
  336.  
  337.     Serial.println("done.");
  338.     Serial.print("Total File Size ");
  339.     Serial.println(mailFileSize);
  340.   }
  341.   else {
  342.     // if the file didn't open, print an error:
  343.     Serial.println("error opening maillog.txt");
  344.   }
  345.   SD.remove("day00.txt");                          // Deletes day00.txt
  346.   myFile = SD.open("day00.txt", FILE_WRITE);      // Creates and opens up newly created day00.txt
  347.   myFile.println(timestamp);                      // Writes single line to new day00.txt file
  348.   myFile.close();
  349.  
  350.  
  351.   // Time to create lines for the last 5 lines. and write to a new list.
  352.  
  353.   mailFileSize = mailFileSize - 139;               // Subtracts back to 5 lines (To get the starting position.
  354.   // knowing the file size from the interger. And knowing each line is = 28 bytes. x previous 5 lines.
  355.   // 28 x 5 == 140 bytes back.
  356.   Serial.println(mailFileSize);                    // Testing. Shows location number. Correct.
  357.  
  358.   myFile = SD.open("maillog.txt");
  359.   //myFile.seek(29);                       // Goes to that location
  360.   /*
  361.   Serial.println(myFile.position());              // current position of cursor. Always starts at 0
  362.    Serial.println(myFile.read());                  // reads the current character. and auto increases the position#
  363.    //Serial.println(myFile.read());
  364.    Serial.println(myFile.position());
  365.    //Serial.println(myFile.peek());
  366.    //Serial.println(myFile.seek(mailFileSize));
  367.    Serial.println(myFile.read());
  368.    Serial.println(myFile.position());
  369.    Serial.println(myFile.read());
  370.    Serial.println(myFile.position());
  371.    Serial.println(myFile.read());
  372.    Serial.println(myFile.position());
  373.    */
  374.  
  375.   while (myFile.position() < 28) {
  376.     Serial.print(myFile.read());                 // Reads the character. Spits it out as a Decimal number
  377.     Serial.print(" ");                           // example: 50 48 49 53 45 48 50 45 48 57 32 83 65 84 32 49 50 58 53 49 32 60 47 98 114 62 13 10
  378.  
  379.     //previous5[prev_index] = myFile.read();
  380.     prev_index++;                                // increases the index value. Since it started at 0. Counts for every character in the file.
  381.  
  382.   }
  383.   Serial.println("end");
  384.   //Serial.println(previous5);
  385.  
  386.  
  387.   //Serial.println(myFile.peek());
  388.  
  389.   // read the next 28 characters. And set to char
  390.  
  391.  
  392.  
  393.   myFile.close();
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.  
  401.  
  402.  
  403.  
  404. }
  405.  
  406.  
  407.  
  408.  
  409. // - - - - - - - - - - RTC - Real Time Clock Get time - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  410.  
  411. byte bcdToDec(byte val)  {
  412.   // Convert binary coded decimal to normal decimal numbers
  413.   return ( (val / 16 * 10) + (val % 16) );
  414. }
  415.  
  416.  
  417.  
  418. void printDate() {
  419.  
  420.   // Reset the register pointer
  421.   Wire.beginTransmission(DS1307_ADDRESS);
  422.  
  423.   byte zero = 0x00;
  424.   Wire.write(zero);
  425.   Wire.endTransmission();
  426.  
  427.   Wire.requestFrom(DS1307_ADDRESS, 7);
  428.  
  429.   int second = bcdToDec(Wire.read());
  430.   int minute = bcdToDec(Wire.read());
  431.   int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  432.   int weekDay = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
  433.   int monthDay = bcdToDec(Wire.read());
  434.   int month = bcdToDec(Wire.read());
  435.   int year = bcdToDec(Wire.read());
  436.  
  437.   if (second < 10)  second = ("0", second);
  438.   if (minute < 10)  minute = ("0", minute);
  439.   if (hour < 10)  hour = ("0", hour);
  440.  
  441.  
  442.   //print the date EG   3/1/11 23:59:59
  443.   Serial.print(month);
  444.   Serial.print("/");
  445.   Serial.print(monthDay);
  446.   Serial.print("/");
  447.   Serial.print(weekDay);
  448.   Serial.print("-");
  449.   Serial.print(year);
  450.   Serial.print(" ");
  451.   Serial.print(hour);
  452.   Serial.print(":");
  453.   Serial.print(minute);
  454.   Serial.print(":");
  455.   Serial.println(second);
  456.  
  457.  
  458.  
  459.    
  460.     char * DayOfWeek[7] = {"SUN", "MON", "TUES", "WED", "THU", "FRI", "SAT"};
  461.  
  462.     sprintf(timestamp,  "20%02d-%02d-%02d %s %02d:%02d </br>", year, month, monthDay, DayOfWeek[weekDay], hour, minute);
  463.     Serial.print("TIME2: ");
  464.     Serial.println(timestamp);
  465.  
  466.  
  467.  
  468.   /*
  469.     // String timestampbuild;                                                                                      // You need to build the time stamp string first...
  470.     timestampbuild = (year + "-" + month, "-" + monthDay + " " + weekDay + " " + hour + ":" + minute +  "</br>"); // This builds the variables and characters into the variable TIMESTAMPBUILD
  471.     //timestampbuild.toCharArray(timestamp, 27);                                                                  // This now converts the STRING to a CHARACTER ARRAY in which the CHAR can understand
  472.  
  473.     Serial.print("TIME2: ");
  474.     Serial.println(timestampbuild);
  475.  
  476.     Serial.print("TIME: ");
  477.  
  478.     Serial.println(timestamp);
  479.   */
  480.  
  481. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement