-
Notifications
You must be signed in to change notification settings - Fork 5
/
chapter_1-3.qmd
347 lines (239 loc) · 17.8 KB
/
chapter_1-3.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# 1.3 Transforming XIAO and its Expansion Board into a Morse Code Transmitter {.unnumbered}
<br />
Everyone knows that "SOS" is an internationally recognized emergency signal, a form of Morse code. Today, we will transform Seeed Studio's XIAO into a Morse code transmitter. We will try to make the onboard buzzer of the expansion board send signals automatically. In addition, we will learn how to control the buzzer manually with a button.
## 1.3.1 Background Knowledge
### 1.3.1.1 Buzzer
A buzzer is an integrated electronic sound device that generates sound based on the input of an electrical signal. Buzzers are often installed on electronic products for sound generation. There are two types of buzzers: active (source buzzers) and passive (sourceless buzzers).
- **Active Buzzers:** These buzzers have a simple oscillation circuit inside. When connected to a DC power supply, the buzzer can convert a constant DC into a certain frequency pulse signal, thereby driving the internal aluminum sheet to vibrate and make a sound. Active buzzers can usually only emit some fixed-pitch (frequency) sounds and are widely used in the sound devices of computers, printers, copiers, alarms, electronic toys, car electronics, phones, timers, and other electronic products.
- **Passive Buzzers:** These buzzers work similarly to loudspeakers. They don't have an internal oscillator and need to be connected to a changing current signal to work. They usually use different frequency square wave signals for driving. The sound generated by passive buzzers will change according to the change in input signal, and they can output a variety of sounds like speakers, not just emitting a fixed single tone (frequency).
<!-- ![](https://cdn.nlark.com/yuque/0/2023/jpeg/2392200/1684913092337-d9a94a03-d2e8-493b-94c6-22d08db1b628.jpeg) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_1.jpeg)
The standalone buzzer module is shown in the figure below.
<div style="text-align:center;"><img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_2.png" width="300" height="auto" style="margin:0 auto;"/></div>
In the Seeed Studio XIAO expansion board, there is an onboard passive buzzer connected to pin A3. We can output PWM pulse signals to this pin to control the buzzer.
<!-- ![XIAO蜂鸣器.png](https://cdn.nlark.com/yuque/0/2021/png/2746511/1612687823459-80d12700-2195-426b-adef-2e97dd5dd36e.png#averageHue=%23686866&height=303&id=Ky3GI&originHeight=383&originWidth=413&originalType=binary&ratio=1&rotation=0&showTitle=false&size=28973&status=done&style=none&title=&width=327) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_3.png)
### 1.3.1.2 `tone()` and `noTone()` Functions
#### **`tone()`Function**
The `tone()`function can generate a fixed frequency PWM signal to drive a passive buzzer to make a sound, and it can define the frequency and duration of the sound.
##### Syntax:
`tone(pin, frequency);` <br />
`tone(pin, frequency, duration);`
##### Parameters:
`pin:` The pin to which the buzzer is connected (in the Seeed Studio XIAO expansion board, it's A3). <br />
`frequency:`The frequency of the sound (unit: Hz), the type allowed is unsigned integer.<br />
`duration:`The duration of the sound (unit: milliseconds, this parameter is optional), the type allowed is unsigned long.
#### **`noTone()` Function**
This function is used to stop the sound of the buzzer controlled by the `tone()` function. If there is no sound generated, the function is invalid.
##### Syntax:
`noTone(pin);`
##### Parameters:
`pin:` The pin to stop the sound.
### 1.3.1.3 Common Operators
In previous studies, we have used some operators. Next, we will learn about common types of operators and their usage methods.
#### **Arithmetic Operators: **
| Operator | Explanation |
|----------|-------------------------|
| = | Assignment operator |
| + | Addition operator |
| - | Subtraction operator |
| * | Multiplication operator |
| / | Division operator |
| % | Modulus operator |
#### **Comparison Operators:**
| Operator | Explanation |
|----------|--------------------------|
| != | Not equal to |
| < | Less than |
| <= | Less than or equal to |
| == | Equal to |
| > | Greater than |
| >= | Greater than or equal to |
#### **Boolean Operators:**
| Operator | Explanation |
|----------|---------------|
| && | Logical "and" |
| ! | Logical "not" |
| || | Logical "or" |
#### **Compound Operators:**
| Operator | Explanation |
|----------|----------------------|
| ++ | Self-increment |
| += | Compound addition |
| -- | Self-decrement |
| -= | Compound subtraction |
For detailed explanations, see: <https://www.arduino.cc/reference/en/>
### 1.3.1.4 Morse Code
Morse code is a method of expressing information in telecommunication, named after the inventor of the telegraph, Samuel Morse.
<!-- ![](https://cdn.nlark.com/yuque/0/2020/jpeg/2392200/1603846193944-6ea73875-67de-4ba5-a446-8dda9676e52b.jpeg#averageHue=%238b867f&height=317&id=U6xpZ&originHeight=317&originWidth=220&originalType=binary&ratio=1&rotation=0&showTitle=false&size=0&status=done&style=none&title=&width=220) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_4.jpg)
Source of the picture: <https://en.wikipedia.org/wiki/Samuel_Morse> <br />
The international Morse code encodes the 26 English letters A to Z, some non-English letters, Arabic numbers, and a small number of punctuation marks and prosigns. There is no distinction between upper and lower case letters. Each Morse code symbol consists of a series of dots (·) and dashes (---). The duration of a dot is the basic unit of time measurement in Morse code transmission. The duration of a dash is three times the duration of a dot. After each dot or dash in a character, there is a time when the signal is absent, called a space, equal to the duration of a dot. For example, the standard emergency distress signal SOS is expressed in Morse code as shown in the figure below.
<!-- ![150px-SOS.svg.png](https://cdn.nlark.com/yuque/0/2020/png/2392200/1603846441960-5e9f2c7f-7de0-42a9-97f4-80a551dd156c.png#averageHue=%235a0000&height=10&id=bGB4N&originHeight=10&originWidth=150&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1097&status=done&style=none&title=&width=150) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_5.png)
If it's expressed in sound, it sounds like this.
<audio controls>
<source src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/sos.wav" type="audio/wav">
Your browser does not support the audio element.
</audio>
As can be seen, Morse code essentially encodes duration to transmit signals. With such encoding rules, people can present duration in many ways, such as intermittently emitting sounds, intermittently lighting up searchlights, etc., to ultimately achieve the purpose of sending information.
<!-- ![](https://cdn.nlark.com/yuque/0/2020/jpeg/2392200/1603846838461-ea51e722-f05f-478d-be0f-f1327907c17a.jpeg#averageHue=%237f909f&height=962&id=WHt1r&originHeight=1011&originWidth=800&originalType=binary&ratio=1&rotation=0&showTitle=false&size=0&status=done&style=none&title=&width=761) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_6.jpeg)
Source of the picture:<https://en.wikipedia.org/wiki/Morse_code> <br />
Morse code was used most when communication was not developed. People used Morse code for long-distance information transmission through radio. The old device below is an early telegraph device, where the operator controls the long and short signals of the telegraph by pressing the circular handle on the right.
<!-- ![](https://cdn.nlark.com/yuque/0/2020/jpeg/2392200/1603846816937-54826ec7-a061-46e9-b51e-61e0caf679fb.jpeg#averageHue=%23c7c7bf&height=657&id=dvnyK&originHeight=876&originWidth=1024&originalType=binary&ratio=1&rotation=0&showTitle=false&size=0&status=done&style=stroke&title=&width=768) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_7.jpg)
Source of the picture: <https://en.wikipedia.org/wiki/Morse_code> <br />
If you are interested in Morse code, you can visit the following website. The website can translate the letters and numbers you enter into Morse code and provide a download of the sound file. <br />
<https://morsedecoder.com/>
## 1.3.2 Task 1: Automatic Broadcasting of "SOS"
### Analysis
Automatic broadcasting means that when the control board is started, the onboard buzzer automatically emits the Morse code of "SOS". The program is written in three steps:
- Define the buzzer pin
- Initialization, setting the state of the buzzer pin
- Loop the buzzer to play the Morse code of "SOS"
Let's first look at how to reflect the Morse code of "SOS" through the program. If you import the audio file of Morse code into the audio editing software, you can see the waveform of the sound and the duration of each syllable, which is generally divided into long and short sounds. To facilitate understanding and programming, we use a binary way to mark the switch of the buzzer, 1 indicates the buzzer is on, 0 indicates the buzzer is off, and the gray number represents how long the current status needs to last. After a Morse code ends, because it needs to be looped, you need to leave time between the two Morse codes, here it is set to 0.8 seconds.
<!-- ![](https://cdn.nlark.com/yuque/0/2020/png/2392200/1603866605792-3b94b31b-4bff-426f-8166-d1dae05f5856.png#averageHue=%23646464&height=529&id=yQCMh&originHeight=529&originWidth=1405&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=&width=1405) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_8.png)
To emit a short sound, which corresponds to a dot in Morse code, from the buzzer, you can use the following code in Arduino:
``` cpp
tone(pinBuzzer, 200);
delay(100);
noTone(pinBuzzer);
delay(100);
```
In this code snippet:
- `tone(pinBuzzer, 200)` generates a sound at a frequency of 200 Hz on the buzzer connected to the `pinBuzzer` pin.
- `delay(100)` waits for 100 milliseconds. This is how long the sound lasts.
- `noTone(pinBuzzer)` stops the sound on the buzzer.
- The final `delay(100)` ensures there's a pause before the next sound is generated, representing the space between the signals.
The code you provided is a complete Arduino program for emitting the SOS Morse code signal using a buzzer. Here is the English explanation:
#### **Writing the Program **
**Step 1:** Define pins and create variables
``` cpp
int pinBuzzer = 3; // Define the buzzer on pin 3, if you're using XIAO RP2040/XIAO ESP32, change 3 to A3
```
**Step 2:** Set pin state
``` cpp
void setup() {
pinMode(pinBuzzer, OUTPUT); // Set the buzzer pin to output state
}
```
**Step 3:** Loop to play "SOS" Morse code
``` cpp
void loop() {
// Emit three short signals:
for(int i = 0; i < 3; i++){
tone(pinBuzzer, 200);
delay(100);
noTone(pinBuzzer);
delay(100);
}
delay(200);
// Emit three long signals:
for(int i = 0; i < 3; i++){
tone(pinBuzzer, 200);
delay(300);
noTone(pinBuzzer);
delay(100);
}
delay(200);
// Emit three short signals again:
for(int i = 0; i < 3; i++){
tone(pinBuzzer, 200);
delay(100);
noTone(pinBuzzer);
delay(100);
}
delay(800); // Wait before repeating
}
```
> Get this program from Github <br />
> <https://github.com/mouseart/XIAO-Mastering-Arduino-and-TinyML/tree/main/code/L3_SOS_XIAO_en>
#### **Uploading the Program**
To upload the program to your hardware, connect your XIAO to your computer using the data cable included in the kit. After this, click on 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 check your program. If it passes verification, click on 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 your hardware. When the debug area shows "Done uploading.", you can listen to the Morse code sound. Is it the rhythm you expected?
<!-- ![](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.
## 1.3.3 Task 2: Control the buzzer with a button
Controlling the buzzer with a button to emit Morse code can be done manually. The code logic is simple: use an if statement to determine if the button is pressed. If it is, then the buzzer emits a sound.
#### **Analysis **
The program is also written in three steps:
- Define the buzzer and button pins.
- Initialize by setting the state of the buzzer and button pins.
- Determine whether the button is pressed; if pressed, emit a sound.
#### **Write the program: **
**Step 1:** Define the buzzer and button pins
``` cpp
const int buttonPin = 1; // Button is connected to pin 1; adjust for your board (e.g., D1 for XIAO RP2040/XIAO ESP32)
int buzzerPin = 3; // Buzzer is connected to pin 3; adjust for your board (e.g., A3 for XIAO RP2040/XIAO ESP32)
```
**Step 2:** Set the button and buzzer pin states
``` cpp
void setup() {
// Set the buzzer pin as an output
pinMode(buzzerPin, OUTPUT);
// Configure the button pin as input with internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
}
```
**Step 3:** Check the button state, if the button is pressed, the buzzer sounds. Here, the `tone()` function is used to control the passive buzzer to make a sound.
``` cpp
void loop() {
// Read the state of the button
int buttonState = digitalRead(buttonPin);
// If the button is pressed
if (buttonState == LOW) {
// While the button remains pressed, keep the buzzer sounding
while (buttonState == LOW) {
tone(buzzerPin, 200); // Make the buzzer sound at 200Hz
delay(10); // Small delay to avoid CPU overload; can be adjusted or a more sophisticated debouncing method used
buttonState = digitalRead(buttonPin); // Continuously check the button state within the loop
}
// When the button is released, ensure the buzzer stops
noTone(buzzerPin);
}
}
```
> ⚠️ Note: <br />
>There are two identical buttons on the expansion board, one is the RESET button, which is closer to the Type-C interface, and the other is the user-defined button, which is closer to the lithium battery interface. When testing, press the one closer to the lithium battery interface.
The complete program is as follows:
``` cpp
/*
* Button-Controlled Buzzer
*/
const int buttonPin = 1; // Button is connected to pin 1; adjust for your board (e.g., D1 for XIAO RP2040/XIAO ESP32)
int buzzerPin = 3; // Buzzer is connected to pin 3; adjust for your board (e.g., A3 for XIAO RP2040/XIAO ESP32)
void setup() {
// Set the buzzer pin as an output
pinMode(buzzerPin, OUTPUT);
// Configure the button pin as input with internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// Read the state of the button
int buttonState = digitalRead(buttonPin);
// If the button is pressed
if (buttonState == LOW) {
// While the button remains pressed, keep the buzzer sounding
while (buttonState == LOW) {
tone(buzzerPin, 200); // Make the buzzer sound at 200Hz
delay(10); // Small delay to avoid CPU overload; can be adjusted or a more sophisticated debouncing method used
buttonState = digitalRead(buttonPin); // Continuously check the button state within the loop
}
// When the button is released, ensure the buzzer stops
noTone(buzzerPin);
}
}
```
> Get this program from Github <br />
> <https://github.com/mouseart/XIAO-Mastering-Arduino-and-TinyML/tree/main/code/L3_ButtonSOS_XIAO_en>
#### **Uploading the program**
We will upload the written program to the hardware. First, connect the XIAO to your computer using the data cable from the kit.
<!-- ![](https://cdn.nlark.com/yuque/0/2021/png/2746511/1615883758760-2df32372-1a05-412c-ba57-f4d4f6e17aef.png#averageHue=%23dddcdc&height=1073&id=qPn4d&originHeight=1073&originWidth=2896&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=&width=2896) -->
![](https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/chapter_1-3/chapter_1-3_9.png)
Next, click the <img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/verify-button.png" alt="verify-button.png" width="30" height="30" /> (verify button) to validate the program. If there are no errors, click the <img src="https://files.seeedstudio.com/wiki/XIAO_Big_Power-Board-ebook-photo/upload-button.png" alt="upload-button.png" width="30" height="30" /> (upload button) to upload the program to the hardware. When the debug area shows "Done uploading.", we can press the button on the XIAO expansion board and test whether the buzzer will sound.
## 1.3.4 Extended Exercise
The passive buzzer can emit different pitches to form a simple melody. Research how to make Arduino play notes through a search engine. You can open the extended exercise code to experience the effect of playing "Happy Birthday" with the buzzer.
> Get this program from Github <br />
> <https://github.com/mouseart/XIAO-Mastering-Arduino-and-TinyML/tree/main/code/L3_HappyBirthday_en>