Pages: 1 [2]   Go Down
Author Topic: Seeeduino Stalker Sketches  (Read 7495 times)
0 Members and 1 Guest are viewing this topic.
UK
Offline Offline
Sr. Member
****
Karma: 0
Posts: 273
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi CRS8291,

Thanks for your useful comments on this project:

http://www.airsensor.co.uk/component/zoo/item/energy-monitor.html

I will try and test/update soon  smiley
Logged

Washington State, US
Offline Offline
Newbie
*
Karma: 0
Posts: 29
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I have been doing some modification of the code and have been getting unpredictable results writing to the SD card. I have been using Dane Elec cards which are not recommended by the developer of the Fat16 library. I am now trying a Kingston card and things look better but time will tell. The Fat16 developer recommends Sandisk cards.

I have also built a simple shield to clean up the signal from the IR sensor. It uses a TLC3702CP push-pull comparator to give a nice clean 0 - 5 vdc square wave signal. The comparator eliminates any problems due to background light changes. I set the trigger at 3 volts so anything below 3 volts gives a 0 volt signal and anything above results in a 5 volt signal. The comparator is not entirely neccessary but makes the system more robust. I am new to the Eagle program but tried to put together a schematic:



Edit: If you use 3.3 volts for VDD you do not need the R2 voltage divider.
« Last Edit: October 15, 2010, 07:51:00 pm by CRS8291 » Logged

Washington State, US
Offline Offline
Newbie
*
Karma: 0
Posts: 29
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

This sketch uses the Fat16 and messenger libraries to write incoming data from the serial port to the SD card. It will break the string up using the delimiter in the "Messenger message = Messenger(',');" statement. I am going to use this sketch to receive power data via xBees from my remote power meter.

Code:
/*
 * StalkerFile16MessengerLogger.pde
 * Sketch writes all incoming data from serial port to SD card
 *
 * Sketch tested using Kingston 2 GB card
 * Dane Elec card would not work - See Fat16 readme.txt for info
 *
 * CRS8291 - Arduino forum username
 */

#include <Messenger.h> // the messenger library - http://www.arduino.cc/playground/Code/Messenger
#include <Fat16.h>      // the SD Card library - http://code.google.com/p/fat16lib/
#include <Wire.h>  
#include <Time.h>  
#include <DS1307RTC.h> // a basic DS1307 library - http://www.arduino.cc/playground/Code/Time

//Messenger message = Messenger(); // space delimiter
Messenger message = Messenger(','); // ',' delimiter
#define MAXSIZE 60
char tempString[MAXSIZE];
const char *fileName = "logdata.csv";  // the name of the log file

SdCard card;
Fat16 LogFile;

void setup(void)
{
  setSyncProvider(RTC.get);   // the function to get the time from the RTC

  message.attach(messageCompleted);

  // initialize the SD card
  if (!card.init())
    error(1);

  // initialize a FAT16 volume
  if (!Fat16::init(&card))
    error(2);

  // open file for append, create if it doesn't exist
  if (!LogFile.open(fileName, O_CREAT | O_APPEND | O_WRITE))
    error(3);

  // clear write error
  LogFile.writeError = false;
  LogFile.println("Start");

  Serial.begin(9600);
}

void loop(void)
{  
  while ( Serial.available() ) message.process( Serial.read() );
}

// routine handle file errors
void error(int err)
{
  Serial.print("Error: ");
  Serial.println(err); // Error code
}

void pauseWithoutDelay (unsigned long delayInterval)
{
  unsigned long startDelayMillis;
  startDelayMillis = millis();
  do {
  }
  while (millis() - startDelayMillis < delayInterval);
}

// Define messenger function
void messageCompleted() {
  // This loop will echo each element of the message separately
  while ( message.available() ) {
    message.copyString(tempString,MAXSIZE);
    Serial.print(tempString); // Echo the string
    Serial.println(); // Terminate the message with a carriage return
    LogFile.print(tempString);
    LogFile.println();
    if (!LogFile.sync())
      error(4);
  }
}

