Global variable not sticking

Can you try initializing sensorOrPen as sensor / 0?That's what was causing a bug on my end.