Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <TimerOne.h>
- // Define the sensor pins
- #define TRANSMITTER_PIN 9 // IR Transmitter pin. Needs to be 9 or 10 due to Timer1 usage
- #define RECEIVER_PIN 2 // IR Receiver pin
- int counter = 0; // Object counter
- int lastState = HIGH; // Last detected IR state
- void setup() {
- pinMode(RECEIVER_PIN, INPUT);
- pinMode(TRANSMITTER_PIN, OUTPUT);
- // Setup 38 kHz carrier frequency on the TRANSMITTER_PIN with Timer1
- Timer1.initialize(26); // initialize Timer1, and set a 1/2 period of 26 microseconds = 38.5kHz
- Timer1.pwm(TRANSMITTER_PIN, 512); // setup pwm on pin TRANSMITTER_PIN, 50% duty cycle
- Serial.begin(9600); // Open serial connection
- }
- void loop() {
- int currentState = digitalRead(RECEIVER_PIN); // Read the current state of the receiver
- // Check if the beam was broken
- if (lastState == HIGH && currentState == LOW) {
- counter++; // Increment the counter
- Serial.println("Object detected!");
- Serial.print("Total number of objects detected: ");
- Serial.println(counter);
- }
- lastState = currentState; // Update the last state
- delay(100); // Delay to avoid multiple detection of the same object
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement