Guest User

Automatic coin counter

a guest
Dec 8th, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 4.09 KB | Software | 0 0
  1. #include <EEPROM.h>
  2. #include <LiquidCrystal.h>
  3.  
  4. int PUL = 2;
  5. int interruptPin = 3; // Пин для прерывания
  6. volatile unsigned int coinCount = 0; // Счётчик монет
  7.  
  8. unsigned long previousMicros = 0; // Переменная для хранения времени последнего изменения состояния
  9. unsigned int highDuration = 50;  // Продолжительность высокого уровня в микросекундах
  10. unsigned int lowDuration = 1000; // Продолжительность низкого уровня в микросекундах
  11. unsigned int lastRPM = 0;        // Последнее отображённое значение RPM
  12. unsigned int targetRPM = 60;    // Целевое количество оборотов в минуту
  13. unsigned int lastCoinCount = 0; // Последнее отображённое значение coinCount
  14.  
  15.  
  16. bool isHigh = false;            // Текущее состояние сигнала
  17.  
  18. LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // Настройка пинов для 1602 LCD
  19. int lcdKey = 0;
  20. int lastKey = -1;
  21. const int keyPin = A0;
  22. const int eepromAddress = 0; // Адрес для сохранения targetRPM
  23.  
  24. void setup() {
  25.   pinMode(PUL, OUTPUT);
  26.   pinMode(interruptPin, INPUT_PULLUP);
  27.   attachInterrupt(digitalPinToInterrupt(interruptPin), countCoins, FALLING);
  28.  
  29.   lcd.begin(16, 2);
  30.  
  31.   // Загружаем значение targetRPM из EEPROM
  32.   EEPROM.get(eepromAddress, targetRPM);
  33.   if (targetRPM < 2 || targetRPM > 500) { // Проверка диапазона
  34.     targetRPM = 60; // Значение по умолчанию
  35.   }
  36.  
  37.   // Рассчитываем начальное значение lowDuration
  38.   calculateLowDuration();
  39.  
  40.   lastRPM = targetRPM;
  41.   lastCoinCount = coinCount;
  42.  
  43.   // Отображение начальных данных на экране
  44.   updateLCD();
  45. }
  46.  
  47. void loop() {
  48.   unsigned long currentMicros = micros();
  49.  
  50.   // Определяем, нужно ли переключить состояние
  51.   if (isHigh && (currentMicros - previousMicros >= highDuration)) {
  52.     digitalWrite(PUL, LOW);
  53.     isHigh = false;
  54.     previousMicros = currentMicros;
  55.   } else if (!isHigh && (currentMicros - previousMicros >= lowDuration)) {
  56.     digitalWrite(PUL, HIGH);
  57.     isHigh = true;
  58.     previousMicros = currentMicros;
  59.   }
  60.  
  61.   // Обработка кнопок на LCD Shield
  62.   lcdKey = readLCDButtons();
  63.   if (lcdKey != lastKey) {
  64.     lastKey = lcdKey;
  65.     handleLCDMenu(lcdKey);
  66.   }
  67.  
  68.   // Обновление экрана только при изменении данных
  69.   if (targetRPM != lastRPM || coinCount != lastCoinCount) {
  70.     updateLCD();
  71.     lastRPM = targetRPM;
  72.     lastCoinCount = coinCount;
  73.   }
  74. }
  75.  
  76. int readLCDButtons() {
  77.   int adcKeyValue = analogRead(keyPin);
  78.   if (adcKeyValue < 50)   return 0; // RIGHT
  79.   if (adcKeyValue < 195)  return 1; // UP
  80.   if (adcKeyValue < 380)  return 2; // DOWN
  81.   if (adcKeyValue < 555)  return 3; // LEFT
  82.   if (adcKeyValue < 790)  return 4; // SELECT
  83.   return -1; // НИКАКАЯ
  84. }
  85.  
  86. void handleLCDMenu(int key) {
  87.   switch (key) {
  88.     case 1: // UP
  89.       targetRPM += 2;
  90.       if (targetRPM > 500) targetRPM = 500; // Ограничиваем максимальное значение
  91.       calculateLowDuration();
  92.       break;
  93.     case 2: // DOWN
  94.       if (targetRPM > 2) {
  95.         targetRPM -= 2;
  96.         calculateLowDuration();
  97.       }
  98.       break;
  99.     case 4: // SELECT
  100.       // Сохраняем значение targetRPM в памяти
  101.       EEPROM.put(eepromAddress, targetRPM);
  102.       break;
  103.   }
  104. }
  105.  
  106. void calculateLowDuration() {
  107.   float stepsPerRevolution = 800; //360.0 / 0.45; // Шагов на полный оборот
  108.   lowDuration = 1000000.0 / (targetRPM * stepsPerRevolution / 60.0);
  109. }
  110.  
  111. void updateLCD() {
  112.   lcd.clear();
  113.   lcd.setCursor(0, 0);
  114.   lcd.print("Coins:");
  115.   lcd.setCursor(7, 0);
  116.   lcd.print(coinCount);
  117.   lcd.setCursor(0, 1);
  118.   lcd.print("RPM:");
  119.   lcd.setCursor(5, 1);
  120.   lcd.print(targetRPM);
  121. }
  122.  
  123. void countCoins() {
  124.   coinCount++;
  125. }
  126.  
Advertisement
Add Comment
Please, Sign In to add comment