Proteus仿真电路图如下:
单片机源程序如下:- /**
- *版权所有(c)2018,艁ukasz Marcin Podkalicki
- *2009年12月13日
- *简单定时器(启动/复位/停止),使用基于TM1637的一个按钮和7段显示模块。 *
- *注意,这个ATtiny13项目使用的内部时钟并不精确
- *时间可以向前或向后流动,但是嘿!
- *它仍然足够做一个好的鸡蛋计时器:)
- */
- //#include <stdint.h>
- #include <avr/io.h>
- #include <util/delay.h>
- #include <avr/interrupt.h>
- #include "tm1637.h"
- #define BUTTON_PIN PB2
- #define TIMER_UPDATE (1 << 1)
- #define TIMER_STOP (1 << 2)
- #define TIMER_START (1 << 3)
- #define TIMER_RESET (1 << 4)
- static volatile uint8_t timer_counter;
- static volatile uint8_t timer_events;
- static volatile uint8_t timer_seconds;
- static volatile uint8_t timer_minutes;
- static volatile uint8_t timer_colon;
- static void timer_init(void);
- static void timer_handler(void);
- static void timer_process(void);
- static void timer_display(const uint8_t minutes, const uint8_t seconds, const uint8_t colon);
- ISR(TIM0_COMPA_vect)
- {
- timer_handler();
- }
- int main(void)
- {
- /* setup */
- timer_init();
- /* loop */
- while (1) {
- timer_process();
- }
- }
- void timer_init(void)
- {
- TM1637_init(1, 4);
- DDRB &= ~_BV(BUTTON_PIN); //明确设置按钮针作为输入
- PORTB |= _BV(BUTTON_PIN); // 设置按钮销的上拉电阻器
- TCCR0A |= _BV(WGM01); // 将计时器计数器模式设置为CTC
- TCCR0B |= _BV(CS01)|_BV(CS00); // 将预分频器设置为64(CLK=1200000Hz/64/250=75Hz)
- OCR0A = 249; // 设置定时器计数器最大值(250-1)
- TIMSK |= _BV(OCIE0A);// 启用定时器CTC中断
- timer_counter = timer_seconds = timer_minutes = 0; // 重置计数器
- timer_events = TIMER_UPDATE | TIMER_RESET; // 重置计时器和更新显示
- timer_colon = 1; // 显示冒号
- sei(); //启用全局中断
- }
- void timer_handler(void)
- {
- if (!(timer_events & TIMER_START)) {
- return;
- }
- timer_counter++;
- if (timer_counter == 38) {
- timer_colon = 1;
- timer_events |= TIMER_UPDATE;
- } else if (timer_counter == 75) {
- timer_colon = 0;
- timer_counter = 0;
- if (++timer_seconds == 60) {
- timer_seconds = 0;
- if (++timer_minutes == 100) {
- timer_minutes = 0;
- }
- }
- timer_events |= TIMER_UPDATE;
- }
- }
- void timer_process(void)
- {
- /* 过程启动/停止/重置 */
- if ((PINB & _BV(BUTTON_PIN)) == 0) {
- _delay_ms(10); // 去噪时间
- while((PINB & _BV(BUTTON_PIN)) == 0);
- if (timer_events & TIMER_START) {
- timer_colon = 1;
- timer_events = TIMER_UPDATE | TIMER_STOP;
- } else if (timer_events & TIMER_STOP) {
- timer_minutes = timer_seconds = 0;
- timer_colon = 1;
- timer_events = TIMER_UPDATE | TIMER_RESET;
- } else if (timer_events & TIMER_RESET) {
- timer_events = TIMER_START;
- }
- }
- /* 更新显示 */
- if (timer_events & TIMER_UPDATE) {
- timer_display(timer_minutes, timer_seconds, timer_colon);
- timer_events &= ~TIMER_UPDATE;
- }
- }
- void timer_display(const uint8_t minutes, const uint8_t seconds, const uint8_t colon)
- {
- /* 显示分钟数*/
- TM1637_display_digit(0, minutes / 10);
- TM1637_display_digit(1, minutes % 10);
- /* 显示秒数 */
- TM1637_display_digit(2, seconds / 10);
- TM1637_display_digit(3, seconds % 10);
- /* 显示/隐藏冒号 */
- TM1637_display_colon(colon);
- }
复制代码
51hei下载:
25tm1637.zip
(33.26 KB, 下载次数: 55)
|