Skip to content

Instantly share code, notes, and snippets.

@bjoern-r
Created April 14, 2020 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoern-r/63c5fbd2770d281e3e432547f765e787 to your computer and use it in GitHub Desktop.
Save bjoern-r/63c5fbd2770d281e3e432547f765e787 to your computer and use it in GitHub Desktop.
Simple Arduino sketch to control a relais to switch a relais if the voltage read from the adc is below a certain level
/*
Battery Guard
Use an arduino nano and connect the input voltage with an voltage divider to A0
I used 9kOhm and 1kOhm to get a /10 divider to be able to measure up to 50V
Switch points are for a 12v AGM battery.
The relais is controlled via D7.
*/
#define NUM_READINGS 10
#define RELAIS_PIN 7
#define ADC_REF 5.0
#define CUTOFF_VALUE ((9*1023)/(ADC_REF*10))
#define OFF_VALUE ((10.5*1023)/(ADC_REF*10))
//#define ON_VALUE ((12.5*1023)/(ADC_REF*10))
#define ON_VALUE ((11.5*1023)/(ADC_REF*10))
int readings[NUM_READINGS]; // the readings from the analog input
const int inputPin = A0;
void handleOutput(int value){
static int aboveCount = 0;
static int belowCount = 0;
if (value>ON_VALUE){
aboveCount++;
belowCount=0;
//Serial.print("+");
}
if (value<OFF_VALUE){
belowCount++;
aboveCount = 0;
//Serial.print("-");
}
if(value<CUTOFF_VALUE) {
digitalWrite(LED_BUILTIN, LOW);
digitalWrite(RELAIS_PIN, LOW);
}else if (belowCount> 100){
digitalWrite(LED_BUILTIN, LOW);
digitalWrite(RELAIS_PIN, LOW);
}else if (aboveCount > 100){
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(RELAIS_PIN, HIGH);
}
}
// the setup routine runs once when you press reset:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(RELAIS_PIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
digitalWrite(RELAIS_PIN, LOW);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
//analogReference(INTERNAL2V56);
for (int thisReading = 0; thisReading < NUM_READINGS; thisReading++) {
readings[thisReading] = 0;
}
Serial.print("LOW: ");
Serial.println(CUTOFF_VALUE);
Serial.print("High: ");
Serial.println(ON_VALUE);
}
// the loop routine runs over and over again forever:
void loop() {
static int total = 0;
static int readIndex = 0;
// subtract the last reading:
total = total - readings[readIndex];
// read from the sensor:
readings[readIndex] = analogRead(inputPin);
// add the reading to the total:
total = total + readings[readIndex];
// advance to the next position in the array:
readIndex = (++readIndex)%NUM_READINGS;
// calculate the average:
int average = total / NUM_READINGS;
float voltage = average * (ADC_REF / 1023.0)*10;
// print out the value you read:
Serial.print(voltage);
Serial.print(" V\t");
// send it to the computer as ASCII digits
Serial.println(average);
handleOutput(average);
delay(60); // delay in between reads for stability
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment