Advertisement
costi0n

objectCounter_and_Timer

May 24th, 2023
891
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | Software | 0 0
  1. #include <TimerOne.h>
  2.  
  3. // Define the sensor pins
  4. #define TRANSMITTER_PIN 9  // IR Transmitter pin. Needs to be 9 or 10 due to Timer1 usage
  5. #define RECEIVER_PIN 2     // IR Receiver pin
  6.  
  7. int counter = 0;   // Object counter
  8. int lastState = HIGH;  // Last detected IR state
  9.  
  10. void setup() {
  11.   pinMode(RECEIVER_PIN, INPUT);
  12.   pinMode(TRANSMITTER_PIN, OUTPUT);
  13.  
  14.   // Setup 38 kHz carrier frequency on the TRANSMITTER_PIN with Timer1
  15.   Timer1.initialize(26);  // initialize Timer1, and set a 1/2 period of 26 microseconds = 38.5kHz
  16.   Timer1.pwm(TRANSMITTER_PIN, 512);  // setup pwm on pin TRANSMITTER_PIN, 50% duty cycle
  17.  
  18.   Serial.begin(9600);  // Open serial connection
  19. }
  20.  
  21. void loop() {
  22.   int currentState = digitalRead(RECEIVER_PIN);  // Read the current state of the receiver
  23.  
  24.   // Check if the beam was broken
  25.   if (lastState == HIGH && currentState == LOW) {
  26.     counter++;  // Increment the counter
  27.     Serial.println("Object detected!");
  28.     Serial.print("Total number of objects detected: ");
  29.     Serial.println(counter);
  30.   }
  31.  
  32.   lastState = currentState;  // Update the last state
  33.  
  34.   delay(100);  // Delay to avoid multiple detection of the same object
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement