Arduino的快速指南

2018-12-26 16:47 更新

Arduino - Overview

Arduino是一个基于易于使用的硬件和软件的原型平台(开源)。 它包括一个可编程的电路板(称为微控制器)和一个称为Arduino IDE(集成开发环境)的现成软件,用于将计算机代码写入并上传到物理板。

主要特点是 -

  • Arduino板卡能够读取来自不同传感器的模拟或数字输入信号,并将其转换为输出,例如激活电机,打开/关闭LED,连接到云和许多其他操作。

  • 您可以通过Arduino IDE(称为上传软件)向板上的微控制器发送一组指令来控制板功能。

  • 与大多数以前的可编程电路板不同,Arduino不需要额外的硬件(称为编程器),以便将新代码加载到板上。 您可以简单地使用USB电缆。

  • 此外,Arduino IDE使用C ++的简化版本,使其更容易学习编程。

  • 最后,Arduino提供了一个标准的外形规格,将微控制器的功能打破成更易于使用的封装。

Board

Board Types

根据使用的不同微控制器,可提供各种Arduino板。 然而,所有Arduino板都有一个共同点:它们通过Arduino IDE编程。

差异基于输入和输出的数量(可以在单个板上使用的传感器,LED和按钮的数量),速度,工作电压,外形尺寸等。一些电路板设计为嵌入式并且没有编程 接口(硬件),您需要单独购买。 有些可以直接从3.7V电池运行,其他人需要至少5V。

这里有一个不同的Arduino板的列表。

基于ATMEGA328微控制器的Arduino板卡

Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface
Arduino Uno R3 5V 16MHz 14 6 6 1 USB via ATMega16U2
Arduino Uno R3 SMD 5V 16MHz 14 6 6 1 USB via ATMega16U2
Red Board 5V 16MHz 14 6 6 1 USB via FTDI
Arduino Pro 3.3v/8 MHz 3.3V 8MHz 14 6 6 1 FTDI-Compatible Header
Arduino Pro 5V/16MHz 5V 16MHz 14 6 6 1 FTDI-Compatible Header
Arduino mini 05 5V 16MHz 14 8 6 1 FTDI-Compatible Header
Arduino Pro mini 3.3v/8mhz 3.3V 8MHz 14 8 6 1 FTDI-Compatible Header
Arduino Pro mini 5v/16mhz 5V 16MHz 14 8 6 1 FTDI-Compatible Header
Arduino Ethernet 5V 16MHz 14 6 6 1 FTDI-Compatible Header
Arduino Fio 3.3V 8MHz 14 8 6 1 FTDI-Compatible Header
LilyPad Arduino 328 main board 3.3V 8MHz 14 6 6 1 FTDI-Compatible Header
LilyPad Arduino simply board 3.3V 8MHz 9 4 5 0 FTDI-Compatible Header

基于ATMEGA32u4微控制器的Arduino板卡

Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface
Arduino Leonardo 5V 16MHz 20 12 7 1 Native USB
Pro micro 5V/16MHz 5V 16MHz 14 6 6 1 Native USB
Pro micro 3.3V/8MHz 5V 16MHz 14 6 6 1 Native USB
LilyPad Arduino USB 3.3V 8MHz 14 6 6 1 Native USB

基于ATMEGA2560微控制器的Arduino板卡

Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface
Arduino Mega 2560 R3 5V 16MHz 54 16 14 4 USB via ATMega16U2B
Mega Pro 3.3V 3.3V 8MHz 54 16 14 4 FTDI-Compatible Header
Mega Pro 5V 5V 16MHz 54 16 14 4 FTDI-Compatible Header
Mega Pro Mini 3.3V 3.3V 8MHz 54 16 14 4 FTDI-Compatible Header

基于AT91SAM3X8E微控制器的Arduino板卡

Board Name Operating Volt Clock Speed Digital i/o Analog Inputs PWM UART Programming Interface
Arduino Mega 2560 R3 3.3V 84MHz 54 12 12 4 USB native

Arduino - Board Description

在本章中,我们将了解Arduino板上的不同组件。 我们将研究Arduino UNO板,因为它是Arduino板系列中最受欢迎的板。 此外,它是开始使用电子和编码的最佳板。 有些板子看起来有点不同于下面给出的,但大多数Arduinos有大部分这些组件是共同的。

Board Description
Power USB

电源USB

Arduino板可以使用计算机的USB电缆供电。 所有您需要做的是将USB电缆连接到USB连接(1)。

Barrel Jack

电源(Barrel Jack)

Arduino板可以通过将其连接到桶形插座(2)直接从交流电源供电。

Voltage Regulator

稳压器

电压调节器的功能是控制提供给Arduino板的电压,并稳定处理器和其他元件使用的直流电压。

Crystal Oscillator

晶体振荡器

晶振帮助Arduino处理时间问题。 Arduino如何计算时间? 答案是,通过使用晶体振荡器。 在Arduino晶体顶部打印的数字是16.000H9H。 它告诉我们,频率是16,000,000赫兹或16MHz。

Arduino Reset

Arduino重设

你可以重置你的Arduino板,即从一开始你的程序。 您可以通过两种方式重置UNO板。 首先,通过使用板上的复位按钮(17)。 其次,您可以将外部复位按钮连接到标有RESET(5)的Arduino引脚。

Pins

引脚(3.3,5,GND,Vin)

  • 3.3V(6) - 电源3.3输出电压

  • 5V(7) - 电源5输出电压

  • 与Arduino板使用的大多数组件工作正常与3.3伏和5伏。

  • GND(8)(接地) - Arduino上有几个GND引脚,其中任何一个都可用于将电路接地。

  • Vin(9) - 此引脚也可用于从外部电源(如交流主电源)为Arduino板供电。

Analog pins

模拟引脚

Arduino UNO板有五个模拟输入引脚A0到A5。 这些引脚可以从模拟传感器(如湿度传感器或温度传感器)读取信号,并将其转换为可由微处理器读取的数字值。

Main microcontroller

主微控制器

每个Arduino板都有自己的微控制器(11)。 你可以假设它作为你的董事会的大脑。 Arduino上的主IC(集成电路)与板对板略有不同。 微控制器通常是ATMEL公司的。 在从Arduino IDE加载新程序之前,你必须知道你的板子有什么IC。 此信息位于IC顶部。 有关IC结构和功能的更多详细信息,请参见数据表。

ICSP pin

ICSP pin

大多数情况下,ICSP(12)是一个AVR,一个由MOSI,MISO,SCK,RESET,VCC和GND组成的Arduino的微小编程头。 它通常被称为SPI(串行外设接口),其可以被认为是输出的“扩展"。 实际上,您正在将输出设备驱动到SPI总线的主机。

Power LED indicator

电源LED指示灯

当您将Arduino插入电源以指示电路板已正确上电时,此LED应点亮。 如果这个指示灯不亮,那么连接有问题。

TX and RX LEDs

TX和RX LED

TX和RX LED ...

Digital I/O

数字I / O

Arduino UNO板有14个数字I / O引脚(15)(其中6个提供PWM(脉宽调制)输出)这些引脚可配置为输入数字引脚,用于读取逻辑值(0或1)或数字 输出引脚来驱动不同的模块,如LED,继电器等。标有“〜"的引脚可用于产生PWM。

AREF

AREF

AREF代表模拟参考。 它有时用于设置外部参考电压(0和5伏之间)作为模拟输入引脚的上限。

Arduino - Installation

在了解Arduino UNO主板的主要部分后,我们准备好学习如何设置Arduino IDE。 一旦我们学到这一点,我们将准备好在Arduino板上传我们的程序。

在本节中,我们将学习简单的步骤,如何在我们的计算机上设置Arduino IDE,并准备板通过USB电缆接收程序。

第1步 - 首先,您必须有您的Arduino板(你可以选择你最喜欢的板子)和一根USB电缆。 如果您使用Arduino UNO,Arduino Duemilanove,Nano,Arduino Mega 2560或Diecimila,您将需要一个标准USB电缆(A插头到B插头),您将连接到USB打印机,如下图所示。

USB Cable

如果使用Arduino Nano,您将需要A到Mini-B电缆,如下图所示。

Mini Cable

步骤2 - 下载Arduino IDE软件。

您可以从下载页面获得不同版本的Arduino IDE Arduino官方网站。 您必须选择与操作系统(Windows,IOS或Linux)兼容的软件。 文件下载完成后,解压缩文件。

Opening Arduino Nightly Windows

步骤3 - 打开您的开发板。

Arduino Uno,Mega,Duemilanove和Arduino Nano通过USB连接到计算机或外部电源自动获取电源。 如果您使用Arduino Diecimila,您必须确保电路板配置为从USB连接提取电源。 电源选择使用跳线,一小块塑料安装在USB和电源插孔之间的三个引脚中的两个。 检查它是否在最靠近USB端口的两个引脚上。

使用USB电缆将Arduino板连接到计算机。 绿色电源LED(标有PWR)应发光。

步骤4 - 启动Arduino IDE。

下载Arduino IDE软件后,需要解压缩该文件夹。 在文件夹中,您可以找到带有无穷大标签(application.exe)的应用程序图标。 双击该图标以启动IDE。

Launch Arduino IDE

步骤5 - 开启第一个专案。

一旦软件启动,您有两个选项 -

  • Create a new project.
  • Open an existing project example.

要创建新项目,请选择文件→新建

Edit File

要打开现有项目示例,请选择文件→示例→基本→Blink。

Open Project

在这里,我们只选择一个名为 Blink 的示例。 它打开和关闭LED有一些时间延迟。 您可以从列表中选择任何其他示例。

步骤6 - 选择您的Arduino主板。

为了避免在将程序上载到板上时出现任何错误,必须选择与连接到计算机的板匹配的正确的Arduino板名称。

转到工具→板并选择您的板。

Select Board

在这里,我们根据我们的教程选择了Arduino Uno板,但是你必须选择与你使用的板匹配的名字。

步骤7 - 选择串行端口。

选择Arduino板的串行设备。 转到工具→串行端口菜单。 这可能是COM3或更高(COM1和COM2通常保留为硬件串行端口)。 要找到,你可以断开你的Arduino板,并重新打开菜单,消失的条目应该是Arduino板。 重新连接电路板并选择该串行端口。

Serial Port

步骤8 - 将程序上传到您的主板。

在解释如何将我们的程序上传到开发板之前,我们必须演示Arduino IDE工具栏中出现的每个符号的功能。

Upload program

A - 用于检查是否存在编译错误。

B - 用于将程序上传到Arduino板。

C - 用于创建新草图的快捷方式。

D - 用于直接打开示例草图之一。

E - 用于保存草图。

F - 用于从板接收串行数据并将串行数据发送到板的串行监视器。

现在,只需点击环境中的“上传"按钮。 等待几秒钟; 您将看到板上的RX和TX LED,闪烁。 如果上传成功,则状态栏中将显示“完成上传"消息。

注意 - 如果您有Arduino Mini,NG或其他电路板,则需要在单击Arduino软件上的上传按钮之前,立即按下电路板上的复位按钮。

Arduino - Program Structure

在本章中,我们将深入研究Arduino程序结构,并将学习更多Arduino世界中使用的新术语。 Arduino软件是开源的。 Java环境的源代码在GPL下发布,C / C ++微控制器库在LGPL下。

草图 - 第一个新的术语是名为“草图"的Arduino程序。

Structure

Arduino程序可以分为三个主要部分:结构,值(变量和常量)和函数 在本教程中,我们将逐步了解Arduino软件程序,以及如何编写程序,而不会出现任何语法或编译错误。

让我们从结构开始。 软件结构包括两个主要功能 -

  • Setup( ) function
  • Loop( ) function
Structure
Void setup ( ) {

}
  • 目的 - 草图启动时会调用 setup()函数。 使用它来初始化变量,引脚模式,开始使用库等。在每次上电或复位Arduino板之后,设置功能将只运行一次。

  • INPUT - -

  • OUTPUT - -

  • 返回 - -

Void Loop ( ) {

}
  • 目的 - 创建用于初始化并设置初始值的 setup()函数后, loop() ,并循环连续,允许您的程序更改和响应。 使用它来主动控制Arduino板。

  • INPUT - -

  • OUTPUT - -

  • 返回 - -

Arduino - Data Types

C中的数据类型是指用于声明不同类型的变量或函数的扩展系统。 变量的类型确定它在存储器中占用多少空间以及如何解释存储的位模式。

下表提供了您将在Arduino编程期间使用的所有数据类型。

void Boolean char Unsigned char byte int Unsigned int word
long Unsigned long short float double array String-char array String-object

void

void关键字仅用于函数声明。 它表示该函数预计不会向调用它的函数返回任何信息。

Example

Void Loop ( ) {
   // rest of the code
}

Boolean

布尔值保存两个值之一,true或false。 每个布尔变量占用一个字节的内存。

Example

boolean val = false ; // declaration of variable with type boolean and initialize it with false
boolean state = true ; // declaration of variable with type boolean and initialize it with false

Char

一种数据类型,占用存储字符值的一个字节的内存。 字符文字用单引号写成:\'A\',对于多个字符,字符串使用双引号:“ABC"。

但是,字符存储为数字。 您可以在 ASCII图表中查看特定编码。 这意味着可以对字符进行算术运算,其中使用字符的ASCII值。 例如,\'A\'+ 1的值为66,因为大写字母A的ASCII值为65。

Example

Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with character a
Char chr_c = 97 ;//declaration of variable with type char and initialize it with character 97

ASCII Char Table

unsigned char

无符号字符是一种无符号数据类型,占用一个字节的内存。 unsigned char数据类型对0到255之间的数字进行编码。

Example

Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it with character y

byte

一个字节存储一个8位无符号数,从0到255。

Example

byte m = 25 ;//declaration of variable with type byte and initialize it with 25

int

整数是数字存储的主数据类型。 int存储16位(2字节)值。 这产生-32,768至32,767的范围(最小值为-2 ^ 15,最大值为(2 ^ 15)-1)。

int 大小因板而异。 例如,在Arduino Due中, int 存储32位(4字节)值。 这产生-2,147,483,648至2,147,483,647(最小值-2 ^ 31和最大值(2 ^ 31)-1)的范围。

Example

int counter = 32 ;// declaration of variable with type int and initialize it with 32

Unsigned int

无符号整数(无符号整数)与存储2字节值的方式相同。 然而,它们不是存储负数,而是存储正值,产生0到65,535(2 ^ 16)-1的有用范围。 Due存储4字节(32位)值,范围从0到4,294,967,295(2 ^ 32-1)。

Example

Unsigned int counter = 60 ; // declaration of variable with 
   type unsigned int and initialize it with 60

Word

在Uno和其他基于ATMEGA的主板上,一个字存储一个16位无符号数。 在到期和零时,它存储一个32位无符号数。

Example

word w = 1000 ;//declaration of variable with type word and initialize it with 1000

Long

长变量是用于数字存储的扩展大小变量,并存储32位(4字节),从2,147,483,648到2,147,483,647。

Example

Long velocity = 102346 ;//declaration of variable with type Long and initialize it with 102346

unsigned long

无符号长变量是用于数字存储的扩展大小变量,并存储32位(4字节)。 与标准长整数不同,无符号整数不会存储负数,使得它们的范围为0到4,294,967,295(2 ^ 32 - 1)。

Example

Unsigned Long velocity = 101006 ;// declaration of variable with 
   type Unsigned Long and initialize it with 101006

short

short是16位数据类型。 在所有Arduinos(基于ATMega和ARM),一个短存储一个16位(2字节)的值。 这产生-32,768至32,767的范围(最小值为-2 ^ 15,最大值为(2 ^ 15)-1)。

Example

short val = 13 ;//declaration of variable with type short and initialize it with 13

float

浮点数的数据类型是具有小数点的数字。 浮点数通常用于近似模拟值和连续值,因为它们的分辨率高于整数。

浮点数可以大到3.4028235E + 38,也可以低到3.4028235E + 38。 它们被存储为32位(4字节)的信息。

Example

float num = 1.352;//declaration of variable with type float and initialize it with 1.352

double

在Uno和其他基于ATMEGA的主板上,双精度浮点数占用四个字节。 也就是说,double实现与float完全相同,精度没有增益。 在Arduino Due上,双精度具有8字节(64位)精度。

Example

double num = 45.352 ;// declaration of variable with type double and initialize it with 45.352

Arduino - Variables & Constants

在我们开始解释变量类型之前,一个非常重要的主题我们需要确保,你完全理解称为变量范围

What is Variable Scope?

Arduino使用的C编程语言中的变量具有名为scope的属性。 范围是程序的一个区域,有三个地方可以声明变量。 他们是 -

  • Inside a function or a block, which is called local variables.
  • In the definition of function parameters, which is called formal parameters.
  • Outside of all functions, which is called global variables.

Local Variables

在函数或块中声明的变量是局部变量。 它们只能由该函数或代码块中的语句使用。 局部变量不知道在它们自己之外运行。 以下是使用局部变量的示例 -

Void setup () {

}

Void loop () {
   int x , y ;
   int z ; Local variable declaration
   x = 0;
   y = 0; actual initialization
   z = 10;
}

Global Variables

全局变量定义在所有函数之外,通常在程序的顶部。 全局变量将在程序的整个生命周期中保持其价值。

全局变量可以通过任何函数访问。 也就是说,一个全局变量可以在整个程序中声明后使用。

以下示例使用全局变量和局部变量 -

Int T , S ;
float c = 0 ; Global variable declaration

Void setup () {

}

Void loop () {
   int x , y ;
   int z ; Local variable declaration
   x = 0;
   y = 0; actual initialization
   z = 10;
}

Arduino - Operators

运算符是一个符号,它告诉编译器执行特定的数学或逻辑函数。 C语言具有丰富的内置运算符,并提供以下类型的运算符:

  • Arithmetic Operators
  • Comparison Operators
  • Boolean Operators
  • Bitwise Operators
  • Compound Operators

Arithmetic Operators

假设变量A保持10,变量B保持20,则 -

Show Example

Operator name Operator simple Description Example
assignment operator = Stores the value to the right of the equal sign in the variable to the left of the equal sign. A = B
addition + Adds two operands A + B will give 30
subtraction - Subtracts second operand from the first A - B will give -10
multiplication * Multiply both operands A * B will give 200
division / Divide numerator by denominator B / A will give 2
modulo % Modulus Operator and remainder of after an integer division B % A will give 0

Comparison Operators

假设变量A保持10,变量B保持20,则 -

Show Example

