Topic 7. Arduino Coin Jar

An Arduino coin jar is a DIY project that involves using an Arduino microcontroller to automatically count coins as they are deposited into a jar or container. This is typically achieved using sensors to detect the presence of a coin and then updating a counter that can be displayed on an LCD screen or another output device.

Key Components and Functionality

  1. Arduino Board: The main controller that processes the data from sensors and controls the output devices.
  2. Sensor: Usually an ultrasonic sensor like the HC-SR04 is used to detect the coin. Other types of sensors, such as weight sensors or optical sensors, can also be used.
  3. Display (Optional): An LCD or LED display to show the count of the coins deposited in the jar.
  4. Power Supply: Typically provided by a USB cable connected to a computer or a battery pack.
  5. Container: A jar or any container where coins will be deposited.

How It Works

  1. Detection: The sensor detects a change when a coin is dropped into the jar. For example, an ultrasonic sensor measures the distance to the coins in the jar. When a new coin is added, the distance changes.
  2. Counting: The Arduino processes the sensor data to determine if a coin has been added. If the sensor detects a coin, it increments the count.
  3. Display: The updated coin count is displayed on an LCD screen or communicated through another output method.

Building

What do you need

1 x Ultrasonic Distance Sensor (4-pin)

1 x LCD screen 16 x 2

1 x Green LED

1 x Red LED

1 x Positional Micro Servo

4 x 220 Ω Resistor

Tinkercad

Arduino code
#include <LiquidCrystal.h>
#include <Servo.h> // Include the Servo library

// Инициализация библиотеки с номерами интерфейсных пинов
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo jarDoor; // Create a Servo object

const int trigger = 8;   // Пин триггера
const int echo = 7;      // Пин эха
const int redLed = 9;    // Пин красного светодиода
const int greenLed = 10; // Пин зеленого светодиода
const int servoPin = 13;  // Пин сервомотора
float distance;
float duration;
int coinCount = 0;

// Пользовательский символ для значка монеты
byte Heart[8] = {
  0b00000,
  0b01010,
  0b11111,
  0b11111,
  0b01110,
  0b00100,
  0b00000,
  0b00000
};

// Пользовательский символ для смайлика
byte smileyFace[8] = {
  0b00000,
  0b00000,
  0b01010,
  0b00000,
  0b00000,
  0b10001,
  0b01110,
  0b00000
};

void setup() {
  // Установка числа столбцов и строк ЖК-дисплея
  lcd.begin(16, 2);
  
  // Создание пользовательских символов
  lcd.createChar(0, Heart);
  lcd.createChar(1, smileyFace);
  
  // Инициализация пина триггера как выходного
  pinMode(trigger, OUTPUT);
  
  // Инициализация пина эха как входного
  pinMode(echo, INPUT);

  // Инициализация пинов светодиодов как выходных
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);

  // Инициализация сервомотора
  jarDoor.attach(servoPin);
  jarDoor.write(0); // Ensure the door is initially closed
}

void loop() {
  // Отправка короткого LOW импульса для очистки HIGH импульса
  digitalWrite(trigger, LOW);
  delayMicroseconds(5);
  
  // Отправка HIGH импульса длительностью 10 микросекунд для активации датчика
  digitalWrite(trigger, HIGH);
  delayMicroseconds(10);
  
  // Установка триггера обратно в LOW
  digitalWrite(trigger, LOW);
  
  // Измерение длительности эхо-импульса
  duration = pulseIn(echo, HIGH);
  
  // Расчет расстояния на основе длительности
  distance = duration * 0.034 / 2;
  
  // Вывод расстояния на ЖК-дисплей
  lcd.setCursor(12, 0);
  lcd.print("D:");
  lcd.print(distance);
  
  // Проверка, если расстояние меньше 12 см
  if (distance < 12) {
    // Отключение красного светодиода и включение зеленого
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);

    // Открытие дверцы
    jarDoor.write(90); // Adjust the angle as needed to open the door

    // Увеличение счетчика монет и вывод сообщения
    coinCount++;
    lcd.setCursor(0, 1);
    lcd.print("Coin inserted! ");
    lcd.write(byte(0));
    
    // Закрытие дверцы через 2 секунды
    delay(2000);
    jarDoor.write(0); // Adjust the angle as needed to close the door
  } else {
    // Включение красного светодиода и отключение зеленого
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);

    // Вывод текущего количества монет и призыв к вставке монеты
    lcd.setCursor(0, 0);
    lcd.print(coinCount);
    lcd.print(" Coins");
    lcd.setCursor(0, 5);
    lcd.setCursor(0, 1);
    lcd.print("Insert a coin! ");
        lcd.write(byte(1));  // Отображение смайлика

  }
  
  // Задержка перед следующим измерением
  delay(2000);
}