0

Данный момент использую Arduino Uno и у меня есть подключен Ethernet Shield w5100 подключен термометром для измерения температуры всё как бы клёво работает ну вот задался идеи чтобы подключить функцию называемый uptime как это реализовать в данном коде? просто интересно знать сколько работает Arduino временем.

    // OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library
#include <OneWire.h>
#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[] = {
  0x??, 0x??, 0x??, 0x??, 0x??, 0x??    // Enter your ethernet MAC address. You will find it behind your arduino board.
};
IPAddress ip(192, 168, 1, 102);        // Set your IP address for Arduino Board

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

//--------------------Переменные для Uptime---------------------
long previousMillis = 0;//переменная для хранения значений таймера
int day=0;//значение дней
int hour=0;//значение часов
int min=0;//значение минут
int second=0;//значение сукунд
//--------------------Переменные для Uptime КОНЕЦ-------------

OneWire  ds(2);  // on pin 10 (a 4.7K resistor is necessary)

void setup(void) {
  // 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(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  } 

  ds.reset();
  ds.select(addr);
  ds.write(0x44);        // start conversion, use ds.write(0x44,1) with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);    
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

   // 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");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          client.print("<p style='text-align: center;'>&nbsp;</p>");
          client.print("<p style='text-align: center;'><span style='font-size: x-large;'><strong>Welcome To My Home</strong></span></p>");
          client.print("<p style='text-align: center;'><span style='color: #0000ff;'><strong style='font-size: large;'>Room Temperature = ");
          client.println(celsius);
          client.print("</strong></span><h style='text-align: center;'><span style='color: #0000ff;'><strong style='font-size: large;'><sup>o</sup>C</strong></span></h></p>");
          client.print("<p style='text-align: center;'>&nbsp;</p>");
          client.print("<p style='text-align: center;'>&nbsp;</p>");
          client.print("<p style='text-align: center;'>&nbsp;");

          // Date and Time script
          client.print("<script language='javascript'>");
          client.println();
          client.print("<!--");
          client.println();
          client.print("var today = new Date()");
          client.println();
          client.print("document.write(today); //--> </script>");
          client.print("</p>");

          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 disconnected");
  }
}

1 ответ 1

1

Ну, вот, например, решение отсюда:

/*
 * DEVICE UPTIME
 * -------------
 * Returns the total time in days hours minutes and seconds that arduino running *
 * Limitations apply:
 * Arduino UNO autoresets the board on new serial connection so logs are reseted too.
 * millis overflow every 50 days or so
 * The stats are not aqurate for very long period of time but its good for diagnostic 
 * purposes when arduino is used for final (standalone) project 
 * I use it on my relay board in order to get info if something went wrong
 * Good to know that a power failure caused syste to reset.
 *
 */


//  Creator Nikos Georgousis
//  JAN 2011

int incomingByte =0;
long currentmillis=0;
//############################################ SETUP vvvv  ####################################
void setup () {
 Serial.begin(9600); // open serial port
 Serial.println("'Project Uptime"); //print something to notify user on restart 
}
//############################################ SETUP ^^^^ #####################################
//############################################ LOOP vvvv  #####################################
void loop () {
 SerialCheck (); //redirect ro serial check
}
//############################################ LOOP ^^^^  #####################################
//########################################### SERIALCHECK vvvv  ###############################
void SerialCheck () {
 if (Serial.available() > 0) {
   incomingByte = Serial.read();
   {    
     if (incomingByte==63) // if ? received then answer with data
     {
       currentmillis=millis(); // get the  current milliseconds from arduino
       // report milliseconds
       Serial.print("Total milliseconds running: "); 
       Serial.println(currentmillis);
       uptime(); //call conversion function to display human readable time
     }
   }
 }
}
//######################################## SERIALCHECK ^^^^  #################################
//############################################ UPTIME vvvvv  #################################
void uptime()
{
 long days=0;
 long hours=0;
 long mins=0;
 long secs=0;
 secs = currentmillis/1000; //convect milliseconds to seconds
 mins=secs/60; //convert seconds to minutes
 hours=mins/60; //convert minutes to hours
 days=hours/24; //convert hours to days
 secs=secs-(mins*60); //subtract the coverted seconds to minutes in order to display 59 secs max 
 mins=mins-(hours*60); //subtract the coverted minutes to hours in order to display 59 minutes max
 hours=hours-(days*24); //subtract the coverted hours to days in order to display 23 hours max
 //Display results
 Serial.println("Running Time");
 Serial.println("------------");
 if (days>0) // days will displayed only if value is greater than zero
 {
   Serial.print(days);
   Serial.print(" days and :");
 }
 Serial.print(hours);
 Serial.print(":");
 Serial.print(mins);
 Serial.print(":");
 Serial.println(secs);
}
//############################################ UPTIME ^^^^  #################################

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.