# Count the number of passing devices using an Arduino UNO and a photoresistor.
Created 2020-11-19 by Leif Krüger, leif@leifkruger.se
###### tags: `Arduino, photoresistor`
The equipment will count the number of passing devices and a buzzer will alert when the desired number of 50 and 100 is reached. This tutorial will describe step by step how to built, code and test/verify the equipment.
### Table of Contents
[ToC]
### 1. Purpose and goal
This exercise is an example of how to use a microcontroller, Arduino UNO with some code, a photoresistor and some other components, to count the number of passing devices. You should also get a signal when the predetermined 50 and 100 devices have passed. It must also be possible to reset the counter with a push button. For practical reasons, the counter is limited to a maximum of 127 (in the optional step 12-13 theres no limit).
### 2. Estimated time required for the exercise (< 1.5 h)
**Preparation time:** 15 minutes
Read the instructions and pick out components.
**Assembly of components:** 20 minutes.
**Code transfer:** 5 minutes
**Test and troubleshooting:** 30 minutes
**Documentation and reflection of the exercise:** 20 minutes
**Total time:** < 1.5 h
### 3. Preparation :memo:
1. Read through the entire exercise to get an overview.
2. Look through the component list, see <a href="https://hackmd.io/lCiXnJBlSq-4gHSwOXubBw?view#10-Appendix-B-(Component-list)">Appendix B</a>.
Is there anything that needs to be procured?
3. Tape, paper and a scissor can be good to have.
4. Assumes that the Arduino IDE is already installed.
### 4. Assemble the parts
*A tip! If you want to test safer, feel free to try <a href="https://www.tinkercad.com/#Tinkercad">Tinkercad</a> first.*
*Another tip! Start to only assemble three LED and test. When it works assemble the rest.*
1. Start reading the wire diagram, see <a href="https://hackmd.io/lCiXnJBlSq-4gHSwOXubBw?view#9-Appendix-A-(Wiring-diagram)">Appendix A</a>.
2. Wait, don't connect external power supply or data cable in this stage.
3. Place breadboard and Arduino in a suitable way, preferably according to the wiring diagram.
4. Place components.
5. Connect all wires. Double check!
6. When all seems to be OK, then connect the data cable so the Arduino get power.
### 5. Program code for Arduino
1. Create a new sketch in the Arduino IDE.
2. Copy the code into Arduino IDE.
You will find the code in <a href="https://hackmd.io/lCiXnJBlSq-4gHSwOXubBw?view#11-Appendix-C-(The-code)">Appendix C</a>.
3. Transfer the code to the Arduino microcontroller.
### 6. Test and verify (and "troubleshooting")
1. Point a lamp at the photoresistor.
2. Push once at the reset button.
3. If all seems up and running, test cover the photoresistor and then uncover (= one pulse). It make a count every time the signal from photoresitor goes from high to low. The counter should now step up one step. Look at the LED.
4. If not, try to reset counter with button. Check LED 0000000.
Try step 1 again.
5. If this work, test give 50 pulses and a buzzer sounds.
Check LED 0110010 = 50
6. If this work, test give 100 pulses and a buzzer sounds.
Check LED 1100100 = 100
7. If not, check wires again and then the code.
8. To get a more distinct "pulse" from the photoresistor you may create "aperture", like in a camera lens. Take a piece of paper, roll around the photoresistor like a cone. Now you avoid stray lights.



A tip! To create multiple pulses at once, cut to a piece of paper as shown above. This example will give 5 pulses.
Note! A photoresistor is not primarily intended to be used in this way as it has an analog output and it may be unclear what is logical one and zero, respectively. Therefore, the 1023 steps of the analog input are converted. In order for this to be true, this is mapped to correspond to 0-100% and over 50% is defined as logical one.
Why not connect the photoresistor to a digital input instead?
The problem here is that the signal after the photoresistor is only about 4 V (with light). It is not enough for a logical 1 (specification 4.75-5.25 V).
### 7. Documentation and evaluation
Make notes. Think about what can be made easier / better, etc.
### 8. Further development
The counter is limited to 127 and in the next step "128" the binary counter will be reset "0". If you develop this exercise, you can connect a 7-segment alternative LCD display instead of the LED and then the calculator can count "unlimited". Change the code so the buzzer sounds every 100 counts etc.
If you have another photoresistor, there is the possibility to sense the direction of how an object is moving (e.g. in or out). For this to work, some adjustments need to be made to the code.
OPTION: In steps 12 and 13 there is a suggestion to use the Arduino UNO as a web server and then you see the presentation in a browser, e.g. <a href="https://www.mozilla.org/firefox/download/thanks/">Mozilla Firefox</a>.
### 9. Appendix A (Wiring diagram)



