Reading from photoresistor displays as NULL

Hi everyone.

I have been experimenting with publishing variables to the Particle cloud, and I have managed to get some events published. My setup is simple: One magnetic reed switch (door sensor) and one photoresistor.

I have managed to get a message published for the door sensor but I can’t really get any value out of the photoresistor. I am attaching this screenshot from the dashboard:

And below is my the code running on my Photon

    // pin assignments
    int lightPin = 0;
    int lightReading=0;
    int switchPin = 6;
    int ledPin = 7;

    void setup() {

    // set the inputs and outputs    
    pinMode(lightPin, INPUT);
    pinMode(switchPin, INPUT_PULLUP);
    pinMode(ledPin, OUTPUT);
    digitalWrite(switchPin, HIGH);
    Particle.variable("Light Sensor", lightReading); 


    void loop() {
    // read the data from the photoresistor and publish the result
    int lightReading = analogRead(lightPin);
    Particle.publish ("Light Sensor", lightReading);
     // check to see if the door is open. if it is, publish a message 
       if(digitalRead(switchPin) == LOW)
            {digitalWrite(ledPin, LOW);}

    else{digitalWrite(ledPin, HIGH);
       Particle.publish ("Door Sensor", "Door is open");


I’d really appreciate it if someone could shed some light on this. Also, is it ok that I have declared the light sensor value as a particle variable as well here?

    Particle.variable("Light Sensor", lightReading); 

Many Thanks!

@JohnPixle, Particle.publish() requires you to convert the published data to a string. So, you can change your line to Particle.publish ("Light Sensor", String(lightReading));, for example, and it should work. :wink:


@peekay123 Thanks for the input! I did it as you suggested.

Now instead of NULL I get 1 and 0 readings from the light sensor. Seems that if it receives some light it give me 1, otherwise it is stuck at zero.

Any insights?


@JohnPixle, how is your photocell wired up to the photon?

You should use real pin names like A0 instead of numeric values. I believe you are doing an analog read of pin D0 right now, which could be returning only 1 and 0.

1 Like

@bko nice catch! I missed that :persevere:

1 Like

@bko thank you for your input. Indeed I had not thought of that. After flashing the fixed code I was getting readings like 3, 0, 1, 4 so I just added the required resistor that i had missed to boost up the values. This works fine now.

Thanks a lot

@peekay It was missing the resistor :no_mouth:

Thank you

1 Like

It was missing the resistor :no_mouth:

Thank you for your input