Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions Science/src/co2/co2_sensor.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
#include "co2_sensor.h"

#define CO2_READ_DELAY 500

// The Teensy has two I2C interfaces: Wire and Wire1.
// This lets us easily switch between them.
#define WIRE Wire1
Expand All @@ -12,31 +10,34 @@ void Co2Sensor::setup() {
WIRE.begin();
}

bool Co2Sensor::hasError() {
int Co2Sensor::checkError() {
// The exact cases are:
// - 1: ok
// - 2: failed
// - 254: pending
// - 255: no data
// For now we can just check for any error at all.
return WIRE.read() != 1;
return WIRE.read();
}

float Co2Sensor::read() {
// Send the 'r' (read) command to the CO2 sensor.
WIRE.beginTransmission(address);
WIRE.write('r');
WIRE.endTransmission();
delay(CO2_READ_DELAY);

// Read the response (a null-terminated string).
WIRE.requestFrom(address, 20, 1);
if (hasError()) return -1;
int error = checkError();
if (error != 1) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit of a subjective take here, but I think you should keep all the error handling logic in the hasError function and keep returning just true or false. The idea is to encapsulate as much as possible into the smallest units possible. If you want to check what type of error you got, or print the type of error, or do something else related to the error, that can still go into hasError() because it's not related to reading the actual co2. By having one function to handle and decide what to do when you get an error, you can reuse that logic.

If you want to send this error number to the dashboard though, that makes sense to have it return an int. Just be careful not to serial print things in the meantime as the serial lines are reserved for other (binary) communication and printing anything else will interfere

Serial.print("CO2 Error: ");
Serial.println(error);
return -1;
}
int i = 0;
char response[20];
while (WIRE.available()) {
char character = WIRE.read();
response[i] = character;
response[i++] = character;
if (character == 0) break;
}

Expand Down
2 changes: 1 addition & 1 deletion Science/src/co2/co2_sensor.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class Co2Sensor {
private:
int address;
bool hasError();
int checkError();

public:
Co2Sensor(int addresss);
Expand Down