Controling relay or valve pin with serial input

I have the following code that opens and closes a solenoid valve. However I would like to press O for Open Or C for Close on the keyboard and this should send digitalWrite(pin, LOW); / digitalWrite(pin, HIGH); to my arduino.

#define VALVE_PIN 2

class valveControl {
//defining attributes
private:
byte pin;
public:
valveControl(byte pin) {
// Use 'this->' to make the difference between the
// 'pin' attribute of the class and the
// local variable 'pin' created from the parameter.
this->pin = pin;
init();
}

void init() {
  pinMode(pin, OUTPUT);
  // Always try to avoid duplicate code.
  // Instead of writing digitalWrite(pin, LOW) here,
  // call the function off() which already does that
  off();
}

void on() {
  digitalWrite(pin, HIGH);
}

void off() {
  digitalWrite(pin, LOW);
}

}; // don't forget the semicolon at the end of the class

class valveControler {
// class definition
};
valveControl valve(VALVE_PIN);
void setup() { }
void loop() {
valve.on();
delay(100000);
valve.off();
delay(100000);
}

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

Do you know how to read a character from the keyboard and test its value ?

Welcome

Would you share code examples?

consider

#define VALVE_PIN 2
enum { Open = HIGH, Close = LOW };

void loop ()
{
    if (Serial.available ())  {
        char c = Serial.read ();

        if ('o' == c)
            digitalWrite (VALVE_PIN, Open);
        else if ('c' == c)
            digitalWrite (VALVE_PIN, Close);
    }
}

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

    digitalWrite (VALVE_PIN, Close);
    pinMode      (VALVE_PIN, OUTPUT);
}

Helped me a lot!

@19940224Alex, i'm curious, why did you start with a class?

I study Computer Science and we are thought to code in OOP rather than procedural programming. Also there are other components/ objects that I would like to add. Still a newbie.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.