Operator name Operator simple Description Example
equal to == Checks if the value of two operands is equal or not, if yes then condition becomes true. (A == B) is not true
not equal to != Checks if the value of two operands is equal or not, if values are not equal then condition becomes true. (A != B) is true
less than < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true
greater than > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true
less than or equal to <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true
greater than or equal to >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true

Boolean Operators

假设变量A保持10,变量B保持20,则 -

Show Example

Operator name Operator simple Description Example
and && Called Logical AND operator. If both the operands are non-zero then then condition becomes true. (A && B) is true
or || Called Logical OR Operator. If any of the two operands is non-zero then then condition becomes true. (A || B) is true
not ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false

Bitwise Operators

假设变量A保持10,变量B保持20,则 -

Show Example

Operator name Operator simple Description Example
and & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
or | Binary OR Operator copies a bit if it exists in either operand (A | B) will give 61 which is 0011 1101
xor ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
not ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -60 which is 1100 0011
shift left << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
shift right >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111

Compound Operators

假设变量A保持10,变量B保持20,则 -

Show Example

Operator name Operator simple Description Example
increment &plus;&plus; Increment operator, increases integer value by one A&plus;&plus; will give 11
decrement -- Decrement operator, decreases integer value by one A-- will give 9
compound addition &plus;= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand B &plus;= A is equivalent to B = B&plus; A
compound subtraction -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand B -= A is equivalent to B = B - A
compound multiplication *= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand B*= A is equivalent to B = B* A
compound division /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand B /= A is equivalent to B = B / A
compound modulo %= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand B %= A is equivalent to B = B % A
compound bitwise or |= bitwise inclusive OR and assignment operator A |= 2 is same as A = A | 2
compound bitwise and &= Bitwise AND assignment operator A &= 2 is same as A = A & 2

Arduino - Control Statements

决策结构要求程序员指定要由程序评估或测试的一个或多个条件。 如果条件被确定为真,并且可选地,如果条件被确定为假,则应当与要执行的一个或多个语句一起执行。

以下是在大多数编程语言中找到的典型决策结构的一般形式 -

Decision Making

控制语句是控制程序执行流程的源代码中的元素。 他们是 -

S.NO. Control Statement & Description
1

If statement

它采用括号中的表达式和语句或语句块。 如果表达式为真,则执行语句或语句块,否则跳过这些语句。

2

If …else statement

一个 if 语句后面可以有一个可选的else语句,当表达式为false时执行。

3

If…else if …else statement

if 语句之后可以有一个可选的 else if ... else 语句,这对于使用single if ... else if语句测试各种条件非常有用。

4

switch case statement

类似于if语句, switch ... case 通过允许程序员指定应在各种条件下执行的不同代码来控制程序的流程。

5

Conditional Operator ? :

条件运算符? :是C中唯一的三元运算符。

Arduino - Loops

编程语言提供允许更复杂的执行路径的各种控制结构。

循环语句允许我们多次执行一个语句或一组语句,以下是大多数编程语言中循环语句的一般形式 -

Loop Architecture

C编程语言提供以下类型的循环来处理循环需求。

S.NO. Loop & Description
1

while loop

while循环将连续循环,无限循环,直到圆括号()内的表达式变为假。 某些东西必须改变被测试的变量,或者while循环永远不会退出。

2

do…while loop

do ... while 循环类似于while循环。 在while循环中,循环继续条件在循环开始时测试,然后再执行循环体。

3

for loop

A for循环执行语句预定次数。 循环的控制表达式在for循环括号内完全初始化,测试和操作。

4

Nested Loop

C语言允许您在另一个循环内使用一个循环。 下面的例子说明了这个概念。

5

Infinite loop

它是没有终止条件的循环,因此循环变为无限。

Arduino - Functions

函数允许在代码段中构造程序以执行单独的任务。 创建函数的典型情况是当需要在程序中多次执行相同的操作时。

将代码片段标准化为函数具有几个优点 -

  • 函数帮助程序员保持组织。 通常这有助于概念化程序。

  • 函数将一个动作编码在一个地方,以便函数只需要考虑一次并调试一次。

  • 如果代码需要更改,这也减少了修改错误的几率。

  • 函数使整个草图更小和更紧凑,因为代码段被重复使用多次。

  • 它们使得通过使其模块化在其他程序中重用代码变得更容易,并且使用函数通常使得代码更可读。

在Arduino草图或程序中有两个必需的函数,即setup()和loop()。 其他函数必须在这两个函数的括号之外创建。

定义函数的最常用的语法是 -

Function

Function Declaration

一个函数声明在任何其他函数之外,高于或低于循环函数。

我们可以用两种不同的方式声明函数 -

第一种方法是在循环函数上面写入一个函数原型的函数的一部分,它包括 -

  • Function return type
  • Function name
  • Function argument type, no need to write the argument name

函数原型后面必须加上分号(;)。

以下示例显示使用第一种方法的函数声明的演示。

Example

int sum_func (int x, int y) // function declaration {
   int z = 0;
   z = x+y ;
   return z; // return the value
}

void setup () {
   Statements // group of statements
}

Void loop () {
   int result = 0 ;
   result = Sum_func (5,6) ; // function call
}

第二部分,称为函数定义或声明,必须在循环函数下声明,它包括 -

  • Function return type
  • Function name
  • Function argument type, here you must add the argument name
  • The function body (statements inside the function executing when the function is called)

以下示例演示使用第二种方法的函数声明。

Example

int sum_func (int , int ) ; // function prototype

void setup () {
   Statements // group of statements
}

Void loop () {
   int result = 0 ;
   result = Sum_func (5,6) ; // function call
}

int sum_func (int x, int y) // function declaration {
   int z = 0;
   z = x+y ;
   return z; // return the value
}

第二种方法只是在循环函数上面声明函数。

Arduino - Strings

字符串用于存储文本。 它们可用于在LCD或Arduino IDE串行监视器窗口中显示文本。 字符串也可用于存储用户输入。 例如,用户在键盘上连接到Arduino的字符。

在Arduino编程中有两种类型的字符串:

  • Arrays of characters, which are the same as the strings used in C programming.
  • The Arduino String, which lets us use a string object in a sketch.

在本章中,我们将学习Arduino草图中的字符串,对象和字符串的使用。 在本章结束时,您将学习在草图中使用哪种类型的字符串。

String Character Arrays

我们要学习的第一种类型的字符串是字符串 char 的一系列字符。 在上一章中,我们学习了一个数组是什么; 连续一系列相同类型的变量存储在内存中。 字符串是一个char变量数组。

字符串是一个特殊的数组,在字符串的末尾有一个额外的元素,它总是具有值0(零)。 这被称为“空终止字符串"。

String Character Array Example

此示例将显示如何创建字符串并将其打印到串行监视器窗口。

示例

void setup() {
   char my_str[6]; // an array big enough for a 5 character string
   Serial.begin(9600);
   my_str[0] = 'H'; // the string consists of 5 characters
   my_str[1] = 'e';
   my_str[2] = 'l';
   my_str[3] = 'l';
   my_str[4] = 'o';
   my_str[5] = 0; // 6th array element is a null terminator
   Serial.println(my_str);
}

void loop() { 

}

以下示例显示了字符串由什么组成; 一个具有可打印字符的字符数组和0作为数组的最后一个元素,表示这是字符串结束的位置。 通过使用 Serial.println()并传递字符串的名称,可以将字符串打印到Arduino IDE Serial Monitor窗口。

这个相同的例子可以以更方便的方式编写,如下所示 -

示例

void setup() {
   char my_str[] = "Hello";
   Serial.begin(9600);
   Serial.println(my_str);
}

void loop() {

}

在这个草图中,编译器计算字符串数组的大小,并且自动使用null终止字符串。 一个数组是六个元素长,由五个字符后跟一个零,其创建方式与上一个草图完全相同。

Manipulating String Arrays

我们可以在草图中更改字符串数组,如下图所示。

Example

void setup() {
   char like[] = "I like coffee and cake"; // create a string
   Serial.begin(9600);
   // (1) print the string
   Serial.println(like);
   // (2) delete part of the string
   like[13] = 0;
   Serial.println(like);
   // (3) substitute a word into the string
   like[13] = ' '; // replace the null terminator with a space
   like[18] = 't'; // insert the new word
   like[19] = 'e';
   like[20] = 'a';
   like[21] = 0; // terminate the string
   Serial.println(like);
}

void loop() {

}

Result

I like coffee and cake
I like coffee
I like coffee and tea

草图以下列方式工作。

Creating and Printing the String

在上面给出的草图中,创建一个新的字符串,然后打印出来显示在串行监视器窗口中。

Shortening the String

通过用零终止零(2)替换字符串中的第14个字符来缩短字符串。 这是从0开始计算的字符串数组中的元素号13。

打印字符串时,所有字符都打印到新的空终止零。 其他字符不消失; 它们仍然存在于内存中,并且字符串数组仍然是相同的大小。 唯一的区别是任何使用字符串的函数只能看到第一个空终止符。

Changing a Word in the String

最后,草图用“茶"代替“蛋糕"一词(3)。 它首先必须用空格替换空终止符,如[13],以便将字符串恢复为原始创建的格式。

新字符用单词“tea"覆盖单词“cake"的“cak"。 这是通过覆盖单个字符。 “蛋糕"的“e"被替换为新的空结束字符。 结果是字符串实际上以两个空字符终止,原始字符在字符串的末尾,而新字符替换“蛋糕"中的“e"。 这在打印新字符串时没有区别,因为打印字符串的函数在遇到第一个空终止符时停止打印字符串字符。

Functions to Manipulate String Arrays

上一个sketch通过访问字符串中的单个字符以手动方式操作字符串。 为了更容易操作字符串数组,您可以编写自己的函数来执行,也可以使用 C 语言库中的一些字符串函数。

Given below is the list Functions to Manipulate String Arrays

下一个草图使用一些C字符串函数。

Example

void setup() {
   char str[] = "This is my string"; // create a string
   char out_str[40]; // output from string functions placed here
   int num; // general purpose integer
   Serial.begin(9600);

   // (1) print the string
   Serial.println(str);

   // (2) get the length of the string (excludes null terminator)
   num = strlen(str);
   Serial.print("String length is: ");
   Serial.println(num);

   // (3) get the length of the array (includes null terminator)
   num = sizeof(str); // sizeof() is not a C string function
   Serial.print("Size of the array: ");
   Serial.println(num);

   // (4) copy a string
   strcpy(out_str, str);
   Serial.println(out_str);

   // (5) add a string to the end of a string (append)
   strcat(out_str, " sketch.");
   Serial.println(out_str);
   num = strlen(out_str);
   Serial.print("String length is: ");
   Serial.println(num);
   num = sizeof(out_str);
   Serial.print("Size of the array out_str[]: ");
   Serial.println(num);
}

void loop() {

}

Result

This is my string
String length is: 17
Size of the array: 18
This is my string
This is my string sketch.
String length is: 25
Size of the array out_str[]: 40

草图以下列方式工作。

Print the String

新创建的字符串将打印到串行监视器窗口,如以前的草图所做。

Get the Length of the String

strlen()函数用于获取字符串的长度。 字符串的长度仅适用于可打印字符,不包括空终止符。

该字符串包含17个字符,因此我们在串行监视器窗口中看到17个字符。

Get the Length of the Array

运算符sizeof()用于获取包含字符串的数组的长度。 长度包括空终止符,因此长度比字符串的长度多1。

sizeof()看起来像一个函数,但技术上是一个运算符。 它不是C字符串库的一部分,但在草图中用于显示数组大小和字符串大小(或字符串长度)之间的差异。

Copy a String

strcpy()函数用于将str []字符串复制到out_num []数组。 strcpy()函数将传递给它的第二个字符串复制到第一个字符串中。 这个字符串的副本现在存在于out_num []数组中,但只占用了数组的18个元素,因此我们在数组中仍然有22个自由char元素。 这些自由元素在内存中的字符串之后找到。

将字符串复制到数组中,以便我们在数组中有一些额外的空间用于草图的下一部分,这是在字符串的末尾添加一个字符串。

Append a String to a String (Concatenate)

草图将一个字符串连接到另一个字符串,这称为并置。 这是使用strcat()函数完成的。 strcat()函数将传递给它的第二个字符串传递到传递给它的第一个字符串的末尾。

连接后,打印字符串的长度以显示新的字符串长度。 然后打印数组的长度,以显示在40个元素长的数组中有一个25个字符长的字符串。

请记住,25个字符的长字符串实际上占用了26个字符的数组,因为null终止零。

Array Bounds

当使用字符串和数组时,在字符串或数组的边界内工作是非常重要的。 在示例草图中,创建了一个长度为40个字符的数组,以分配可用于处理字符串的内存。

如果数组太小,我们试图复制一个大于数组的字符串,那么字符串将复制到数组的末尾。 超出数组末尾的内存可能包含草图中使用的其他重要数据,然后将被我们的字符串覆盖。 如果超出字符串末尾的内存溢出,它可能会导致草图崩溃或导致意外行为。

Arduino - String Object

在Arduino编程中使用的第二种类型的字符串是字符串对象。

What is an Object?

对象是一个包含数据和函数的构造。 字符串对象可以像变量一样创建,并分配一个值或字符串。 String对象包含对包含在String对象中的字符串数据进行操作的函数(在面向对象编程(OOP)中称为“方法")。

下面的草图和解释将清楚一个对象是什么,以及如何使用String对象。

Example

void setup() { 
   String my_str = "This is my string.";
   Serial.begin(9600);

   // (1) print the string
   Serial.println(my_str);

   // (2) change the string to upper-case
   my_str.toUpperCase();
   Serial.println(my_str);

   // (3) overwrite the string
   my_str = "My new string.";
   Serial.println(my_str);

   // (4) replace a word in the string
   my_str.replace("string", "Arduino sketch");
   Serial.println(my_str);

   // (5) get the length of the string
   Serial.print("String length is: ");
   Serial.println(my_str.length());
}

void loop() { 

}

Result

This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22

创建字符串对象,并在草图顶部分配一个值(或字符串)。

String my_str = "This is my string." ;

这将创建一个名为 my_str 的String对象,并给它一个值“这是我的字符串"。

这可以与创建变量并为其分配一个值(如整数)相比较 -

int my_var = 102;

草图以下列方式工作。

Printing the String

该字符串可以打印到串行监视器窗口,就像字符数组字符串。

Convert the String to Upper-case

创建的字符串对象my_str,有多个可以操作的函数或方法。 这些方法通过使用对象名称后跟点运算符(。)和要使用的函数的名称来调用。

my_str.toUpperCase();

toUpperCase()函数对包含在类型为String的 my_str 对象中的字符串进行操作,并将对象包含的字符串数据(或文本)转换为大写 字符。 String类包含的函数列表可以在Arduino String参考中找到。 从技术上讲,String被称为一个类,用于创建String对象。

Overwrite a String

赋值运算符用于为替换旧字符串的 my_str 对象分配一个新字符串

my_str = "My new string." ;

赋值运算符不能用于字符数组字符串,但仅适用于String对象。

Replacing a Word in the String

replace()函数用于替换传递给它的第二个字符串传递给它的第一个字符串。 replace()是另一个内置到String类中的函数,因此可以在String对象my_str上使用。

Getting the Length of the String

通过使用length()可以很容易地获得字符串的长度。 在示例草图中,由length()返回的结果直接传递到Serial.println(),而不使用中间变量。

When to Use a String Object

字符串对象比字符串字符数组更容易使用。 该对象具有内置函数,可以对字符串执行多个操作。

使用String对象的主要缺点是,它使用了大量的内存,并可以迅速使用Arduinos的RAM内存,这可能会导致Arduino挂起,崩溃或行为意外。 如果在Arduino上的草图很小,并限制对象的使用,那么应该没有问题。

字符数组字符串更难使用,你可能需要编写自己的函数来操作这些类型的字符串。 其优点是,你可以控制字符串数组的大小,所以你可以保持数组小,以节省内存。

你需要确保你不要超出数组边界的字符串数组的末尾。 String对象没有这个问题,并且会处理你的字符串边界,只要有足够的内存来操作。 String对象可以尝试在内存不足时写入不存在的内存,但不会在其操作的字符串的末尾写入。

Where Strings are Used

在本章中,我们研究了字符串,它们在内存中的行为及其操作。

当我们研究如何从串行监视器窗口获取用户输入并将输入保存在字符串中时,本课程的下一部分将介绍字符串的实际用法。

Arduino - Time

Arduino提供四种不同的时间操作功能。 他们是 -

S.No. Function & Description
1

delay () function

delay()函数的工作方式非常简单。 它接受单个整数(或数字)参数。 此数字表示时间(以毫秒为单位)。

2

delayMicroseconds () function

delayMicroseconds()函数接受单个整数(或数字)参数。 有一千毫秒在一毫秒,和一百万微秒在一秒钟。

3

millis () function

此函数用于返回当时的毫秒数,Arduino板开始运行当前程序。

4

micros () function

micros()函数返回从时间开始的微秒数,Arduino板开始运行当前程序。 该数字溢出,即在大约70分钟后回到零。

Arduino - Arrays

数组是具有相同类型的连续的一组存储器位置。 要引用数组中的特定位置或元素,我们指定数组的名称和数组中特定元素的位置编号。

下图给出了一个名为C的整数数组,它包含11个元素。 通过给出数组名称后跟特定元素的位置编号([]),您引用这些元素中的任何一个。 位置编号更正式地称为下标或索引(此数字指定从数组开始的元素数)。 第一个元素具有下标0(零),有时称为零元素。

因此,数组C的元素是C [0](发音为“C sub zero"),C [1],C [2]等等。 阵列C中的最高下标是10,其比阵列(11)中的元素的数量小1。 数组名遵循与其他变量名相同的约定。

Elements of Array

下标必须是整数或整数表达式(使用任何整数类型)。 如果程序使用表达式作为下标,则程序评估表达式以确定下标。 例如,如果我们假设变量a等于5,变量b等于6,那么语句将2添加到数组元素C [11]。

下标数组名是一个左值,它可以在赋值的左侧使用,就像非数组变量名一样。

让我们更仔细地检查给定图中的数组C. 整个数组的名称是C.它的11个元素被称为C [0]到C [10]。 C [0]的值为-45,C [1]的值为6,C [2]的值为0,C [7]的值为62,C [10]的值为 78。

要打印包含在数组C的前三个元素中的值的总和,我们将写 -

Serial.print (C[ 0 ] + C[ 1 ] + C[ 2 ] );

要将C [6]的值除以2并将结果赋给变量x,我们将写为 -

x = C[ 6 ] / 2;

Declaring Arrays

数组占用内存中的空间。 要指定元素的类型和数组所需的元素数量,请使用形式的声明 -

type arrayName [ arraySize ] ;

编译器保留适当的内存量。 (回想一个声明,它保留内存更恰当地称为定义)。 arraySize必须是大于零的整数常量。 例如,要告诉编译器为整数数组C保留11个元素,请使用声明 -

int C[ 12 ]; // C is an array of 12 integers

数组可以声明为包含任何非引用数据类型的值。 例如,字符串类型的数组可以用于存储字符串。

Examples Using Arrays

本节提供了许多演示如何声明,初始化和操作数组的例子。

Example 1: Declaring an Array and using a Loop to Initialize the Array’s Elements

程序声明一个10元素的整数数组 n 行a-b使用 For 语句将数组元素初始化为零。 与其他自动变量一样,自动数组不会隐式初始化为零。 第一个输出语句(行c)显示在后续for语句(行d-e)中打印的列的列标题,以列表格式打印数组。

示例

int n[ 10 ] ; // n is an array of 10 integers

void setup () {

}

void loop () {
   for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0 {
      n[ i ] = 0; // set element at location i to 0
      Serial.print (i) ;
      Serial.print (‘\r’) ;
   }
   for ( int j = 0; j < 10; ++j ) // output each array element's value {
      Serial.print (n[j]) ;
      Serial.print (‘\r’) ;
   } 
}

结果 - 它会产生以下结果 -


Element Value

0

1

2

3

4

5

6

7

8

9

0

0

0

0

0

0

0

0

0

0

Example 2: Initializing an Array in a Declaration with an Initializer List

数组元素也可以在数组声明中通过带有等号的数组名和以逗号分隔的逗号分隔的初始值的列表来初始化。 程序使用初始化器列表初始化具有10个值(行a)的整数数组,并以表格格式(行b-c)打印数组。

示例

// n is an array of 10 integers
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ;

void setup () {

}

void loop () {
   for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0 {
      Serial.print (i) ;
      Serial.print (‘\r’) ;
   }
   for ( int j = 0; j < 10; ++j ) // output each array element's value {
      Serial.print (n[j]) ;
      Serial.print (‘\r’) ;
   } 
}