edit: The sketch was tested using hyperterminal. According to the author of the Messenger library, the Arduino Serial Monitor window will not work since it does not send a CR at the end of each input.
« Last Edit: October 16, 2010, 09:25:09 am by CRS8291 » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 2
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Dear Stalkers

A newbie question: how do you connect your Stalker to USB? I've wired a FTDI/USB of Sparkfun to the stalkers FTDI bus (tx->rx, rx->tx: is it ok?), but when loading a sketch, one LED is on, an other is blinking, Sparkfun's txLED blinking, arduino console says "uploading", but nothing else happens!
Where could be the problem?  Should I choose another board from arduino's menu? Which one? Using Arduino21.

Thanks a lot
Andrais
« Last Edit: November 08, 2010, 11:37:32 am by andrais » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 10
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I built the enery project completely (with RTC and datalogger), use the original sketch, but it doesn't work as it should !
http://www.airsensor.co.uk/component/zoo/item/energy-monitor.html

Problem 1: the TSL257: the LED pulses from the Siemens electricity meter are not measured (triggerd).
(I used TSL261 or TSL257)

I tried the TSL257 with a single led (different light intensities), then the pulses come through and everthing works well.
I don't think the problem is the clarity but more the sensitivity (speed) of the TSL257. (I'm not sure)

Alternative/Solution?

Problem 2: according to the site te output should be this:


but in reality I see this:

Start
17:32:41,07/12/91,,0,0
17:32:41,07/12/91,,0,0
17:32:41,07/12/91,,0,0
17:32:41,07/12/91,,0,0
17:32:41,07/12/91,,0,0
17:32:41,07/12/91,,0,0
17:32:41,07/12/91,,0,0
17:32:41,07/12/91,,0,0


Who can help me?

gr. John
« Last Edit: November 15, 2010, 09:11:42 am by softwareregi » Logged

UK
Offline Offline
Sr. Member
****
Karma: 0
Posts: 273
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi softwareregi,

I think the sensor choice will depend on the meter LED - the advantage of using the IR sensor is that it is less sensitive to ambient light - using the visible light version requires more care shielding the sensor from the surrounding light but is less fussy about the pulse LED.

Your output looks slightly odd - if the sensor wasn't picking anything up you would get '0' - could you share you code with us?

Maybe you have it working by now?
Logged

Washington State, US
Offline Offline
Newbie
*
Karma: 0
Posts: 29
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

softwareregi,

The bad data looks like a problem with RAM. If you are using a 168 Stalker you need to adjust the RX_BUFFER_SIZE from 128 to 16 in the HardwareSerial.cpp file and it should work.

The HardwareSerial.cpp file can be found in the following directory:

\arduino-0021\hardware\arduino\cores\arduino

The line you are modifying should look like this:

// #define RX_BUFFER_SIZE 128
#define RX_BUFFER_SIZE 16

Make sure to adjust the value back to a suitable value before compiling a sketch that requires a larger input buffer.

The Fat16 library uses more RAM than the filelogger library so I have had to use the filelogger library for many of my 168 sketches.
Logged

Washington State, US
Offline Offline
Newbie
*
Karma: 0
Posts: 29
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Here is some updated code I have been using. Currently I have a Stalker 168 at the power meter that is transmitting data via xBee to a Stalker 328 in the house that displays data every minute. I would recommend to any new users to buy Stalker 328 which will simplify the sketches. The Fat16 library can not always be used with the 168 so I have had to use the filelogger library for the 168. Even then I had to cut back the code to stay within RAM constraints. The following links are updated links to the Robotshop Stalker parts:

http://www.robotshop.com/seeedstudio-stalker-sensor-network-node-atmega-328.html

The USB to serial adapter that I am using has been discontinued but I think this is the updated replacement:

http://www.robotshop.com/seeedstudio-uartsb-v3-1-usb-serial-4.html

Here is the sketch for the remote sender located at the power meter:

