What I am looking to do is when I hold my hand over a photocell sensor, it prints out a 0 once and goes back to printing constant 1's even though my hand blocking the sensor light.
With the code I have right now, it is printing constant 1's when the light is being shined into the sensor and 0's when I hold my hand over the sensor.
int threshold = 1023;
//PHOTOCELL ---------------
//light off= 1023
int pr0;
int np0= analogRead(0);
void setup() {
Serial.begin(9600);
}
void loop(){
//Serial.println(np0);
//a0
if (np0 == threshold) {
pr0 = 0;
}else{
pr0 = 1;
}
Serial.println(pr0);
}
I tried to store and call previous values to reset to 1. But doesn't do exactly what I want.
int threshold = 1023;
//PHOTOCELL ---------------
//light off= 1023
int pr0;
int np0;
int static op0;
void setup() {
Serial.begin(9600);
}
void loop(){
//Serial.println(np0);
//a0
np0= analogRead(0);
op0=np0;
if (np0 == threshold) {
pr0 = 0;
}else{
pr0 = 1;
}
if(op0 == 0){
pr0 = 1;
}
Serial.println(pr0);
}
Tried while loops, breaks, switch cases and do while loops but no luck.
#define SENSE_PIN 0
bool blocked;
void setup() {
Serial.begin(9600);
pinMode(SENSE_PIN, INPUT);
// assume that the sensor is not initially blocked so that a 0 is printed right away
blocked = false;
}
void loop() {
// check to see if the light is blocked - fill in this condition yourself
if (analogRead(SENSE_PIN) > [something]) {
// make sure that the previous reading saw that the sensor was _not_
// blocked, so that we only print 0 when it changes from nonblocked to blocked
if (!blocked) {
Serial.println("0");
blocked = true;
}
}
// if the sensor is not blocked, print out 1 always, and set the blocked state
// to false in case the sensor is blocked
else {
Serial.println("1");
blocked = false;
}
}
You need to fill in the condition for a blocked state (i.e. analogRead(SENSE_PIN) > 1000) and then it should work.
Is it possible to print the 0/1 outside of the if/else loop?
I want to have multiple instances of this (multiple sensors) print out a single array of the 0/1 for each of the sensors.
I tried to comment out the Serial.println and use a variable to link the outputs of each if/else statements from each pin.
Hi, I'm not entirely sure what you mean. If you want to use multiple sensors and have them do the same thing, then you can simply duplicate the if-else statement from earlier but check a different pin.