三、51单片机开关控制马达/电机/小风扇
- 51单片机
使用51单片机 + ULN2003 芯片,实现效果:按住按钮1秒打开/关闭电机,10 秒后关闭电机
代码:
#include "reg52.h"
typedef unsigned int u16; // 对系统默认数据类型进行重定义
typedef unsigned char u8;
// 0~9数字
unsigned char numbers[] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};
sbit LSA = P2 ^ 2;
sbit LSB = P2 ^ 3;
sbit LSC = P2 ^ 4;
sbit DC_P0 = P1 ^ 0;// 电机控制口,ULN2003芯片接入的是 0 脚
sbit KEY1 = P3 ^ 1; // 按钮 1
void delay_10us(u16 ten_us)
{
ten_us = ten_us * 110;
while (ten_us--)
;
}
void wz(u8 i) // 此显示位有8位
{
switch (i) // 位选
{
case 0:
LSC = 1;
LSB = 1;
LSA = 1;
break;
case 1:
LSC = 1;
LSB = 1;
LSA = 0;
break;
case 2:
LSC = 1;
LSB = 0;
LSA = 1;
break;
case 3:
LSC = 1;
LSB = 0;
LSA = 0;
break;
case 4:
LSC = 0;
LSB = 1;
LSA = 1;
break;
case 5:
LSC = 0;
LSB = 1;
LSA = 0;
break;
case 6:
LSC = 0;
LSB = 0;
LSA = 1;
break;
case 7:
LSC = 0;
LSB = 0;
LSA = 0;
break;
}
}
void LED_draw(unsigned char position, number) // 每一帧进行绘制
{
wz(position); // LED的位置
P0 = numbers[number]; // 显示数字 段选
delay_10us(10);
P0 = 0x00; // 消音
}
/**
* 按住按钮1秒打开/关闭电机
* 10 秒后关闭电机
**/
void main()
{
u8 time = 0, currentNumber = 0, key_flag = 0;
DC_P0 = 0; // init 关闭电机
while (1) {
if (currentNumber < 10) {
LED_draw(0, currentNumber % 10); // 个位
delay_10us(10);// 延迟补位
} else {
LED_draw(0, currentNumber / 10); // 十位
LED_draw(1, currentNumber % 10); // 个位
}
time++;
if (time == 50) { // 用于控制间隔
time = 0;
if (currentNumber != 0)
currentNumber--;
else {
DC_P0 = 0; // 关闭
}
if (key_flag == 1 && KEY1 == 0) {// 按钮还在按下状态时,执行打开/关闭逻辑
key_flag = 0;
if (DC_P0 == 0) {
DC_P0 = 1; // 打开
currentNumber = 10;
} else {
DC_P0 = 0; // 关闭
currentNumber = 0;
}
}
}
if (KEY1 == 0)// 按下按钮 1
key_flag = 1;
}
}
效果