当前位置:首页 > 科学研究 > 电子编程 > 正文内容

Arduino Programming Basic - If and Loop

RonWang1年前 (2024-04-08)电子编程292

Arduino 程序基础,介绍Arduino程序的基本组成,第一部分编写了10个例子,关于变量及变量名称,串口监视器,if循环,for循环,while循环等。第二部分介绍了函数,全局变量,局部变量和静态变量,数据类型,Bollean运算,注释语句等。

if and Loop Define 条件和循环语句定义

C arduino program If loop sentence

if 条件语句 1-8

int ledPin=13;
int delayPeriod =100;
void setup()
{
pinMode(ledPin,OUTPUT);
}
void loop()
{
  digitalWrite(ledPin,HIGH);
  delay(delayPeriod);
  digitalWrite(ledPin,LOW);
  delay(delayPeriod);
  delayPeriod =delayPeriod +100 ;
  if (delayPeriod>3000);
  {
  delayPeriod =100;
  }
}

For 循环语句例子 1-9

int ledPin=13;
int delayPeriod =100;
void setup()
{
pinMode(ledPin,OUTPUT);
}
void loop()
{
   for (int i=0; i<20;i++)
    {
      digitalWrite(ledPin,HIGH);
      delay(delayPeriod);
      digitalWrite(ledPin,LOW);
      delay(delayPeriod);
      }
      delay(3000);
}

这个程序的缺点是loop函数会运行较长的时间,处理器会被for循环语句占用,别的进程就无法调用处理,所以改进算法是尽可能快的让loop函数执行完,把进程空出来处理别的程序。

改进算法 1-9a

int ledPin=13;
int delayPeriod =100;
int count = 0;
void setup()
{
  pinMode(ledPin,OUTPUT);
}
void loop()
{
      digitalWrite(ledPin,HIGH);
      delay(delayPeriod);
      digitalWrite(ledPin,LOW);
      delay(delayPeriod);
      count++ ;
      if (count == 20)
      {
        count = 0;
        delay(3000); 
       }
}

While 循环 1-10

int ledPin=13;
int delayPeriod =100;
void setup()
{
pinMode(ledPin,OUTPUT);
}
void loop()
{
  int i=0;
  while(i<20)
   {
      digitalWrite(ledPin,HIGH);
      delay(delayPeriod);
      digitalWrite(ledPin,LOW);
      delay(delayPeriod);
      i++ ;
    }
  delay(3000);
}

Code written on Arduino IDE Software

版权声明:本文为原创文章,版权归donstudio所有,欢迎分享本文,转载请保留出处!

本文链接:http://www.donstudio.cn/?id=246

标签: Arduino

相关文章

Arduino Project 005 - LED Chase Lights

Arduino Project 005 - LED Chase Lights

You’re going to use a string of LEDs (10 in total) to make an LED chase effect, similar to that used...

Arduino Project 015 - Simple Motor Control

Arduino Project 015 - Simple Motor Control

First, you’re going to simply control the speed of a DC motor in one direction, using a power transi...

Arduino Project 002 - LED SOS Morse Code Singal

Arduino Project 002 - LED SOS Morse Code Singal

Arduino 电子编程--灯项目及控制,主要使用Arduino编程控制LED灯,实现基本控制Project 2 LED闪烁S.O.S信号。项目2 Project 2 S.O.S...

 ​Arduino Project 048 - Human Body Infrared Detector and Relay Light

​Arduino Project 048 - Human Body Infrared Detector and Relay Light

Project 48 Human Body Infrared Detector and Relay Light/*  * Coding by Ronwang&...

Arduino Project 009 - LED Fire Effect

Arduino Project 009 - LED Fire Effect

Project 9 will use LEDs and a flickering random light effect, via PWM again, to mimic the effect of...

Arduino Project 012 - Piezo Sounder Melody Player

Arduino Project 012 - Piezo Sounder Melody Player

Rather than using the piezo to make annoying alarm sounds, why not use it to play a melody? You are...