-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathchapter_1-2.qmd
320 lines (220 loc) · 18.9 KB
/
chapter_1-2.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# 1.2 Using the Button Switch on the XIAO Expansion Board to Control an LED Light {.unnumbered}
<br />
In the previous section, we learned how to control an LED light to blink using only the Seeed Studio XIAO and the onboard LED light. However, there was no interaction with the external environment, such as controlling the LED light through light or sound. In this section, we will introduce a simple sensor - the button switch, to form an automatic control system of sensor-controller-actuator. Before starting the task, we need to learn some basic knowledge, like what variables are and the common program structures, so that we can better understand and run the program.
## 1.2.1 Background Knowledge
In the last section, we only used the onboard LED light of the Seeed Studio XIAO without connecting other modules. It could take quite some effort for beginners to use Dupont wires to connect external sensors to a board the size of a thumb and also involve a breadboard. Is there a simpler method?
### 1.2.1.1 Seeed Studio XIAO Expansion Board
The [Seeed Studio XIAO Expansion Board](https://www.seeedstudio.com/Seeeduino-XIAO-Expansion-board-p-4746.html), only half the size of Raspberry Pi 4, is powerful and can quickly and easily build prototypes and projects. The board has a variety of peripherals such as OLED, RTC, expandable memory, passive buzzer, RESET/User button, 5V servo/sensor connector, various data interfaces... You can explore the infinite possibilities of Seeed Studio XIAO. The board also supports [CircuitPython](https://circuitpython.org/). <br />
All models in the Seeed Studio XIAO series have uniform specifications and support the Seeed Studio XIAO [Grove Shield](https://seeedstudio.com/Grove-Shield-for-Seeeduino-XIAO-p-4621.html) and [Seeed Studio XIAO Expansion Board](https://www.seeedstudio.com/Seeeduino-XIAO-Expansion-board-p-4746.html). The series includes [XIAO SAMD21](https://www.seeedstudio.com/Seeeduino-XIAO-Arduino-Microcontroller-SAMD21-Cortex-M0+-p-4426.html), [XIAO RP2040](https://www.seeedstudio.com/XIAO-RP2040-v1-0-p-5026.html), [XIAO nRF52840](https://www.seeedstudio.com/Seeed-XIAO-BLE-nRF52840-p-5201.html), [XIAO nRF52840 Sense](https://www.seeedstudio.com/Seeed-XIAO-BLE-Sense-nRF52840-p-5253.html), [XIAO ESP32C3](https://www.seeedstudio.com/Seeed-XIAO-ESP32C3-p-5431.html) and [XIAO ESP32S3](https://www.seeedstudio.com/XIAO-ESP32S3-Sense-p-5639.html). The front and back function interfaces of the XIAO expansion board are shown in the following figure:
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684898711192-4dab285f-6077-4f5d-84e1-d19500c39ac9.jpeg) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_1.jpeg)
To make it easier and quicker to build projects with Seeed Studio XIAO, we equipped it with a powerful expansion board. This board has a wealth of onboard peripherals and can quickly connect to more electronic modules to implement various functions. The expansion board brings out all the pins of XIAO, as shown in the pin diagram below:
![](https://files.seeedstudio.com/wiki/Seeeduino-XIAO-Expansion-Board/Update_pic/pinpinpin4.jpg)
In most cases, the XIAO expansion board is suitable for all Seeed Studio XIAO series products. <br />
When we need to use the XIAO expansion board, we need to connect the XIAO development board to the corresponding position on the expansion board, as shown in the figure below. Connect the pin headers on the XIAO main board to the position circled in yellow on the expansion board. Be sure to align it before pressing down to avoid damaging the pins. After that, we can start working on projects in combination with the expansion board.
<!-- ![页面_4.png](https://cdn.nlark.com/yuque/0/2021/png/2746511/1615806858604-8e938c29-515f-4f61-8329-7178662f6f3b.png#averageHue=%23858585&height=308&id=GzIL2&originHeight=530&originWidth=985&originalType=binary&ratio=1&rotation=0&showTitle=false&size=53243&status=done&style=none&title=&width=572) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_2.png)
> ⚠️ Note <br />
> Please first plug the Seeed Studio XIAO into the two female headers on the expansion board, and then plug in the Type-C power supply, otherwise it will damage the Seeed Studio XIAO and the expansion board.
### 1.2.1.2 Three Basic Structures of Programs
The three basic structures of programs are sequential structure, selection structure, and loop structure.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684899917009-c627d8d8-510e-442a-a8d1-ed9a35fd9fe3.jpeg) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_3.jpeg)
#### **Sequential Structure**
As the name suggests, the program in a sequential structure is executed in the order of the statements. It is the most basic and simple program structure. As shown in the figure below, the program will first execute the operation in the S1 box, then the operation in the S2 box, and so on.
<!-- ![顺序结构.png](https://cdn.nlark.com/yuque/0/2021/png/2746511/1615875380657-0bc53b9b-6288-431f-ac82-39bb2a216d03.png#averageHue=%23232323&height=256&id=gDvkN&originHeight=600&originWidth=584&originalType=binary&ratio=1&rotation=0&showTitle=false&size=16936&status=done&style=none&title=&width=249) -->
<img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_4.png" width="300" height="auto" />
#### **Selection Structure**
In a program,sometimes we need to make judgments based on the situation to decide the next step. For instance, the program might need to judge the light value in the current environment. If the light value is high, indicating a bright environment, there's no need to light up the light. If the light value is low, indicating a dim environment, then it's necessary to turn on the light. In such cases, we use a selection structure. <br />
As shown in the following figures, the selection structure will judge whether the condition is fulfilled. If "True", it executes S1; if "False", it executes S2; or if "True", it executes S1, if "False", it exits the selection structure.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684903938231-98df9719-c5e3-40a9-bc21-293565d27e6c.jpeg) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_5.jpeg)
##### The if Statement
The if statement is the most common selection structure, which executes the following statement when the given expression is true. The if statement has three structural forms as shown in the following example. Simple branch structure: Execute when the condition is fulfilled.
``` cpp
if (expression) {
statement;
}
```
Dual branch structure: Execute statement1 when the condition is fulfilled, otherwise execute statement2.
```cpp
if (expression) {
statement1;
}
else {
statement2;
}
```
Multi-branch structure: Use nested if statements to judge different situations.
``` cpp
if (expression1) {
statement1;
}
else if (expression2) {
statement2;
}
else if (expression3) {
statement3;
}
```
##### `switch……case` Statement
<br />
When dealing with multiple selection branches, using an "if......else" structure to write a program can be quite lengthy. In this case, it's much more convenient to use a `switch` statement. The `switch` structure compares the expression in parentheses with the constants after `case`. If they match, it executes the corresponding statement and exits the structure via a `break` statement. If none match, it runs the statement after `default`. It's important to note that the expression in parentheses after `switch` must be of integer or character type.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684907532843-f65cafa8-681a-490c-8153-1ffd74507480.jpeg) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_6.jpeg)
``` cpp
switch (expression) {
case constant_expression1:
statement1;
break;
case constant_expression2:
statement2;
break;
……
default:
statementn;
break;
}
```
<br />
##### `break` Statement <br />
The `break` statement can only be used in a `switch` multi-branch selection structure and loop structures. It is used to terminate the current program structure, allowing the program to jump to subsequent statements for execution.
#### **Loop Structure** <br />
A loop structure is used when a part of the program needs to be executed repeatedly, based on given judgment conditions to determine whether to continue executing a certain operation or exit the loop. There are three common types of loop statements:
<br />
##### `while` Loop <br />
The `while` loop is a type of "when" loop that executes the statements in the loop body when a certain condition is met.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684908451724-796c9fa0-a2d7-40fe-80cc-54ced2d081ed.jpeg) -->
<div align="center"><img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_7.jpeg" width="300" height="auto" /></div>
```cpp
while (expression) {
statement;
}
```
##### `do……while` Loop
This is a type of "until" loop. The statement in the loop body is executed once before the expression is evaluated. If the expression is true, the loop continues.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684908453750-2896ad3b-15f3-499b-95c4-35f6cabfba7f.jpeg) -->
<div align="center"><img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_8.jpeg" width="300" height="auto" /></div>
```cpp
do {
statement;
} while (expression);
```
<br />
##### `for` Loop
This includes three expressions: Expression1 for initialization, Expression2 for judgment, and Expression3 for increment.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684908867915-598217ed-fa2a-438a-a2c5-6732f0c219be.jpeg) -->
<div align="center"><img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_9.jpeg" width="300" height="auto" /></div>
```cpp
for (Expression1; Expression2; Expression3) {
statement;
}
```
In addition to the above loop statements, there are control statements, `break` and `continue`, in the loop structure used to prematurely end the loop or exit the loop. In this lesson, we just need to understand these program structures. In later courses, we will gradually master them through project examples.
## 1.2.2 Task 1: Control the LED on the XIAO using the button on the XIAO expansion board
### **Analysis**
The effect we want to achieve is that when the button is pressed, the LED lights up; when the button is released, the LED goes off. The program is written in three steps:
- Define pins and create variables.
- Initialize and set pin status.
- Read the button status, implement condition judgment. If the button is pressed, the light is on, otherwise, the light is off.
### Variable
> In a program, a value that can change is called a variable. For example, defining an integer variable `i` as `int i;`. We can assign a value to the variable at the same time as we define it, such as `int i =0;`. Furthermore, depending on the data type, different statements are used to define variables, such as defining a floating point number, `float x = 1.9;`, and so on. For more details, refer to the Arduino data types and constants documentation <https://www.arduino.cc/reference/en/#variables>.
### **Writing the Program:**
**Step 1:** Define pins and create variables. The on-board button switch on the XIAO expansion board is `D1`, so we define it as pin 1 and set a variable for the button status. Note that `LED_BUILTIN` will set the LED to the correct pin, so we don't need to manually define it:
``` cpp
const int buttonPin = 1; // The on-board button switch on the XIAO expansion board is D1, which we define as pin 1
// If you are using XIAO RP2040, please change 1 to D1
int buttonState = 0; // buttonState is a variable to store the button status
```
**Step 2:** Set pin status. Set the LED pin to output status and the button pin to input pull-up status. Use `INPUT_PULLUP` to enable internal pull-up resistors. When the button is not pressed, it returns `1` or `HIGH` (high level). When the button is pressed, it returns `0` or `LOW` (low level).
``` cpp
void setup() {
pinMode(LED_BUILTIN, OUTPUT);// Set the LED pin to output status
pinMode(buttonPin, INPUT_PULLUP);// Set the button pin to input status
}
```
**Step 3:** Continuously read the button status. If the button is pressed, the light is on, otherwise, the light is off. Because the on-board LED of the XIAO is negative logic, when the button is pressed and returns `0`, the LED is on; when it returns `1`, the LED is off.
``` cpp
void loop() {
// Read the button status and store it in the buttonState variable
buttonState = digitalRead(buttonPin);
// Check whether the button is pressed, if the button is pressed
if (buttonState == HIGH) {
// Turn on the LED:
digitalWrite(LED_BUILTIN, HIGH);
}
else {
// Turn off the LED:
digitalWrite(LED_BUILTIN, LOW);
}
}
```
> Get this program from Github <br />
> <https://github.com/mouseart/XIAO-Mastering-Arduino-and-TinyML/blob/main/code/L2_Button_XIAO_en/L2_Button_XIAO_en.ino>
### **Uploading the Program**
We upload the program we wrote to the hardware. First, use the data cable in the kit to connect the XIAO to the computer.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684977221668-62259e38-ab6e-4645-b9c9-be8b2ec59bdb.jpeg) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_10.jpeg)
Note the position of the buttons on the XIAO extensions used for testing in the figure. <br />
Then click the verify button <img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/verify-button.png" alt="verify-button.png" width="30" height="30" /> to verify the program. If it is correct, click the upload button <img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/upload-button.png" alt="upload-button.png" width="30" height="30" /> to upload the program to the hardware. When the debugging area displays "Done uploading.", we can press the button to see if the LED lights up.
<!-- ![L2.jpg](https://cdn.nlark.com/yuque/0/2021/jpeg/2746511/1616585235857-fdcaddb5-6a91-41eb-954a-96703b87cf5f.jpeg#averageHue=%23dad2cd&height=2273&id=aQiVX&originHeight=2273&originWidth=3082&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1870913&status=done&style=none&title=&width=3082) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_11.jpg)
> ⚠️ Note <br />
>There are two identical buttons on the expansion board. One is the RESET button near the Type-C interface, and the other is the user-defined button near the lithium battery interface. Test with the one near the lithium battery interface.
## 1.2.3 Task 2: Use the button on the XIAO expansion board to control the external LED on the XIAO ESP32C3
For the Seeed XIAO ESP32C3, it doesn't have an on-board LED for users to use. To run the Blink program, you need to first connect an LED to the `D10` pin of the board as shown:
![](https://files.seeedstudio.com/wiki/XIAO_WiFi/connect-led-2.png)
> ⚠️ Note <br />
> Be sure to add a resistor (about 150Ω) in series with the LED to limit the current flowing through the LED to prevent overcurrent from burning out the LED.
Then copy the following program into the Arduino IDE:
``` cpp
/*
* Button controlling external LED of XIA
Apologies for the confusion. It seems that there was an issue with quoting text from the document. Let's continue:
#### Task 2: Use the button on the XIAO expansion board to control the external LED on the XIAO ESP32C3
For the Seeed XIAO ESP32C3, it doesn't have an on-board LED for users to use. To execute the Blink program, you first need to connect an LED to the board's `D10` pin as shown.
> ⚠️ Note: Make sure to add a resistor (about 150Ω) in series with the LED to limit the current flowing through the LED and prevent overcurrent from burning out the LED.
Then, copy the following program into the Arduino IDE:
```cpp
/*
* Button controlling external LED of XIAO ESP32C3
*/
const int buttonPin = 1; // The pin number of the button
int buttonState = 0; // Variable for reading the button status
int led = D10; // Pin number of the LED
void setup() {
// Initialize the LED pin as an output:
pinMode(led, OUTPUT);
// Initialize the button pin as an input:
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// Read the state of the button:
buttonState = digitalRead(buttonPin);
// Check if the button is pressed. If it is, the button state is HIGH
if (buttonState == HIGH) {
// Turn the LED on:
digitalWrite(led, HIGH);
}
else {
// Turn the LED off:
digitalWrite(led, LOW);
}
}
```
> Get this program from Github <br />
> <https://github.com/mouseart/XIAO-Mastering-Arduino-and-TinyML/tree/main/code/L2_Button_XIAO_ESP32C3_en>
### **Powering XIAO with an external battery**
When demonstrating the effect, in addition to using a data cable to power the computer, you can also use an external lithium battery. This makes it convenient to move and do projects, as shown in the picture.
<!-- ![页面_13.png](https://cdn.nlark.com/yuque/0/2021/png/2746511/1616585803526-8cf1d09c-7ca9-43cc-894a-d803bfc68826.png#averageHue=%23b6b5b3&height=296&id=W0Le8&originHeight=586&originWidth=923&originalType=binary&ratio=1&rotation=0&showTitle=false&size=64471&status=done&style=none&title=&width=467) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_12.png)
<!-- ![L1.jpg](https://cdn.nlark.com/yuque/0/2021/jpeg/2746511/1616585167964-b133a132-c044-49c6-888f-e4d0f571c16f.jpeg#averageHue=%23f0efee&height=2320&id=DhR5b&originHeight=2320&originWidth=3500&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1678625&status=done&style=none&title=&width=3500) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_13.jpg)
## 1.2.4 Expanded Exercise
### **Flow Chart **
Before writing the program, you can first draw a flow chart of the program to help organize your thoughts. The common flow chart symbols are as follows:
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684910895830-8ac3d9c1-0015-404a-8e62-acd8284b3acf.jpeg) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_14.jpeg)
The button-controlled LED program we implemented in this section is represented by the following flow chart. You can try drawing it yourself.
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684911242655-4e6036ff-1151-48ba-8bc0-43bb8271c080.jpeg) -->
<div style="text-align:center;"><img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-2/chapter_1-2_15.jpeg" width="300" height="auto" style="margin:0 auto" />