arduino编程语言
How can you write programs for your Arduino board?
您如何为Arduino开发板编写程序?
Arduino, natively, supports a language that we call the Arduino Programming Language, or Arduino Language.
Arduino本身支持一种称为Arduino编程语言或Arduino语言的语言。
This language is based upon the Wiring development platform, which in turn is based upon Processing, which if you are not familiar with, is what p5.js is based upon. It’s a long history of projects building upon other projects, in a very Open Source way. The Arduino IDE is based upon the Processing IDE, and the Wiring IDE which builds on top of it.
该语言基于Wiring开发平台,而Wiring开发平台又基于Processing ,如果您不熟悉, 它将是p5.js的基础。 以非常开源的方式在其他项目之上构建项目的历史悠久。 Arduino IDE基于处理IDE和在其之上构建的Wiring IDE。
When we work with Arduino we commonly use the Arduino IDE (Integrated Development Environment), a software available for all the major desktop platforms (macOS, Linux, Windows), which gives us 2 things: a programming editor with integrated libraries support, and a way to easily compile and load our Arduino programs to a board connected to the computer.
当我们使用Arduino时,我们通常使用Arduino IDE(集成开发环境),该软件可用于所有主要的台式机平台(macOS,Linux,Windows),它为我们提供了2项功能:具有集成库支持的编程编辑器和轻松地将Arduino程序编译并加载到与计算机连接的板上的方法。
The Arduino Programming Language is basically a framework built on top of C++. You can argue that it’s not a real programming language in the traditional term, but I think this helps avoiding confusion for beginners.
Arduino编程语言基本上是基于C ++构建的框架。 您可以争辩说它不是传统术语中的真正编程语言,但是我认为这有助于避免使初学者感到困惑。
A program written in the Arduino Programming Language is called sketch. A sketch is normally saved with the .ino
extension (from Arduino
).
用Arduino编程语言编写的程序称为sketch 。 草图通常保存与该.ino
延伸部(从Ardu ino
)。
The main difference from “normal” C or C++ is that you wrap all your code into 2 main functions. You can have more than 2, of course, but any Arduino program must provide at least those 2.
与“普通” C或C ++的主要区别是将所有代码包装到2个主要函数中。 当然,可以有2个以上,但是任何Arduino程序都必须至少提供2个。
One is called setup()
, the other is called loop()
. The first is called once, when the program starts, the second is repeatedly called while your program is running.
一个叫做setup()
,另一个叫做loop()
。 第一个调用一次,程序启动时,第二个在程序运行时重复调用。
We don’t have a main()
function like you are used to in C/C++ as the entry point for a program. Once you compile your sketch, the IDE will make sure the end result is a correct C++ program and will basically add the missing glue by preprocessing it.
我们没有main()
函数,就像您在C / C ++中习惯于将其作为程序的入口点一样。 编译完草图之后,IDE将确保最终结果是正确的C ++程序,并通过预处理将基本上添加缺失的胶水。
Everything else is normal C++ code, and as C++ is a superset of C, any valid C is also valid Arduino code.
其他所有内容都是普通的C ++代码,并且由于C ++是C的超集,因此任何有效的C也是有效的Arduino代码。
One difference that might cause you troubles is that while you can spawn your program over multiple files, those files must all be in the same folder. Might be a deal breaking limitation if your program will grow very large, but at that point it will be easy to move to a native C++ setup, which is possible.
可能引起麻烦的一个不同之处是,尽管可以在多个文件上生成程序,但这些文件必须全部位于同一文件夹中。 如果您的程序会变得很大,可能会成为一个突破性的限制,但是到那时,可以轻松地迁移到本机C ++设置。
Part of the Arduino Programming Language is the built-in libraries that allow you to easily integrate with the functionality provided by the Arduino board.
Arduino编程语言的一部分是内置库,可让您轻松地与Arduino开发板提供的功能集成。
Your first Arduino program will surely involve making a led turn on the light, and then turn off. To do so, you will use the pinMode()
, delay()
and digitalWrite()
functions, along with some constants like HIGH
, LOW
, OUTPUT
.
您的第一个Arduino程序肯定会涉及到先打开灯然后关闭。 为此,您将使用pinMode()
, delay()
和digitalWrite()
函数,以及一些常量,例如HIGH
, LOW
, OUTPUT
。
Like this, the canonical first Arduino project (the “Hello, World!”):
这样,第一个规范的Arduino项目(“ Hello,World!”):
#define LED_PIN 13
void setup() {
// Configure pin 13 to be a digital output
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// Turn on the LED
digitalWrite(LED_PIN, HIGH);
// Wait 1 second (1000 milliseconds)
delay(1000);
// Turn off the LED
digitalWrite(LED_PIN, LOW);
// Wait 1 second
delay(1000);
}
This is all part of the Arduino Programming Language, or we’d better call it suite or library.
这都是Arduino编程语言的一部分,或者我们最好称其为suite或library 。
支持其他语言 (Support for other language)
As a reminder, I want to note that you are not limited to using this language and IDE to program an Arduino. Projects exist, among others, to let you run Node.js code on it using the Johnny Five project, Python code using pyserial and Go code with Gobot, but the Arduino Programming Language is definitely the one you’ll see most tutorials based upon, since it’s the native and canonical way to work with these devices.
提醒一下,我想指出的是,您不仅限于使用此语言和IDE对Arduino进行编程。 存在一些项目,其中包括让您使用Johnny Five项目在其上运行Node.js代码,使用pyserial和Gobot与Gobot进行 Python代码,但是Arduino编程语言绝对是您将看到的大多数基于该语言的教程,因为这是使用这些设备的本机和规范方法。
Arduino编程语言内置常量 (The Arduino Programming Language Built-in constants)
Arduino sets two constants we can use to
Arduino设置了两个我们可以用来常量
HIGH
equates to a high level of voltage, which can differ depending on the hardware (>2V on 3.3V boards like Arduino Nano, >3V on 5V boards like Arduino Uno) LOW
equates to a low level of voltage. Again, the exact value depends on the board used
HIGH
等于高电压,低电压取决于硬件(在3.3V板上,例如Arduino Nano上> 2V,在5V板上例如Arduino Uno上> 3V),这取决于硬件。LOW表示LOW
。 同样,确切值取决于所使用的电路板
Then we have 3 constants we can use in combination with the pinMode()
function:
然后,我们可以将3个常量与pinMode()
函数结合使用:
INPUT
sets the pin as an input pinINPUT
将引脚设置为输入引脚OUTPUT
sets the pin as an output pinOUTPUT
将引脚设置为输出引脚INPUT_PULLUP
sets the pin as an internal pull-up resistorINPUT_PULLUP
将引脚设置为内部上拉电阻
The other constant we have is LED_BUILTIN
, which points to the number of the on-board pin, which usually equates to the number 13
.
我们拥有的另一个常量是LED_BUILTIN
,它指向板载引脚的编号,通常等于13
。
In addition to this, we have the C/C++ constants true
and false
.
除此之外,我们还有C / C ++常量true
和false
。
Arduino数学常数 (Arduino Math Constants)
M_PI
the constant pi (3.14159265358979323846
)M_PI
常数pi(3.14159265358979323846
)M_E
the constant eM_E
常数eM_LN10
the natural logarithm of the number 10.M_LN10
数字10的自然对数。M_LN2
the natural logarithm of the number 2.M_LN2
数字2的自然对数。M_LOG10E
the logarithm of the e to base 10.M_LOG10E
e以10为底的对数。M_LOG2E
the logarithm of the e to base 2.M_LOG2E
e以2为底的对数。M_SQRT2
the square root of 2.M_SQRT2
的平方根2。NAN
the NAN (not a number) constant.NAN
NAN(不是数字)常量。
Arduino编程语言内置函数 (The Arduino Programming Language Built-in Functions)
In this section I am going to make a reference for the built-in functions provided by the Arduino Programming Language.
在本节中,我将为Arduino编程语言提供的内置函数提供参考。
程序生命周期 (Program lifecycle)
setup()
this function is called once, when the program starts, and when the Arduino is shut down and restarted.setup()
函数,在程序启动时以及在Arduino关闭并重新启动时都会调用一次此函数。loop()
this function is repeatedly called while the Arduino program is running.loop()
在Arduino程序运行时反复调用此函数。
处理I / O (Handling I/O)
The following functions help with handling input and output from your Arduino device.
以下功能有助于处理Arduino设备的输入和输出。
数字量I / O (Digital I/O)
digitalRead()
reads the value from a digital pin. Accepts a pin number as a parameter, and returns theHIGH
orLOW
constant.digitalRead()
从数字引脚读取值。 接受引脚号作为参数,并返回HIGH
或LOW
常数。digitalWrite()
writes aHIGH
orLOW
value to a digital output pin. You pass the pin number andHIGH
orLOW
as parameters.digitalWrite()
将HIGH
或LOW
值写入数字输出引脚。 您传递引脚号和HIGH
或LOW
作为参数。pinMode()
sets a pin to be an input, or an output. You pass the pin number and theINPUT
orOUTPUT
value as parameters.pinMode()
将引脚设置为输入或输出。 您将引脚号和INPUT
或OUTPUT
值作为参数传递。pulseIn()
reads a digital pulse fromLOW
toHIGH
and then toLOW
again, or fromHIGH
toLOW
and toHIGH
again on a pin. The program will block until the pulse is detected. You specify the pin number and the kind of pulse you want to detect (LHL or HLH). You can specify an optional timeout to stop waiting for that pulse.pulseIn()
读取的数字脉冲从LOW
到HIGH
,然后到LOW
再次,或从HIGH
到LOW
以及HIGH
再次上的销。 程序将阻塞直到检测到脉冲。 您可以指定引脚号和要检测的脉冲类型(LHL或HLH)。 您可以指定一个可选的超时时间以停止等待该脉冲。pulseInLong()
is same aspulseIn()
, except it is implemented differently and it can’t be used if interrupts are turned off. Interrupts are commonly turned off to get a more accurate result.pulseInLong()
是作为相同pulseIn()
除了它是实现方式不同,并且如果中断被关闭它不能被使用。 通常关闭中断以获取更准确的结果。shiftIn()
reads a byte of data one bit at a time from a pin.shiftIn()
一次从一个引脚读取一个字节的数据。shiftOut()
writes a byte of data one bit at a time to a pin.shiftOut()
将一个字节的数据写入一位引脚。tone()
sends a square wave on a pin, used for buzzers/speakers to play tones. You can specify the pin, and the frequency. It works on both digital and analog pins.tone()
在引脚上发送方波,用于蜂鸣器/扬声器播放音调。 您可以指定引脚和频率。 它适用于数字和模拟引脚。noTone()
stops thetone()
generated wave on a pin.noTone()
停止pin上的tone()
生成的波。
模拟量I / O (Analog I/O)
analogRead()
reads the value from an analog pin.analogRead()
从模拟引脚读取值。analogReference()
configures the value used for the top input range in the analog input, by default 5V in 5V boards and 3.3V in 3.3V boards.analogReference()
配置用于模拟输入中最高输入范围的值,默认为5V板上为5V,3.3V板上为3.3V。analogWrite()
writes an analog value to a pinanalogWrite()
将模拟值写入引脚analogReadResolution()
lets you change the default analog bits resolution foranalogRead()
, by default 10 bits. Only works on specific devices (Arduino Due, Zero and MKR)analogReadResolution()
您可以更改默认模拟位分辨率analogRead()
默认为10位。 仅适用于特定设备(Arduino Due,Zero和MKR)analogWriteResolution()
lets you change the default analog bits resolution foranalogWrite()
, by default 10 bits. Only works on specific devices (Arduino Due, Zero and MKR)analogWriteResolution()
您可以更改默认模拟位分辨率analogWrite()
默认为10位。 仅适用于特定设备(Arduino Due,Zero和MKR)
时间功能 (Time functions)
delay()
pauses the program for a number of milliseconds specified as parameterdelay()
将程序暂停指定为参数的毫秒数delayMicroseconds()
pauses the program for a number of microseconds specified as parameterdelayMicroseconds()
将程序暂停指定为参数的微秒数micros()
the number of microseconds since the start of the program. Resets after ~70 minutes due to overflowmicros()
自程序启动以来的微秒数。 大约70分钟后由于溢出而重置millis()
the number of milliseconds since the start of the program. Resets after ~50 days due to overflowmillis()
自程序启动以来的毫秒数。 大约50天后由于溢出而重置
数学函数 (Math functions)
abs()
the absolute value of a numberabs()
的绝对值constrain()
constrains a number to be within a range, see usageconstrain()
将数字限制在一个范围内, 请参阅用法map()
re-maps a number from one range to another, see usagemap()
将数字从一个范围重新映射到另一个范围, 请参阅用法max()
the maximum of two numbersmax()
两个数的最大值min()
the minimum of two numbersmin()
两个数的最小值pow()
the value of a number raised to a powerpow()
升为幂的数字的值sq()
the square of a numbersq()
一个数字的平方sqrt()
the square root of a numbersqrt()
的平方根cos()
the cosine of an anglecos()
角度的余弦sin()
the sine of an anglesin()
角度的正弦tan()
the tangent of an angletan()
角的切线
Note: there are more built-in mathematical functions if you need them, documented here.
注意:如果需要,还有更多内置数学函数,请参见此处 。
使用字母数字字符 (Working with alphanumeric characters)
isAlpha()
checks if a char is alpha (a letter)isAlpha()
检查char是否为alpha(字母)isAlphaNumeric()
checks if a char is alphanumeric (a letter or number)isAlphaNumeric()
检查字符是否为字母数字(字母或数字)isAscii()
checks if a char is an ASCII characterisAscii()
检查char是否为ASCII字符isControl()
checks if a char is a control characterisControl()
检查char是否为控制字符isDigit()
checks if a char is a numberisDigit()
检查字符是否为数字isGraph()
checks if a char is a printable ASCII character, and contains content (it is not a space, for example)isGraph()
检查char是否为可打印的ASCII字符并包含内容(例如,它不是空格)isHexadecimalDigit()
checks if a char is an hexadecimal digit (A-F 0-9)isHexadecimalDigit()
检查char是否为十六进制数字(AF 0-9)isLowerCase()
checks if a char is a letter in lower caseisLowerCase()
检查字符是否为小写字母isPrintable()
checks if a char is a printable ASCII characterisPrintable()
检查char是否为可打印的ASCII字符isPunct()
checks if a char is a punctuation (a comma, a semicolon, an exclamation mark etc)isPunct()
检查char是否为标点符号(逗号,分号,感叹号等)isSpace()
checks if a char is a space, form feed\f
, newline\n
, carriage return\r
, horizontal tab\t
, or vertical tab\v
.isSpace()
检查char是否为空格,换页\f
,换行\n
,回车符\r
,水平制表符\t
或垂直制表符\v
。isUpperCase()
checks if a char is a letter in upper caseisUpperCase()
检查字符是否为大写字母isWhitespace()
checks if a char is a space character or an horizontal tab\t
isWhitespace()
检查char是空格字符还是水平制表符\t
随机数生成 (Random numbers generation)
random()
generate a pseudo-random numberrandom()
生成一个伪随机数randomSeed()
initialize the pseudo-random number generator with an arbitrary initial numberrandomSeed()
使用任意初始数初始化伪随机数生成器
In Arduino, like in most languages, it’s impossible to get really random numbers, and the sequence is always the same, so you seed it with the current time or (in the case of Arduino) you can read the input from an analog port.
在Arduino中,就像在大多数语言中一样,不可能获得真正的随机数,并且序列始终是相同的,因此您可以使用当前时间作为种子的种子,或者(对于Arduino)可以从模拟端口读取输入 。
使用位和字节 (Working with bits and bytes)
bit()
computes the value of a bit (0 = 1, 1 = 2, 2 = 4, 3 = 8…)bit()
计算一个位的值(0 = 1、1 = 2、2 = 4、3 = 8…)bitClear()
clear (sets to 0) a bit of a numeric variable. Accepts a number, and the number of the bit starting from the rightbitClear()
清除(设置为0)一个数字变量。 接受一个数字,该位数从右开始bitRead()
read a bit of a number. Accepts a number, and the number of the bit starting from the rightbitRead()
读取一个数字。 接受一个数字,该位数从右开始bitSet()
sets to 1 a bit of a number. Accepts a number, and the number of the bit starting from the rightbitSet()
将数字的一位设置为1。 接受一个数字,该位数从右开始bitWrite()
write 1 or 0 to a specific bit of a number Accepts a number, the number of the bit starting from the right, and the value to write (0 or 1)bitWrite()
向数字的特定位写入1或0接受一个数字,该位的数字从右开始以及要写入的值(0或1)highByte()
get the high-order (leftmost) byte of a word variable (which has 2 bytes)highByte()
获取单词变量的高位(最左边)字节(具有2个字节)lowByte()
get the low-order (rightmost) byte of a word variable (which has 2 bytes)lowByte()
获取单词变量的低位(最右边)字节(具有2个字节)
中断 (Interrupts)
noInterrupts()
disables interruptsnoInterrupts()
禁用中断interrupts()
re-enables interrupts after they’ve been disabledinterrupts()
在禁用后重新启用中断attachInterrupt()
allow a digital input pin to be an interrupt. Different boards have different allowed pins, check the official docs.attachInterrupt()
允许数字输入引脚为中断。 不同的板有不同的允许的引脚, 请检查官方文档 。detachInterrupt()
disables an interrupt enabled usingattachInterrupt()
detachInterrupt()
禁用使用attachInterrupt()
启用的中断
arduino编程语言