结果 - 它会产生以下结果 -


Element Value

0

1

2

3

4

5

6

7

8

9

32

27

64

18

95

14

90

70

60

37

Example 3: Summing the Elements of an Array

通常,数组的元素表示要在计算中使用的一系列值。 例如,如果数组的元素表示考试成绩,则教授可能希望总计数组的元素并使用该和来计算考试的类平均值。 程序对10元素整数数组 a 中包含的值进行求和。

示例

const int arraySize = 10; // constant variable indicating size of array
int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;

void setup () {

}
void loop () {
   // sum contents of array a
   for ( int i = 0; i < arraySize; ++i )
      total += a[ i ];
   Serial.print (“Total of array elements : ") ;
   Serial.print(total) ;
}

结果 - 它会产生以下结果 -

Total of array elements: 849

数组对Arduino很重要,应该需要更多的关注。 以下与数组相关的重要概念应该清楚Arduino -

S.NO. Concept & Description
1 Passing Arrays to Functions

要将数组参数传递给函数,请指定没有任何括号的数组的名称。

2 Multi-Dimensional Arrays

具有两个维度(即,下标)的数组通常表示由以行和列排列的信息组成的值的表。

Arduino - I/O Functions

Arduino板上的引脚可以配置为输入或输出。 我们将解释这些模式下引脚的功能。 重要的是要注意,大多数Arduino模拟引脚可以以与数字引脚完全相同的方式配置和使用。

Pins Configured as INPUT

Arduino引脚默认配置为输入,因此在使用它们作为输入时,不需要使用 pinMode()显式声明为输入。 以这种方式配置的引脚被称为处于高阻抗状态。 输入引脚对它们采样的电路提出非常小的要求,相当于引脚前面的100兆欧的串联电阻。

这意味着将输入引脚从一个状态切换到另一个状态需要非常小的电流。 这使得引脚可用于诸如实现电容式触摸传感器或将LED读作光电二极管的任务。

被配置为pinMode(pin,INPUT)的引脚,没有任何连接到它们,或者连接到它们的未连接到其他电路的引线,报告引脚状态似乎随机变化,从环境拾取电噪声,或电容耦合状态 的附近针。

Pull-up Resistors

如果没有输入,上拉电阻通常用于将输入引脚转向到已知状态。 这可以通过在输入上添加上拉电阻(to + plus; 5V)或下拉电阻(接地电阻)来实现。 10K电阻是上拉或下拉电阻的良好值。

Using Built-in Pull-up Resistor with Pins Configured as Input

Atmega芯片内置了20000个上拉电阻,可通过软件访问。 通过将 pinMode()设置为INPUT_PULLUP可访问这些内置上拉电阻。 这有效地反转了INPUT模式的行为,其中HIGH表示传感器关闭,LOW表示传感器打开。 此上拉的值取决于所使用的微控制器。 在大多数基于AVR的板上,该值保证在20kΩ和50kΩ之间。 在Arduino Due上,它在50kΩ和150kΩ之间。 有关确切值,请参考板上微控制器的数据手册。

当将传感器连接到配置有INPUT_PULLUP的引脚时,另一端应连接到地。 在简单开关的情况下,这导致当开关打开时引脚读取高,当按下开关时引脚读取低。 上拉电阻提供足够的电流来点亮与配置为输入的引脚微调连接的LED。 如果项目中的LED似乎工作,但很昏暗,这可能是发生了什么。

控制引脚是高电平还是低电平的相同寄存器(内部芯片存储器位置)控制上拉电阻。 因此,当引脚处于INPUTmode状态时,被配置为具有上拉电阻的引脚将被配置为HIGH,如果引脚被pinMode()切换到OUTPUT模式。 这也在另一个方向工作,并且如果切换到具有pinMode()的输入,留在高电平状态的输出引脚将设置上拉电阻。

示例

pinMode(3,INPUT) ; // set pin to input without using built in pull up resistor
pinMode(5,INPUT_PULLUP) ; // set pin to input using built in pull up resistor

Pins Configured as OUTPUT

配置为具有pinMode()的OUTPUT的引脚被称为处于低阻抗状态。 这意味着它们可以向其他电路提供大量的电流。 Atmega引脚可以向其他器件/电路提供(提供正电流)或吸收(提供负电流)高达40 mA(毫安)的电流。 这是足以照亮LED的电流(不要忘记串联电阻),或者运行许多传感器,但没有足够的电流来运行继电器,电磁阀或电机。

试图从输出引脚运行高电流器件,可能损坏或破坏引脚中的输出晶体管,或损坏整个Atmega芯片。 通常,这导致微控制器中的“死"引脚,但是剩余的芯片仍然充分地起作用。 因此,最好通过470Ω或1k电阻将OUTPUT引脚连接到其他器件,除非特定应用需要从引脚提取的最大电流。

pinMode() Function

pinMode()函数用于将特定引脚配置为输入或输出。 可以使用INPUT_PULLUP模式使能内部上拉电阻。 此外,INPUT模式显式禁止内部上拉。

pinMode() Function Syntax

Void setup () {
   pinMode (pin , mode);
}
  • pin - 您希望设置模式的引脚的编号

  • 模式 - INPUT,OUTPUT或INPUT_PULLUP。

示例

int button = 5 ; // button connected to pin 5
int LED = 6; // LED connected to pin 6

void setup () {
   pinMode(button , INPUT_PULLUP); 
   // set the digital pin as input with pull-up resistor
   pinMode(button , OUTPUT); // set the digital pin as output
}

void setup () {
   If (digitalRead(button ) == LOW) // if button pressed {
      digitalWrite(LED,HIGH); // turn on led
      delay(500); // delay for 500 ms
      digitalWrite(LED,LOW); // turn off led
      delay(500); // delay for 500 ms
   }
}

digitalWrite() Function

digitalWrite()功能用于向数字引脚写入HIGH或LOW值。 如果该引脚已配置为具有 pinMode()的OUTPUT, 其电压将被设置为相应的值:5V(或3.3V板上的3.3V)对于HIGH,0V(接地)对于LOW。 如果引脚配置为INPUT,则digitalWrite()将使能(HIGH)或禁止(LOW)输入引脚上的内部上拉。 建议将 pinMode()设置为INPUT_PULLUP,以启用 内部上拉电阻。

如果不将pinMode()设置为OUTPUT,并将LED连接到引脚,则在调用digitalWrite(HIGH)时,LED可能会变暗。 没有明确设置pinMode(),digitalWrite()将使能内部上拉电阻,它像一个大电流限制电阻。

digitalWrite() Function Syntax

Void loop() {
   digitalWrite (pin ,value);
}
  • pin - 您希望设置模式的引脚的编号

  • - HIGH或LOW。

示例

int LED = 6; // LED connected to pin 6

void setup () {
   pinMode(LED, OUTPUT); // set the digital pin as output
}

void setup () { 
   digitalWrite(LED,HIGH); // turn on led
   delay(500); // delay for 500 ms
   digitalWrite(LED,LOW); // turn off led
   delay(500); // delay for 500 ms
}

analogRead( ) function

Arduino能够检测是否有一个电压施加到其引脚,并通过digitalRead()函数报告。 在开/关传感器(其检测物体的存在)和模拟传感器之间存在差异,其值连续变化。 为了读取这种类型的传感器,我们需要一个不同类型的引脚。

在Arduino板的右下部分,您将看到六个标记为“模拟输入"的引脚。 这些特殊引脚不仅可以判断是否有电压施加到它们,而且它的值。 通过使用 analogRead()函数,我们可以读取施加到其中一个引脚的电压。

此函数返回0和1023之间的数字,表示0和5伏特之间的电压。 例如,如果施加到引脚号0的电压为2.5V,则analogRead(0)返回512。

analogRead() function Syntax

analogRead(pin);
  • pin - 要读取的模拟输入引脚的编号(大多数电路板上为0至5,Mini和Nano上为0至7,Mega上为0至15)

示例

int analogPin = 3;//potentiometer wiper (middle terminal) 
   // connected to analog pin 3 
int val = 0; // variable to store the value read

void setup() {
   Serial.begin(9600); // setup serial
} 

void loop() {
   val = analogRead(analogPin); // read the input pin
   Serial.println(val); // debug value
}

Arduino - Advanced I/O Function

在本章中,我们将学习一些高级的输入和输出函数。

analogReference() Function

配置用于模拟输入的参考电压(即用作输入范围顶部的值)。 选项是 -

  • DEFAULT - 5伏(5V Arduino板)或3.3伏(3.3V Arduino板)的默认模拟参考值

  • INTERNAL - 内置参考,ATmega168或ATmega328上的1.1伏特,ATmega8上的2.56伏特(不适用于Arduino Mega)

  • INTERNAL1V1 - 内置1.1V参考(仅限Arduino Mega)

  • INTERNAL2V56 - 内建的2.56V参考(仅限Arduino Mega)

  • EXTERNAL - 施加到AREF引脚的电压(仅限0到5V)用作参考

analogReference() Function Syntax

analogReference (type);

type - 可以使用以下任何类型(DEFAULT,INTERNAL,INTERNAL1V1,INTERNAL2V56,EXTERNAL)

对AREF引脚的外部参考电压不要使用小于0V或大于5V的任何值。 如果在AREF引脚上使用外部参考,则必须在调用 analogRead()函数之前将模拟参考设置为EXTERNAL。 否则,将短路有效参考电压(内部生成的)和AREF引脚,可能会损坏Arduino板上的微控制器。

MicroController

或者,您可以通过5K电阻将外部参考电压连接到AREF引脚,从而允许在外部和内部参考电压之间切换。

注意,电阻将改变用作参考的电压,因为AREF引脚上有一个内部32K电阻。 两者用作分压器。 例如,通过电阻器施加的2.5V将在AREF引脚处产生2.5 * 32 /(32&amp;加; 5)=〜2.2V。

示例

int analogPin = 3;// potentiometer wiper (middle terminal) connected to analog pin 3 
int val = 0; // variable to store the read value

void setup() {
   Serial.begin(9600); // setup serial
   analogReference(EXTERNAL); // the voltage applied to the AREF pin (0 to 5V only) 
      // is used as the reference.
}

void loop() {
   val = analogRead(analogPin); // read the input pin
   Serial.println(val); // debug value
}

Arduino - Character Functions

所有数据作为字符输入计算机,包括字母,数字和各种特殊符号。 在本节中,我们讨论C ++用于检查和处理单个字符的能力。

字符处理库包括执行字符数据的有用测试和操作的几个函数。 每个函数接收一个字符,表示为int或EOF作为参数。 字符通常作为整数操作。

记住,EOF通常具有值-1,并且一些硬件架构不允许负值存储在char变量中。 因此,字符处理函数将字符操作为整数。

下表总结了字符处理库的功能。 使用字符处理库中的函数时,请包含< cctype> 标题。

S.No. Prototype & Description
1

int isdigit(int c)

如果c是数字,则返回1,否则返回0。

2

int isalpha(int c)

如果c是字母,则返回1,否则返回0。

3

int isalnum(int c)

如果c是数字或字母,则返回1,否则返回0。

4

int isxdigit(int c)

如果c是十六进制数字字符,则返回1,否则返回0。

(有关二进制,八进制,十进制和十六进制数字的详细说明,请参见附录D,数字系统。)

5

int islower(int c)

如果c是小写字母,则返回1,否则返回0。

6

int isupper(int c)

如果c是大写字母,则返回1; 0否则。

7

int isspace(int c)

