Wednesday, February 18, 2015

3: Gas Sensors

I purchased 2: an MQ-4 (methane) and MQ-7 (carbon monoxide/CO). I shopped around for wiring and code examples and then reworked it for my sensibilities.

The MQ-x's need to heat up before their readings stabilize so I chose to power them separately from the Nano. I stripped one end of a USB cable and soldered a jumper to the red and black wires (i.e., 5v & ground). The wiring is simple. There are 4 pins on my devices, labeled G, AO, DO & V.

Wiring:
  USB 5v to V
  USB ground to G
  Arduino pin A0 to AO

— the adjustment screw didn't seem to do much —


And here's a sketch:

// Works with MQ-4/methane & MQ-7/CO
// Power to sensor external (USB) 5v->V pin & GND->G pin; 
// AO pin to Arduino A0
const int LedPin = 6;
const int gasSensor = A0;
int sensorValue;
int baseValue;

void setup() {
  int i, val, last=-1;
  pinMode(LedPin, OUTPUT);
  Serial.begin(9600);
  // wait for sensor to warm up -- and value to stabilize
  for(i = 0; i < 50; ++i) { // a guess about waiting
    val = analogRead(gasSensor);
    // Debug only
    Serial.print(i);Serial.print(","); Serial.println(val);
    if(val == last) break;
    // blink LED to indicate sensor warm up
    digitalWrite(LedPin, HIGH);
    delay(100);
    digitalWrite(LedPin, LOW);
    delay(4000); // 4 seconds
    last = val;
  }
  baseValue = val + 10; // just a guess
}

void loop() {
  sensorValue = analogRead(gasSensor);
  Serial.println(sensorValue); // Debug
  if (sensorValue > baseValue) {
    digitalWrite(LedPin, HIGH); // I need to show multiple levels
  } else {
    digitalWrite(LedPin, LOW);
  }
  delay(1000);
}

I've also successfully (seemingly) programmed an RFID reader. My sensor came with 2 testing samples: a keyfob and a credit card. I copied different sketches from the Internet and nothing worked. It turned out that my code wasn't at fault. I just tested using the fob. When I finally tried the card my sketch worked. Bad fob! There is a lesson here somewhere.

No comments:

Post a Comment