作业帮 > 综合 > 作业

单片机编程题:开关控制四盏灯

来源:学生作业帮 编辑:百度作业网作业帮 分类:综合作业 时间:2024/06/13 13:18:16
单片机编程题:开关控制四盏灯
用开关K1,K2控制红黄兰绿四盏灯的亮灭.四盏灯接在P2口,K1,K2接在P1口.
是没有按时候先亮第一盏,按K1亮第二盏而第一盏就灭了,再按K2就亮第三盏前面两盏就灭了,再把K1打开就亮第四盏前三盏暗,最后再把K2打开就回到第一盏灯亮其他暗.就是这样的,很麻烦.还要用C语言来编.应该是C51的东西吧.
单片机编程题:开关控制四盏灯
昨天就看到有人问了,不会还是你吧,你要说清楚啊,想怎么控制,一起亮,一起灭?一个按键开,一个按键关?说具体点,要不怎么帮你 
今天晚上上线晚了,明天上班抽时间给你写吧,一会儿就搞定了,要不要留个邮箱啊,电路图也给你吧 
还有,一定要按这个顺序吗?如果我乱按会出现什么情况,直接无效? 
算了,直接贴上来吧
#include "reg52.h"
#define uint unsigned int
#define uchar unsigned char
sbit LED_R = P2^0; 
sbit LED_Y = P2^1; 
sbit LED_B = P2^2; 
sbit LED_G = P2^3;  
sbit Key1 = P1^0;   
sbit Key2 = P1^1;
uchar Key1_Times = 0, Key2_Times = 0, Key_Flag = 0;
void Delay(uint x)
{
 uint a,b;
 for(a = x; a > 0; a--)
  for(b = 110; b > 0; b--);
}
void KeyScan()
{
 if(Key1 == 0)
 {
  Delay(10);
  if(Key1 == 0)
  {     
   Key_Flag = 1;
   Key1_Times++;
   if(Key1_Times == 3)
    Key1_Times = 2;
  }
  while(!Key1);
 } 
 if(Key2 == 0)
 {
  Delay(10);
  if(Key2 == 0)
  {     
   Key_Flag = 1;
   Key2_Times++;    
   if(Key2_Times == 3)
    Key2_Times = 2;
  } 
  while(!Key2);
 }
}
void main()
{
 P2 = 0xff;
 LED_R = 0;
 while(1)
 {
  KeyScan();
  if(Key_Flag == 1)
  {
   Key_Flag = 0;
    
   if((Key1_Times == 1) && (Key2_Times == 0))
   {
    LED_R = 1;
    LED_Y = 0;
   }
   else if((Key1_Times == 1) && (Key2_Times == 1))
   {
    LED_R = 1;
    LED_Y = 1;
    LED_B = 0;
   }
   else if((Key1_Times == 1) && (Key2_Times == 2))
   {
    Key2_Times--;
   }
   else if((Key1_Times == 2) && (Key2_Times == 0))
   {
    Key1_Times--;
   }   
   else if((Key1_Times == 2) && (Key2_Times == 1))
   {
    LED_R = 1;
    LED_Y = 1;
    LED_B = 1; 
    LED_G = 0;
   }    
   else if((Key1_Times == 2) && (Key2_Times == 2))
   {
    LED_Y = 1;
    LED_B = 1; 
    LED_G = 1; 
    LED_R = 0;
    Key1_Times = 0;
    Key2_Times = 0;
   }
  }   
 }
}