布尔变量控制LED
boolean pushButton;//定义变量
void setup() {
// put your setup code here, to run once:
pinMode(2,INPUT_PULLUP);
pinMode(13,OUTPUT);//设定状态
}
void loop() {
// put your main code here, to run repeatedly:
pushButton = digitalRead(2);//监测状态
if (pushButton)
{
digitalWrite(13,HIGH);//判断为1,点亮LED
}
else
{
digitalWrite(13,LOW);//判断为0,关闭LED
}
}
注意:这一个实验中,运用布尔变量后,开关的逻辑与上一次学习使用逻辑表达式时的逻辑是相反的。 若要调整为与上一次相同,在按下按钮后灯才亮的情况,则在if语句括号里的pushButton前加上!运算符即可实现
boolean pushButton1;//定义变量
boolean pushButton2;
void setup() {
// put your setup code here, to run once:
pinMode(2,INPUT_PULLUP);
pinMode(8,INPUT_PULLUP);
pinMode(13,OUTPUT);//设定状态
}
void loop() {
// put your main code here, to run repeatedly:
pushButton1 = digitalRead(2);
pushButton2 = digitalRead(8);//监测状态
if (!pushButton1 && !pushButton2)
{
digitalWrite(13,HIGH);//两个布尔变量都判定为F,才能点亮LED
}
else
{
digitalWrite(13,LOW);//只要有一个布尔变量判定为T,就无法点亮LED
}
}
猜数字
因为手上暂时没有一位的数码管,所以暂时只看了教程。记下了一些感觉需要注意的点
注意:1,因为数码管的引脚比较多且密集,连线时一定不要链接错了,特别是用杜邦线代替跳线的时候。。。。
2.限流电阻的连接不要忘了
3.注意开关引脚的位置,切不可弄混了
然后为了体验接线,找来了四位数码管,并在社区内找了一位大佬的代码,尝试连接操作(大佬帖子:http://t.csdn.cn/FEu6Y)
代码如下:
int digitalPin= 2;
int weiPin= 10;
int count = -1;
void setup() {
for(int x=0; x<4; x++) {
pinMode(weiPin+x, OUTPUT);
digitalWrite(weiPin+x, HIGH);
}
for(int x=0; x<8; x++) {
pinMode(digitalPin+x, OUTPUT);
}
}
void loop() {
count++;
if(count<10){
display(4,count);
delay(1000);
}else if(count<100){
for(int i=0;i<50;i++){
display(3,count/10);
delay(10);
display(4,count%10);
delay(10);
}}else if(count<1000){
for(int i=0;i<50;i++){
display(2,count/100);
delay(20/3);
display(3,count/10%10);
delay(20/3);
display(4,count%10);
delay(20/3);
}
}
}
void displayDigital(unsigned int digit) {
unsigned char abcdefgh[][8] = {//定义一个数组,存储不同数字的abcdefgh各段的取值
{0,0,0,0,0,0,1,1},//0
{1,0,0,1,1,1,1,1},//1
{0,0,1,0,0,1,0,1},//2
{0,0,0,0,1,1,0,1},//3
{1,0,0,1,1,0,0,1},//4
{0,1,0,0,1,0,0,1},//5
{0,1,0,0,0,0,0,1},//6
{0,0,0,1,1,1,1,1},//7
{0,0,0,0,0,0,0,1},//8
{0,0,0,1,1,0,0,1},//9
{0,0,0,1,0,0,0,1},//A
{1,1,0,0,0,0,0,1},//b
{0,1,1,0,0,0,1,1},//C
{1,0,0,0,0,1,0,1},//d
{0,1,1,0,0,0,0,1},//E
{0,1,1,1,0,0,0,1},//F
{1,1,1,1,1,1,1,0},//DOT = 16
{1,1,1,1,1,1,0,1},//MINUS= 17
{1,1,1,1,1,1,1,1} //BLANK =18
};
if(digit > 18)return;
for (unsigned int x=0; x<8; x++)
digitalWrite( digitalPin+ x, abcdefgh[digit][x] );
}
//指定位显示给定数字函数
void display(unsigned int wei, unsigned int digit) {
const int BLANK=18;
for(int x=0; x<=3; x++) {
digitalWrite(weiPin + x,LOW);// 数字位引脚置低电平
}
displayDigital(BLANK); //调用函数关闭所有显示字段
digitalWrite(weiPin +wei-1 , HIGH);//选择位显引脚
displayDigital(digit);//调用函数位显数字字段
}
最后也是成功跑起来了(连错线真的好痛苦。。。。。)