控制俩个led灯按键开关c语言代码
时间: 2024-10-13 22:02:56 浏览: 42
在C语言中控制两个LED灯和按键开关的基本原理是通过设置IO端口(通常是GPIO)的方式来操作硬件。这里是一个简单的示例,假设我们有一个按键连接到Pin0,LED1连接到Pin1,LED2连接到Pin2。请注意,实际代码会依赖于具体的硬件平台和库,例如AVR、Arduino或Linux GPIO。
```c
#include <stdio.h>
#include <stdlib.h> // 引入stdlib.h用于系统调用
// 假设这是GPIO相关的头文件和函数
#include "pio.h" // 这里需要替换为实际的GPIO库
#define LED1_PIN 1
#define LED2_PIN 2
#define BUTTON_PIN 0
int main(void) {
int ledState = 0; // 初始化LED状态为关闭
while (1) { // 无限循环
// 检查按键是否按下
if (!pio_read(BUTTON_PIN)) { // 如果键被按下
ledState = !ledState; // 切换LED状态
}
// 更新LED状态
pio_write(LED1_PIN, ledState); // 打开LED1
pio_write(LED2_PIN, ledState ^ 1); // 关闭LED2或打开LED2(异或操作)
// 等待一段时间让LED闪烁
delay_ms(500); // 这里也需要替换为实际的延时函数
}
return 0;
}
阅读全文
相关推荐


















