arduino按钮使用的两个小实验
一:按钮控制一个灯
控制要求:按钮控制灯
实物连接图:
控制代码:
//智慧自动化2018.6.14 int key=7;//设置控制按键的数字IO脚 void setup() { pinMode(key,OUTPUT);//设置数字IO引脚为输出模式 } void loop() { int i;//定义发量 while(1) { i=analogRead(0);//读取模拟0口电压值 if(i>1000)//如果电压值大于1000 digitalWrite(key,HIGH);//设置第七引脚为高电平,点亮led灯 else digitalWrite(key,LOW);//设置第七引脚为低电平,熄灭led灯 } }
二:按钮生产随机数
控制要求:随机数生成
实物连接图:
控制代码:
//智慧自动化2018.6.14 int a=7; int b=6; int c=5; int d=10; int e=11; int f=8; int g=9; int dp=4; //显示数字1 void digital_1(void) { unsigned char j; digitalWrite(c,HIGH);//给数字接口5 引脚高电平,点亮c 段 digitalWrite(b,HIGH);//点亮b 段 for(j=7;j<=11;j++)//熄灭其余段 digitalWrite(j,LOW); digitalWrite(dp,LOW);//熄灭小数点DP 段 } //显示数字2 void digital_2(void) { unsigned char j; digitalWrite(b,HIGH); digitalWrite(a,HIGH); for(j=9;j<=11;j++) digitalWrite(j,HIGH); digitalWrite(dp,LOW); digitalWrite(c,LOW); digitalWrite(f,LOW); } //显示数字3 void digital_3(void) { digitalWrite(g,HIGH); digitalWrite(a,HIGH); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(dp,LOW); digitalWrite(f,LOW); digitalWrite(e,LOW); } //显示数字4 void digital_4(void) { digitalWrite(c,HIGH); digitalWrite(b,HIGH); digitalWrite(f,HIGH); digitalWrite(g,HIGH); digitalWrite(dp,LOW); digitalWrite(a,LOW); digitalWrite(e,LOW); digitalWrite(d,LOW); } //显示数字5 void digital_5(void) { unsigned char j; digitalWrite(a,HIGH); digitalWrite(b, LOW); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(e, LOW); digitalWrite(f,HIGH); digitalWrite(g,HIGH); digitalWrite(dp,LOW); } //显示数字6 void digital_6(void) { unsigned char j; for(j=7;j<=11;j++) digitalWrite(j,HIGH); digitalWrite(c,HIGH); digitalWrite(dp,LOW); digitalWrite(b,LOW); } //显示数字7 void digital_7(void) { unsigned char j; for(j=5;j<=7;j++) digitalWrite(j,HIGH); digitalWrite(dp,LOW); for(j=8;j<=11;j++) digitalWrite(j,LOW); } //显示数字8 void digital_8(void) { unsigned char j; for(j=5;j<=11;j++) digitalWrite(j,HIGH); digitalWrite(dp,LOW); } void setup() { int i; for(i=4;i<=11;i++) { pinMode(i,OUTPUT);//设置4~11口味输出模式 } } void loop() { while(1) { digital_1();//显示数字1 while(analogRead(0)>512);//如果读到模拟0口的值为0则说明有按键按下 delay(200);//延时200ms digital_2(); while(analogRead(0)>512); delay(200); digital_3(); while(analogRead(0)>512); delay(200); digital_4(); while(analogRead(0)>512); delay(200); digital_5(); while(analogRead(0)>512); delay(200); digital_6(); while(analogRead(0)>512); delay(200); digital_7(); while(analogRead(0)>512); delay(200); digital_8(); while(analogRead(0)>512); delay(200); } }