Code:
/*
 * Stalker168PowerMeterRemote.pde
 * written for Seeeduino Stalker 168
 * http://www.robotshop.com/seeedstudio-stalker-wireless-sensor-network-node-5.html
 *
 * Electrical meter reading program using Itron smart meter
 * Sketch writes incoming data from TAOS TSL261R-LF IR detector
 * http://www.mouser.com/ProductDetail/TAOS/TSL261R-LF/?qs=CIfwDiMrXj0BIeOZ4sD%2fhg%3d%3d
 *
 * sends data using XBee-PRO ZNet 2.5 XBP24-BCIT-004
 * http://www.mouser.com/ProductDetail/Digi-International/XBP24-BCIT-004/?qs=sGAEpiMZZMtJacPDJcUJY2Ro%2fNGQ4eBC7%2fwjC79KdPU%3d
 *
 * used TLC3702CP push-pull comparator to clean up signal
 * http://www.mouser.com/ProductDetail/Texas-Instruments/TLC3702CP/?qs=sGAEpiMZZMuS%2fmO2LfY7hhByNnTW%252b7YUu2V8j1TPY%2fQ%3d
 *
 * Data output in following format with example
 * siteID, unixTime, watts, totalWatts, temperature counts
 * 14,1287238560,10,1678,21345
 *
 * CRS8291 - Arduino forum username
 */

#include "FileLogger.h" // http://code.google.com/p/arduino-filelogger/
#include <Time.h>  
#include <Wire.h>  
#include <DS1307RTC.h> // a basic DS1307 library - http://www.arduino.cc/playground/Code/Time

const int ledPin = 8;   // LED watt indicator initialization.
int ledState = LOW;  // LED indicator lamp state
unsigned long ledOnTime = 0;     // start time of LED indicator lamp

volatile unsigned int wattSensor = 0;  // Counts power pulses in interrupt, 1 pulse = 1 watt
unsigned int wattSensorCount; //number of watts during logging interval (1 minute)
unsigned long totalWatts = 0;  // Total power used for the month

byte Buffer[33]; //Buffer for printing to SD card
int result; //status of SD card write - 0 = "OK", 1 = "Fail initializing", 2 = "Fail appending"
int length; //length of buffer string

time_t oldtime=0; //last time loop has ran

const int tempPin = 1; //the analog pin the TMP36's Vout (sense) pin is connected to
unsigned int tempReading; //raw temperature response (0 to 1023) times 100 readings

void setup(void)
{
  pinMode(ledPin, OUTPUT);  // LED watt indicator initialization

  attachInterrupt(1, wattSensorInterrupt, FALLING);

  setSyncProvider(RTC.get);   // the function to get the time from the RTC

  Serial.begin(9600);
}

void loop(void)
{
  time_t t = now();
  // turn watt led off if 50 ms has passed since watt counted
  if (digitalRead(ledPin) == HIGH && millis() - ledOnTime >= 50) {
    digitalWrite(ledPin, LOW);
  }
  if( minute(t) != oldtime) //use this if 1 minute intervals is desired
  {
    wattSensorCount = wattSensor; //get the count from the interrupt handler
    wattSensor = 0;           //reset the watts count
    totalWatts = totalWatts + wattSensorCount; //total watts counter
    oldtime = minute(t); //use this for one minute interval
    measureTemperature();

    do
    {
      Buffer[0]='1'; //Site ID = "14"
      Buffer[1]='4';
      Buffer[2]=','; //data string delimeter
      //format of printDigits - printDigits(tempBuffer,bufferPntr,numberDigits)
      printDigits(t,3,10); //t = now()
      Buffer[13]=',';
      printDigits(wattSensorCount,14,3); //wattSensorTemp
      Buffer[17]=',';
      printDigits(totalWatts,18,7); //totalWatts
      Buffer[25]=',';
      printDigits(tempReading,26,5); //raw temperature reading
      Buffer[31]=0x0D; //carriage return/line feed
      Buffer[32]=0x0A;

      length=sizeof(Buffer);
      result = FileLogger::append("data.txt", Buffer, length); // write data to SD card
    }
    while( result != 0);

    // send data string three times to xBee seven seconds apart
    for (int k=0; k < 3;k++) {
      for (int i=0; i < length ;i++) {
        Serial.print(Buffer[i]); //Serial print buffer string to serial monitor or xBee
      }
      pauseWithoutDelay(7000);
    }
  }
}