如果c是空格字符换行符(\'\\ n\'),空格,则返回1

(\'\\ f\'),回车符(\'\\ r\'),水平制表符(\'\\ t\')或垂直制表符(\'\\ v\'),否则为0。

8

int iscntrl(int c)

如果c是控制字符,返回1,如换行符(\'\\ n\'),换页符(\'\\ f\'),回车符(\'\\ r\'),水平制表符 \\ v\'),alert(\'\\ a\')或退格(\'\\ b\') - 否则为0。

9

int ispunct(int c)

如果c是除空格,数字或字母以外的打印字符,则返回1,否则返回0。

10

int isprint(int c)

如果c是包含空格(\'\')的打印字符,则返回1,否则返回0。

11

int isgraph(int c)

如果c是除空格(\'\')之外的打印字符,则返回1,否则返回0。

Examples

以下示例演示如何使用函数 isdigit,isalpha,isalnum isxdigit 函数 isdigit 确定其参数是否为数字(0-9)。 函数 isalpha 确定其参数是大写字母(A-Z)还是小写字母(a-z)。 函数 isalnum 确定其参数是大写,小写字母还是数字。 函数 isxdigit 确定其参数是否为十六进制数字(A-F,a-f,0-9)。

Example 1

void setup () {
   Serial.begin (9600);
   Serial.print ("According to isdigit:\r");
   Serial.print (isdigit( '8' ) ? "8 is a": "8 is not a");
   Serial.print (" digit\r" );
   Serial.print (isdigit( '8' ) ?"# is a": "# is not a") ;
   Serial.print (" digit\r");
   Serial.print ("\rAccording to isalpha:\r" );
   Serial.print (isalpha('A' ) ?"A is a": "A is not a");
   Serial.print (" letter\r");
   Serial.print (isalpha('A' ) ?"b is a": "b is not a");
   Serial.print (" letter\r");
   Serial.print (isalpha('A') ?"& is a": "& is not a");
   Serial.print (" letter\r");
   Serial.print (isalpha( 'A' ) ?"4 is a":"4 is not a");
   Serial.print (" letter\r");
   Serial.print ("\rAccording to isalnum:\r");
   Serial.print (isalnum( 'A' ) ?"A is a" : "A is not a" );

   Serial.print (" digit or a letter\r" );
   Serial.print (isalnum( '8' ) ?"8 is a" : "8 is not a" ) ;
   Serial.print (" digit or a letter\r");
   Serial.print (isalnum( '#' ) ?"# is a" : "# is not a" );
   Serial.print (" digit or a letter\r");
   Serial.print ("\rAccording to isxdigit:\r");
   Serial.print (isxdigit( 'F' ) ?"F is a" : "F is not a" );
   Serial.print (" hexadecimal digit\r" );
   Serial.print (isxdigit( 'J' ) ?"J is a" : "J is not a" ) ;
   Serial.print (" hexadecimal digit\r" );
   Serial.print (isxdigit( '7' ) ?"7 is a" : "7 is not a" ) ;

   Serial.print (" hexadecimal digit\r" );
   Serial.print (isxdigit( '$' ) ? "$ is a" : "$ is not a" );
   Serial.print (" hexadecimal digit\r" );
   Serial.print (isxdigit( 'f' ) ? “f is a" : "f is not a");
   
}

void loop () {

}

Result

According to isdigit:
8 is a digit
# is not a digit
According to isalpha:
A is a letter
b is a letter
& is not a letter
4 is not a letter
According to isalnum:
A is a digit or a letter

8 is a digit or a letter
# is not a digit or a letter
According to isxdigit:
F is a hexadecimal digit
J is not a hexadecimal digit
7 is a hexadecimal digit

$ is not a hexadecimal digit
f is a hexadecimal digit

我们使用每个函数的条件运算符(?:)来确定字符串“is a"或字符串“is not a"是否应该在每个测试字符的输出中打印。 例如,行 a 表示如果\'8\'是数字,即如果 isdigit 返回真(非零)值,则打印字符串“8 is a" 如果\'8\'不是数字(即,如果 isdigit 返回0),则打印字符串“8不是a"。

Example 2

以下示例演示了函数 islower isupper 的使用。 函数 islower 确定其参数是否为小写字母(a-z)。 函数 isupper 确定其参数是否为大写字母(A-Z)。

int thisChar = 0xA0;

void setup () {
   Serial.begin (9600);
   Serial.print ("According to islower:\r") ;
   Serial.print (islower( 'p' ) ? "p is a" : "p is not a" );
   Serial.print ( " lowercase letter\r" );
   Serial.print ( islower( 'P') ? "P is a" : "P is not a") ;
   Serial.print ("lowercase letter\r");
   Serial.print (islower( '5' ) ? "5 is a" : "5 is not a" );
   Serial.print ( " lowercase letter\r" );
   Serial.print ( islower( '!' )? "! is a" : "! is not a") ;
   Serial.print ("lowercase letter\r");

   Serial.print ("\rAccording to isupper:\r") ;
   Serial.print (isupper ( 'D' ) ? "D is a" : "D is not an" );
   Serial.print ( " uppercase letter\r" );
   Serial.print ( isupper ( 'd' )? "d is a" : "d is not an") ;
   Serial.print ( " uppercase letter\r" );
   Serial.print (isupper ( '8' ) ? "8 is a" : "8 is not an" );
   Serial.print ( " uppercase letter\r" );
   Serial.print ( islower( '$' )? "$ is a" : "$ is not an") ;
   Serial.print ("uppercase letter\r ");
}

void setup () {

}

Result

According to islower:
p is a lowercase letter
P is not a lowercase letter
5 is not a lowercase letter
! is not a lowercase letter

According to isupper:
D is an uppercase letter
d is not an uppercase letter
8 is not an uppercase letter
$ is not an uppercase letter

Example 3

以下示例演示如何使用函数 isspace,iscntrl,ispunct,isprint isgraph

  • 函数 isspace 确定其参数是否为空格字符,如空格(\'\'),换页符(\'\\ f\'),换行符(\'\\ n\' \\ r\'),水平制表符(\'\\ t\')或垂直制表符(\'\\ v\')。

  • 函数 iscntrl 确定其参数是否为控制字符,如水平制表符(\'\\ t\'),垂直制表符(\'\\ v\' \\ a\'),backspace(\'\\ b\'),回车(\'\\ r\')或换行符(\'\\ n\')。

  • 函数 ispunct 确定其参数是否是除空格,数字或字母之外的打印字符,如$,#,(,),[,],{,},;

  • 函数 isprint 确定其参数是否为可以在屏幕上显示的字符(包括空格字符)。

  • 函数 isgraph 测试与isprint相同的字符,但不包括空格字符。

void setup () {
   Serial.begin (9600);
   Serial.print ( " According to isspace:\rNewline ") ;
   Serial.print (isspace( '\n' )? " is a" : " is not a" );
   Serial.print ( " whitespace character\rHorizontal tab") ;
   Serial.print (isspace( '\t' )? " is a" : " is not a" );
   Serial.print ( " whitespace character\n") ;
   Serial.print (isspace('%')? " % is a" : " % is not a" );
   
   Serial.print ( " \rAccording to iscntrl:\rNewline") ;
   Serial.print ( iscntrl( '\n' )?"is a" : " is not a" ) ;
   Serial.print (" control character\r");
   Serial.print (iscntrl( '$' ) ? " $ is a" : " $ is not a" );
   Serial.print (" control character\r");
   Serial.print ("\rAccording to ispunct:\r");
   Serial.print (ispunct(';' ) ?"; is a" : "; is not a" ) ;
   Serial.print (" punctuation character\r");
   Serial.print (ispunct('Y' ) ?"Y is a" : "Y is not a" ) ;
   Serial.print ("punctuation character\r");
   Serial.print (ispunct('#' ) ?"# is a" : "# is not a" ) ;
   Serial.print ("punctuation character\r");

   Serial.print ( "\r According to isprint:\r");
   Serial.print (isprint('$' ) ?"$ is a" : "$ is not a" );
   Serial.print (" printing character\rAlert ");
   Serial.print (isprint('\a' ) ?" is a" : " is not a" );
   Serial.print (" printing character\rSpace ");
   Serial.print (isprint(' ' ) ?" is a" : " is not a" );
   Serial.print (" printing character\r");
   
   Serial.print ("\r According to isgraph:\r");
   Serial.print (isgraph ('Q' ) ?"Q is a" : "Q is not a" );
   Serial.print ("printing character other than a space\rSpace ");
   Serial.print (isgraph (' ') ?" is a" : " is not a" );
   Serial.print ("printing character other than a space ");
}

void loop () {

}

Result

According to isspace:
Newline is a whitespace character
Horizontal tab is a whitespace character
% is not a whitespace character
According to iscntrl:
Newline is a control character
$ is not a control character
According to ispunct:
; is a punctuation character
Y is not a punctuation character
# is a punctuation character
According to isprint:
$ is a printing character
Alert is not a printing character
Space is a printing character
According to isgraph:
Q is a printing character other than a space
Space is not a printing character other than a space

Arduino - Math Library

Arduino数学库(math.h)包括一些用于操作浮点数的有用的数学函数。

Library Macros

以下是在标题math.h中定义的宏:

Given below is the list of macros defined in the header math.h

Library Functions

以下函数在标题 math.h 中定义 -

Given below is the list of functions are defined in the header math.h

Example

以下示例显示如何使用最常用的math.h库函数 -

double double__x = 45.45 ;
double double__y = 30.20 ;

void setup() {
   Serial.begin(9600);
   Serial.print("cos num = ");
   Serial.println (cos (double__x) ); // returns cosine of x
   Serial.print("absolute value of num = ");
   Serial.println (fabs (double__x) ); // absolute value of a float
   Serial.print("floating point modulo = ");
   Serial.println (fmod (double__x, double__y)); // floating point modulo
   Serial.print("sine of num = ");
   Serial.println (sin (double__x) ) ;// returns sine of x
   Serial.print("square root of num : ");
   Serial.println ( sqrt (double__x) );// returns square root of x
   Serial.print("tangent of num : ");
   Serial.println ( tan (double__x) ); // returns tangent of x
   Serial.print("exponential value of num : ");
   Serial.println ( exp (double__x) ); // function returns the exponential value of x.
   Serial.print("cos num : ");

   Serial.println (atan (double__x) ); // arc tangent of x
   Serial.print("tangent of num : ");
   Serial.println (atan2 (double__y, double__x) );// arc tangent of y/x
   Serial.print("arc tangent of num : ");
   Serial.println (log (double__x) ) ; // natural logarithm of x
   Serial.print("cos num : ");
   Serial.println ( log10 (double__x)); // logarithm of x to base 10.
   Serial.print("logarithm of num to base 10 : ");
   Serial.println (pow (double__x, double__y) );// x to power of y
   Serial.print("power of num : ");
   Serial.println (square (double__x)); // square of x
}

void loop() {

}

Result

cos num = 0.10
absolute value of num = 45.45
floating point modulo =15.25
sine of num = 0.99
square root of num : 6.74
tangent of num : 9.67
exponential value of num : ovf
cos num : 1.55
tangent of num : 0.59
arc tangent of num : 3.82
cos num : 1.66
logarithm of num to base 10 : inf
power of num : 2065.70

Arduino - Trigonometric Functions

你需要使用三角学,就像计算移动物体的距离或角速度。 Arduino提供了传统的三角函数(sin,cos,tan,asin,acos,atan),可以通过写他们的原型来概括。 Math.h包含三角函数的原型。

Trigonometric Exact Syntax

double sin(double x); //returns sine of x radians
double cos(double y); //returns cosine of y radians
double tan(double x); //returns the tangent of x radians
double acos(double x); //returns A, the angle corresponding to cos (A) = x
double asin(double x); //returns A, the angle corresponding to sin (A) = x
double atan(double x); //returns A, the angle corresponding to tan (A) = x

Example

double sine = sin(2); // approximately 0.90929737091
double cosine = cos(2); // approximately -0.41614685058
double tangent = tan(2); // approximately -2.18503975868

Arduino - Due & Zero

Arduino Due是基于Atmel SAM3X8E ARM Cortex-M3 CPU的微控制器板。 它是基于32位ARM内核微控制器的第一个Arduino板。

重要功能 -

  • It has 54 digital input/output pins (of which 12 can be used as PWM outputs)
  • 12 analog inputs
  • 4 UARTs (hardware serial ports)
  • 84 MHz clock, an USB OTG capable connection
  • 2 DAC (digital to analog), 2 TWI, a power jack, an SPI header, a JTAG header
  • Reset button and an erase button
Arduino Due

Characteristics of the Arduino Due Board

Operating volt CPU speed Analog in/out Digital IO/ PWM EEPROM [KB] SRAM [KB] Flash [KB] USB UART
3.3 Volt 84 Mhz 12/2 54/12 - 96 512 2 micro 4

Communication

  • 4 Hardware UARTs
  • 2 I2C
  • 1 CAN Interface (Automotive communication protocol)
  • 1 SPI
  • 1 Interface JTAG (10 pin)
  • 1 USB Host (like as Leonardo)
  • 1 Programming Port

与大多数Arduino板不同,Arduino Due板运行在3.3V。 I / O引脚可以承受的最大电压为3.3V。 将高于3.3V的电压施加到任何I / O引脚可能会损坏电路板。

该板包含支持微控制器所需的一切。 您可以使用micro-USB电缆将其连接到计算机,或者使用AC-to-DC适配器或电池为其供电以开始使用。 Due与所有工作在3.3V的Arduino屏蔽兼容。

Arduino Zero

零是由UNO建立的平台的简单和强大的32位扩展。 零板通过提供更高的性能,为设备提供各种项目机会来扩展系列,并且作为学习32位应用程序开发的一个伟大的教育工具。

重要特点是 -

  • Zero应用程序涵盖从智能物联网设备,可穿戴技术,高科技自动化,到疯狂的机器人。

  • 该板由Atmel的SAMD21 MCU供电,该MCU配有32位ARMCortex®M0 +内核。

  • 其最重要的特性之一是Atmel的嵌入式调试器(EDBG),它提供了一个完整的调试接口,无需额外的硬件,显着增加了软件调试的易用性。

  • EDBG还支持可用于器件和引导加载程序编程的虚拟COM端口。

Arduino Zero

Characteristics of the Arduino Zero board

Operating volt CPU speed Analog in/out Digital IO/ PWM EEPROM [KB] SRAM [KB] Flash [KB] USB UART
3.3 Volt 48 Mhz 6/1 14/10 - 32 256 2 micro 2

与大多数Arduino和Genuino主板不同,Zero运行在3.3V。 I / O引脚可以承受的最大电压为3.3V。 将高于3.3V的电压施加到任何I / O引脚可能会损坏电路板。

该板包含支持微控制器所需的一切。 您可以使用micro-USB电缆将其连接到计算机,也可以使用AC-to-DC适配器或电池为其供电以开始使用。 零点与工作在3.3V的所有屏蔽兼容。

Arduino - Pulse Width Modulation

脉冲宽度调制或PWM是用于改变脉冲串中的脉冲的宽度的常用技术。 PWM有许多应用,如控制伺服和速度控制器,限制电机和LED的有效功率。

Basic Principle of PWM

脉宽调制基本上是一种方波,具有变化的高低时间。 基本PWM信号如下图所示。

PWM

有很多术语与PWM相关 -

  • 准时 - 时间信号持续时间较长。

  • 关闭时间 - 时间信号的持续时间低。

  • 周期 - 它表示为PWM信号的导通时间和关断时间的总和。

  • 占空比 - 它表示为在PWM信号周期内保持开启的时间信号的百分比。

Period

如图所示,T sub表示导通时间,T suboff表示信号的截止时间。 期间是开和关时间的和,并且如下式所示计算:

$$T_{total} = T_{on}+T_{off}$$

Duty Cycle

占空比被计算为该时间段的接通时间。 使用上面计算的周期,占空比计算为 -

$$D = \frac{T_{on}}{T_{on}+T_{off}} = \frac{T_{on}}{T_{total}}$$

analogWrite() Function

analogWrite()函数将模拟值(PWM波)写入引脚。 它可用于以不同的亮度点亮LED或以各种速度驱动电机。 在调用analogWrite()函数之后,引脚将生成指定占空比的稳定方波,直到下一次调用analogWrite()或调用相同引脚上的digitalRead()或digitalWrite()。 大多数引脚上的PWM信号频率约为490 Hz。 在Uno和类似的板上,引脚5和6的频率约为980Hz。 Leonardo上的针脚3和11也以980Hz运行。

在大多数Arduino板上(具有ATmega168或ATmega328),此功能在引脚3,5,6,9,10和11上工作。在Arduino Mega上,它在引脚2-13和44-46上工作。老Arduino 具有ATmega8的板仅支持引脚9,10和11上的 analogWrite()

UNO PWM Pins

Arduino Due在引脚2至13以及引脚DAC0和DAC1上支持 analogWrite() 与PWM引脚不同,DAC0和DAC1是数模转换器,用作真正的模拟输出。

在调用analogWrite()之前,不需要调用pinMode()将引脚设置为输出。

analogWrite() Function Syntax

analogWrite ( pin , value ) ;

value - 占空比:0(始终关闭)和255(始终打开)之间。

示例

int ledPin = 9; // LED connected to digital pin 9
int analogPin = 3; // potentiometer connected to analog pin 3
int val = 0; // variable to store the read value

void setup() {
   pinMode(ledPin, OUTPUT); // sets the pin as output
}

void loop() {
   val = analogRead(analogPin); // read the input pin
   analogWrite(ledPin, (val / 4)); // analogRead values go from 0 to 1023, 
      // analogWrite values from 0 to 255
}

Arduino - Random Numbers

要生成随机数,可以使用Arduino随机数函数。 我们有两个功能 -

  • randomSeed(seed)
  • random()

randomSeed (seed)

函数randomSeed(seed)重置Arduino的伪随机数生成器。 虽然random()返回的数字的分布基本上是随机的,但是序列是可预测的。 您应该将发电机重置为某个随机值。 如果您有一个未连接的模拟引脚,它可能会拾取来自周围环境的随机噪声。 这些可以是无线电波,宇宙射线,来自蜂窝电话的电磁干扰,荧光灯等。

Example

randomSeed(analogRead(5)); // randomize using noise from analog pin 5

random( )

随机函数生成伪随机数。 以下是语法。

random( ) Statements Syntax

long random(max) // it generate random numbers from 0 to max
long random(min, max) // it generate random numbers from min to max

Example

long randNumber;

void setup() {
   Serial.begin(9600);
   // if analog input pin 0 is unconnected, random analog
   // noise will cause the call to randomSeed() to generate
   // different seed numbers each time the sketch runs.
   // randomSeed() will then shuffle the random function.
   randomSeed(analogRead(0));
}

void loop() {
   // print a random number from 0 to 299
   Serial.print("random1=");
   randNumber = random(300);
   Serial.println(randNumber); // print a random number from 0to 299
   Serial.print("random2=");
   randNumber = random(10, 20);// print a random number from 10 to 19
   Serial.println (randNumber);
   delay(50);
}

让我们现在刷新我们对一些基本概念的知识,例如位和字节。

Bits

位只是一个二进制数字。

  • 二进制系统使用两个数字,0和1。

  • 类似于十进制数字系统,其中数字的数字不具有相同的值,位的“有效性"取决于其在二进制数中的位置。 例如,十进制数666中的数字相同,但具有不同的值。

Bits

Bytes

一个字节由8位组成。

  • 如果一个位是一个数字,逻辑上字节表示数字。

  • 可以对它们执行所有数学运算。

  • 一个字节中的数字也不具有相同的含义。

  • 最左边的位具有被称为最高有效位(MSB)的最大值。

  • 最右边的位具有最小值,因此称为最低有效位(LSB)。

  • 由于可以以256种不同的方式组合一个字节的八个零和一个,所以可以由一个字节表示的最大十进制数是255(一个组合表示零)。

Arduino - Interrupts

中断停止Arduino的当前工作,以便可以做一些其他工作。

假设你坐在家里,和别人聊天。 突然电话响了。 您停止聊天,拿起电话与来电者通话。 当你完成电话交谈后,在电话铃响之前,你回去和人聊天。

同样,你可以认为主程序是聊天的,电话铃声会导致你停止聊天。 中断服务程序是在电话上通话的过程。 当电话通话结束时,你回到你的主程序聊天。 此示例准确地说明了中断如何使处理器执行操作。

主程序运行并在电路中执行某些功能。 但是,当发生中断时,主程序在执行另一个程序时停止。 当该例程结束时,处理器再次返回主程序。

Interrupt

Important features

这里有一些关于中断的重要功能 -

  • 中断可以来自各种来源。 在这种情况下,我们使用的是由数字引脚上的状态改变触发的硬件中断。

  • 大多数Arduino设计有两个硬件中断(称为“interrupt0"和“interrupt1")分别硬连接到数字I / O引脚2和3。

  • Arduino Mega有六个硬件中断,包括引脚21,20,19和18上的附加中断(“中断2"到“中断5")。

  • 您可以使用称为“中断服务程序"(通常称为ISR)的特殊函数来定义例程。

  • 您可以定义例程并在上升沿,下降沿或两者都指定条件。 在这些特定条件下,将处理中断。

  • 每次在输入引脚上发生事件时,都可以自动执行该功能。

Types of Interrupts

有两种类型的中断 -

  • 硬件中断 - 它们响应外部事件而发生,例如外部中断引脚变为高电平或低电平。

  • 软件中断 - 它们响应于在软件中发送的指令而发生。 “Arduino语言"支持的唯一类型的中断是attachInterrupt()函数。

Using Interrupts in Arduino

中断在Arduino程序中非常有用,因为它有助于解决时序问题。 中断的良好应用是读取旋转编码器或观察用户输入。 通常,ISR应尽可能短且快。 如果您的草图使用多个ISR,则一次只能运行一个。 其他中断将在当前完成之后执行,其顺序取决于它们具有的优先级。

通常,全局变量用于在ISR和主程序之间传递数据。 要确保ISR和主程序之间共享的变量正确更新,请将它们声明为volatile。

attachInterrupt Statement Syntax

attachInterrupt(digitalPinToInterrupt(pin),ISR,mode);//recommended for arduino board
attachInterrupt(pin, ISR, mode) ; //recommended Arduino Due, Zero only
//argument pin: the pin number
//argument ISR: the ISR to call when the interrupt occurs; 
   //this function must take no parameters and return nothing. 
   //This function is sometimes referred to as an interrupt service routine.
//argument mode: defines when the interrupt should be triggered.

以下三个常量被预定义为有效值 -

  • LOW 可在引脚为低电平时触发中断。

  • CHANGE 可在引脚更改值时触发中断。

  • 每当引脚从高电平变为低电平时, FALLING

示例

int pin = 2; //define interrupt pin to 2
volatile int state = LOW; // To make sure variables shared between an ISR
//the main program are updated correctly,declare them as volatile.

void setup() {
   pinMode(13, OUTPUT); //set pin 13 as output
   attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);
   //interrupt at pin 2 blink ISR when pin to change the value
} 
void loop() { 
   digitalWrite(13, state); //pin 13 equal the state value
} 

void blink() { 
   //ISR function
   state = !state; //toggle the state when the interrupt occurs
}

Arduino - Communication

已经定义了数百个通信协议来实现这种数据交换。 每个协议可以分为两种类型之一:并行或串行。

Parallel Communication

通过输入/输出端口在Arduino和外设之间进行并行连接是较短距离(最多几米)的理想解决方案。 然而,在其他情况下,当需要在两个设备之间建立较长距离的通信时,不可能使用并行连接。 并行接口同时传输多个位。 它们通常需要数据总线 - 通过八条,十六条或更多的线路进行传输。 数据在巨大的,崩溃的1和0的波传输。

Parallel Communication

Advantages and Drawbacks of Parallel Communication

并行通信肯定有其优势。 它比串行,直接和相对容易实现更快。 然而,它需要许多输入/输出(I / O)端口和线路。 如果你不得不将一个项目从一个基本的Arduino Uno移动到一个Mega,你知道一个微处理器上的I / O线可能是宝贵的,很少。 因此,我们更喜欢串行通信,牺牲针脚空间的潜在速度。

Serial Communication Modules

今天,大多数Arduino板都是用几种不同的串行通信系统作为标准设备。

使用这些系统中的哪一个取决于以下因素:

  • How many devices the microcontroller has to exchange data with?
  • How fast the data exchange has to be?
  • What is the distance between these devices?
  • Is it necessary to send and receive data simultaneously?

有关串行通信的最重要的事情之一是协议,应该严格遵守。 它是一组规则,必须应用这些规则,使得设备可以正确地解释它们相互交换的数据。 幸运的是,Arduino自动处理这一点,使程序员/用户的工作减少到简单的写(要发送的数据)和读(接收的数据)。

Types of Serial Communications

串行通信可以进一步分类为 -

  • 同步 - 同步的设备使用相同的时钟,它们的时序彼此同步。

  • 异步 - 异步设备具有自己的时钟,并由前一状态的输出触发。

很容易找出设备是否同步。 如果给所有连接的设备提供相同的时钟,则它们是同步的。 如果没有时钟线,它是异步的。

例如,UART(通用异步收发器)模块是异步的。

异步串行协议有一些内置的规则。 这些规则只是帮助确保稳健且无错误的数据传输的机制。 这些机制,我们得到避免外部时钟信号,是 -

  • Synchronization bits
  • Data bits
  • Parity bits
  • Baud rate

Synchronization Bits

同步位是与每个数据包一起传送的两个或三个特殊位。 它们是起始位和停止位。 正确的名称,这些位分别标记数据包的开始和结束。

始终只有一个起始位,但停止位的数量可以配置为一个或两个(尽管通常保持为1)。

起始位始终由从1到0的空闲数据线指示,而停止位将通过将线保持在1处而转换回空闲状态。

Synchronization Bits

Data Bits

每个分组中的数据量可以设置为从5到9位的任何大小。 当然,标准数据大小是你的基本8位字节,但其他大小有它们的用途。 7位数据包可以比8更有效,特别是如果你只是传输7位ASCII字符。

Parity Bits

用户可以选择是否应该有奇偶校验位,如果是,则奇偶校验应该是奇数还是偶数。 如果数据位中的1的数目是偶数,则奇偶校验位为0。 奇数的平等恰恰相反。

Baud Rate

术语波特率用于表示每秒传输的位数[bps]。 注意,它是指位,而不是字节。 协议通常要求每个字节与几个控制位一起传输。 这意味着串行数据流中的一个字节可以包括11个比特。 例如,如果波特率为300bps,则每秒可以传输最大37字节和最小27字节。

Arduino UART

以下代码将使Arduino在启动时发送hello world。

void setup() {
   Serial.begin(9600); //set up serial library baud rate to 9600
   Serial.println("hello world"); //print hello world
}

void loop() {

}

将Arduino草图上传到Arduino后,在Arduino IDE的右上部分打开串行监视器

在串行监视器的顶部框中键入任何内容,然后按键盘上的发送或输入。 这将发送一系列字节到Arduino。

以下代码返回它作为输入接收的任何内容。

以下代码将使Arduino根据提供的输入提供输出。

void setup() {
   Serial.begin(9600); //set up serial library baud rate to 9600
}

void loop() {
   if(Serial.available()) //if number of bytes (characters) available for reading from { 
      serial port
      Serial.print("I received:"); //print I received
      Serial.write(Serial.read()); //send what you read
   }
}

请注意, Serial.print Serial.println 将发回实际的ASCII代码,而 Serial.write 将返回实际的文本。 有关详细信息,请参阅ASCII代码。

Arduino - Inter Integrated Circuit

内部集成电路(I2C)是用于微控制器和新一代专用集成电路之间的串行数据交换的系统。 当它们之间的距离很短(接收器和发射器通常在同一个印刷电路板上)时使用。 通过两根导线建立连接。 一个用于数据传输,另一个用于同步(时钟信号)。

如下图所示,一个设备始终是主设备。 它在通信开始之前执行一个从芯片的寻址。 以这种方式,一个微控制器可以与112个不同的设备通信。 波特率通常为100 Kb / sec(标准模式)或10 Kb / sec(慢波特率模式)。 最近出现了波特率为3.4 Mb / s的系统。 通过I2C总线通信的器件之间的距离限制为几米。

I2C

Board I2C Pins

I2C总线由两个信号SCL和SDA组成。 SCL是时钟信号,SDA是数据信号。 当前总线主机总是产生时钟信号。 一些从设备可能迫使时钟低时延迟主设备发送更多数据(或者在主设备尝试将时钟发出之前需要更多时间来准备数据)。 这被称为“时钟伸展"。

以下是不同Arduino板卡的引脚 -

  • Uno, Pro Mini A4 (SDA), A5 (SCL)
  • Mega, Due 20 (SDA), 21 (SCL)
  • Leonardo, Yun 2 (SDA), 3 (SCL)

Arduino I2C

我们有两种模式 - 主代码和从机代码 - 使用I2C连接两个Arduino板。 他们是 -

  • Master Transmitter / Slave Receiver
  • Master Receiver / Slave Transmitter

Master Transmitter / Slave Receiver

让我们现在看看什么是主发送器和从接收器。

Master Transmitter

以下函数用于初始化Wire库,并将I2C总线作为主器件或从器件加入。 这通常只调用一次。

  • Wire.begin(address) - 在我们的例子中,地址是7位从地址,因为未指定主机,它将作为主机加入总线。

  • Wire.beginTransmission(address) - 开始向给定地址的I2C从器件发送数据。

  • Wire.write(value) - 用于从主设备传输到从设备的队列字节(在beginTransmission()和endTransmission()之间的调用)。

  • Wire.endTransmission() - 结束由beginTransmission()开始的对从设备的传输,并传输由wire.write()排队的字节。

示例

#include <Wire.h> //include wire library

void setup() //this will run only once { 
   Wire.begin(); // join i2c bus as master
} 

short age = 0; 

void loop() {   
   Wire.beginTransmission(2); 
   // transmit to device #2
   Wire.write("age is = ");
   Wire.write(age); // sends one byte
   Wire.endTransmission(); // stop transmitting
   delay(1000); 
}

Slave Receiver

使用以下功能 -

  • Wire.begin(address) - 地址是7位从机地址。

  • Wire.onReceive(接收数据处理程序) - 当从设备从主设备接收数据时调用的函数。

  • Wire.available() - 返回可用于使用Wire.read()检索的字节数,应在Wire.onReceive()处理程序中调用。

示例

#include <Wire.h> //include wire library

void setup() {  //this will run only once
   Wire.begin(2); // join i2c bus with address #2
   Wire.onReceive(receiveEvent); // call receiveEvent when the master send any thing 
   Serial.begin(9600); // start serial for output to print what we receive 
}

void loop() {   
   delay(250); 
}

//-----this function will execute whenever data is received from master-----//

void receiveEvent(int howMany) { 
   while (Wire.available()>1) // loop through all but the last {
      char c = Wire.read(); // receive byte as a character
      Serial.print(c); // print the character
   }
}

Master Receiver / Slave Transmitter

让我们现在看看什么是主接收器和从发送器。

Master Receiver

主器件,被编程为请求,然后读取从唯一寻址的从器件Arduino发送的数据字节。

使用以下功能 -

Wire.requestFrom(地址,字节数) - 由主设备用于从从设备请求字节。 然后可以使用函数wire.available()和wire.read()函数检索字节。

示例

#include <Wire.h> //include wire library void setup() { 
   Wire.begin(); // join i2c bus (address optional for master) 
   Serial.begin(9600); // start serial for output
} 

void loop() { 
   Wire.requestFrom(2, 1); // request 1 bytes from slave device #2
   while (Wire.available()) // slave may send less than requested {
      char c = Wire.read(); // receive a byte as character
      Serial.print(c); // print the character
   } 
   delay(500); 
}

Slave Transmitter

使用以下功能。

Wire.onRequest(handler) - 当主设备从此从设备请求数据时调用该函数。

示例

#include <Wire.h> 

void setup() { 
   Wire.begin(2); // join i2c bus with address #2
   Wire.onRequest(requestEvent); // register event
} 

Byte x = 0;

void loop() { 
   delay(100); 
} 

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()

void requestEvent() { 
   Wire.write(x); // respond with message of 1 bytes as expected by master
   x++; 
}

Arduino - Serial Peripheral Interface

串行外设接口(SPI)总线是用于串行通信的系统,其使用多达四个导体,通常为三个。 一个导体用于数据接收,一个导体用于数据发送,一个导体用于同步,以及一个导体用于选择与之通信的设备。 它是一个全双工连接,这意味着数据被同时发送和接收。 最大波特率高于I2C通信系统中的波特率。

Board SPI Pins

SPI使用以下四根导线 -

  • SCK - 这是由主机驱动的串行时钟。

  • MOSI - 这是主器件驱动的主输出/从器件输入。

  • MISO - 这是由主设备驱动的主输入/从设备输出。

  • SS - 这是从机选择线。

使用以下功能。 你必须包括SPI.h.

  • SPI.begin() - 通过将SCK,MOSI和SS设置为输出来初始化SPI总线,将SCK和MOSI拉低,将SS拉高。

  • SPI.setClockDivider(divider) - 相对于系统时钟设置SPI时钟分频器。 在基于AVR的板上,可用的分频器为2,4,8,16,32,64或128.默认设置为SPI_CLOCK_DIV4,它将SPI时钟设置为系统时钟的四分之一(5 Mhz 板在20MHz)。

  • 分隔符 - 它可以是(SPI_CLOCK_DIV2,SPI_CLOCK_DIV4,SPI_CLOCK_DIV8,SPI_CLOCK_DIV16,SPI_CLOCK_DIV32,SPI_CLOCK_DIV64,SPI_CLOCK_DIV128)。

  • SPI.transfer(val) - SPI传输基于同时发送和接收:接收的数据在receivedVal中返回。

  • SPI.transfer(val) - SPI传输基于同时发送和接收:接收的数据在receivedVal中返回。...

我们在SPI中有四种操作模式,如下所示:

  • 模式0(默认值) - 时钟通常为低电平(CPOL = 0),数据在从低电平到高电平(前沿)(CPHA = 0)的转换时采样。

  • 模式1 - 时钟通常为低电平(CPOL = 0),并且数据在从高电平到低电平(后沿)(CPHA = 1)的转换时采样。

  • 模式2 - 时钟通常为高电平(CPOL = 1),数据在从高电平到低电平(前沿)(CPHA = 0)的转换时采样。

  • 模式3 - 时钟通常为高电平(CPOL = 1),数据在从低电平到高电平(后沿)(CPHA = 1)的转换时采样。

  • SPI.attachInterrupt(handler) - 当从设备从主设备接收数据时调用的函数。

现在,我们将两个Arduino UNO板连接在一起; 一个作为主机,另一个作为从机。

  • (SS) : pin 10
  • (MOSI) : pin 11
  • (MISO) : pin 12
  • (SCK) : pin 13

地面是常见的。 以下是两个电路板之间的连接的图解表示 -

Connection of Boards

让我们看看SPI作为主机和SPI作为从机的例子。

SPI as MASTER

Example

#include <SPI.h>

void setup (void) {
   Serial.begin(115200); //set baud rate to 115200 for usart
   digitalWrite(SS, HIGH); // disable Slave Select
   SPI.begin ();
   SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8
}

void loop (void) {
   char c;
   digitalWrite(SS, LOW); // enable Slave Select
   // send test string
   for (const char * p = "Hello, world!\r" ; c = *p; p++) {
      SPI.transfer (c);
      Serial.print(c);
   }
   digitalWrite(SS, HIGH); // disable Slave Select
   delay(2000);
}

SPI as SLAVE

Example

#include <SPI.h>
char buff [50];
volatile byte indx;
volatile boolean process;

void setup (void) {
   Serial.begin (115200);
   pinMode(MISO, OUTPUT); // have to send on master in so it set as output
   SPCR |= _BV(SPE); // turn on SPI in slave mode
   indx = 0; // buffer empty
   process = false;
   SPI.attachInterrupt(); // turn on interrupt
}
ISR (SPI_STC_vect) // SPI interrupt routine { 
   byte c = SPDR; // read byte from SPI Data Register
   if (indx < sizeof buff) {
      buff [indx++] = c; // save data in the next index in the array buff
      if (c == '\r') //check for the end of the word
      process = true;
   }
}

void loop (void) {
   if (process) {
      process = false; //reset the process
      Serial.println (buff); //print the array on serial monitor
      indx= 0; //reset button to zero
   }
}

Arduino - Blinking LED

LED是小型,强大的灯,用于许多不同的应用。 首先,我们将工作在闪烁LED,微控制器的Hello World。 它就像打开和关闭灯一样简单。 建立这个重要的基线将为您提供坚实的基础,因为我们致力于更复杂的实验。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × LED
  • 1 × 330Ω Resistor
  • 2 × Jumper

Procedure

按照电路图并连接面包板上的组件,如下图所示。

Breadboard

注意 - 要了解LED的极性,请仔细查看。 两个腿中较短的,朝向灯泡的平边缘指示负端子。

LED

如电阻器的元件需要将其端子弯曲成90°角,以适当地适应面包板插座。 您也可以将端子切短。

Resistors

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开新的草图文件。

Sketch

Arduino Code

/*
   Blink
   Turns on an LED on for one second, then off for one second, repeatedly.
*/

// the setup function runs once when you press reset or power the board

void setup() {  // initialize digital pin 13 as an output.
   pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever

void loop() {
   digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
   delay(1000); // wait for a second
   digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
   delay(1000); // wait for a second
}

Code to Note

pinMode(2,OUTPUT) - 在使用Arduino的引脚之前,您需要告诉Arduino Uno R3它是一个INPUT还是OUTPUT。 我们使用一个内置的“函数"pinMode()来做到这一点。

digitalWrite(2,HIGH) - 当使用引脚作为OUTPUT时,可以将其命令为HIGH(输出5伏)或LOW(输出0伏)。

Result

你应该看到你的LED打开和关闭。 如果没有看到所需的输出,请确保您已正确组装电路,并验证并将代码上传到电路板。

Arduino - Fading LED

这个例子演示了在熄灭LED时使用analogWrite()函数。 AnalogWrite使用脉冲宽度调制(PWM),以非常快速地打开和关闭数字引脚,开/关之间具有不同的比率,以创建衰减效果。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × LED
  • 1 × 330Ω Resistor
  • 2 × Jumper

Procedure

按照电路图并连接面包板上的组件,如下图所示。

Components on Breadboard

注意 - 要了解LED的极性,请仔细查看。 两个腿中较短的,朝向灯泡的平边缘指示负端子。

LED

如电阻器的元件需要将其端子弯曲成90°角,以适当地适应面包板插座。 您也可以将端子切短。

Resistors

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开新的草图文件。

Sketch

Arduino Code

/*
   Fade
   This example shows how to fade an LED on pin 9 using the analogWrite() function.

   The analogWrite() function uses PWM, so if you want to change the pin you're using, be
   sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with
   a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
*/

int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:

void setup() {
   // declare pin 9 to be an output:
   pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:

void loop() {
   // set the brightness of pin 9:
   analogWrite(led, brightness);
   // change the brightness for next time through the loop:
   brightness = brightness + fadeAmount;
   // reverse the direction of the fading at the ends of the fade:
   if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
   }
   // wait for 30 milliseconds to see the dimming effect
   delay(300);
}

Code to Note

在将引脚9声明为您的LED引脚之后,在代码的setup()函数中没有做任何事情。 您将在代码的主循环中使用的analogWrite()函数需要两个参数:一个告诉函数哪个引脚要写入,另一个指示写入哪个PWM值。

为了使LED熄灭和亮起,逐渐将PWM值从0(一直关闭)逐渐增加到255(一直开启),然后回到0,以完成周期。 在上面给出的草图中,PWM值使用称为亮度的变量设置。 每次通过循环,它增加变量 fadeAmount 的值。

如果亮度在其值的任一极值(0或255),则fadeAmount变为其负值。 换句话说,如果fadeAmount是5,那么它被设置为-5。 如果它是-5,那么它被设置为5.下一次通过循环,这个改变也导致亮度改变方向。

analogWrite()可以非常快速地更改PWM值,因此草图结束时的延迟控制淡入淡出的速度。 尝试改变延迟的值,看看它如何改变衰落效果。

Result

你应该看到你的LED亮度逐渐变化。

Arduino - Reading Analog Voltage

此示例将向您展示如何读取模拟引脚0上的模拟输入。输入从analogRead()转换为电压,并打印输出到Arduino软件(IDE)的串行监视器。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × 5K variable resistor (potentiometer)
  • 2 × Jumper

Procedure

按照电路图并连接面包板上的组件,如下图所示。

Analog Breadboard

Potentiometer

电位计(或电位计)是一种简单的机电换能器。 它将来自输入操作器的旋转或线性运动转换为电阻变化。 这种变化是(或可以)用于控制从高保真系统的体积到巨大集装箱船的方向的任何东西。

我们知道的锅最初被称为变阻器(本质上是可变线绕电阻)。 现在可用的罐的种类现在相当惊人,并且初学者(特别是)可能非常难以确定哪种类型适合于给定的任务。 几个不同的锅类型,它们都可以用于相同的任务,使得工作更难。

Potentiometer

左边的图像显示锅的标准原理图符号。 右边的图像是电位计。

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

Arduino Code

/*
   ReadAnalogVoltage
   Reads an analog input on pin 0, converts it to voltage, 
   and prints the result to the serial monitor.
   Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
   Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
*/

// the setup routine runs once when you press reset:

void setup() {
   // initialize serial communication at 9600 bits per second:
   Serial.begin(9600);
}

// the loop routine runs over and over again forever:

void loop() {
   // read the input on analog pin 0:
   int sensorValue = analogRead(A0);
   // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
   float voltage = sensorValue * (5.0 / 1023.0);
   // print out the value you read:
   Serial.println(voltage);
}

Code to Note

在下面给出的程序或草图中,您在设置功能中做的第一件事是开始串行通信,以9600位/秒,在您的主板和您的计算机之间用线 -

Serial.begin(9600);

在代码的主循环中,您需要建立一个变量来存储来自电位器的电阻值(其范围在0到1023之间,非常适合int数据类型)

int sensorValue = analogRead(A0);

要将值从0-1023更改为对应于电压的范围,引脚正在读取,您需要创建另一个变量,一个float,并做一点计算。 要在0.0和5.0之间缩放数字,将5.0除以1023.0,再乘以sensorValue -

float voltage= sensorValue * (5.0 / 1023.0);

最后,您需要将此信息打印到串口窗口。 你可以用最后一行代码中的Serial.println()命令来做到这一点 -

Serial.println(voltage)

现在,通过单击顶部绿色栏右侧的图标或按Ctrl + Shift + M打开Arduino IDE中的串行监视器。

Serial Monitor

Result

你会看到一个稳定的数字流从0.0到5.0。 当您转动电位器时,这些值会改变,对应于引脚A0上的电压。

Arduino - LED Bar Graph

此示例显示如何读取模拟引脚0处的模拟输入,将值从analogRead()转换为电压,并将其输出到Arduino软件(IDE)的串行监视器。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × 5k ohm variable resistor (potentiometer)
  • 2 × Jumper
  • 8 × LED or you can use (LED bar graph display as shown in the image below)

Procedure

按照电路图并连接面包板上的组件,如下图所示。

Bar Breadboard

Connection to Bar Breadboard

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

10 Segment LED Bar Graph

LED Bar Graph

这些10段条形图LED有许多用途。 具有紧凑的占地面积,简单的连接,它们易于原型或成品。 基本上,它们是容纳在一起的10个单独的蓝色LED,每个具有单独的阳极和阴极连接。

它们也有黄色,红色和绿色的颜色。

注意 - 这些条形图上的引脚可能与数据表中列出的内容不同。 将装置旋转180度将校正变化,使得销11成为第一销。

Arduino Code

/*
   LED bar graph
   Turns on a series of LEDs based on the value of an analog sensor. 
   This is a simple way to make a bar graph display. 
   Though this graph uses 8LEDs, you can use any number by
      changing the LED count and the pins in the array.
   This method can be used to control any series of digital
      outputs that depends on an analog input.
*/

// these constants won't change:
const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 8; // the number of LEDs in the bar graph
int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // an array of pin numbers to which LEDs are attached

void setup() {
   // loop over the pin array and set them all to output:
   for (int thisLed = 0; thisLed < ledCount; thisLed++) {
      pinMode(ledPins[thisLed], OUTPUT);
   }
}

void loop() {
   // read the potentiometer:
   int sensorReading = analogRead(analogPin);
   // map the result to a range from 0 to the number of LEDs:
   int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
   // loop over the LED array:
   for (int thisLed = 0; thisLed < ledCount; thisLed++) {
      // if the array element's index is less than ledLevel,
      // turn the pin for this element on:
      if (thisLed < ledLevel) {
         digitalWrite(ledPins[thisLed], HIGH);
      }else { // turn off all pins higher than the ledLevel:
         digitalWrite(ledPins[thisLed], LOW);
      }
   }
} 

Code to Note

草图的工作方式如下:首先,您阅读输入。 将输入值映射到输出范围,在这种情况下为十个LED。 然后,您设置一个 for-loop 以迭代输出。 如果系列中的输出数量低于映射的输入范围,则将其打开。 如果没有,你把它关闭。

Result

当模拟读数的值增加时,您将看到LED逐个打开,而当读数减少时,LED逐个关闭。

Arduino - Keyboard Logout

本示例使用键盘库在您的计算机上注销您的用户会话,当ARDUINO UNO上的引脚2被拉到地面时。 草图在两个或三个键的同时按顺序模拟按键,并且在短暂的延迟之后,它释放它们。

警告 - 当您使用 Keyboard.print()命令时,Arduino接管您的计算机键盘。 为确保在使用此功能运行草图时不会失去对计算机的控制,请在调用Keyboard.print()之前设置可靠的控制系统。 此草图旨在仅在引脚拉到地后发送键盘命令。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Leonardo, Micro, or Due board
  • 1 × pushbutton
  • 1 × Jumper

Procedure

按照电路图并挂接面包板上的组件,如下图所示。

Keyboard Breadboard

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

对于本例,您需要使用Arduino IDE 1.6.7

Sketch

注意 - 您必须在Arduino库文件中包含键盘库。 使用名称库(突出显示)将键盘库文件复制并粘贴到文件中,如以下屏幕截图所示。

Arduino library file

Arduino Code

/*
   Keyboard logout
   This sketch demonstrates the Keyboard library.
   When you connect pin 2 to ground, it performs a logout.
   It uses keyboard combinations to do this, as follows:
   On Windows, CTRL-ALT-DEL followed by ALT-l
   On Ubuntu, CTRL-ALT-DEL, and ENTER
   On OSX, CMD-SHIFT-q
   To wake: Spacebar.
   Circuit:
   * Arduino Leonardo or Micro
   * wire to connect D2 to ground.
*/

#define OSX 0
#define WINDOWS 1
#define UBUNTU 2

#include "Keyboard.h"

// change this to match your platform:
int platform = WINDOWS;

void setup() {
   // make pin 2 an input and turn on the
   // pullup resistor so it goes high unless
   // connected to ground:
   
   pinMode(2, INPUT_PULLUP);
   Keyboard.begin();
}

void loop() {
   while (digitalRead(2) == HIGH) {
      // do nothing until pin 2 goes low
      delay(500);
   }
   
   delay(1000);
   
   switch (platform) {
      case OSX:
      Keyboard.press(KEY_LEFT_GUI);
	  
      // Shift-Q logs out:
      Keyboard.press(KEY_LEFT_SHIFT);
      Keyboard.press('Q');
      delay(100);
	  
      // enter:
      Keyboard.write(KEY_RETURN);
      break;
	  
      case WINDOWS:
      // CTRL-ALT-DEL:
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press(KEY_DELETE);
      delay(100);
      Keyboard.releaseAll();
	  
      //ALT-l:
      delay(2000);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press('l');
      Keyboard.releaseAll();
      break;
	  
      case UBUNTU:
      // CTRL-ALT-DEL:
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press(KEY_DELETE);
	  
      delay(1000);
      Keyboard.releaseAll();
	  
      // Enter to confirm logout:
      Keyboard.write(KEY_RETURN);
      break;
   }
   
   // do nothing:
   while (true);
}

Keyboard.releaseAll();

   // enter:
      Keyboard.write(KEY_RETURN);
      break;
      case WINDOWS:
	  
   // CTRL-ALT-DEL:
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press(KEY_DELETE);
      delay(100);
      Keyboard.releaseAll();
	  
   //ALT-l:
      delay(2000);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press('l');
      Keyboard.releaseAll();
      break;
	  
   case UBUNTU:
      // CTRL-ALT-DEL:
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press(KEY_DELETE);
      delay(1000);
      Keyboard.releaseAll();
	  
      // Enter to confirm logout:
      Keyboard.write(KEY_RETURN);
      break;
   }
   
// do nothing:
   while (true);
}

