[C] syntaxhighlighter_viewsource syntaxhighlighter_copycode
#define IN 3
#define OUT 2
#define Keyone 4
#define LED1 7
#define LED2 8
#define LED3 9
#define LED4 10
#define LED5 11
#define LED6 12
#define LED7 13
float val;
int state=0;
void LED()//点亮LED
{
int j;
for(j=LED1;j<=LED7;j++)
digitalWrite(j,LOW);
if(val<80)
for(j=LED1;j<val/10+LED1-1;j++)
digitalWrite(j,HIGH);
}
void Metre()//串口输出距离单位为米
{
Serial.print("Metre:");
Serial.println(val/100.0);
}
void Inch()//串口输出距离为英寸
{
Serial.print("Inch:");
Serial.println(val/2.54);
}
void Cm()//串口输出距离为厘米
{
Serial.print("Cm:");
Serial.println(val);
}
void Distance()//计算距离
{
float distance;
digitalWrite(OUT,LOW);
delayMicroseconds(2);
digitalWrite(OUT,HIGH);//开始触发
delayMicroseconds(10);
digitalWrite(OUT,LOW);//结束触发
distance=pulseIn(IN,HIGH);
distance=distance/58;
val=distance;
}
void setup() {
Serial.begin(9600);//串口初始化
pinMode(IN,INPUT);
pinMode(OUT,OUTPUT);
pinMode(Keyone,INPUT);
pinMode(LED1,OUTPUT);
pinMode(LED2,OUTPUT);
pinMode(LED3,OUTPUT);
pinMode(LED4,OUTPUT);
pinMode(LED5,OUTPUT);
pinMode(LED6,OUTPUT);
pinMode(LED7,OUTPUT);
}
void loop() {
Distance();//计算距离
if(digitalRead(Keyone)==1)//按键按下
{
delay(20);
while(digitalRead(Keyone));
state++;
}
switch(state%3)//控制输出的单位
{
case 0:Cm();break;
case 1:Metre();break;
case 2:Inch();break;
default :break;
}
LED();
delay(20);
}