### 10. Appendix B (Component list)
| Quantity | Components | Data sheet / Product info |
| -------- |:----------------------------- |:---------- |
| 1 | Microcontroler Arduino UNO R3 | <a href="https://store.arduino.cc/arduino-uno-rev3">Arduino Uno Rev3</a> / <a href="https://www.electrokit.com/produkt/utvecklingskort-atmega328p-uno-kompatibelt-2/">Arduino UNO</a>|
| 1 | Photoresistor |<a href="https://www.electrokit.com/uploads/productfile/41015/41015727_-_Photoresistor_Module.pdf">Photoresistor_Module.pdf</a> / <a href="https://www.electrokit.com/produkt/ljussensor/">Photoresistor</a>
| 7 | Red LED | <a href="https://www.electrokit.com/produkt/led-rod-5mm-standard-diffus/">Red LED</a> |
| 1 | Active Buzzer Module | <a href="https://www.electrokit.com/uploads/productfile/41015/Active_Piezo_Buzzer.pdf">Active_Buzzer_Module.pdf</a> / <a href="https://www.electrokit.com/produkt/piezohogtalare-aktiv/">Active Buzzer Module</a> |
| 1 | Momentan button | <a href="https://www.electrokit.com/produkt/tryckknapp-pcb-6x6x4-8mm-svart/">Momentan button</a> |
| 1 | 10k Ohm resistor | <a href="https://www.electrokit.com/produkt/mah-starter-kit-for-arduino-rev-3-2/">10k Ohm resistor</a> |
| 1 | 220 Ohm resistor | <a href="https://www.electrokit.com/produkt/mah-starter-kit-for-arduino-rev-3-2/">220 Ohm resistor</a> |
| 1 | Breadboard | <a href="https://www.electrokit.com/produkt/kopplingsdack-840-anslutningar/">Breadboard</a> |
| 1 | Wiring diagram |<a href="https://hackmd.io/lCiXnJBlSq-4gHSwOXubBw?view#9-Appendix-A-(Wiring-diagram)">Appendix A</a>|
| 1 | A normal desk lamp | |
| 20-25 | Breadboard wires |<a href="https://www.electrokit.com/produkt/kopplingstrad-byglar-for-kopplingsdack-mjuka-65st/">Breadboard wires</a> |
| 1 | Software Arduino IDE |<a href="https://www.arduino.cc/en/software">Software Arduino IDE</a> |
| 1 | Data cable, computer-Arduino |<a href="https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1-8m/">Data cable</a> |
| 1 | Program code |<a href="https://hackmd.io/lCiXnJBlSq-4gHSwOXubBw?view#11-Appendix-C-(The-code)">Appendix C</a>|
### 11. Appendix C (The code)
```cpp
/*
Filename: counter_photoresistor_arduino.cpp
This program count the number of passing devices (< 128) using an
Arduino UNO and a photoresistor.
This exercise is an example of how to use a microcontroller,
Arduino UNO with some code, a photoresistor and some other components,
to count the number of passing devices.
You should also get a signal when the predetermined 50 and 100 units
have passed. It must also be possible to reset the counter with a push button.
For practical reasons, the counter is limited to a maximum of 127,
because after next count, the counter start at zero again.
Created 2020-11-19 by Leif Krüger, leif@leifkruger.se
*/
//Constants. They're used here to set pin numbers
const int resetButtonPin = 13; //Reset button
const int photoresistorPin = A0;
const int buzzerPin = 8;
const int ledPin6 = 6; //Bit 64
const int ledPin5 = 5; //Bit 32
const int ledPin4 = 4; //Bit 16
const int ledPin3 = 3; //Bit 8
const int ledPin2 = 2; //Bit 4
const int ledPin1 = 1; //Bit 2
const int ledPin0 = 0; //Bit 1
//Variables
int resetButtonState = 0; //Current state of the reset button
int photoresistorState = 0; //Current state of the photoresistor
int lastPhotoresistorState = 0; //Previous state of the photoresistor
int counter = 0; //Count passing devices
int binaryArray[7]; //Binary array, show status after convert from decimal
int i; //Used when convert decimal to binary
void setup() {
pinMode(buzzerPin, OUTPUT); //Initialize the buzzer and LED pin as output
pinMode(ledPin6, OUTPUT); //Binary pin 6
pinMode(ledPin5, OUTPUT); // -"- 5
pinMode(ledPin4, OUTPUT); // -"- 4
pinMode(ledPin3, OUTPUT); // -"- 3
pinMode(ledPin2, OUTPUT); // -"- 2
pinMode(ledPin1, OUTPUT); // -"- 1
pinMode(ledPin0, OUTPUT); //Binary pin 0
pinMode(photoresistorPin, INPUT); //Initialize photoresistor as an input
pinMode(resetButtonPin, INPUT); //Initialize resetbutton pin as an input
}
void loop() {
resetButtonState = digitalRead(resetButtonPin); //Read resetbutton state
photoresistorState = analogRead(photoresistorPin); //Read photoresistor
//Translate analog value 0-5 V to digital step
//0-1023 and then convert it to 0-100
photoresistorState = map(photoresistorState, 0, 1023, 0, 100);
//Defines what is to be interpreteded as logic one (1) och logic zero (0)
if (photoresistorState > 50) {
photoresistorState = 1;
}
else {
photoresistorState = 0;
}
//Check if the resetbutton is pressed
if (resetButtonState == HIGH || counter >= 127) {
digitalWrite(ledPin6, LOW); //Turn LED off
digitalWrite(ledPin5, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin0, LOW);
counter = 0; //Reset counter
}
else {
//Compare the buttonState to its previous state
if (photoresistorState != lastPhotoresistorState) {
// if the state has changed, increment the counter
if (photoresistorState == HIGH) {
// if the current state is HIGH then the button went from off to on
}
else {
// if the current state is LOW then the button went from on to off
counter++;
//Translate counter into binary
//to each LED starting with LSB
//LSB = Least Significant Bit
//In this case D0
int n = counter;
for( i=0 ; n > 0; i++) {
binaryArray[i]=n%2;
n= n/2;
}
//Step backwards in binaryarray
//LED light on or off
for(i = i-1 ; i >= 0 ; i--) {
if (binaryArray[i] == 1) {
digitalWrite(i, HIGH);
}
else {
digitalWrite(i, LOW);
}
}
//Give alarm when counter reach 50 or 100
if (counter == 50 || counter == 100) {
digitalWrite (buzzerPin, HIGH); //Buzzer sound
delay (200);
digitalWrite (buzzerPin, LOW);
}
}
}
}
delay(5); // Delay a little bit to avoid bouncing
//Save the current state as the last state, for next time through the loop
lastPhotoresistorState = photoresistorState;
delay (5);
}
```
### 12. OPTION Modified version (est. time < 1 h)
It's also a possible use a webserver for presentaion of number counts. The limitation of 127 vill no longer exits. The LED is not needed any more.
Estimated time required for this extended exercise (< 1 h)
#### The following parts are needed in addition to the previous ones.
| Quantity | Components | Data sheet / Product info |
| -------- |:----------------------------- |:---------- |
| 1 | Arduino Ethernet Shield 2 (utan PoE) |[:link:https://www.electrokit.com/produkt/arduino-ethernet-shield-2-utan-poe/] |
| 1 | Patchkabel U/UTP Cat6a 1m grå |[:link:https://www.electrokit.com/produkt/patchkabel-u-utp-cat6a-1m-gra/] |
| 1 | Switch or router | |
### 13. OPTION Appendix D (The code - modified version)
In this modified version a webserver is used for presentation. Your computer (laptop/tablet) and the Arduino UNO webserver must be at the same network e.g. 192.168.1.x (change if needed).
You must have a Arduino Ethernet Sheild so you can connect a ethernet cable to a switch or router. Arduino library "Ethernet" must aslo be installed.

The advantage is that you not need the LED any more and one resistor at 220 Ohm.
Otherwise it is the same connection with the photoresistor and the reset pushbutton.
Upload the code to Arduino and then use your browser in your computer (laptop/PC/Tablet) to show the information. In this code uses http://192.168.1.100/ (otherwise change).
#### Test and verify
Do the same test as under point 6 above but use a web browser instead of LED.
If everything working you will see someting like 
Tip! You can also use the serial monitor (in the Arduino IDE) to view all messages between the Arduino webserver and your browser.
```cpp
/*
Filename: counter_photoresistor_arduino_web.cpp
This program count the number of passing devices using an
Arduino UNO and a photoresistor.
This exercise is an example of how to use a microcontroller,
Arduino UNO with some code, a photoresistor and some other components,
to count the number of passing devices.
You should also get a signal when the predetermined 50 and 100 units
have passed. It must also be possible to reset the counter with a push button.
Created 2020-11-19 by Leif Krüger, leif@leifkruger.se
Modified 24 November 2020 by Leif Kruger, leif@leifkruger.se
Web Server
A simple web server that using an Arduino Ethernet shield.
It show number of passing devices on the web.
Webpage update frequency every 2 seconds.
Tip! Use serial monitor du see output messages
Number of count use a web browser, surf to http://192.168.1.100/
Original code is taken from the Arduino -Examples-Ethernet-WebServer created by:
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified 02 Sept 2015
by Arturo Guadalupi
also looked at
https://www.circuitbasics.com/display-sensor-data-with-an-ethernet-connected-arduino-web-server/
*/
#include <SPI.h>
#include <Ethernet.h>
const int resetButtonPin = 13; //Reset button
const int photoresistorPin = A0;
const int buzzerPin = 8;
//Variables
int resetButtonState = 0; //Current state of the reset button
int photoresistorState = 0; //Current state of the photoresistor
int lastPhotoresistorState = 0; //Previous state of the photoresistor
int counter = 0; //Count passing devices
int i; //Used when convert decimal to binary
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 100);
EthernetServer server(80);
void setup()
{
Serial.begin (9600);
Ethernet.begin(mac, ip);
server.begin( );
pinMode(buzzerPin, OUTPUT); //Initialize the buzzer and LED pin as output
pinMode(photoresistorPin, INPUT); //Initialize photoresistor as an input
pinMode(resetButtonPin, INPUT); //Initialize resetbutton pin as an input
}
void loop( )
{
digitalWrite(buzzerPin, LOW);
resetButtonState = digitalRead(resetButtonPin); //Read resetbutton state
photoresistorState = analogRead(photoresistorPin);
//Translate analog value 0-5 V to digital step 0-1023
photoresistorState = map(photoresistorState, 0, 1023, 0, 100);
//Defines what is to be interpreteded as logic one (1) och logic zero (0)
if (photoresistorState > 50) {
photoresistorState = 1;
}
else {
photoresistorState = 0;
}
if (resetButtonState == HIGH) {//Check if the resetbutton is pressed
counter = 0; //Reset counter for passing devices
}
else {
//Compare the buttonState to its previous state
if (photoresistorState != lastPhotoresistorState) {
// if the state has changed, increment the counter
if (photoresistorState == HIGH) {
// if the current state is HIGH then the button went from off to on
}
else {
// if the current state is LOW then the button went from on to off
counter++;
}
}
}
//Give alarm when counter reach 50 or 100
if (counter == 50 || counter == 100) {
digitalWrite (buzzerPin, HIGH);
delay (200);
digitalWrite (buzzerPin, LOW);
}
delay(5); // Delay a little bit to avoid bouncing
//Save the current state as the last state, for next time through the loop
lastPhotoresistorState = photoresistorState;
EthernetClient client = server.available();
if (client)
{
boolean currentLineIsBlank = true;
while (client.connected ( ) )
{
if (client.available ( ) )
{
char character = client.read ( );
Serial.write(character);
if (character == '\n' && currentLineIsBlank)
{
client.println ("HTTP/1.1 200 OK");
client.println ("Content-Type: text/html");
client.println ("charset='utf-8'");
client.println ("Connection: close");
client.println ("Refresh: 2");
client.println ( );
client.println ("<!DOCTYPE HTML>");
client.println ("<html>");
client.println ("<head>");
client.println ("<Title>Number of counts</Title>");
client.println ("</head>");
client.println ("<body bgcolor='#DDDD50'>");
client.println ("<font size=16>Passing devices: ");
client.println (counter);
client.println ("</font><br />");
client.println ("</body>");
client.println ("</html>");
break;
}
if ( character == '\n')
{
currentLineIsBlank = true;
}
else if (character != '\r')
{
currentLineIsBlank = false;
}
}
}
delay(5);
client.stop();
}
}
```