Code to Note

在将程序上传到开发板之前,请确保将正在使用的正确操作系统分配给平台变量。

在草图运行时,按下按钮将引脚2连接到地,板将发送注销序列到USB连接的PC。

Result

当将引脚2连接到地时,它执行注销操作。

它使用以下键盘组合注销 -

  • Windows 上,按CTRL-ALT-DEL,然后按ALT-l

  • Ubuntu ,CTRL-ALT-DEL和ENTER

  • OSX 上,CMD-SHIFT-q

Arduino - Keyboard Message

在此示例中,当按下按钮时,文本字符串作为键盘输入发送到计算机。 字符串报告按钮按下的次数。 一旦你有了编程和接线,打开你喜欢的文本编辑器看到的结果。

警告 - 当您使用 Keyboard.print()命令时,Arduino接管您的计算机键盘。 为确保在使用此功能运行草图时不会失去对计算机的控制,请在调用 Keyboard.print()之前设置可靠的控制系统。 这个草图包括一个按钮来切换键盘,以便它只在按下按钮后运行。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Leonardo, Micro, or Due board
  • 1 × momentary pushbutton
  • 1 × 10k ohm resistor

Procedure

按照电路图并连接面包板上的组件,如下图所示。

Keyboard Message Breadboard

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

Arduino Code

