【C语言】两开关控制灯(未经验证仅供参考)

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<windows.h>
#include<time.h>
int ScanKey(int A)
{ 

	if (A == 0)//检测按键是否按下
		Sleep(20);//延迟保证按下
	if (A == 0)
	{
		return 0;
	}
	else
	{
		return 1;
	}

}
int ScanKey2(int B)
{
	if (B == 0)
		Sleep(20);
	if (B == 0)
	{
	  return 0;
	}
	else
	  return 1;

}
int main()
{
	time_t start, end;
	start = time(NULL);
		int C = 0;//灯
		int A = 0;
		int B = 0;//两个开关
		int ScanKey(A);//按键状态,表现其输入值
		int ScanKey2(B);//同上
		for (;;){//死循环
			end = time(NULL);
			if ((A == 0) && (B == 0) && (difftime(end, start)==300))//五分钟没按灯灭
			{ 
				C = 0;
			}
			else{
				if ((ScanKey(A) == 0) && (ScanKey2(B) == 0))//开关都没按,灯灭
				{
					C = 0;
				}
				else
					if ((ScanKey(A) == 1) && (ScanKey2(B) == 1))//开关都按,灯灭
					{
					C = 0;
					}
					else
						if ((ScanKey(A) == 1) && (ScanKey2(B) == 0))//灯灭时,按一开关灯亮
						{
					C = 1;
						}
						else
							if ((ScanKey(A) == 0) && (ScanKey2(B) == 1))//同上
							{
					C = 1;
							}
							else
							{
								C = 0;//其他状态,灯灭
							}
			}
	}
	system("pause");
	return 0;
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要通过蓝牙控制开关,需要以下步骤: 1. 确定使用的蓝牙模块,例如HC-05或HC-06。 2. 将蓝牙模块与MCU(单片机)连接,可以使用串口通信或者SPI/I2C总线。 3. 程序中需要使用蓝牙模块的驱动,例如使用AT指令控制蓝牙模块。在程序中发送AT指令,可以设置蓝牙模块的名称、波特率等。 4. 程序需要通过蓝牙模块接收手机或电脑端的指令,可以使用串口中断或者轮询的方式读取蓝牙模块的数据。 5. 根据接收到的指令,控制开关。可以使用单片机的GPIO口控制的亮灭。 下面是一个基本的C语言程序,实现通过蓝牙控制开关: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define LED_PIN 2 // 的GPIO口 // 初始化蓝牙模块 void initBluetooth() { // 使用AT指令设置蓝牙模块的名称和波特率 // ... } // 接收蓝牙指令 bool receiveCommand(char* buffer) { // 轮询蓝牙模块,读取数据到buffer中 // 如果读取到了数据,返回true;否则返回false // ... } // 控制开关 void controlLED(bool onOff) { // 控制LED_PIN口输出高电平或低电平 // ... } int main() { // 初始化蓝牙模块 initBluetooth(); // 主循环 while (true) { // 接收蓝牙指令 char buffer[64]; if (receiveCommand(buffer)) { // 控制开关 if (strcmp(buffer, "on") == 0) { controlLED(true); } else if (strcmp(buffer, "off") == 0) { controlLED(false); } } } return 0; } ``` 需要注意的是,具体的实现方式,可能会因为使用的蓝牙模块或单片机不同,而有所不同。此处仅提供一个基本的思路和代码示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值