My very first code, Looking for feedback...

This is the first code I've ever written. I'm new to programming so excuse my lack of knowledge. I wrote this for an automatic water top off for my reef aquarium. I've seen a lot of examples with people using regular mechanical float switches but I wanted to do something better by using optical IR liquid level. I added the delays because the optical level is really sensitive so when it would get close to triggering it would turn on the pump ON for a split second repeatedly until the water level was low enough to fully trigger. Is there a better way of doing this. I also wanted to somehow add a functionality that if the sensor was triggered ON for more than 1 minute without turning OFF it would shut down the whole system. Ill will gladly take suggestions on how to do this.

here is my code:

const int analogPin = A0;       // pin that is attached to IR liquid sensor
const int pump = 12;            // pin that is attached to the transister NTE253 that triggers the pump ON
const int threshold = 800;      // an arbitrary threshold level that's in the range of the analog input


void setup(){
  pinMode (pump,OUTPUT);
  Serial.begin(9600);
}
void loop() {
 int analogValue = analogRead(analogPin);
  if (analogValue > threshold) {
  delay (500);  
    digitalWrite(pump, HIGH);
  delay (500);
  } 
  else {
    digitalWrite(pump, LOW);
  delay (20000);
  }
  Serial.println(analogValue);
  delay (1000);
}

THIS CODE SUCKS !