/*
   Keyboard Message test For the Arduino Leonardo and Micro,
      Sends a text string when a button is pressed.
   The circuit:
   * pushbutton attached from pin 4 to +5V
   * 10-kilohm resistor attached from pin 4 to ground
*/

#include "Keyboard.h"
const int buttonPin = 4; // input pin for pushbutton
int previousButtonState = HIGH; // for checking the state of a pushButton
int counter = 0; // button push counter

void setup() {
   pinMode(buttonPin, INPUT); // make the pushButton pin an input:
   Keyboard.begin(); // initialize control over the keyboard:
}

void loop() {
   int buttonState = digitalRead(buttonPin); // read the pushbutton:
   if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it's currently pressed: {
      // increment the button counter
      counter++;
      // type out a message
      Keyboard.print("You pressed the button ");
      Keyboard.print(counter);
      Keyboard.println(" times.");
   }
   // save the current button state for comparison next time:
   previousButtonState = buttonState;
}

Code to Note

将按钮的一个端子连接到Arduino上的引脚4。 将另一个引脚连接到5V。 使用电阻作为下拉电阻,通过将其从引脚4连接到地来提供对地的参考。

一旦你编写了电路板,拔下USB电缆,打开一个文本编辑器,并将文本光标放在打字区域。 通过USB再次将板连接到计算机,然后按按钮写入文档。

Result

通过使用任何文本编辑器,它将显示通过Arduino发送的文本。

Arduino - Mouse Button Control

使用鼠标库,您可以使用Arduino Leonardo,Micro或Due来控制计算机的屏幕光标。

此特定示例使用五个按钮来移动屏幕上的光标。 四个按钮是定向的(上,下,左,右),一个是用于鼠标左键单击。 来自Arduino的光标移动总是相对的。 每次读取输入时,相对于其当前位置更新光标的位置。

每当按下一个方向按钮时,Arduino将移动鼠标,将HIGH输入映射到适当方向的范围5。

第五按钮用于控制来自鼠标的左击。 当按钮被释放时,计算机将识别事件。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Leonardo, Micro or Due board
  • 5 × 10k ohm resistor
  • 5 × momentary pushbuttons

Procedure

按照电路图并挂接面包板上的组件,如下图所示。

Mouse Button Breadboard

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

对于本例,您需要使用Arduino IDE 1.6.7

Sketch

Arduino Code

/*
   Button Mouse Control
   For Leonardo and Due boards only .Controls the mouse from 
   five pushbuttons on an Arduino Leonardo, Micro or Due.
   Hardware:
   * 5 pushbuttons attached to D2, D3, D4, D5, D6
   The mouse movement is always relative. This sketch reads
   four pushbuttons, and uses them to set the movement of the mouse.
   WARNING: When you use the Mouse.move() command, the Arduino takes
   over your mouse! Make sure you have control before you use the mouse commands.
*/

#include "Mouse.h"
// set pin numbers for the five buttons:
const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;
int range = 5; // output range of X or Y movement; affects movement speed
int responseDelay = 10; // response delay of the mouse, in ms

void setup() {
   // initialize the buttons' inputs:
   pinMode(upButton, INPUT);
   pinMode(downButton, INPUT);
   pinMode(leftButton, INPUT);
   pinMode(rightButton, INPUT);
   pinMode(mouseButton, INPUT);
   // initialize mouse control:
   Mouse.begin();
}

void loop() {
   // read the buttons:
   int upState = digitalRead(upButton);
   int downState = digitalRead(downButton);
   int rightState = digitalRead(rightButton);
   int leftState = digitalRead(leftButton);
   int clickState = digitalRead(mouseButton);
   // calculate the movement distance based on the button states:
   int xDistance = (leftState - rightState) * range;
   int yDistance = (upState - downState) * range;
   // if X or Y is non-zero, move:
   if ((xDistance != 0) || (yDistance != 0)) {
      Mouse.move(xDistance, yDistance, 0);
   }

   // if the mouse button is pressed:
   if (clickState == HIGH) {
      // if the mouse is not pressed, press it:
      if (!Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.press(MOUSE_LEFT);
      }
   } else {                           // else the mouse button is not pressed:
      // if the mouse is pressed, release it:
      if (Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.release(MOUSE_LEFT);
      }
   }
   // a delay so the mouse does not move too fast:
   delay(responseDelay);
}

Code to Note

使用micro-USB电缆将电路板连接到计算机。 这些按钮连接到引脚2至6的数字输入。确保使用10k下拉电阻。

Arduino - Keyboard Serial

此示例侦听来自串行端口的字节。 当接收到,板子发送一个击键回到计算机。 发送的击键比接收的击键高一个,因此如果从串行监视器发送“a",您将从连接到计算机的电路板接收到“b"。 “1"将返回“2",依此类推。

警告 - 当您使用 Keyboard.print()命令时,Leonardo,Micro或Due板会占用计算机的键盘。 为确保在使用此功能运行草图时不会失去对计算机的控制,请在调用Keyboard.print()之前设置可靠的控制系统。 该草图旨在仅在板通过串行端口接收到一个字节后才发送一个Keyboard命令。

Components Required

您将需要以下组件 -

  • 1 × Arduino Leonardo, Micro, or Due board

Procedure

只需使用USB电缆将电路板连接到计算机。

Keyboard Serial Breadboard

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

注意 - 您必须在Arduino库文件中包含键盘库。 将键盘库文件复制并粘贴到文件中,名称\'libraries\'以黄色突出显示。

Arduino library file

Arduino Code

/*
   Keyboard test
   For the Arduino Leonardo, Micro or Due Reads
      a byte from the serial port, sends a keystroke back. 
   The sent keystroke is one higher than what's received, e.g. if you send a, you get b, send
      A you get B, and so forth.
   The circuit:
   * none
*/

#include "Keyboard.h"

void setup() {
   // open the serial port:
   Serial.begin(9600);
   // initialize control over the keyboard:
   Keyboard.begin();
}

void loop() {
   // check for incoming serial data:
   if (Serial.available() > 0) {
      // read incoming serial data:
      char inChar = Serial.read();
      // Type the next ASCII value from what you received:
      Keyboard.write(inChar + 1);
   }
}

Code to Note

一旦编程,打开你的串口监视器并发送一个字节。 板子将回复一个击键,这是一个更高的数字。

Result

当你发送一个字节时,板子将以一个高于Arduino IDE串行监视器的数字的键击来回复。

Arduino - Humidity Sensor

在本节中,我们将学习如何使用不同的传感器连接我们的Arduino板。 我们将讨论以下传感器 -

  • Humidity sensor (DHT22)
  • Temperature sensor (LM35)
  • Water detector sensor (Simple Water Trigger)
  • PIR SENSOR
  • ULTRASONIC SENSOR
  • GPS

Humidity Sensor (DHT22)

DHT-22(也称为AM2302)是一个数字输出,相对湿度和温度传感器。 它使用电容式湿度传感器和热敏电阻测量周围空气,并在数据引脚上发送数字信号。

在本例中,您将了解如何将此传感器与Arduino UNO一起使用。 室温和湿度将打印到串行监视器上。

The DHT-22 Sensor

DHT-22 Sensor

连接很简单。 左边的第一个引脚为3-5V电源,第二个引脚连接到数据输入引脚,最右边的引脚连接到地。

Technical Details

  • 电源 - 3-5V

  • 最大电流 - 2.5mA

  • 湿度 - 0-100%,精确度为2-5%

  • 温度 - 40至80°C,精度为±0.5°C

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × DHT22
  • 1 × 10K ohm resistor

Procedure

按照电路图并挂接面包板上的组件,如下图所示。

Humidity Sensor Circuit Connection

Humidity Sensor Breadboard

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

Arduino Code

// Example testing sketch for various DHT humidity/temperature sensors

#include "DHT.h"
#define DHTPIN 2 // what digital pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
   Serial.begin(9600);
   Serial.println("DHTxx test!");
   dht.begin();
}

void loop() {
   delay(2000); // Wait a few seconds between measurements
   float h = dht.readHumidity();
   // Reading temperature or humidity takes about 250 milliseconds!
   float t = dht.readTemperature();
   // Read temperature as Celsius (the default)
   float f = dht.readTemperature(true);
   // Read temperature as Fahrenheit (isFahrenheit = true)
   // Check if any reads failed and exit early (to try again).
   if (isnan(h) || isnan(t) || isnan(f)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
   }
   
   // Compute heat index in Fahrenheit (the default)
   float hif = dht.computeHeatIndex(f, h);
   // Compute heat index in Celsius (isFahreheit = false)
   float hic = dht.computeHeatIndex(t, h, false);
   Serial.print ("Humidity: ");
   Serial.print (h);
   Serial.print (" %\t");
   Serial.print ("Temperature: ");
   Serial.print (t);
   Serial.print (" *C ");
   Serial.print (f);
   Serial.print (" *F\t");
   Serial.print ("Heat index: ");
   Serial.print (hic);
   Serial.print (" *C ");
   Serial.print (hif);
   Serial.println (" *F");
}

Code to Note

DHT22传感器具有四个端子(V cc,DATA,NC,GND),它们连接到电路板,如下:

  • DATA pin to Arduino pin number 2
  • Vcc pin to 5 volt of Arduino board
  • GND pin to the ground of Arduino board
  • We need to connect 10k ohm resistor (pull up resistor) between the DATA and the Vcc pin

一旦硬件连接完成,您需要添加DHT22库到您的Arduino库文件,如前所述。

Result

您将看到串口监视器上的温度和湿度显示,每2秒更新一次。

Arduino - Temperature Sensor

温度传感器LM35系列是精密集成电路温度器件,输出电压与摄氏温度成线性比例。

LM35器件优于以开尔文校准的线性温度传感器,因为用户不需要从输出中减去大的恒定电压以获得方便的Centigrade缩放。 LM35器件不需要任何外部校准或调整,即可在室温下提供±1/4°C的温度范围,在-55°C至150°C的温度范围内提供±3°C的典型精度。

LM35 device

Technical Specifications

  • Calibrated directly in Celsius (Centigrade)
  • Linear &plus; 10-mV/°C scale factor
  • 0.5°C ensured accuracy (at 25°C)
  • Rated for full −55°C to 150°C range
  • Suitable for remote applications

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × LM35 sensor

Procedure

按照电路图并连接面包板上的组件,如下图所示。

Temperature Sensor Circuit Connection

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

Arduino Code

float temp;
int tempPin = 0;

void setup() {
   Serial.begin(9600);
}