void measureTemperature (void) {
  tempReading = 0;        // the analog reading from the sensor
  analogRead(tempPin); //discard first reading
  for (int i = 0; i < 100; i++) {
    tempReading = tempReading + analogRead(tempPin); // add up 100 readings from the temperature sensor
  }
}

void printDigits(unsigned long tempBuffer, int bufferPntr, int numberDigits) //assign data to output array
{
  for (int i = 0; i < numberDigits; i++) {
    Buffer[bufferPntr+numberDigits-1-i] = tempBuffer%10 + '0';
    tempBuffer /= 10;
  }
}

void wattSensorInterrupt() // routine called when external interrupt is triggered
{
  wattSensor = wattSensor + 1;  //Update number of pulses, 1 pulse = 1 watt
  ledOnTime = millis();
  digitalWrite(ledPin, HIGH);
}

void pauseWithoutDelay (unsigned long delayInterval) {
  unsigned long startDelayMillis = millis();
  while (millis() - startDelayMillis < delayInterval);
}

The next reply will contain the sketch for the incoming data.
Logged

Washington State, US
Offline Offline
Newbie
*
Karma: 0
Posts: 29
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The sketch for incoming data uses the Messenger library to parse the incoming data. It seems to be a pretty easy way to hadle incoming data streams. The data validation section still needs a little work.

Code:
/*
 *
 * Stalker328PowerMeterLocal.pde
 * written for Seeeduino Stalker 328
 * http://www.robotshop.com/seeedstudio-stalker-sensor-network-node-atmega-328.html
 *
 * Sketch writes incoming electrical power data from serial port to SD card
 * Parses data using Messenger library into seperate elements using "," delimiter
 *
 * displays data on RobotShop DFRobot LCD Keypad shield
 * http://www.robotshop.com/dfrobot-lcd-keypad-shield-arduino-1.html
 * LCD shield pin 10 backlight control needs to be bent/removed to not interfere with SD card
 *
 * receives data using XBee-PRO ZNet 2.5 XBP24-BCIT-004
 * http://www.mouser.com/ProductDetail/Digi-International/XBP24-BCIT-004/?qs=sGAEpiMZZMtJacPDJcUJY2Ro%2fNGQ4eBC7%2fwjC79KdPU%3d
 *
 * Sketch tested using Kingston, Transcend, and Sandisk 2 GB cards
 * Dane Elec card and Ritech cards would not work - See Fat16 readme.txt for info
 *
 * Incoming data in following format with example
 * siteID, unixTime, watts, totalWatts, temperatureCounts
 * 14,1287238560,10,1678,21300
 *
 * CRS8291 - Arduino forum username
 */

#include <Fat16.h>      // the SD Card library - http://code.google.com/p/fat16lib/
#include <Messenger.h> // the messenger library - http://www.arduino.cc/playground/Code/Messenger
#include <Wire.h>  
#include <Time.h>  
#include <DS1307RTC.h> // a basic DS1307 library - http://www.arduino.cc/playground/Code/Time
#include <LiquidCrystal.h>
#include <stdio.h>  //Needed for sprintf conversion from long to char *

LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //config for DFRobot shield

const char *fileName = "logdata.csv";  // the name of the log file

SdCard card;
Fat16 LogFile;

//Messenger message = Messenger(); // use this for space delimiter
Messenger message = Messenger(','); // use this for ',' delimiter

int nextLcdPrint = 1; // Switch/Case option for printing to LED

int siteID = 0;
time_t unixTime = 0; // unix time from remote Stalker
time_t t; // unix time for local Stalker

long watts = 0; // watts counted in one minute
unsigned long totalWatts = 0; // total watts since reset
unsigned long previousUnixTime = 0; // previous unix time of remote data string

unsigned long demandMinutes[15];  //Array that holds each powerusage reading done during the last 15 minutes
unsigned long demandMinutesKwh=0; //Average of last 15 minutes in Kwh
unsigned long maxDemandKwh=0; //Maximum 15 minute demand in Kwh

int tempReading = 0; // temperature counts * 100 from remote sensor
int temperatureF; // temperature * 10 in degrees F
int todayMinTemp = 1400; // set todays min to 140.0 deg F
int todayMaxTemp = -400; // set todays max temperature to -40.0 deg F
int yesterdayMinTemp = -990; // set yesterdays min temperature to -99.0 deg F
int yesterdayMaxTemp = -990; // set yesterdays max temperature to -99.0 deg F
int newDay; // used for moving min/max temperatures to yesterdays min/max
int newMonth; // used for resetting monthly totals

// temporary variables for validating received data
int siteIDIn; // Site ID
time_t unixTimeIn; // Unix Time
long wattsIn; // watts for last minute
unsigned long totalWattsIn; // total watts
int tempReadingIn; // temperature counts

int alarmPin = 3; // Piezo Buzzer; http://www.adafruit.com/index.php?main_page=product_info&cPath=35&products_id=160
unsigned long alarmOn=0; // alarm start time
int alarmThreshold = 3000; // alarm threshold - 3.000 kwh

void setup(void)
{
  Serial.begin(9600);

  // initialize the SD card
  if (!card.init())
    error(1);

  // initialize a FAT16 volume
  if (!Fat16::init(&card))
    error(2);

  // open file for append, create if it doesn't exist
  if (!LogFile.open(fileName, O_CREAT | O_APPEND | O_WRITE))
    error(3);

  // clear write error
  LogFile.writeError = false;

  pinMode(alarmPin, OUTPUT);

  LogFile.print("Start");
  LogFile.println();

  setSyncProvider(RTC.get);   // the function to get the time from the RTC

  message.attach(messageCompleted);

  for (int i=0; i<15 ;i++) //Initialize last fifteen minute Kwh to 0
    demandMinutes[i]=0;
    
  newDay = day(); // set new day variable to today
  newMonth = month(); // set new month variable to current month

  lcd.begin(16, 2);
  lcd.setCursor(0, 0); //line 0, column 0
  lcd.print("Collecting Data");
  lcd.setCursor(0, 1);  //line 1, column 0
  lcd.print("  Please Wait  ");
}

void loop(void)
{
  while ( Serial.available() ) message.process( Serial.read() );

  t = now(); // get local unix time

  // change LCD display every five seconds
  if(second(t) % 5 == 0) {
    switch(nextLcdPrint) {

    case 1: // display date, time, and current temperature
      lcd.setCursor(0, 0);  //line=0, x=0
      LcdPrintDate(); // print date and time

        lcd.setCursor(0, 1);  //line=1, x=0
      lcd.print("Temp:");
      lcd.setCursor(5, 1);  //line=1, x=6
      LcdPrintTemperature(temperatureF); //Print temperature in deg F
      lcd.setCursor(12, 1);  //line=1, x=12
      lcd.print("    "); // clear out rest of line
      nextLcdPrint = 2; // go to next case
      // sound alarm or wait one second
      if (demandMinutesKwh > alarmThreshold && maxDemandKwh > alarmThreshold) alarm();
      else pauseWithoutDelay (1000); // Delay sketch for one second
      break;

    case 2: // display todays and yesterdays min/max temperatures
      lcd.setCursor(0, 0);  //line=0, x=0
      lcd.print("Tday:           ");
      lcd.setCursor(5, 0);  //line=0, x=5
      LcdPrintMinMax(todayMinTemp); //Print todays min temperature
      lcd.setCursor(11, 0);  //line=0, x=11
      LcdPrintMinMax(todayMaxTemp); //Print todays max temperature

      lcd.setCursor(0, 1);  //line=1, x=0
      lcd.print("Yday:           ");
      lcd.setCursor(5, 1);  //line=1, x=5
      LcdPrintMinMax(yesterdayMinTemp); //Print yesterdays min temperature
      lcd.setCursor(11, 1);  //line=1, x=11
      LcdPrintMinMax(yesterdayMaxTemp); //Print yesterdays max temperature
      nextLcdPrint = 3; // go to next case
      // sound alarm or wait one second
      if (demandMinutesKwh > alarmThreshold && maxDemandKwh > alarmThreshold) alarm();
      else pauseWithoutDelay (1000); // Delay sketch for one second
      break;

    case 3: // display 1 minute and accumulated power usage
      lcd.setCursor(0, 0);  //line=0, x=0
      lcd.print("1min:");
      lcd.setCursor(5, 0);  //line=0, x=5
      LcdPrintValue(watts*60); //Print 1 minute usage in Kwh
      lcd.setCursor(13, 0);  //line=0, x=13
      lcd.print("Kwh");

      lcd.setCursor(0, 1);  //line=1, x=0
      lcd.print("Sum :");
      lcd.setCursor(5, 1);  //line=1, x=5
      LcdPrintValue(totalWatts); //Print total accumulated Kw usage
      lcd.setCursor(13, 1);  //line=1, x=13
      lcd.print("Kw ");
      nextLcdPrint = 4; // go to next case
      // sound alarm or wait one second
      if (demandMinutesKwh > alarmThreshold && maxDemandKwh > alarmThreshold) alarm();
      else pauseWithoutDelay (1000); // Delay sketch for one second
      break;

    case 4: // display current and max 15 minute demand
      lcd.setCursor(0, 0);  //line=0, x=0
      lcd.print("Demd:");
      lcd.setCursor(5, 0);  //line=0, x=5
      LcdPrintValue(demandMinutesKwh); //Print current demand data in Kwh
      lcd.setCursor(13, 0);  //line=1, x=13
      lcd.print("Kwh");

      lcd.setCursor(0, 1);  //line=1, x=0
      lcd.print("MaxD:");
      lcd.setCursor(5, 1);  //line=1, x=5
      LcdPrintValue(maxDemandKwh); //Print maximum demand data in Kwh
      lcd.setCursor(13, 1);  //line=1, x=13
      lcd.print("Kwh");
      nextLcdPrint = 1; // go back to 1st case option
      // sound alarm or wait one second
      if (demandMinutesKwh > alarmThreshold && maxDemandKwh > alarmThreshold) alarm();
      else pauseWithoutDelay (1000); // Delay sketch for one second
      break;

    default:
      nextLcdPrint = 1;  
    }
  }
}

// display LCD power data
void LcdPrintValue(unsigned long value) {
  int value1 = value / 1000; // convert unsigned long to seperate integer values
  int value2 = value % 1000;
  byte len = 8;
  char buffer[len];
  sprintf(buffer, "%4i.%03i", value1, value2);
  lcd.print(buffer);
}

// display LCD date and time
void LcdPrintDate() {
  byte len = 16;
  char buffer[len];
  sprintf(buffer, "%02i/%02i/%04i %02i:%02i", month(unixTime),day(unixTime),year(unixTime),hour(unixTime),minute(unixTime));
  lcd.print(buffer);
}

//display LCD temperature
void LcdPrintTemperature(int value) {
  byte len = 8;
  char buffer[len];
  sprintf(buffer, "%3i.%1i\337F", value / 10, abs(value) % 10);
  lcd.print(buffer);
}

// display LCD min/max temperature data
void LcdPrintMinMax(int value) {
  byte len = 6;
  char buffer[len];
  sprintf(buffer, "%3i.%1i", value / 10, abs(value) % 10);
  lcd.print(buffer);
}

// calculate temperature in deg F
void calcTemperature () {
  if (tempReading >= 9999) temperatureF = ((tempReading * 0.058) - 579.5);
  else temperatureF = ((tempReading * 0.058) - 580.5); //add/subtract 0.5 for rounding
}

It looks like I have to break the sketch into two parts, part II next.
Logged

Washington State, US
Offline Offline
Newbie
*
Karma: 0
Posts: 29
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Here is the remainder of the sketch:

