1

In a library I am using with an OBD adapter, they define a public function to get the state of the OBD connection using some strange (and, in my opinion, useless) custom defined variable type:

// states
typedef enum {
    OBD_DISCONNECTED = 0,
    OBD_CONNECTING = 1,
    OBD_CONNECTED = 2,
    OBD_FAILED = 3
} OBD_STATES;

...

// get connection state
virtual OBD_STATES getState() { 
      return m_state; 
}

How can I get the state into a variable such as boolean isConnected or int state so it can interact with the rest of my code? I have tried the following with no luck:

boolean isConnected = obd.getState() == OBD_CONNECTED;
if(isConnected) { ... }

int state = (int) obd.getState();
if(state == 2) { ...}

2 Answers 2

4

In response to your answer: why don't you think it is convenient? As you already noticed, you can use the enum values directly in your sketch.

Anyway, it is better to use a switch statement:

Serial.write("ODB State: ");
switch (odb.getState()) {
  case ODB_DISCONNECTED: 
    Serial.write("Disconnected");
    break;

  case OBD_CONNECTING:
    Serial.write("Connecting");
    break;

  case OBD_CONNECTED:
    Serial.write("Connected");
    break;

  case OBD_FAILED:
    Serial.write("Failed");
    break;

  default:
    // Error case
    break;
}
Serial.write("\n");

This way, whenever the enum is changed (e.g. added items), you automatically fall into the error state, so you know you have to adapter the code.

2
  • 1
    I realize now it is actually pretty convenient. I was just used to java where I typically return some sort of integer and then provide static constants from the constructor class to compare it against. Commented Apr 8, 2018 at 2:48
  • Java has enum type too Commented Apr 8, 2018 at 4:40
1

I found the answer to my problem, but it is not very convenient.

Serial.write("ODB State: ");
OBD_STATES state = obd.getState();
if(state == OBD_DISCONNECTED) Serial.write("Disconnected");
if(state == OBD_CONNECTING) Serial.write("Connecting");
if(state == OBD_CONNECTED) Serial.write("Connected");
if(state == OBD_FAILED) Serial.write("Failed");
Serial.write("\n");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.