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

Arduino Programming Basic - If and Loop

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

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.parentscn.com/?id=246

标签: Arduino

相关文章

Arduino Project 041 - Ultrasonic Distance OLED 128X64 Display

Arduino Project 041 - Ultrasonic Distance OLED 128X64 Display

About the Ultrasonic sensor knowledge and infor mation click the link : Arduino Project 038 - S...

Arduino Project 001 - LED Blink

Arduino Project 001 - LED Blink

Arduino 电子编程--灯项目及控制,主要使用Arduino编程控制LED灯,实现基本控制Project 1 LED闪烁,基本的应用Project 3和4红绿灯项目项目1 Project...

Arduino Project 032 - BMP280 Pressure Sensor LCD Display

Arduino Project 032 - BMP280 Pressure Sensor LCD Display

For this project we will use Arduino Uno and BMP280 along with LCD 16x2 display module to display te...

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...

Arduino Project 030B - MX1508 H-Driver Motor

Arduino Project 030B - MX1508 H-Driver Motor

MX1508 H-BridgeDual Motor DriverThe driver can drive up to two motors. The H-Bridge dual motor drive...

C语言调试运行环境Pelles C的安装

C语言调试运行环境Pelles C的安装

C语言调试运行环境之TurboC一文介绍了在32位Windows系统下安装C语言运行环境之TubroC,但是由于TurobC只能在32位系统下运行,导致现在很多Windows10和Windows 11...