(no just kidding, ha ha . XD I'll take a look at it ...)

I added the delays because the optical level is really sensitive so when it would get close to triggering it would turn on the pump ON for a split second repeatedly until the water level was low enough to fully trigger.

A common control problem solved by adding hysteresis. (http://en.wikipedia.org/wiki/Hysteresis)

The concept is very simple, instead of turning the pump on when the level is less than X and turning it off when the level is greater than X, turn the pump on when the level is less than X minus some delta and turn it off when the level is greater than X plus some delta.

I wrote this for an automatic water top off for my reef aquarium

. I’ve seen a lot of examples with people using regular mechanical float switches but I wanted to do something better by using optical IR liquid level.

What if I told you there was something even better than that ?
see page 5 of this: (datasheet attached)
http://pdf.datasheetcatalog.com/datasheet/nationalsemiconductor/DS005700.PDF
See if you can figure out how this chip can be used to do what you asked.
See if you can figure out how this may be better than a float switch,

I added the delays because the optical level is really sensitive so when it would get close to triggering it would turn on the pump ON for a split second repeatedly until the water level was low enough to fully trigger.
Is there a better way of doing this.

I also wanted to somehow add a functionality that if the sensor was triggered ON for more than 1 minute without turning OFF it would shut down the whole system. Ill will gladly take suggestions on how to do this.

See attached sketch from which the below code was copied:
Study the code in this sketch and see if you can figure out how this relates to your question:

void loop()
 {
    
    // Text on display  
    int garagesensorpinStatus = 0;                      
    garagesensorpinStatus = digitalRead(garagesensorpin); 
    
    if (garagesensorpinStatus == HIGH)
      {
        lcd.setCursor(0,0);              
        lcd.print("Garasjen");        
        lcd.setCursor(0,1);             
        lcd.print("er ");                  
        lcd.write(2);                
        lcd.print("pen   ");         
      } 
      else 
      {                
        lcd.setCursor(0,0);       
        lcd.print("Garasjen");         
        lcd.setCursor(0,1);          
        lcd.print("er lukket");            
    }

    // Backlight on - ten seconds - then off again   
    int blpinStatus = 0;
    blpinStatus = digitalRead(blpin);
    static unsigned long blTime;
    static boolean blOn;
    
    if (blpinStatus == LOW) {
      delay(20);        // Debounce
      blOn = true;
      blTime = millis();
      lcd.backlight();
    } 
    if (blOn == true && millis() - blTime > 10000)
     {
      lcd.noBacklight();
      blOn = false;
     }
}

LM1830.pdf (121 KB)

garagesensor.ino (2.45 KB)

I got really busy with work but now I have time for my project again...

What if I told you there was something even better than that? see page 5 of this: (datasheet attached) http://pdf.datasheetcatalog.com/datasheet/nationalsemiconductor/DS005700.PDF See if you can figure out how this chip can be used to do what you asked. See if you can figure out how this may be better than a float switch,

This chip seems really interesting. I don't fully understand it but I went ahead and ordered one a few days ago to tinker with it. I need to study the data sheet some more.

Study the code in this sketch and see if you can figure out how this relates to your question:

yes, thats exactly what i was looking for. Ill try to write something with this over the next few days.

Any questions about the chip ?

raschemmel: Any questions about the chip ?

I think understands what is does. its works as a oscillator??? Also I'm really not understanding the wiring. Cant seem to get it working on a breadboard.

If you didn't understand how the chip works you were supposed to ask BEFORE trying to run it on a breadboard. That's why I asked you if you had any questions about the chip. First of all, I am a little confused as to how you could have wired it up if you didn't understand how it works. Why didn't you ask before trying to use ? Where did you get the schematic you are using ? Draw a schematic of how you wired it and post a photo of it. Let's hope you haven't blown the chip already.

raschemmel: If you didn't understand how the chip works you were supposed to ask BEFORE trying to run it on a breadboard. That's why I asked you if you had any questions about the chip. First of all, I am a little confused as to how you could have wired it up if you didn't understand how it works. Why didn't you ask before trying to use ? Where did you get the schematic you are using ? Draw a schematic of how you wired it and post a photo of it. Let's hope you haven't blown the chip already.

dont think i fired it, i didnt put any power to the board. I was just trying to piece it together using the examples on the datasheet but could figure it out. Ive hit a brick wall...

First of all . Tell what you have learned by looking at the datasheet.
Before you do fry the chip let me just say it should be obvious that the transistor is used to do everything from send a simple digital LOW (10K Pullup resistor from the collector of the transistor to +Vcc) to drive piezo buzzers or sump pumps .
The first thing I need to know is how do YOU think the chip is SUPPOSED to be used , based on the examples on the last pages of the datasheet ? (which examples did you try and exactly HOW did you test them ?)

Read this:

http://www.aaroncake.net/circuits/pumpcon.asp
http://www.ecircuitslab.com/2012/11/water-alarm-schematic.html
http://citroen.tramontana.co.hu/electrics/windscreen-washer-fluid-level
http://www.hobby-hour.com/electronics/fluid_level_control_schematics.php

Note the Operating Voltage range up to 28Vdc. This means a 12V battery can be used to power the circuit and a 5V zener diode with a series current limiting resistor used to lower the voltage for interfacing to the arduino.

When the probe is not touching the water it equal to an open circuit situation and surely the probe resistance will be many M ohms and it is greater than the Rref(13K). The internal transistor will be switched ON and Q1 whose base is connected to the collector of the internal transistor will be in OFF condition keeping the relay inactive. When the reverse scenario occurs (fluid level touches the probe) the internal transistor is switched OFF and this in turn makes the transistor Q1 ON resulting in the activation. The load connected through the relay whether pump, lamp, alarm, solenoid valve or anything is driven.

Probe: The probe used here can be any metal rod with size and shape of your choice. The tank must be made of metal and it should be properly grounded. For non metal tanks fix a small metal contactor at its bottom level and ground it. The probe must be placed at the level you want to monitor.
Notes.
The circuit can be assembled on a Perf board.
I used 12V DC for powering the circuit.
Maximum supply voltage LM1830 can handle is 28V.
The tweeter I used was of a 16 ohm type.
The relay I used is a 200 ohm/12V type.
Maximum load current Q1 (2N2222) can handle is 800mA.
The switching current/voltage ratings of the relay must be according to the load you want to drive using it.
It is recommended to mount the IC on a holder.

LM1830 APP NOTE snoa576a.pdf (117 KB)

if we are in teaching mode, shouldnt the code we offer avoid bad habits and inefficiencies such as

identical blocks of code in both branches of an if statement?

solution one
execute the common code, THEN do the if, with only the unique stuff in each branch

solution two…more educational, less efficient, but still a lot better than the example given:

refactor common code to its own function
call the function in each branch of the if

its even worse in an embedded scenario as we are duplicating long strings, unless the compiler optimizes duplicate strings to a single instance…does it? I dont know. do you? its a question that doesnt need to be asked if we give good clean examples…

@BareMetal, If you are referring to the sketch "Garagesensor", that was to give the OP an example of the use of "millis" and nothing else.

yes I was and I dont want to sound too critical because you are obviosuly working hard to help people and I seriously appreciate your excellent posts....

just saying it wasnt the best example, no matter its reason for inclusion as it contained fundamental no.nos that might perplex a newbie.

just my opinion, some may find it helpful. after 39 years of programming, for me clean code is always the best/easiest/safest...read the story of Van Halen's tour rider for NO brown m&ms in the dressing room

Then your more qualified to post a better example because I've only been programming since last october and I didn't write the example we're talking about.

raschemmel: Then your more qualified to post a better example because I've only been programming since last october and I didn't write the example we're talking about.

maybe so, but much more lazy, too. you are doing a great job. its folk like you who make this forum work. grumpy old gits like me just add occasional spice.

maybe so, but much more lazy, too. you are doing a great job. its folk like you who make this forum work. grumpy old gits like me just add occasional spice.

Thanks for the compliment. You are too kind. I have been criticized for being too strict (accused of Drill Sargeant mentality) You might find this funny , but the truth is that my first real job (in 1966) was working at a restaurant chain in CA, USA called "Bob's Big Boy" Family Restaurants. I was 17 and they hired me because I had NO experience. They said they preferred a clean slate. They proceeded to indoctrinate me. Their policy was that a "Newbie" (new employee) was never responsible for their actions because they "know not what they doith..." so the "Trainer" (every newbie was assigned a trainer) was responsible for the actions of their "grunts" (newbies). When a manager or other experienced person saw a newbie making a mistake, he would simply ask them "Who trained you?" and then he would go look for that person to chew out. This system of accountability seemed to work because you were never promoted based on your direct actions. Instead, you got promoted when your Newbie got promoted. If he didn't get promoted , then neither did you. Over time you eventually learned how to "program" people to do things correctly (similar I suppose to military training). The concept was that everything was based on prior training and if that was correct , everything that followed would be correct (eventually). The short version is that nothing should be ignored and what may seem like a trivial error is significant because it is an indication of inadequate training because when the training is correct, there are no mistakes, and everything is repeatable and correct. I don't know if any of this makes any sense but that's the basic premise. Everything comes down to attention to detail and overlook nothing.

the chinese say "give a man a fish and you feed him for a day...teach him to fish and you feed him for life"

im also a SCUBA instructor and have a military / law enforcement background, and I tend to agree with your basic philosophy of teching fishermen rather than feeding them forma day with handouts.

in the nicest possible way, I can see a hint of the drill sergeant...but it aint such a bad thing, dont take it as a huge criticism, its an observation. as I said before, forumsget like this depend on guys like you.

"I dont know, but I been told... 'duino pins are made of gold read your datasheet in full then you wont get no more bull"

get down and give me 0x12!!!!

:)

"I dont know, but I been told... 'duino pins are made of gold read your datasheet in full then you wont get no more bull"

get down and give me 0x12!!!!

Brings back memories of Air Force Basic Training at Lackland AFB, San Antonio , TX, (1969)

raschemmel:

"I dont know, but I been told... 'duino pins are made of gold read your datasheet in full then you wont get no more bull"

get down and give me 0x12!!!!

Brings back memories of Air Force Basic Training at Lackland AFB, San Antonio , TX, (1969)

glad you liked it. for me its Hendon Metropolitan Police concentration...sorry..."training" camp.