Code:
// routine handle file errors
void error(int err)
{
  //  Serial.print("Error: ");
  //  Serial.println(err); // Error code
}

// Define messenger function
void messageCompleted() {
  // This loop will echo each element of the message separately
  while ( message.available() ) {
    siteIDIn = message.readInt();      // read Site ID
    unixTimeIn = message.readLong();   // read Unix Time
    wattsIn = message.readInt();       // read watts for last minute
    totalWattsIn = message.readLong();  // read total watts
    tempReadingIn = message.readInt();  // read temperature counts
  }

  // check data and return if not within limits
  if (siteIDIn != 14) return; // check for correct Site ID
  if (unixTimeIn == previousUnixTime) return; // do not write duplicates
  //if (unixTimeIn < 1288569600 || unixTimeIn > 1325376000) return; // date between Nov 1, 2010 and Jan 1, 2012
  //if (wattsIn < 0 || wattsIn > 600) return; // check watts
  //if (totalWattsIn < 0 || totalWattsIn > 2500000) return; // check total watts
  //if (tempReadingIn < 3100 || tempReadingIn > 32410) return; // temperature between -40 to 130 deg F

  // assign temporary input data to validated data
  siteID = siteIDIn;
  unixTime = unixTimeIn;
  watts = wattsIn;
  totalWatts = totalWattsIn;
  tempReading = tempReadingIn;

  previousUnixTime = unixTime;
  calcTemperature (); // calculate temperature
/*
  Serial.print(siteID);
  Serial.print(',');
  Serial.print(unixTime);
  Serial.print(',');
  Serial.print(watts);
  Serial.print(',');
  Serial.print(totalWatts);
  Serial.print(',');
  Serial.print(tempReading);
  Serial.println();
*/
  LogFile.print(siteID);
  LogFile.print(',');
  LogFile.print(unixTime);
  LogFile.print(',');
  LogFile.print(watts);
  LogFile.print(',');
  LogFile.print(totalWatts);
  LogFile.print(',');
  LogFile.print(tempReading);
  LogFile.println();
  if (!LogFile.sync())
    error(4);

  // calculate 15 minute rolling average
  for (int i=0; i<15 ;i++) //Block move previous 14 minutes by one step
    demandMinutes[i]=demandMinutes[i+1];
  demandMinutes[14]=watts*60; //Assign latest one minute average to 15 minute average array
  demandMinutesKwh=0; //Reset demandMinutesKwh to 0
  for (int i=0; i<15 ;i++)  //Calculate new 15 minute demand
    demandMinutesKwh=demandMinutesKwh+demandMinutes[i];
  demandMinutesKwh=demandMinutesKwh/15;

  // assign maxDemandKwh to demandMinutesKwh if new high demand
  if (demandMinutesKwh > maxDemandKwh)
    maxDemandKwh=demandMinutesKwh;

  // reset maxDemandKwh to zero once a month
  if (month(t) != newMonth) {
    newMonth = month(t);
      maxDemandKwh = 0;
  }

  // move todays min/max temperature to yesterday min/max at midnight
  if (day(t) != newDay) {
    newDay = day(t);
    yesterdayMinTemp = todayMinTemp;
    yesterdayMaxTemp = todayMaxTemp;
    todayMinTemp = 1400; // reset todays min temp to 140.0 deg F
    todayMaxTemp = -400; // reset todays max temp to -40.0 deg F
  }
  // check current temperature against min/max temperature
  if (temperatureF < todayMinTemp) todayMinTemp = temperatureF;
  if (temperatureF > todayMaxTemp) todayMaxTemp = temperatureF;
}

void pauseWithoutDelay (unsigned long delayInterval) {
  unsigned long startDelayMillis = millis();
  while (millis() - startDelayMillis < delayInterval);
}

void alarm () {
  alarmOn = millis();
  analogWrite(alarmPin, 80);
  while ((millis()-alarmOn) <= 1000);
  analogWrite(alarmPin, LOW);
}
Logged

Pages: 1 [2]   Go Up
Jump to: