Having trouble publishing pin statuses

Hi

I’m setting up a magnetic door sensor, and I want my spark to publish the status of the door each second. I have one wire of the sensor in D1, set to HIGH, and the second wire in D6. Every second the spark publishes the status of D6 (high or low). However, when I read the event, the output doesn’t change if I close or open the circuit. Here’s the code:

int sensorIn = D6;
int sensorOut = D0;

void setup() {
    pinMode(sensorIn, INPUT);
    pinMode(sensorOut, OUTPUT);

    digitalWrite(sensorOut, HIGH);
}

void loop() {
    if (digitalRead(sensorIn) == HIGH) {
        Spark.publish("status","high");
    } else {
        Spark.publish("status", "low");
    }
    delay(1000);
}

Can anyone see what’s going wrong? If I change D6 to D7, the blue led turns on when I connect the circuit so I know it’s not a problem with the door sensor.

Thanks

Yet the code speaks of

int sensorIn = D6;
int sensorOut = D0;

A typo in either?

Hi @zorazor

Do you have a pull-down resistor on the input (D6 in your code)? If you leave the input floating it may not behave as you expect!

Another way is to use

   pinMode(sensorIn, INPUT_PULLDOWN);

Which activates the internal pull-down in the input pin.

As @Moors7 points out, your code and your text don’t agree on which pin you are using.

3 Likes

@Moors7 Right theyre both supposed to be D1.

@bko I looked up what a pull-down resistor is, and that fixed it! Thanks so much!

3 Likes