29 March 2010

Task 38 - button-activated photocell (LDR) output to Serial Monitor

/*
* Project: button_&_LDR_task_38
* Author: Jane-Maree Howard
* Date: Monday 29/03/2010
* Platform: Arduino 18
* Purpose: To send the reading from the LDR to the Serial Monitor
* whenever the button is pressed.
* The circuit:
* Connect one end of the photocell to 5V, the other end to Analog 0.
* Then connect one end of a 10K resistor from Analog 0 to ground
* Connect the pushbutton to pin 2 from +5V, &
* a 10K resistor attached from pin 2 to ground
*/

int buttonPin = 2; // the number of the pushbutton pin

int photocellPin = 0; // the cell and 10K pulldown are connected to a0
int photocellReading; // the analog reading from the sensor divider
int buttonState = 0; // variable for reading the pushbutton status

void setup()
{
/* We'll send the LDR state to the Serial monitor */
Serial.begin(9600); // baud rate 9600 should be set on the SM
// initialize the pushbutton pin 2 as an input:
pinMode(buttonPin, INPUT);
}//end setup()

void loop()
{
// read the state of the pushbutton value..
buttonState = digitalRead(buttonPin);
// read the value of the photocell
photocellReading = analogRead(photocellPin); //i.e. analog 0

/* check if the pushbutton is pressed.
if it is, the buttonState is HIGH, so..*/
if (buttonState == HIGH)
{
//..output the LDR reading to the SM
Serial.print("Analog reading = ");
Serial.println(photocellReading); // the raw analog reading
delay(100); // debounce delay
}// if..
else
{
Serial.println("No output");
}//..else
}//end loop()

1 comment:

  1. I deliberately inserted an output "No output" to the SM to show that the program WAS running even when the button wasn't pushed, but it's not really necessary..

    ReplyDelete