Arduino nano clock

Часы на Arduino Nano и светодиодных матрицах 4×64 LED Matrix

03.09.2019, 13:01
Источник: Ардуино радиолюбитель VK

Комплектующие для сборки на али:

Плата ардуино нано https://ali.pub/3q9jj2

Светодиодные матрицы MAX7219 https://ali.pub/3q9jmk

Фоторезистор https://ali.pub/3q9jwa

Модуль часов реального времени DS3231 https://ali.pub/3q9jz0

Схема сборки нашего Ардуино проекта

Распиновка ардуино Nano 3.0:

Код прошивки :

#include
#include «DS3231.h»
#include «MD_MAX72xx_lib.h»
//#include «Font_Data.h»

DS3231 rtc(SDA, SCL); // Real time clock

const byte LDR_PIN = A2; // LDR Sensor pin

#define MAX_DEVICES 4
// Define pins
#define CLK_PIN 13 // or SCK
#define DATA_PIN 11 // or MOSI
#define CS_PIN 10 // or SS
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW

#define USE_NEW_FONT 1

#define BUF_SIZE 20 // text buffer size
#define CHAR_SPACING 1 // pixels between characters

char buf[BUF_SIZE], secs[4];
uint8_t dots;

// SPI hardware interface
// Max72xxPanel matrix = Max72xxPanel(CS_PIN, H_DISPLAYS, V_DISPLAYS);
MD_MAX72XX matrix = MD_MAX72XX(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

const byte WAIT = 100;
const byte SPACER = 1;
byte FONT_WIDTH;

Источник

iw0rm3r/DS3231_MAX7219_Clock

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Многофункциональные Arduino-часы на LED матрице с контроллером MAX7219

Программная основа для сборки многофункциональных часов на базе Arduino Uno/nano с использованием модуля часов реального времени DS3231 и LED матрицы из модулей на базе контроллера MAX7219. Для работы с LED матрицей используются собственные функции, составляющие «обёртку» вокруг легковесной библиотеки Faster_LEDControl, т.к. многоцелевые библиотеки управления LED матрицами, вроде MD_Parola, избыточны и не позволяют уместить нужный функционал во flash-память контроллера Arduino Uno. Проект находится на стадии разработки.

Функционал, реализованный на данный момент:

  1. Режим отображения текущего времени;
  2. Режим вывода текущей даты в виде бегущей строки;
  3. Режим отображения температуры воздуха на основе сопротивления терморезистора (низкая точность);
  4. Режим вывода данных, передаваемых по UART с ПК, в графическом виде. Запланирован для отображения визуализатора спектра воспроизводимой на ПК музыки (рассчитывается приложением на стороне ПК). В данный момент приложение на ПК не закончено, поэтому отображается только громкость в виде горизонтального столбца;
  5. Использование разных шрифтов для разных режимов работы;
  6. Автоматическая настройка яркости/выключение LED матрицы в зависимости от освещённости (используется фоторезистор);
  7. Реализован будильник по внешнему прерыванию от модуля DS3231 с визуальной (при помощи отдельного светодиода) и звуковой сигнализацией (при помощи пъезодинамика). Возможность настройки будильника с помощью LED матрицы пока не реализована, для тестирования используется долгое нажатие на единственную кнопку (устанавливает будильник на 10 сек вперёд);
  8. Тактовая кнопка используется для выключения будильника, либо для переключения между режимами работы.

Используемые компоненты:

  1. Отладочная плата Arduino Uno/nano;
  2. Модуль часов реального времени DS3231;
  3. LED матрица из произвольного числа модулей на контроллерах MAX7219;
  4. Макетная (печатная) плата;
  5. Фоторезистор c резистором на 10 кОм для настройки яркости матрицы;
  6. Термистор c резистором на 10 кОм для определения температуры воздуха (низкая точность);
  7. Пъезодинамик для сигнализации будильника, сигнализации в случае ошибки работы и подзвучивания нажатий кнопок. Лучше подключать через потенциометр для настройки громкости звука;
  8. Отдельный светодиод, подключённый через резистор на 220 Ом, для сигнализации будильника и остановки работы (в случае проблемы с модулем часов);
  9. Тактовая кнопка.

Как использовать?

  1. Скачать исходники проекта с помощью git clone https://github.com/iw0rm3r/DS3231_MAX7219_Clock.git , либо с помощью кнопки «Clone or download» >«Download ZIP»;
  2. Собрать схему, подключив компоненты к пинам Arduino, указанным в основном .ino-файле проекта, либо указав свои пины;
  3. Скомпилировать и загрузить проект в контроллер с помощью Arduino IDE, либо другой связки ПО.

Структура проекта:

  1. DS3231_MAX7219_Clock.ino – основной файл проекта (используемые библиотеки, пины, настройки, глобальные переменные)
  2. a_MAX7219_stuff.ino – всё, что относится к выводу данных на LED матрицу
  3. b_DS3231_stuff.ino – все основные функции;
  4. z_setup_loop.ino – функции setup() и loop();
  5. iwTimer.cpp – класс таймера на основе функции millis() для реализации многозадачности;
  6. 5bite_rus_forum.h и 7segment_fixed.h – файлы шрифтов (источники указаны в комментариях).

Планируемый функционал:

  • Визуализатор звукового спектра (отдельная программа на ПК);
  • Стабилизация значений освещённости для устранения скачков яркости;
  • Режим настройки часов через LED матрицу с помощью кнопок;
  • Режим настройки будильника через LED матрицу с помощью кнопок;
  • Возможность настройки времени и будильника через UART с ПК;
  • Возможность отключения вывода отладочных сообщений по UART при компиляции;
  • Возможность автоматического перехода к режиму часов по тайм-ауту.

About

Многофункциональные Arduino-часы на LED матрице с контроллером MAX7219

Источник

7-Segment Clock with Arduino Nano + DS3231 + LDR © LGPL

Another clock project with 1, 2″ matrix display.

Arduino Nano R3
works well with Arduino Uno or Elegoo Uno
× 1
Adafruit 7-Segment Backpack — 1.2″ Tall Digits
— 1.2″ Tall Digits in my case (optional if you buy the bundle)
× 1
Adafruit 1.2 4-Digit 7-Segment Display w/I2C Backpack — Green
× 1
Adafruit DS3231
or DS1307 if your prefer
× 1
Resistor 100k ohm
× 1
Photo resistor
× 1
Breadboard (generic)
× 1
Jumper wires (generic)
10-14 pieces
× 1
Coin Cell Battery CR1220
× 1

In times where you always have a clock on your wrist, be it a watch on your wrist or a smartphone, the Arduino Uno/Nano is a bit dull. You otherwise have NTP server synchronized devices in this article outside, which are constantly online via your Internet connection.

One of my friends refused for personal reasons a device with WiFi connection in his bedroom and so I have the Arduino equipped with a separate clock.

Choose the right product

I was surprised how many different products even Adafruit had available: depending on the desired tension, as well as with different precision! Here I decided for two products: the cheaper DS1307 and the probably more precise DS3231 .

To be clear: both products can be used in this clock. To use the DS1307, pay attention to the correct PIN assignment and the restriction to the temperature display option: remark «//» the displayTemp(); function within the loop().

Adapt the sketch

I went looking for a sketch and found something with another member . I restructured and fit this sketch, but kept its Czech comments and added English remarks.

The ad was supposed to be as big as possible and so I decided on a 7-segment ad: after all, I only wanted to have the time in mind.

The next positive surprise I experienced while reviewing the sketches: here, the DS3231 provides the option to use the temperature , which the DS1307 — in addition to its inaccuracy — missing.

Init the Clocks

If you have a CR1220 button cell battery, you can follow Adafruit’s short tutorial on setting up the clocks. In summary, the time is not downloaded from the Internet, but over time from the local PC. The upload timestamp is transferred to the timers.

Afterwards I added the LED matrix to the circuit for time and temperature output . The period for the change of time and temperature can be set via variables.

In particular, how the control of the individual — flashing — dots and digits on the LED matrix works and is controlled, is well described in the sketch.

Here I refer to more Adafruit sources .

The sketch is rounded off by the adjustment of summer/winter time and the brightness of the LED matrix depending on the ambient light (at night the display should be darker than in daylight).

In the video, you certainly noticed the change of time and temperature. Did you pay attention to the point on the left in the picture? This changes its position (up or down) depending on the seconds.

Give me feedback if you know how to issue an «ERR» on the LED matrix in case of failure of the clock. At the moment «bEEF» will appear:

Источник

clockspot/arduino-clock

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Universal Arduino Digital Clock

To see your clock’s software version, hold Select briefly while powering up the clock.

A universal digital clock codebase for Arduino, maintained by Luke.

  • Time of day with automatic DST change and chimes.
  • Perpetual calendar with day counter and local sunrise/sunset times.
  • Alarm with snooze and automatic weekday/weekend skipping.
  • Chronograph and timer with reset/interval options.
  • Runs on both classic Arduino Nano (AVR) and Nano 33 IoT (SAMD21).
  • Supports web-based config and NTP sync over Wi-Fi on Nano 33 IoT.
  • Simple control via three/four buttons, a rotary encoder, and/or Nano 33 IoT’s IMU (tilt control).
  • Signals via piezo beeper, switch (e.g. appliance timer), and/or pulse (e.g. bell ringer).
  • Supports Nixie displays of two SN74141 chips driving four/six tubes, with anti-cathode poisoning.
  • Supports LED displays of three/four MAX7219 chips (via SPI) driving 8×8 LED matrices (example).
  • Scheduled nightly/weekly display dim/shutoff and switchable backlighting with optional PWM fade.
  • Timekeeping can be internal, or based on a DS3231 RTC (via I2C) for reliability/accuracy.
  • Settings stored persistently in case of power loss, and mirrored in RAM in case of EEPROM/flash failure.

Written to support RLB Designs’ Universal Nixie Driver Board (UNDB):

  • Backlighting (PWM LED) supported on UNDB v8+
  • Switch and pulse signals supported on UNDB v9+
  • Nano 33 IoT support coming on future versions

Configuration, compilation, and upload

Various options, such as enabled functionality, RTC, display, I/O pins, timeouts, and control behaviors, are specified in a config file. This allows you to maintain configs for multiple clock hardware profiles, and simply include the relevant config at the top of arduino-clock.h before compiling. Several example configs are provided, and

sample.h includes all possible options with detailed comments.

You may also wish to adjust the defaults for the clock’s user-configurable values to best suit its intended use, in case the user performs a hard reset. Some of these are specified in the config; others, for now, are hardcoded in arduino-clock.ino ( optsDef[] for settings and initEEPROM() for other values).

I use the Arduino IDE to compile and upload, due to the use of various Arduino and Arduino-oriented libraries. Make sure the relevant libraries are installed in the Library Manager, per the config in use.

  • EEPROM (Arduino) for AVR Arduinos (e.g. classic Nano)
  • SPI (Arduino) and LedControl for MAX7219-based displays
  • Encoder if rotary encoder is used for Up/Down inputs
  • Arduino_LSM6DS3 (Arduino) if using Nano 33 IoT’s IMU for inputs
  • WiFiNINA and WiFiUdp (Arduino) for Wi-Fi and NTP sync support on Nano 33 IoT
  • FlashStorage for persistent storage on Nano 33 IoT
  • Wire (Arduino) and DS3231 if using DS3231 RTC (via I2C)
  • Dusk2Dawn if sunrise/sunset display is enabled
    • Note: At this writing, for Nano 33 IoT, it’s necessary to download this library as .ZIP and add manually, as the version in the Library Manager is old and, in my experience, will not compile for SAMD.

Before compiling and uploading, you will need to select the correct board, port, and (for AVR) processor in the IDE’s Tools menu.

  • If your Arduino does not appear as a port option, you may have a clone that requires drivers for the CH340 chipset.
  • If upload fails for an ATMega328P Arduino (e.g. classic Nano), try selecting/unselecting “Old Bootloader” in the processor menu.

About

Digital clock code for Arduino Nano and Nano 33 IoT, to drive nixie or LED matrix displays

Источник

Adblock
detector