void loop() {
   temp = analogRead(tempPin);
   // read analog volt from sensor and save to variable temp
   temp = temp * 0.48828125;
   // convert the analog volt to its temperature equivalent
   Serial.print("TEMPERATURE = ");
   Serial.print(temp); // display temperature value
   Serial.print("*C");
   Serial.println();
   delay(1000); // update sensor reading each one second
}

Code to Note

LM35传感器具有三个端子:V sub,V out out和GND。 我们将连接传感器如下 -

  • Connect the &plus;Vs to &plus;5v on your Arduino board.
  • Connect Vout to Analog0 or A0 on Arduino board.
  • Connect GND with GND on Arduino.

模数转换器(ADC)基于公式ADC值=样本* 1024 /参考电压(&amp; plus; 5v)将模拟值转换为数字逼近。 因此,对于5伏参考,数字近似将等于输入电压* 205。

Result

您将看到串口监视器上的温度显示,每秒更新一次。

Arduino - Water Detector / Sensor

水传感器砖设计用于水检测,可广泛应用于检测降雨,水位,甚至液体泄漏。

Water Detector / Sensor

将水传感器连接到Arduino是检测泄漏,溢出,洪水,雨水等的好方法。它可用于检测水的存在,水位,体积和/或不存在。 虽然这可以用来提醒你浇水你的植物,有一个更好的Grove传感器。 传感器具有暴露迹线的阵列,当检测到水时读取LOW。

在本章中,我们将水传感器连接到Arduino上的数字引脚8,并将使用非常方便的LED来帮助识别水传感器何时与水源接触。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × Water Sensor
  • 1 × led
  • 1 × 330 ohm resistor

Procedure

按照电路图并连接面包板上的组件,如下图所示。

Water Sensor Circuit Connection

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

Arduino Code

#define Grove_Water_Sensor 8 // Attach Water sensor to Arduino Digital Pin 8
#define LED 9 // Attach an LED to Digital Pin 9 (or use onboard LED)

void setup() {
   pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an Input
   pinMode(LED, OUTPUT); // The LED is an Output
}

void loop() {
   /* The water sensor will switch LOW when water is detected.
   Get the Arduino to illuminate the LED and activate the buzzer
   when water is detected, and switch both off when no water is present */
   if( digitalRead(Grove_Water_Sensor) == LOW) {
      digitalWrite(LED,HIGH);
   }else {
      digitalWrite(LED,LOW);
   }
}

Code to Note

水传感器具有三个端子-S,V out(&amp;正;)和GND( - )。 按如下所示连接传感器 -

  • Connect the &plus;Vs to &plus;5v on your Arduino board.
  • Connect S to digital pin number 8 on Arduino board.
  • Connect GND with GND on Arduino.
  • Connect LED to digital pin number 9 in Arduino board.

当传感器检测到水时,Arduino上的引脚8变为低电平,然后Arduino上的LED打开。

Result

当传感器检测到水时,指示灯将亮起。

Arduino - PIR Sensor

PIR传感器允许您感测运动。 它们用于检测人是否移入或移出传感器的范围。 它们通常存在于家庭或企业中使用的电器和小工具中。 它们通常被称为PIR,“被动红外",“热电"或“IR运动"传感器。

以下是PIR传感器的优点 -

  • Small in size
  • Wide lens range
  • Easy to interface
  • Inexpensive
  • Low-power
  • Easy to use
  • Do not wear out
PIR Sensor

PIR由热电传感器制成,圆形金属罐在中心具有矩形晶体,其可以检测红外辐射的水平。 一切都发射低水平的辐射,和更热的东西,越多的辐射发射。 运动检测器中的传感器分成两半。 这是为了检测运动(变化),而不是平均IR水平。 两个半部被连接,使得它们彼此抵消。 如果一半看到比另一个更多或更少的红外辐射,输出将摆动高或低。

PIR

PIR具有可调设置,并且在3针接地/输出/电源板中安装了接头。

PIR Adjustable Settings

对于许多基本项目或需要检测一个人离开或进入该区域的产品,PIR传感器是伟大的。 请注意,PIR不会告诉您周围的人数或其与传感器的接近程度。 镜头通常固定在一定距离的扫掠,它们有时被宠物在房子里。

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × PIR Sensor (MQ3)

Procedure

按照电路图进行连接,如下图所示。

PIR Sensor Circuit Connection

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

Arduino Code

#define pirPin 2
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int PIRValue = 0;

void setup() {
   Serial.begin(9600);
   pinMode(pirPin, INPUT);
}

void loop() {
   PIRSensor();
}

void PIRSensor() {
   if(digitalRead(pirPin) == HIGH) {
      if(lockLow) {
         PIRValue = 1;
         lockLow = false;
         Serial.println("Motion detected.");
         delay(50);
      }
      takeLowTime = true;
   }
   if(digitalRead(pirPin) == LOW) {
      if(takeLowTime){
         lowIn = millis();takeLowTime = false;
      }
      if(!lockLow && millis() - lowIn > pause) {
         PIRValue = 0;
         lockLow = true;
         Serial.println("Motion ended.");
         delay(50);
      }
   }
}

Code to Note

PIR传感器具有三个端子:V sub,OUT和GND。 按如下所示连接传感器 -

  • Connect the &plus;Vcc to &plus;5v on Arduino board.
  • Connect OUT to digital pin 2 on Arduino board.
  • Connect GND with GND on Arduino.

您可以通过位于传感器板底部的两个可变电阻器来调整传感器灵敏度和延迟时间。

Delay time Adjust

一旦传感器检测到任何运动,Arduino将通过串行端口发送一条消息,说明检测到运动。 PIR感测运动将延迟一定时间以检查是否存在新运动。 如果没有检测到运动,Arduino将发送一条新消息,说明运动已经结束。

Result

如果检测到运动,您将在串行端口上看到一条消息,当运动停止时,将显示另一条消息。

Arduino - Ultrasonic Sensor

HC-SR04超声波传感器使用声纳来确定物体的距离,就像蝙蝠一样。 它提供了优异的非接触范围检测,具有高精度和稳定的读数,易于使用的包装,从2厘米到400厘米或1“到13英尺。

该操作不受阳光或黑色材料的影响,尽管在声学上,软的材料如布可能难以检测。 它配有超声波发射器和接收器模块。

Ultrasonic Sensor

Ultrasonic Sensor Radiations

Technical Specifications

  • Power Supply − &plus;5V DC
  • Quiescent Current − <2mA
  • Working Current − 15mA
  • Effectual Angle − <15°
  • Ranging Distance − 2cm – 400 cm/1″ – 13ft
  • Resolution − 0.3 cm
  • Measuring Angle − 30 degree

Components Required

您将需要以下组件 -

  • 1 × Breadboard
  • 1 × Arduino Uno R3
  • 1 × ULTRASONIC Sensor (HC-SR04)

Procedure

按照电路图进行连接,如下图所示。

Ultrasonic Circuit Connection

Sketch

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

Sketch

Arduino Code

const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor

void setup() {
   Serial.begin(9600); // Starting Serial Terminal
}

void loop() {
   long duration, inches, cm;
   pinMode(pingPin, OUTPUT);
   digitalWrite(pingPin, LOW);
   delayMicroseconds(2);
   digitalWrite(pingPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(pingPin, LOW);
   pinMode(echoPin, INPUT);
   duration = pulseIn(echoPin, HIGH);
   inches = microsecondsToInches(duration);
   cm = microsecondsToCentimeters(duration);
   Serial.print(inches);
   Serial.print("in, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println();
   delay(100);
}

long microsecondsToInches(long microseconds) {
   return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

Code to Note

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。...

  • Connect the &plus;5V pin to &plus;5v on your Arduino board.
  • Connect Trigger to digital pin 7 on your Arduino board.
  • Connect Echo to digital pin 6 on your Arduino board.
  • Connect GND with GND on Arduino.

在我们的程序中,我们通过串口显示传感器测量的距离,单位为英寸和厘米。

Result

您将在Arduino串行监视器上看到传感器测量的距离,单位为英寸和厘米。

Arduino - Connecting Switch

Pushbuttons or switches connect two open terminals in a circuit. This example turns on the LED on pin 2 when you press the pushbutton switch connected to pin 8.

Connecting Switch

Pull-down Resistor

Pull-down resistors are used in electronic logic circuits to ensure that inputs to Arduino settle at expected logic levels if external devices are disconnected or are at high-impedance. As nothing is connected to an input pin, it does not mean that it is a logical zero. Pull down resistors are connected between the ground and the appropriate pin on the device.

An example of a pull-down resistor in a digital circuit is shown in the following figure. A pushbutton switch is connected between the supply voltage and a microcontroller pin. In such a circuit, when the switch is closed, the micro-controller input is at a logical high value, but when the switch is open, the pull-down resistor pulls the input voltage down to the ground (logical zero value), preventing an undefined state at the input.

The pull-down resistor must have a larger resistance than the impedance of the logic circuit, or else it might pull the voltage down too much and the input voltage at the pin would remain at a constant logical low value, regardless of the switch position.

Pull-down Resistor

Components Required

You will need the following components −

  • 1 × Arduino UNO board
  • 1 × 330 ohm resistor
  • 1 × 4.7K ohm resistor (pull down)
  • 1 × LED

Procedure

Follow the circuit diagram and make the connections as shown in the image given below.

Connections of Circuit Diagram

Sketch

Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New.

Sketch

Arduino Code

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 8; // the number of the pushbutton pin
const int ledPin = 2; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
   // initialize the LED pin as an output:
   pinMode(ledPin, OUTPUT);
   // initialize the pushbutton pin as an input:
   pinMode(buttonPin, INPUT);
}

void loop() {
   // read the state of the pushbutton value:
   buttonState = digitalRead(buttonPin);
   // check if the pushbutton is pressed.
   // if it is, the buttonState is HIGH:
   if (buttonState == HIGH) {
      // turn LED on:
      digitalWrite(ledPin, HIGH);
   } else {
      // turn LED off:
      digitalWrite(ledPin, LOW);
   }
}

Code to Note

When the switch is open, (pushbutton is not pressed), there is no connection between the two terminals of the pushbutton, so the pin is connected to the ground (through the pull-down resistor) and we read a LOW. When the switch is closed (pushbutton is pressed), it makes a connection between its two terminals, connecting the pin to 5 volts, so that we read a HIGH.

Result

LED is turned ON when the pushbutton is pressed and OFF when it is released.

Arduino - DC Motor

In this chapter, we will interface different types of motors with the Arduino board (UNO) and show you how to connect the motor and drive it from your board.

There are three different type of motors −

  • DC motor
  • Servo motor
  • Stepper motor

A DC motor (Direct Current motor) is the most common type of motor. DC motors normally have just two leads, one positive and one negative. If you connect these two leads directly to a battery, the motor will rotate. If you switch the leads, the motor will rotate in the opposite direction.

DC Motor

Warning − Do not drive the motor directly from Arduino board pins. This may damage the board. Use a driver Circuit or an IC.

We will divide this chapter into three parts −

  • Just make your motor spin
  • Control motor speed
  • Control the direction of the spin of DC motor

Components Required

You will need the following components −

  • 1x Arduino UNO board
  • 1x PN2222 Transistor
  • 1x Small 6V DC Motor
  • 1x 1N4001 diode
  • 1x 270 Ω Resistor

Procedure

Follow the circuit diagram and make the connections as shown in the image given below.

DC Motor Connections

Precautions

Take the following precautions while making the connections.

  • First, make sure that the transistor is connected in the right way. The flat side of the transistor should face the Arduino board as shown in the arrangement.

  • Second, the striped end of the diode should be towards the +5V power line according to the arrangement shown in the image.

Spin ControlArduino Code

int motorPin = 3;

void setup() {

}

void loop() {
   digitalWrite(motorPin, HIGH);
}

Code to Note

The transistor acts like a switch, controlling the power to the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name 'motorPin' in the sketch.

Result

Motor will spin in full speed when the Arduino pin number 3 goes high.

Motor Speed Control

Following is the schematic diagram of a DC motor, connected to the Arduino board.

Motor Speed Control

Arduino Code

int motorPin = 9;

void setup() {
   pinMode(motorPin, OUTPUT);
   Serial.begin(9600);
   while (! Serial);
   Serial.println("Speed 0 to 255");
}

void loop() {
   if (Serial.available()) {
      int speed = Serial.parseInt();
      if (speed >= 0 && speed <= 255) {
         analogWrite(motorPin, speed);
      }
   }
}

Code to Note

The transistor acts like a switch, controlling the power of the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name 'motorPin' in the sketch.

When the program starts, it prompts you to give the values to control the speed of the motor. You need to enter a value between 0 and 255 in the Serial Monitor.

Command Window

In the 'loop' function, the command 'Serial.parseInt' is used to read the number entered as text in the Serial Monitor and convert it into an 'int'. You can type any number here. The 'if' statement in the next line simply does an analog write with this number, if the number is between 0 and 255.

Result

The DC motor will spin with different speeds according to the value (0 to 250) received via the serial port.

Spin Direction Control

To control the direction of the spin of DC motor, without interchanging the leads, you can use a circuit called an H-Bridge. An H-bridge is an electronic circuit that can drive the motor in both directions. H-bridges are used in many different applications. One of the most common application is to control motors in robots. It is called an H-bridge because it uses four transistors connected in such a way that the schematic diagram looks like an "H."

We will be using the L298 H-Bridge IC here. The L298 can control the speed and direction of DC motors and stepper motors, and can control two motors simultaneously. Its current rating is 2A for each motor. At these currents, however, you will need to use heat sinks.

Spin Direction Control

Components Required

You will need the following components −

  • 1 × L298 bridge IC
  • 1 × DC motor
  • 1 × Arduino UNO
  • 1 × breadboard
  • 10 × jumper wires

Procedure

Following is the schematic diagram of the DC motor interface to Arduino Uno board.

Spin Direction Control Connections

The above diagram shows how to connect the L298 IC to control two motors. There are three input pins for each motor, Input1 (IN1), Input2 (IN2), and Enable1 (EN1) for Motor1 and Input3, Input4, and Enable2 for Motor2.

Since we will be controlling only one motor in this example, we will connect the Arduino to IN1 (pin 5), IN2 (pin 7), and Enable1 (pin 6) of the L298 IC. Pins 5 and 7 are digital, i.e. ON or OFF inputs, while pin 6 needs a pulse-width modulated (PWM) signal to control the motor speed.

The following table shows which direction the motor will turn based on the digital values of IN1 and IN2.

IN1 IN2 Motor Behavior
BRAKE
1 FORWARD
1 BACKWARD
1 1 BRAKE

Pin IN1 of the IC L298 is connected to pin 8 of Arduino while IN2 is connected to pin 9. These two digital pins of Arduino control the direction of the motor. The EN A pin of IC is connected to the PWM pin 2 of Arduino. This will control the speed of the motor.

To set the values of Arduino pins 8 and 9, we have used the digitalWrite() function, and to set the value of pin 2, we have to use the analogWrite() function.

Connection Steps

  • Connect 5V and the ground of the IC to 5V and the ground of Arduino, respectively.
  • Connect the motor to pins 2 and 3 of the IC.
  • Connect IN1 of the IC to pin 8 of Arduino.
  • Connect IN2 of the IC to pin 9 of Arduino.
  • Connect EN1 of IC to pin 2 of Arduino.
  • Connect SENS A pin of IC to the ground.
  • Connect Arduino using Arduino USB cable and upload the program to Arduino using Arduino IDE software.
  • Provide power to Arduino board using power supply, battery, or USB cable.

Arduino Code

const int pwm = 2 ; //initializing pin 2 as pwm
const int in_1 = 8 ;
const int in_2 = 9 ;
//For providing logic to L298 IC to choose the direction of the DC motor

void setup() {
   pinMode(pwm,OUTPUT) ; //we have to set PWM pin as output
   pinMode(in_1,OUTPUT) ; //Logic pins are also set as output
   pinMode(in_2,OUTPUT) ;
}

void loop() {
   //For Clock wise motion , in_1 = High , in_2 = Low
   digitalWrite(in_1,HIGH) ;
   digitalWrite(in_2,LOW) ;
   analogWrite(pwm,255) ;
   /* setting pwm of the motor to 255 we can change the speed of rotation
   by changing pwm input but we are only using arduino so we are using highest
   value to driver the motor */
   //Clockwise for 3 secs
   delay(3000) ;
   //For brake
   digitalWrite(in_1,HIGH) ;
   digitalWrite(in_2,HIGH) ;
   delay(1000) ;
   //For Anti Clock-wise motion - IN_1 = LOW , IN_2 = HIGH
   digitalWrite(in_1,LOW) ;
   digitalWrite(in_2,HIGH) ;
   delay(3000) ;
   //For brake
   digitalWrite(in_1,HIGH) ;
   digitalWrite(in_2,HIGH) ;
   delay(1000) ;
}

Result

The motor will run first in the clockwise (CW) direction for 3 seconds and then counter-clockwise (CCW) for 3 seconds.

Arduino - Servo Motor

A Servo Motor is a small device that has an output shaft. This shaft can be positioned to specific angular positions by sending the servo a coded signal. As long as the coded signal exists on the input line, the servo will maintain the angular position of the shaft. If the coded signal changes, the angular position of the shaft changes. In practice, servos are used in radio-controlled airplanes to position control surfaces like the elevators and rudders. They are also used in radio-controlled cars, puppets, and of course, robots.

Servo Motor

Servos are extremely useful in robotics. The motors are small, have built-in control circuitry, and are extremely powerful for their size. A standard servo such as the Futaba S-148 has 42 oz/inches of torque, which is strong for its size. It also draws power proportional to the mechanical load. A lightly loaded servo, therefore, does not consume much energy.

The guts of a servo motor is shown in the following picture. You can see the control circuitry, the motor, a set of gears, and the case. You can also see the 3 wires that connect to the outside world. One is for power (+5volts), ground, and the white wire is the control wire.

Servo Motor control circuitry

Working of a Servo Motor

The servo motor has some control circuits and a potentiometer (a variable resistor, aka pot) connected to the output shaft. In the picture above, the pot can be seen on the right side of the circuit board. This pot allows the control circuitry to monitor the current angle of the servo motor.

If the shaft is at the correct angle, then the motor shuts off. If the circuit finds that the angle is not correct, it will turn the motor until it is at a desired angle. The output shaft of the servo is capable of traveling somewhere around 180 degrees. Usually, it is somewhere in the 210-degree range, however, it varies depending on the manufacturer. A normal servo is used to control an angular motion of 0 to 180 degrees. It is mechanically not capable of turning any farther due to a mechanical stop built on to the main output gear.

The power applied to the motor is proportional to the distance it needs to travel. So, if the shaft needs to turn a large distance, the motor will run at full speed. If it needs to turn only a small amount, the motor will run at a slower speed. This is called proportional control.

How Do You Communicate the Angle at Which the Servo Should Turn?

The control wire is used to communicate the angle. The angle is determined by the duration of a pulse that is applied to the control wire. This is called Pulse Coded Modulation. The servo expects to see a pulse every 20 milliseconds (.02 seconds). The length of the pulse will determine how far the motor turns. A 1.5 millisecond pulse, for example, will make the motor turn to the 90-degree position (often called as the neutral position). If the pulse is shorter than 1.5 milliseconds, then the motor will turn the shaft closer to 0 degrees. If the pulse is longer than 1.5 milliseconds, the shaft turns closer to 180 degrees.

Angle Turn

Components Required

You will need the following components −

  • 1 × Arduino UNO board
  • 1 × Servo Motor
  • 1 × ULN2003 driving IC
  • 1 × 10 KΩ Resistor

Procedure

Follow the circuit diagram and make the connections as shown in the image given below.

Servo Motor Connections

Sketch

Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New.

Sketch

Arduino Code

/* Controlling a servo position using a potentiometer (variable resistor) */

#include <Servo.h>
   Servo myservo; // create servo object to control a servo
   int potpin = 0; // analog pin used to connect the potentiometer
   int val; // variable to read the value from the analog pin

void setup() {
   myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
   val = analogRead(potpin);
   // reads the value of the potentiometer (value between 0 and 1023)
   val = map(val, 0, 1023, 0, 180);
   // scale it to use it with the servo (value between 0 and 180)
   myservo.write(val); // sets the servo position according to the scaled value
   delay(15);
}

Code to Note

Servo motors have three terminals - power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino. The ground wire is typically black or brown and should be connected to one terminal of ULN2003 IC (10 -16). To protect your Arduino board from damage, you will need some driver IC to do that. Here we have used ULN2003 IC to drive the servo motor. The signal pin is typically yellow or orange and should be connected to Arduino pin number 9.

Connecting the Potentiometer

A voltage divider/potential divider are resistors in a series circuit that scale the output voltage to a particular ratio of the input voltage applied. Following is the circuit diagram −

Connecting Potentiometer

$$V_{out} = (V_{in} \times R_{2})/ (R_{1} + R_{2})$$

Vout is the output potential, which depends on the applied input voltage (Vin) and resistors (R1 and R2) in the series. It means that the current flowing through R1 will also flow through R2 without being divided. In the above equation, as the value of R2 changes, the Vout scales accordingly with respect to the input voltage, Vin.

Typically, a potentiometer is a potential divider, which can scale the output voltage of the circuit based on the value of the variable resistor, which is scaled using the knob. It has three pins: GND, Signal, and +5V as shown in the diagram below −

Potentiometer with Description

Result

By changing the pot’s NOP position, servo motor will change its angle.

Arduino - Stepper Motor

A Stepper Motor or a step motor is a brushless, synchronous motor, which divides a full rotation into a number of steps. Unlike a brushless DC motor, which rotates continuously when a fixed DC voltage is applied to it, a step motor rotates in discrete step angles.

The Stepper Motors therefore are manufactured with steps per revolution of 12, 24, 72, 144, 180, and 200, resulting in stepping angles of 30, 15, 5, 2.5, 2, and 1.8 degrees per step. The stepper motor can be controlled with or without feedback.

Imagine a motor on an RC airplane. The motor spins very fast in one direction or another. You can vary the speed with the amount of power given to the motor, but you cannot tell the propeller to stop at a specific position.

Now imagine a printer. There are lots of moving parts inside a printer, including motors. One such motor acts as the paper feed, spinning rollers that move the piece of paper as ink is being printed on it. This motor needs to be able to move the paper an exact distance to be able to print the next line of text or the next line of an image.

There is another motor attached to a threaded rod that moves the print head back and forth. Again, that threaded rod needs to be moved an exact amount to print one letter after another. This is where the stepper motors come in handy.

Stepper Motor

How a Stepper Motor Works?

A regular DC motor spins in only direction whereas a Stepper motor can spin in precise increments.

Stepper motors can turn an exact amount of degrees (or steps) as desired. This gives you total control over the motor, allowing you to move it to an exact location and hold that position. It does so by powering the coils inside the motor for very short periods of time. The disadvantage is that you have to power the motor all the time to keep it in the position that you desire.

All you need to know for now is that, to move a stepper motor, you tell it to move a certain number of steps in one direction or the other, and tell it the speed at which to step in that direction. There are numerous varieties of stepper motors. The methods described here can be used to infer how to use other motors and drivers which are not mentioned in this tutorial. However, it is always recommended that you consult the datasheets and guides of the motors and drivers specific to the models you have.

Inner Stepper Motor

Components Required

You will need the following components −

  • 1 × Arduino UNO board
  • 1 × small bipolar stepper Motor as shown in the image given below
  • 1 × LM298 driving IC
LM298 driving IC

Procedure

Follow the circuit diagram and make the connections as shown in the image given below.

Stepper Motor Connections

Sketch

Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.

Sketch

Arduino Code

/* Stepper Motor Control */

#include <Stepper.h>
const int stepsPerRevolution = 90;
// change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
   // set the speed at 60 rpm:
   myStepper.setSpeed(5);
   // initialize the serial port:
   Serial.begin(9600);
}

void loop() {
   // step one revolution in one direction:
   Serial.println("clockwise");
   myStepper.step(stepsPerRevolution);
   delay(500);
   // step one revolution in the other direction:
   Serial.println("counterclockwise");
   myStepper.step(-stepsPerRevolution);
   delay(500);
}

Code to Note

This program drives a unipolar or bipolar stepper motor. The motor is attached to digital pins 8 - 11 of Arduino.

Result

The motor will take one revolution in one direction, then one revolution in the other direction.

Arduino - Tone Library

In this chapter, we will use the Arduino Tone Library. It is nothing but an Arduino Library, which produces square-wave of a specified frequency (and 50% duty cycle) on any Arduino pin. A duration can optionally be specified, otherwise the wave continues until the stop() function is called. The pin can be connected to a piezo buzzer or a speaker to play the tones.

Warning − Do not connect the pin directly to any audio input. The voltage is considerably higher than the standard line level voltages, and can damage sound card inputs, etc. You can use a voltage divider to bring the voltage down.

Components Required

You will need the following components −

  • 1 × 8-ohm speaker
  • 1 × 1k resistor
  • 1 × Arduino UNO board

Procedure

Follow the circuit diagram and make the connections as shown in the image given below.

Tone Library Connections

Sketch

Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.

Sketch

To make the pitches.h file, either click the button just below the serial monitor icon and choose "New Tab", or use Ctrl+Shift+N.

New Tab

Then paste the following code −

/*************************************************
* Public Constants
*************************************************/

#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978

Save the above given code as pitches.h

Arduino Code

#include "pitches.h"
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_GS3, NOTE_G3,0, NOTE_B3, NOTE_C4};
// note durations: 4 = quarter note, 8 = eighth note, etc.:

