DCCpp
This is the library version of a program for Arduino to control railroading DCC devices.
CurrentMonitor.cpp
1 /**********************************************************************
2 
3 CurrentMonitor.cpp
4 COPYRIGHT (c) 2013-2016 Gregg E. Berman
5 
6 Part of DCC++ BASE STATION for the Arduino
7 
8 **********************************************************************/
9 
10 #include "Arduino.h"
11 
12 #include "DCCpp_Uno.h"
13 #include "CurrentMonitor.h"
14 #include "Comm.h"
15 
17 
18 void CurrentMonitor::begin(int pin, int inSignalPin, const char *msg, float inSampleMax)
19 {
20  this->pin = pin;
21  this->signalPin = inSignalPin;
22  this->msg = msg;
23  this->current = 0;
24  this->currentSampleMax = inSampleMax;
25 } // CurrentMonitor::begin
26 
28 {
29  if(millis( ) - sampleTime < CURRENT_SAMPLE_TIME) // no need to check current yet
30  return(false);
31  sampleTime = millis(); // note millis() uses TIMER-0. For UNO, we change the scale on Timer-0. For MEGA we do not. This means CURENT_SAMPLE_TIME is different for UNO then MEGA
32  return(true);
33 } // CurrentMonitor::checkTime
34 
36 {
37  if (this->pin == UNDEFINED_PIN || this->signalPin == UNDEFINED_PIN)
38  return;
39 
40  #if defined(ARDUINO_ARCH_ESP32)
41  // Compute an average value of 50 read.
42  int base = 0;
43  for (int j = 0; j < 50; j++)
44  {
45  base += analogRead(this->pin);
46  }
47  this->current = (float) ((base / 50.0) * 0.9) - 100;
48  #else
49  this->current = (float)(analogRead(this->pin) * CURRENT_SAMPLE_SMOOTHING + this->current * (1.0 - CURRENT_SAMPLE_SMOOTHING)); // compute new exponentially-smoothed current
50  #endif
51 
52  // current overload and Signal is on
53  if (this->current > this->currentSampleMax && digitalRead(this->signalPin) == HIGH)
54  {
55  digitalWrite(this->signalPin, LOW);
56  DCCPP_INTERFACE.print(this->msg); // print corresponding error message
57 #if !defined(USE_ETHERNET)
58  DCCPP_INTERFACE.println("");
59 #endif
60  }
61 } // CurrentMonitor::check
62 
static boolean checkTime()
static long int sampleTime
void begin(int pin, int inSignalPin, const char *msg, float inSampleMax=300)
const char * msg
float currentSampleMax