Help on programing a IR photodetector

Hi everyone,

So I'm looking to build an IR detector with a phototransistor. I already have the circuit working but the code seems wrong somewhere. I want it to say "unbroken" constantly until the IR beam is broken by an object, then it should say "broken". I attached the code, please let me know what you think is wrong. Thank you!

define IRPIN 20

define SENSORPIN 4

int sensorState = 0;//, lastState = 0;

void setup() {
// put your setup code here, to run once:
//IRPIN 20
pinMode(IRPIN,OUTPUT);
//SENSORPIN 4
pinMode(SENSORPIN,INPUT);

digitalWrite(SENSORPIN,HIGH);

Serial.begin(9600);

}

void loop() {
// put your main code here, to run repeatedly:
digitalWrite(IRPIN, HIGH);
sensorState = digitalRead(SENSORPIN);

// check if the sensor beam is broken
// if it is, the sensorState is LOW:
if (sensorState == HIGH) {
//
Serial.println("Unbroken");
}
else {
// turn LED off:
if (sensorState == LOW) {
Serial.println("Broken");
}

}
}

IRtest.ino (659 Bytes)

Do you mean PIR sensor?

You say what the code should do but not what it actually does. You tell us what is wrong then we can help to fix it.

Hi, so it seems stuck saying "unbroken" on the serial monitor even though I try and break the beam it does not seem to notice it or type it. I have no clue what it could be.

Can you post a schematic? What is the detector? Can you post data sheets for the emitter and detector?

Are you sure that the emitter is emitting? Many cell phone cameras are sensitive to IR so will show if the IR LED is lighting.

albitcaban:
Hi, so it seems stuck saying "unbroken" on the serial monitor even though I try and break the beam it does not seem to notice it or type it. I have no clue what it could be.

I think the problem is that it is trying to print "unbroken" thousands of times per second and the Serial Output Buffer is being choked and causing the Arduino to wait until it empties - which it never does. You can easily verify this by temporarily adding the line delay(300); into loop()

Because the "unbroken" state is normal you should not be printing it, except once when the IR changes from LOW to HIGH.

...R