int noteDurations[] = {
   4, 8, 8, 4,4,4,4,4 
};

void setup() {
   // iterate over the notes of the melody:
   for (int thisNote = 0; thisNote < 8; thisNote++) {
      // to calculate the note duration, take one second
      // divided by the note type.
      //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
      int noteDuration = 1000/noteDurations[thisNote];
      tone(8, melody[thisNote],noteDuration);
      //pause for the note's duration plus 30 ms:
      delay(noteDuration +30);
   }
}

void loop() {
   // no need to repeat the melody.
}

Code to Note

The code uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally written by Brett Hagman, on whose work the tone() command was based. You may find it useful whenever you want to make musical notes.

Result

You will hear musical notes saved in the pitches.h. file.

Arduino - Wireless Communication

The wireless transmitter and receiver modules work at 315 Mhz. They can easily fit into a breadboard and work well with microcontrollers to create a very simple wireless data link. With one pair of transmitter and receiver, the modules will only work communicating data one-way, however, you would need two pairs (of different frequencies) to act as a transmitter/receiver pair.

Note − These modules are indiscriminate and receive a fair amount of noise. Both the transmitter and receiver work at common frequencies and do not have IDs.

Wireless Communication

Receiver Module Specifications

  • Product Model − MX-05V
  • Operating voltage − DC5V
  • Quiescent Current − 4mA
  • Receiving frequency − 315Mhz
  • Receiver sensitivity − -105DB
  • Size − 30 * 14 * 7mm

Transmitter Module Specifications

  • Product Model − MX-FS-03V
  • Launch distance − 20-200 meters (different voltage, different results)
  • Operating voltage − 3.5-12V
  • Dimensions − 19 * 19mm
  • Operating mode − AM
  • Transfer rate − 4KB / S
  • Transmitting power − 10mW
  • Transmitting frequency − 315Mhz
  • An external antenna − 25cm ordinary multi-core or single-core line
  • Pinout from left → right − (DATA; VCC; GND)

Components Required

You will need the following components −

  • 2 × Arduino UNO board
  • 1 × Rf link transmitter
  • 1 × Rf link receiver

Procedure

Follow the circuit diagram and make the connections as shown in the image given below.

Wireless Communication Connections

Sketch

Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.

Sketch

Note − You must include the keypad library in your Arduino library file. Copy and paste the VirtualWire.lib file in the libraries folder as highlighted in the screenshot given below.

Arduino library file

Arduino Code for Transmitter

//simple Tx on pin D12
#include <VirtualWire.h>
char *controller;

void setup() {
   pinMode(13,OUTPUT);
   vw_set_ptt_inverted(true);
   vw_set_tx_pin(12);
   vw_setup(4000);// speed of data transfer Kbps
}

void loop() {
   controller="1" ;
   vw_send((uint8_t *)controller, strlen(controller));
   vw_wait_tx(); // Wait until the whole message is gone
   digitalWrite(13,1);
   delay(2000);
   controller="0" ;
   vw_send((uint8_t *)controller, strlen(controller));
   vw_wait_tx(); // Wait until the whole message is gone
   digitalWrite(13,0);
   delay(2000);
}

Code to Note

This is a simple code. First, it will send character '1' and after two seconds it will send character '0' and so on.

Arduino Code for Receiver

//simple Rx on pin D12
#include <VirtualWire.h>

void setup() {
   vw_set_ptt_inverted(true); // Required for DR3100
   vw_set_rx_pin(12);
   vw_setup(4000); // Bits per sec
   pinMode(5, OUTPUT);
   vw_rx_start(); // Start the receiver PLL running
}

void loop() {
   uint8_t buf[VW_MAX_MESSAGE_LEN];
   uint8_t buflen = VW_MAX_MESSAGE_LEN;
   if (vw_get_message(buf, &buflen)) // Non-blocking {
      if(buf[0]=='1') {
         digitalWrite(5,1);
      }
      if(buf[0]=='0') {
         digitalWrite(5,0);
      }
   }
}

Code to Note

The LED connected to pin number 5 on the Arduino board is turned ON when character '1' is received and turned OFF when character '0' received.

Arduino - Network Communication

The CC3000 WiFi module from Texas Instruments is a small silver package, which finally brings easy-to-use, affordable WiFi functionality to your Arduino projects.

It uses SPI for communication (not UART!) so you can push data as fast as you want or as slow as you want. It has a proper interrupt system with IRQ pin so you can have asynchronous connections. It supports 802.11b/g, open/WEP/WPA/WPA2 security, TKIP & AES. A built-in TCP/IP stack with a "BSD socket" interface supports TCP and UDP in both the client and the server mode.

Network Communication

Components Required

You will need the following components −

  • 1 × Arduino Uno
  • 1 × Adafruit CC3000 breakout board
  • 1 × 5V relay
  • 1 × Rectifier diode
  • 1 × LED
  • 1 × 220 Ohm resistor
  • 1 × Breadboard and some jumper wires

For this project, you just need the usual Arduino IDE, the Adafruit’s CC3000 library, and the CC3000 MDNS library. We are also going to use the aREST library to send commands to the relay via WiFi.

Procedure

Follow the circuit diagram and make the connections as shown in the image given below.

Network Communication Connections

The hardware configuration for this project is very easy.

  • Connect the IRQ pin of the CC3000 board to pin number 3 of the Arduino board.
  • VBAT to pin 5, and CS to pin 10.
  • Connect the SPI pins to Arduino board: MOSI, MISO, and CLK to pins 11, 12, and 13, respectively.
  • Vin is connected to Arduino 5V, and GND to GND.

Let us now connect the relay.

After placing the relay on the breadboard, you can start identifying the two important parts on your relay: the coil part which commands the relay, and the switch part where we will attach the LED.

  • First, connect pin number 8 of Arduino board to one pin of the coil.
  • Connect the other pin to the ground of Arduino board.

You also have to place the rectifier diode (anode connected to the ground pin) over the pins of the coil to protect your circuit when the relay is switching.

  • Connect the +5V of Arduino board to the common pin of the relay’s switch.

  • Finally, connect one of the other pin of the switch (usually, the one which is not connected when the relay is off) to the LED in series with the 220 Ohm resistor, and connect the other side of the LED to the ground of Arduino board.

Testing Individual Components

You can test the relay with the following sketch −

const int relay_pin = 8; // Relay pin

void setup() {
   Serial.begin(9600);
   pinMode(relay_pin,OUTPUT);
}

void loop() {
   // Activate relay
   digitalWrite(relay_pin, HIGH);
   // Wait for 1 second
   delay(1000);
   // Deactivate relay
   digitalWrite(relay_pin, LOW);
   // Wait for 1 second
   delay(1000);
}

Code to Note

The code is self-explanatory. You can just upload it to the board and the relay will switch states every second, and the LED will switch ON and OFF accordingly.

Adding WiFi Connectivity

Let us now control the relay wirelessly using the CC3000 WiFi chip. The software for this project is based on the TCP protocol. However, for this project, Arduino board will be running a small web server, so we can “listen" for commands coming from the computer. We will first take care of Arduino sketch, and then we will see how to write the server-side code and create a nice interface.

First, the Arduino sketch. The goal here is to connect to your WiFi network, create a web server, check if there are incoming TCP connections, and then change the state of the relay accordingly.

Important Parts of the Code

#include <Adafruit_CC3000.h>
#include <SPI.h>
#include <CC3000_MDNS.h>
#include <Ethernet.h>
#include <aREST.h>

You need to define inside the code what is specific to your configuration, i.e. Wi-Fi name and password, and the port for TCP communications (we have used 80 here).

// WiFi network (change with your settings!)
   #define WLAN_SSID "yourNetwork" // cannot be longer than 32 characters!
   #define WLAN_PASS "yourPassword"
   #define WLAN_SECURITY WLAN_SEC_WPA2 // This can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, 
   // WLAN_SEC_WPA or WLAN_SEC_WPA2

// The port to listen for incoming TCP connections
   #define LISTEN_PORT 80

We can then create the CC3000 instance, server and aREST instance −

// Server instance
   Adafruit_CC3000_Server restServer(LISTEN_PORT); // DNS responder instance
   MDNSResponder mdns; // Create aREST instance
   aREST rest = aREST();

In the setup() part of the sketch, we can now connect the CC3000 chip to the network −

cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);

How will the computer know where to send the data? One way would be to run the sketch once, then get the IP address of the CC3000 board, and modify the server code again. However, we can do better, and that is where the CC3000 MDNS library comes into play. We will assign a fixed name to our CC3000 board with this library, so we can write down this name directly into the server code.

This is done with the following piece of code −

if (!mdns.begin("arduino", cc3000)) {
   while(1);
}

We also need to listen for incoming connections.

restServer.begin();

Next, we will code the loop() function of the sketch that will be continuously executed. We first have to update the mDNS server.

mdns.update();

The server running on Arduino board will wait for the incoming connections and handle the requests.

Adafruit_CC3000_ClientRef client = restServer.available();
rest.handle(client);

It is now quite easy to test the projects via WiFi. Make sure you updated the sketch with your own WiFi name and password, and upload the sketch to your Arduino board. Open your Arduino IDE serial monitor, and look for the IP address of your board.

Let us assume for the rest here that it is something like 192.168.1.103.

Then, simply go to your favorite web browser, and type −

192.168.1.103/digital/8/1

You should see that your relay automatically turns ON.

Building the Relay Interface

We will now code the interface of the project. There will be two parts here: an HTML file containing the interface, and a client-side Javascript file to handle the clicks on the interface. The interface here is based on the aREST.js project, which was made to easily control WiFi devices from your computer.

Let us first see the HTML file, called interface.html. The first part consists importing all the required libraries for the interface −

<head>
   <meta charset = utf-8 />
   <title> Relay Control </title>
   <link rel = "stylesheet" type = "text/css" 
      href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
   <link rel="stylesheet" type = "text/css" href = "style.css">
   <script type = "text/javascript" 
      src = "https://code.jquery.com/jquery-2.1.4.min.js"></script>
   <script type = "text/javascript" 
      src = "https://cdn.rawgit.com/Foliotek/AjaxQ/master/ajaxq.js"></script>
   <script type = "text/javascript" 
      src = "https://cdn.rawgit.com/marcoschwartz/aREST.js/master/aREST.js"></script>
   <script type = "text/javascript" 
      src = "script.js"></script>
</head>

Then, we define two buttons inside the interface, one to turn the relay on, and the other to turn it off again.

<div class = 'container'>
   <h1>Relay Control</h1>
   <div class = 'row'>
      <div class = "col-md-1">Relay</div>
      <div class = "col-md-2">
         <button id = 'on' class = 'btn btn-block btn-success'>On</button>
      </div>
      <div class = "col-md-2">
         <button id = 'off' class = 'btn btn-block btn-danger'>On</button>
      </div>
   </div>
</div>

Now, we also need a client-side Javascript file to handle the clicks on the buttons. We will also create a device that we will link to the mDNS name of our Arduino device. If you changed this in Arduino code, you will need to modify it here as well.

// Create device
var device = new Device("arduino.local");
// Button

$('#on').click(function() {
   device.digitalWrite(8, 1);
});

$('#off').click(function() {
   device.digitalWrite(8, 0);
});

The complete code for this project can be found on the GitHub repository. Go into the interface folder, and simply open the HTML file with your favorite browser. You should see something similar inside your browser −

Relay Control

Try to click a button on the web interface; it should change the state of the relay nearly instantly.

If you managed to get it working, bravo! You just built a Wi-Fi-controlled light switch. Of course, you can control much more than lights with this project. Just make sure your relay supports the power required for the device you want to control, and you are good to go.


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号