opto isolator

I have an opto isolator connected to a digital pin set to input. Things work 90% of the time but I get occasional misreadings. it is setup as follows:

Int SensorPin = 4

in Setup

pin is set as input
(pullup is set)

hardware:

output of opto - emitter is to ground, collector to 5vdc.
an output is sent to the ardunio on the collector with a 10k resistor between it and the 5vdc. (have tried with and without the additional pullup resistor)

as i mentioned - it usually does work but occasionally miss reads.
any suggestions?

oh, and i have tried without the pullups and hooked the output to the emitter side of the opto, between the emitter and a 10k resistor to ground. made things worst.

thanks

Strange that it would not work 100%, sounds like a hardware setup issue to me.

Sometimes the Cathode of the input side needs a resistor to ground (should be on the datasheet), and it may help to decouple the output line with a low value cap to ground. You could also try doing a digitalwrite on the input pin and pulling it low, while using the external 10k pull-ups.

What is wired to the input of the isolator? If it's a mechanical switch contact of some kind then contact bounce could always be a possiblity of flaky or inconsistance readings.

Lefty

The opto input comes off between the collector of another transistor and 5vdc+. (with a 510ohm resistor before it reaches the opto). This transistor is also operating a relay which does open and close properly.

The opto is being monitored in a 'while' function. IE while(SwitchOPEN()){delay (2000) and print (switchOPEN)}

If not the in the programing maybe I have a loose connection somewhere.

Or maybe that delay (during which the processor does nothing) is the problem. If there is nothing to do while the switch is open, do nothing, rather than call delay.

I was looking to have it check every 2 seconds so the serialprint wouldn't get too busy. It is open for quite some time but maybe eliminating the delay and just leaving the serialprint.ln 'SwitchOPEN') is a better way.

The Serial.print(ln) statement is a debugging aid, isn't it? Other than that, it serves no useful purpose, does it?

If not, just comment it out, once you know the code works. Or, look at the infamous Blink Without Delay example for how to write the message only once every 2 seconds, 10 seconds, 20 minutes, etc.

Lubby
I presume your optocoupler is a transistor output, with the base available on one of the pins.

I have found that the base needs to be tied to the emitter with a high value resistor.
This stops it floating up, and causing erratic results.

It may be useful if you also place an LED across the input, which may help spot what is going on.

Mark