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");
}
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.
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.